ANTLR 4 and AST visitors

前端 未结 2 1930
情话喂你
情话喂你 2021-02-08 06:38

I\'m trying to use ASTs with ANTLR4, with this files:

Builder.java

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
         


        
2条回答
  •  遥遥无期
    2021-02-08 07:31

    First I'll explain what you have observed above:

    First and foremost, please read the documentation for the methods you call. The Parser.addParseListener documentation includes the following note:

    THIS IS ONLY FOR ADVANCED USERS. Please give your ParseTreeListener to a ParseTreeWalker instead of giving it to the parser!!!!

    The implementation of toString() for the ParserRuleContext class simply prints the rule invocation stack at the time the context was created. You are printing this once when the listener enters a rule, and once when it exits. For actionexpr, cond, and condexpr you print it again, resulting in a total of 4 identical output lines for each of those contexts.

    Now some notes on your goals:

    • Inside of enterCond and exitCond, the MEASURE text is available by calling ctx.MEASURE().getText().
    • Inside of enterActionexpr and exitActionexpr, the ACTION text is available by calling ctx.ACTION().getText().
    • You can change the COND token by creating a new TerminalNodeImpl and CommonToken for the updated token, and assigning it to the correct index in the field CondContext.children using either a visitor or a listener.

提交回复
热议问题