How exactly is an Abstract Syntax Tree created?

Posted by Howcan on Programmers See other posts from Programmers or by Howcan
Published on 2014-08-22T04:24:25Z Indexed on 2014/08/22 4:27 UTC
Read the original article Hit count: 248

I think I understand the goal of an AST, and I've build a couple of tree structures before, but never an AST. I'm mostly confused because the nodes are text and not number, so I can't think of a nice way to input a token/string as I'm parsing some code.

For example, when I looked at diagrams of AST's, the variable and its value were leaf nodes to an equal sign. This makes perfect sense to me, but how would I go about implementing this? I guess I can do it case by case, so that when I stumble upon an "=" I use that as a node, and add the value parsed before the "=" as the leaf. It just seems wrong, because I'd probably have to make cases for tons and tons of things, depending on the syntax.

And then I came upon another problem, how is the tree traversed? Do I go all the way down the height, and go back up a node when I hit the bottom, and do the same for it's neighbor?

I've seen tons of diagrams on ASTs, but I couldn't find a fairly simple example of one in code, which would probably help.

© Programmers or respective owner

Related posts about data-structures

Related posts about compilers