title: Tree Transformations Using Visitor Pattern
body: <p>(Disclaimer:  these examples are given in the context of building a compiler, but this question is all about the Visitor pattern and does not require any knowledge of compiler theory.)  I'm going through Andrew Appel's Modern Compiler Implementation in Java to try to teach myself compiler theory (so no, this isn't homework) and I'm having trouble understanding how he wants to use the Visitor pattern to transform an AST to an IR tree.  (Note: I'm doing this in Python so I can learn Python also, which is why the upcoming examples are not in Java.)  As I understand it, the visit and accept methods in the Visitor pattern are void-typed by design, so if I have something like</p>
  
  <pre><code>class PlusExp(Exp):
      def __init__(self, exp_left, exp_right):
          self.exp_left = exp_left
          self.exp_right = exp_right
  
      def accept(self, v):
          v.visit_plus_exp(self)
  </code></pre>
  
  <p>then I would like to be able to write a visitor method like</p>
  
  <pre><code>def visit_plus_exp(self, plus_exp):
      return BINOP(BinOp.PLUS, 
                   plus_exp.exp_left.accept(self), 
                   plus_exp.exp_right.accept(self))
  </code></pre>
  
  <p>which would translate the two child expressions into IR and then link them up with the BINOP representing the plus expression.  Of course, this isn't possible unless I modify all the accept functions to return extra info, and that is also messy because sometimes you just want a print visitor that doesn't return anything.  Yet, this text insists that a visitor is the right way to go, and in Java at that, which means it can be done without the flexibility of Python.  I can't think of any solutions that aren't incredibly hacky - can anyone enlighten me as to the intended design?</p>