Representing an Abstract Syntax Tree in C

三世轮回 提交于 2019-12-02 20:07:50

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.

Guy Coder

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!