On Apr 13, 12:46 pm, HD <[email protected]> wrote:
> where FUNCTION, ID,LPAREN,RPAREN,LBRACE,RBRACE are tokens/terminals,
> args, statements are non-terminals. These non-terminals must be
> Children, but how is the Leaf defined?
I'm not sure what the author of the Node class intended but the name
"leaf" seems a bit misleading. In my own Node class I just have a
generically named "value" attribute.
In the binop example leaf is being used to store the operator, since
merely knowing that the node is a "binop" wouldn't be enough. Your
function example is a similar case, you need to store the function ID
somewhere so it could go in the "leaf."
Also keep in mind that leaf is defined as optional. There will be
cases where you don't need it.
> Another example with only non-terminals:
> foo -> bar1
> bar1 -> bar2
> How would the AST tree be defined for the above two rules?
Don't base the shape of the AST on the grammar. Instead, decide what
the language should look like when represented as a tree, and work
toward that. (Though often that kind of production just returns the
right hand side unmodified, i.e. "p[0] = p[1]" in PLY).
>
> And finally - Can anyone give me an example of tree traversing the
> final AST?
Here's a completely untested method that will print all children of a
node, depth first:
def printrec(self):
for child in self.children:
self.printrec(child)
print self.type, self.leaf
Of course you can replace print with something more useful :)
Tree data structures are fairly simple to understand. If you're not
very familiar with them already it would pay to google for some
tutorials.
Pedro
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"ply-hack" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/ply-hack?hl=en
-~----------~----~----~----~------~----~------~--~---