0

I am looking for a way to know if an optional sub rule has been used or not. For example:

my_rule returns [node* n = 0]:
  (v = (optional_subrule)?)
  {
    $n = new node($v ? $v.n : MY_DEFAULT_VALUE);
  }
;

But this does not work. I tried many ways to write it and nothing seems to be possible without writing code...

my_rule returns [node* n = new node()]:
  ((optional_subrule { n->set_subrule(...); })?)
;

And when you have a bison background, you like having your ast node constructors at the end of your rules... And it decreases the readability (imagine a much more bigger rule).

Does anyone know something I missed ?

Thank you.

Julio Guerra
  • 5,523
  • 9
  • 51
  • 75

1 Answers1

1

ANTLR does not allow such a feature. The solution proposed by Bart Kiers must not be used since it results in an undefined behavior code.

So I had to rewrite the rules as :

my_rule returns [node* n = 0]
@init
{
  type temporary_variable = init_value;
}:
  (v = optional_subrule { temporary_variable = $v.result; })?
  mandatory_subrule
  {
    $n = new node(temporary_variable, $mandatory_subrule.result);
  }
;

We now have the advantage of a well-initialised variable, and we still have only one node constructor with every arguments needed.

Community
  • 1
  • 1
Julio Guerra
  • 5,523
  • 9
  • 51
  • 75