Hi all,
Me and my partner are now at the translation phase of our school compiler project. That is, we're about to translate the AST given to us by SableCC into a more primitive intermediate representation (IR) that is closer to the target machine language.
In the type-checking phase, we used the technique with a map to store the types of expression nodes, and then did the type-checking in the out*-methods, on our way back up the AST so to speak. E.g. as a simple example, our type-checking for == looks like:
public void outAEqualExpression(final AEqualExpression expression) {
final Type left = types.get(expression.getLeft());
final Type right = types.get(expression.getRight());
final int line = expression.getEqual().getLine();
final int column = expression.getEqual().getPos();
if (!left.isEqualComparableTo(right)) {
error(INVALID_BINARY_OP.on(line, column, "==", left, right));
}
types.put(expression, BuiltInType.Boolean);
}
Where "types" is our Node -> Type map. We have to use this technique since in SableCC we have no control over the generated AST node classes (except indirectly through the grammar of course), and can't make a completely custom visitor that would return a Type. If we could, the above check would be something like:
if (!expression.getLeft().visit().isEqualComparableTo(expression.getRight().visit())) {
...
}
Which is more commonly seen in compilers, AFAICS.
Now, for the AST -> IR translation phase we're kind of in the same boat: We need the translation of subexpressions/statements ready and waiting on our way back up to the tree. So I guess the natural thing is to use the same tecnique: Store the translation in a Node -> IRNode map.
But before we start I thought I'd ask here on the list: Has anyone else been in a similar situation? If so, how did you handle this? Just using the map technique, or did you hack the SableCC code generation so that you could make completely custom visitors (including control of the method return type)?
Wow, mail got longer than I intended, sorry about that :)
Anyway, quite interested in anyone who has experience with SableCC AST -> IR translation.
Best regards,
Elvis Stansvik