1

I'm trying to use a custom visitor class for a simple expression grammar.

// .h

class MyVisitor: public MyParserBaseVisitor {...}

// .cpp

Any MyVisitor::visitExpr(MyParser::ExprContext *ctx) {
    auto result = visitChildren(ctx);
    std::cout<< result.as<int>() << std::endl;
    return result;
}

Any MyVisitor::visitInteger(MyParser::IntegerContext *ctx) {
    return atoi(ctx->start->getText().c_str());
}

result.as() throws a bad_cast exception and result.isNull() always return true. What am I doing wrong here?

Also, can I use anltrcpp::Any to return a pointer to a custom class object or does it only work with primitive types?

daycoder
  • 21
  • 3
  • Check the exact type returned by `atoi`. Also step into the `as()` function to see what exactly is compared. – Mike Lischke Mar 15 '18 at 08:46
  • `atoi` is returning an `int`. I can't step into the `as()` function as I'm currently depending on the shared libs (`antlr4-runtime.so`). Is there a working example using visitors that I can refer to- just so we know that the visitor framework is working correctly? – daycoder Mar 21 '18 at 17:18
  • I'm not aware of any public source yet. But there will soon be something you can look at. Only a few weeks away (it's part of a product release). Btw, the Any class is header only, so it should always be possible to step through that code. – Mike Lischke Mar 21 '18 at 18:23
  • I stepped into `as()`. It is comparing `int` to a `nullptr`. `visitChildren()` is returning a `nullptr` wrapped in `Any`. Is this a bug and should it be reported? – daycoder Apr 05 '18 at 17:00
  • See where the nullptr comes from. I think it's the default value and shows probably up because your visitor hasn't overridden all necessary methods. – Mike Lischke Apr 05 '18 at 17:53
  • You're right. It's reaching the last token which is EOF and that calls visitTerminal() which returns a nullptr. What's the right way to skip EOF? Which method should be overridden in the visitor? – daycoder Nov 02 '18 at 20:16
  • I fixed it in the meantime by calling `visit(MyParser::NumberContext*)` instead of `visitChildren()` so that it exlcudes visiting EOF. – daycoder Nov 05 '18 at 16:49
  • @daycoder Feel free to add a [self-answer](https://stackoverflow.com/help/self-answer). I think it's pretty common to find that `visitChildren` is returning from a different function than you thought it was based on a misread of the grammar. Having a full answer up front can probably help others better than something at the tail of the comment chain here. – ggorlen Feb 26 '20 at 15:12

0 Answers0