[antlr-interest] Optional rules when duplicating nodes in AST construction

Andrew House ahouse at eecg.toronto.edu
Wed Oct 17 17:23:08 PDT 2012


In my language application, you can declare constants and variables in 
similar but distinct manners.

const name1 is int := 56;
var name2 is int;

Variables can be optionally initialized the same way as constants.

var name3 is int := 6;

As a convenience, I'd like to be able to declare and initialize multiple 
variables of the same type in a single line, as follows.

const N, NTEST is int := 100000, 22;
var test1, test2 is int := 13, 16;

Or even, where the implication is that test5 is uninitialized, with 
unequal-length identifier and value lists:

var test3, test4, test5 is int := 12, 34;

This seems to work as expected for constants, but for variables it 
replicates the first value in the expression list.

My grammar rules are as follows:

constantDeclaration
     :    'const' ID (',' ID)* 'is' dataType ':=' expr (',' expr)* ';'
       -> ^('const' ^(NAME ID) ^(VARTYPE dataType) ^(VALUE expr))+
     ;

varDeclaration
     :    'var' ID (',' ID)* 'is' dataType (':=' expr (',' expr)*)? ';'
         -> ^('var' ^(NAME ID) ^(VARTYPE dataType) ^(VALUE expr)?)+
     ;

For the constant declaration input "const N, NTEST is int := 100000, 
22;" we get the following in the AST, which is what I wanted:
(const (NAME N) (VARTYPE (SCALAR (NAME (TYPEID int)))) (VALUE (EXPR 
100000))) (const (NAME NTEST) (VARTYPE (SCALAR (NAME (TYPEID int)))) 
(VALUE (EXPR 22)))

For the variable declaration input "var test1, test2 is int := 13, 16;" 
we get the following AST, where the 13 is duplicated:
(var (NAME test1) (VARTYPE (SCALAR (NAME (TYPEID int)))) (VALUE (EXPR 
13))) (var (NAME test2) (VARTYPE (SCALAR (NAME (TYPEID int)))) (VALUE 
(EXPR 13)))

A similar result occurs for the case where one variable is left 
uninitialized:
(var (NAME test3) (VARTYPE (SCALAR (NAME (TYPEID int)))) (VALUE (EXPR 
12))) (var (NAME test4) (VARTYPE (SCALAR (NAME (TYPEID int)))) (VALUE 
(EXPR 12))) (var (NAME test5) (VARTYPE (SCALAR (NAME (TYPEID int)))) 
(VALUE (EXPR 12)))

Obviously, the difference between the two grammar rules is that the 
value expression for variables is optional.  Is this repetition 
behaviour an artifact of how ANTLR duplicates optional rules (eg. the 
modifier example on page 167 of the Definitive ANTLR Reference) or is 
there some way to do what I want that is non-obvious?

Thanks in advance for any help anyone can provide.

-- Andrew House


More information about the antlr-interest mailing list