views:

360

answers:

3

I have an ANTLR grammar and am defining a function in my language that allows an optional parameter. How can I check whether the optional parameter is passed in or not within the code generation block?

I'm basically looking for the syntax to do something like this hypothetical tree grammar statement:

myFunc returns [int retval] : 'myFunc' arg1=number arg2=string?
{
    // Check if arg2 exists.
    if (/* arg2 exists */) { $retval = $arg1.value + 10; }
    else { $retval = $arg1.value; }
}

Any suggestions or pointers to documentation are greatly appreciated!

+3  A: 

You should be able to just check if arg2 != null.

Scott Stanchfield
A: 

Scott's answer works like a charm!

Turns out the way to reference ANTLR defined variables in an if statement is without the dollar sign ($), whereas the rest of the time the $ is required.

Also, to check whether a more complex structure than a simple string is present, use

if (arg2.tree != NULL)
Han
A: 

If you want this to be more general then instead of hard coding one optional parameter you can have your code parse multiple elements like so:

myFunc returns [int retval] 
: 'myFunc' funcArgs
{
   // Here you can run through the funcArg Tree and do what
   // ever you'd like here.
}

protected
funcArgs
: arg (COMMA arg)*
chollida