Alternative Return Channel (-r option in JTB1.2.2)


Traditionally (without -r option), JTB 1.2.2 generates ObjectDepthFirst.java in such a way that no value will be returned by default.  For example,
//
// Auto class visitors--probably don't need to be overridden.
//
public Object visit(NodeList n, Object argu) {
   Object _ret=null;
   int _count=0;
   for ( Enumeration e = n.elements(); e.hasMoreElements(); ) {
      ((Node)e.nextElement()).accept(this,argu);
      _count++;
   }
   return _ret;
}

......

//
// User-generated visitor methods below
//

......

/**
 * f0 -> term()
 * f1 -> ( ( <PLUS> | <MINUS> ) term() )*
 */
public Object visit(sum n, Object argu) {
   Object _ret=null;
   n.f0.accept(this, argu);
   n.f1.accept(this, argu);
   return _ret;
}

......

With this default visitor, the best way to return a value throughout the traversal of the syntax tree is to use "argu" instead of "_ret".  Since "argu" is an object that will be passed along, it's very convenient to just utilize a field or two in "argu" to communicate between visit() methods.  Look at Expression Translator for a detailed example.



If -r option is used, visit() methods in ObjectDepthFirst.java will look like:
//
// Auto class visitors--probably don't need to be overridden.
//
public Object visit(NodeList n, Object argu) {
   Object _ret=argu;
   int _count=0;
   for ( Enumeration e = n.elements(); e.hasMoreElements(); ) {
      _ret=((Node)e.nextElement()).accept(this,_ret);
      _count++;
   }
   return _ret;
}

......

//
// User-generated visitor methods below
//

......

/**
 * f0 -> term()
 * f1 -> ( ( <PLUS> | <MINUS> ) term() )*
 */
public Object visit(sum n, Object argu) {
   Object _ret=argu;
   _ret=n.f0.accept(this, _ret);
   _ret=n.f1.accept(this, _ret);
   return _ret;
}

......

As the above code shows, whatever a visit() method returns will be passed as an argument to the next recursive call of another visit() method.  Confusing?  Maybe.  But maybe useful sometimes, as well.  Just remember that any returned value will affect all the consequent visit() methods.  Don't screw up and good luck!
 

Maintained by Wanjun Wang, wanjun@purdue.edu. 
Created August 3, 2000.
Last modified August 3, 2000.