How to code a compiler in C?

后端 未结 2 1727
感动是毒
感动是毒 2021-01-13 16:14

I am coding a compiler in C, and I have read all about compilers in the Dragon book. But I am finding it really hard to implement, and I have no clue as to where to start. E

相关标签:
2条回答
  • 2021-01-13 16:30

    You could look at Appel's Modern Compiler Implementation in C.

    By the sounds of it you need to work out what language you want to compile: do you want a subset of C say or a easy to parse language like Scheme, or just an arithmetic expression language?

    Pick/design a language, write a couple of really small programs in it, write a lexer/parser for part of it, then the back to get parts working (possibly interpreted to start - just so you can see it running) and then iterate chunks that seem interesting, building up to the full language.

    Edit based on extra details supplied

    "i want to make a super set of c , like implementing various advantages of python , but keeping it as simple as c"

    I'm not sure I'd do that by writing everything by hand but if I did ...

    I'd write out some programs in the hybrid language that I want to end up with: so if you want C with Python like list comprehensions then maybe

    void main()
    {
        int[] x = {1,2,3,4,5};
        int[] y = {i*i for i in x where i % 2 == 0};
        for (int i in y) { printf("%d", i); }
    }
    

    [C style arrays that include their count as implied above left as exercise for the reader :-) !]

    Then get an absolutely minimal C program working, hello world or even just adding some numbers statically (if it was hello world I might even start by special casing printf so I didn't have to parse stdio.h - if you're heading towards a C-Python hybrid you may end up keeping that). Once you could do

    void main() 
    {
        int x = 0; 
        int y; 
        y = 5; 
        x + y;
    }
    

    You can start adding complexity: arbitrary function definitions and calls, more operators, return values, arrays, data structures, const, pointers, ... building towards the simplest of the example programs step by step.

    The advantage of starting with the C subset is you have lots of C compilers you can look at for ideas so you get going e.g. TinyCC so by the time you get to the difficulties of adding python-esque pieces you've got a solid base.

    This is skating over a lot of details on a long road. Good luck.

    0 讨论(0)
  • 2021-01-13 16:37

    Most people user specialized parser- and lexer-generating tools like ANTLR or Yacc/Bison with Lex.

    0 讨论(0)
提交回复
热议问题