[antlr-interest] Moving from SableCC to ANTLR; What are tree grammars?

Tyler Distad tyler.distad at gmail.com
Sat Apr 3 19:21:48 PDT 2010


My Computer Science professor has taught his Compiler course with SableCC
for years. I am investigating moving the class to ANTLR.

Under SableCC, after creating a valid grammar, we used the Visitor pattern
to perform semantic checking and AT&T assembly generation. To do this, we
created a SemanticChecker class and a CodeGen class, both extending from the
SableCC DepthFirstAdapter class. This allowed for a beautiful separation of
the grammar definition and our processing code. We could also easily make
multiple passes over our AST.

I have hunted high and low for an ANTLR-specific method of doing anything
remotely similar. It has been intimated (
http://antlr.org/article/1100569809276/use.tree.grammars.tml) that tree
grammars should let me do what I want, but I must be misunderstanding
because my implementation is wholly inadequate.

Two questions:

 1) What is the point of a tree grammar? My work so far seems to indicate
that anything I can do in a "tree grammar" (such as actions, rewrites,
etc.), I can just as easily do in a "combined grammar."

 2) Assuming tree grammars are useful, then when working with them, do I
*really* have to copy/paste my rule definitions from my combined grammar?
The simplecTreeParser example in the examples-v3 file on the ANTLR website
certainly looks that way. I want to just be able to reference my tree
somewhere...not redefine the whole thing for every single pass.

Tyler Distad

For reference, below is a snippet of my non-tree-grammar. I do NOT want to
copy/paste this code into a new tree-grammar definition. I want to be able
to easily work with it from outside the AST.

    stmt: stmtAsmt
        | stmtIf
        | stmtWhile
        | expr SEMICOLON_CH -> ^(STMT expr)
    ;

    stmtAsmt
        : ID ASSIGN_OP expr SEMICOLON_CH
        -> ^(STMT ID expr)
        ;

    stmtIf
        : IF_KW L_PAR_CH expr R_PAR_CH L_BRACE_CH stmt* R_BRACE_CH (ELSE_KW
L_BRACE_CH stmt* R_BRACE_CH)?
        -> ^(STMT expr stmt* stmt*)
        ;

    stmtWhile
        : WHILE_KW L_PAR_CH expr R_PAR_CH L_BRACE_CH stmt* R_BRACE_CH
        -> ^(STMT expr stmt*)
        ;


More information about the antlr-interest mailing list