c++parsingantlr4visitor-pattern

How do I visit a constant term in antlr4 with c++?


I have a grammar that at some point has the following rule:

boolConst : 
        'true'
      | 'false';

This leads to the following code (with visitor activated) being generated:

  class  BoolConstContext : public antlr4::ParserRuleContext {
  public:
     BoolConstContext(antlr4::ParserRuleContext *parent, size_t invokingState);
     virtual size_t getRuleIndex() const override;
     antlr4::tree::TerminalNode *TRUE();
     antlr4::tree::TerminalNode *FALSE();

     virtual std::any accept(antlr4::tree::ParseTreeVisitor *visitor) override;

  };

If I understand this correctly I cannot use the visitor to decent into the tree further, or at least I cannot find a visitTRUE or visitFALSE function in the BaseVisitor class.

Now when implementing a visitor based on the BaseVisitor I have to implement the function virtual std::any visitBoolConst(BoolConstContext *ctx) override.

However, I now need to know which of the two were parsed, whether it was FALSE, or TRUE So I am wondering if doing something like the following is correct and what should be done.

    if (ctx->FALSE() != nullptr) {
        // false was parsed
    } else if (ctx->TRUE() != nullptr) {
        // true was parsed
    } else {
        throw std::exception();
    }

Solution

  • If you were to use named alternatives:

    boolConst : 
            'true' # boolConstTrue
          | 'false' # boolConstFalse;
    

    ANTLR will generate different Context classes for each alternative (BoolConstTrueContext and BoolConstFalseContext). Then the value would be implicit in the type.