开发者

Antlr3 AST creation : how to test an optional subrule?

开发者 https://www.devze.com 2023-03-06 14:04 出处:网络
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]:

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 b开发者_StackOverflow社区e 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消