Representing an Abstract Syntax Tree in C

后端 未结 2 593
梦毁少年i
梦毁少年i 2021-02-01 15:13

I\'m implementing a compiler for a simple toy language in C. I have a working scanner and parser, and a reasonable background on the conceptual function/construction of an AST.

相关标签:
2条回答
  • 2021-02-01 15:55

    You can make any of these work.

    I prefer the union layout, because then all nodes have "the same" layout.

    [You may find it useful to have a "child sublist" option, e.g., and arbitarily big, dynamic array of children, instead of having left- or right-leaning lists.]

    You are going to find that this issue isn't the one that makes building your compiler hard. Rather, it is having symbol tables, performing various kinds of analyses, choosing a machine-level IR, building a code generator, and doing code optimizations. Then you're going to encounter real users and you'll discover what you really did wrong :-}

    I'd pick one and run with it, so that you have a chance to get near the other issues.

    0 讨论(0)
  • 2021-02-01 15:58

    Ira Baxter gave you a good simple and forward looking answer, especially of note is the problems one will encounter down the road, so I will focus on this question:

    Is there a better fourth option I haven't come across yet?

    You are using the imperative language to write a compiler and having problems designing the data structure for the concept of a node in the AST. In the world of functional languages such as ML, OCaml, Haskell, F# one would use a Tagged union to hold all of the different node types in one data structure, which is basically what you have created.

    I don't expect that the OP will switch to a functional language for this problem, but if others regularly deal with trees then they might find it of value to learn a functional language and use it for problems related to trees.

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