Template Function sg::dispatch(RoseVisitor&&, SgNode *)

Template Function sg::dispatch(RoseVisitor&&, SgNode *)#

Function Documentation#

template<class RoseVisitor>
inline std::remove_const<typenamestd::remove_reference<RoseVisitor>::type>::type sg::dispatch(RoseVisitor &&rv, SgNode *n)#

uncovers the type of SgNode and passes it to an function “handle” in RoseVisitor. which should be overloaded with every possible target node. After the traversal, RoseVisitor should contain the intended return data.

The following code has two classes.

  • Counter counts the number of all expression and statement nodes. It implements handlers for SgNode (not interesting nodes), for SgExpression and SgStatement (to count the nodes).

  • Traversal inherits from ASTTraversal and contains a counter. The dispatch function is invoked using a Counter object and a pointer to an AST node. Since the counter object is passed by value we need to store back the result (similar to std::for_each).

    struct Counter
    {
       size_t expr;
       size_t decl;
    
       Counter() : expr(0), decl(0) {}
    
       void handle(const SgNode&) {}
       void handle(const SgExpression&) { ++expr; }
       void handle(const SgStatement&)  { ++stmt; }
    };
    
    struct Traversal : ASTTraversal
    {
      Counter ctr;
    
      void visit(SgNode* n)
      {
        ctr = sg::dispatch(ctr, n);
      }
    
      void run(SgNode& root)
      {
        traverse(&root, preorder);
    
        std::cout << "Expr/Stmt ratio = " << ratio(ctr.expr, ctr.stmt) << std::endl;
      }
    
      static
      float ratio(float a, float b) { return a/b; }
    };
    

Template Parameters:

RoseVisitor. – The visitor that will be called back with the recovered type information. It must implement “handle.” The handle function with the most suitable SgNode type will get invoked.

Parameters:
  • rv – an instance of a rose visitor; ie any class with a “handle” function. Note: rv is essentially passed by value (similar to STL’s for_each).

  • n – The root of the tree to visit. SgNode

Returns:

a copy of the RoseVisitor object, that will contain the intended return data.