[antlr-interest] How to integrate a symbol table with StringTemplate

pragmaik contact at maik-schmidt.de
Tue Oct 25 06:58:42 PDT 2011


Hi!

I am writing a small domain specific language that basically is a subset of
the C language. The output of my compiler is C# code that gets translated by
the Microsoft compiler later on.

At the moment I have an architectural problem, that is I do not know how to
integrate the information in my symbol table with the tree grammar that
actually emits the final string template.

To be concrete: whenever a function is called in my language I'd like to
traverse the actual parameters and compare them to the formal parameters
stored in the symbol table. I need this, so I can add some special
conversion functions to the string template.

My tree grammar starts like this:

tree grammar Translator;

options {
    language = CSharp3;
    tokenVocab = MyTokens;
    ASTLabelType = MyAST;
	output = template;
}

public
compilationUnit
    :    (d+=methodDeclaration | d+=variableDeclaration)+ -> file(defs={$d})
    ;

methodDeclaration
    :    ^(METHOD_DECL type IDENTIFIER a+=formalParameter* block) ->
method(name={$IDENTIFIER.text}, retType={$type.st}, args={$a},
block={$block.st})
    ;

formalParameter
    :    ^(ARG_DECL type IDENTIFIER) -> arg(name={$IDENTIFIER.text},
type={$type.st})
    ;

variableDeclaration
    :    ^(VAR_DECL type IDENTIFIER expression) ->
decl(name={$IDENTIFIER.text}, type={$type.st}, init={$expression.st})
    ;

block 
    :    ^(BLOCK s+=statement*) -> block(stats={$s})
    ;

statement
    :    block                                                            ->
{$block.st}
	|    variableDeclaration                                              ->
{$variableDeclaration.st}
	|	 ^('=' a=expression b=expression)                                 ->
assign(a={$a.st}, b={$b.st})
	|    ^('return' expression?)                                          ->
return(v={$expression.st})
	|    ^('if' expression b1=block b2=block?)                            ->
if(cond={$expression.st}, block1={$b1.st}, block2={$b2.st})
	|    ^(FOREACH type IDENTIFIER  b=block e1=expression e2=expression?) ->
foreach(type={$type.st}, name={$IDENTIFIER.text}, e={$e1.st}, c={$e2.st},
block={$b.st}, counter={COUNTER++})
	|    ^(EXPR ^(CALL IDENTIFIER ^(ELIST p+=expr*)))                     ->
callstat(name={$IDENTIFIER.text}, args={$p})
	;

...

The last rule matches function calls and delegates all the work to
StringTemplate. How could I intercept here and use the information stored in
the symbol table. I already have a Translator constructor that expects a
SymbolTable instance and stores it in a private member named _symbolTable.

Cheers,
Maik


--
View this message in context: http://antlr.1301665.n2.nabble.com/How-to-integrate-a-symbol-table-with-StringTemplate-tp6928895p6928895.html
Sent from the ANTLR mailing list archive at Nabble.com.


More information about the antlr-interest mailing list