Han
Han

Reputation: 5652

ANTLR: Grammar Test for Optional Parameter (using ? operator)

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!

Upvotes: 1

Views: 2151

Answers (3)

chollida
chollida

Reputation: 7894

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)*

Upvotes: 0

Han
Han

Reputation: 5652

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)

Upvotes: 0

Scott Stanchfield
Scott Stanchfield

Reputation: 30652

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

Upvotes: 3

Related Questions