Skip to content

sg::dispatch

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.

Synopsis

Declared in <SageIII/sageInterface/sageGeneric.h>

template<class RoseVisitor>
std::remove_const<std::remove_reference<RoseVisitor>::type>::type
dispatch(
    RoseVisitor&& rv,
    SgNode* n);

Description

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; }
};

Return Value

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

Template Parameters

Name

Description

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

Name

Description

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

Created with MrDocs