Traversing tree in Python

60 views
Skip to first unread message

Daniel

unread,
Jul 2, 2015, 7:47:22 AM7/2/15
to antlr-di...@googlegroups.com
Hi,

I'm using Antlr with Python3. I've following code so far:

def main(argv):
    input = FileStream(argv[1])
    lexer = ConnectivesLexer(input)
    stream = CommonTokenStream(lexer)
    parser = ConnectivesParser(stream)
    tree = parser.prog()

Could you point me the way how to traverse the tree to evaluate something? Maybe is there some tutorial or documentation?

Thanks.

Jonathan Coveney

unread,
Jul 2, 2015, 10:12:44 AM7/2/15
to antlr-di...@googlegroups.com
I'm not sure what you mean? generally the way it works is that your parser does the work necessary to either generate a data structure for further processing, or it does the evaluation itself. basically parser.prog() should be doing the work.

--
You received this message because you are subscribed to the Google Groups "antlr-discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to antlr-discussi...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Terence Parr

unread,
Jul 2, 2015, 12:01:53 PM7/2/15
to antlr-di...@googlegroups.com
I think you want to use a listener or visitor generated by antlr tool :)
Ter

Daniel

unread,
Jul 3, 2015, 4:07:45 AM7/3/15
to antlr-di...@googlegroups.com
Yes, I know that I should use listener or visitor generated by antlr tool.

I want to use visitor pattern, but I don't know how to use it exactly.

I asked for pointing a way (or maybe some tutorial) how to use visitor pattern in Python.

To learn the tool I've very simple grammar now:

grammar Gram;
prog: (expr NEWLINE)* ;
expr: left=expr op=('*'|'/') right=expr
    | left=expr ('+'|'-') right=expr
    | atom=INT
    | '(' expr ')'
    ;
NEWLINE : [\r\n]+ ;
INT     : [0-9]+ ;

And the visitor generated looks like:

class GramVisitor(ParseTreeVisitor):

    def visitProg(self, ctx):
        return self.visitChildren(ctx)

    def visitExpr(self, ctx):
        return self.visitChildren(ctx)

Could you explain me what should I do further on this simple example?
Reply all
Reply to author
Forward
0 new messages