Search code examples
c++antlr

shouldVisitNextChild(node, result) is not called for the child but the parent in visitChildren(ParseTree*) of class AbstractParseTreeVisitor


In AbstractParseTreeVisitor.h I was struggeling over shouldVisitNextChild(node, result)) in the following part (lines 35-48):

virtual std::any visitChildren(ParseTree *node) override {
   std::any result = defaultResult();
   size_t n = node->children.size();
   for (size_t i = 0; i < n; i++) {
     if (!shouldVisitNextChild(node, result)) {
       break;
     }

     std::any childResult = node->children[i]->accept(this);
     result = aggregateResult(std::move(result), std::move(childResult));
   }

   return result;
 }

Although this function is called in the loop over the children, it tests always the parent. The only validation the function can do is check the result. Is this its intension?

I would have expected

  if (!shouldVisitNextChild(node->children[i], result)) {
    break;
  }

This would allow to see the focussed node.


Solution

  • The code is fine :)

    The shouldVisitNextChild first param is the parent node where the child nodes are stored, the secound parameter is result, where the fuction is tracking the current state.

    And you can override this funtion. The default implementation always returns true, indicating that visitChildren should only return after all children are visited. One reason to override this method is to provide a "short circuit" evaluation option for situations where the result of visiting a single child has the potential to determine the result of the visit operation as a whole.

    see more information: https://www.antlr.org/api/Java/org/antlr/v4/runtime/tree/AbstractParseTreeVisitor.html#shouldVisitNextChild(org.antlr.v4.runtime.tree.RuleNode,T)