简体   繁体   中英

Antlr4 Is there a way to walk on a node with a listener

I am working with antlr4 to parse some inner language. The way I do it is the standard way of creating a stream of tokens, then creating a parse tree with set tokens. And the last step is creating a tree. Now that I have a tree I can use the walk command to walk over it. The walk command and the parse tree being created are an extension of the BaseListener class. For my project I use many lookaheads, I mostly use the visitors as a sort of look ahead. A visitor function can be applied on a node from the parser tree. (Assuming you implement a visitor class) I have tried creating a smaller listener class to act as my look ahead on a specific node. However, I'm not managing to figure out if this is even possible. Or is there another / better / smarter way to create a look ahead?

To make the question seem shorter: Can a listener class be used on a node in the antlr4 parser tree-like visitor can?

There's no real reason to do anything fancy with a listener here. To handle your example of resolving the type of an expression, this can be done in a couple of steps. You'll need a listener that builds a symbol table (presumably a scoped symbol table so that each scope in your parse tree has a symbol table and references to “parent” scopes it might search to resolve the data types of any variables.). Depending upon your needs, you can build these scoped symbol tables in your listener, pushing and popping them on a stack as you enter/exit scopes, or you may do this is a separate listener attaching a reference to scope nodes to your parse tree. This symbol table will be required for type resolution, so if you can reference variables in your source prior to encountering the declaration, you'd need too pass your tree with a listener building and retaining the symbol table structure.

With the symbol table structure available to your listener for resolving expression types. If you always use the exit* method overrides then all of the data types for any sub-expressions will have already been resolved. With all of the sub-expression types, you can infer the type of the expression you're about to “exit”. Evaluating the type of child expressions should cover all of the “lookahead” you need to resolve an expression's type.

There's really nothing about this approach that rules out a visitor either, it would just be up to you to visit each child, determining it's type, and then, at the end of the listener, resolve the expression type from the types of it's children.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM