How to set a rule option count in ANTLR

徘徊边缘 提交于 2019-12-11 02:19:31

问题


I need help setting the count for an option match in a rule. This rule example will match (rule2) zero or more times.

rule1: 'text' ( '(' rule2 ')' )*

I know +,*,? for counts but what if I want the (rule2) to match 5 times?

Are +,*,? the only count modifier supported for grammar so I need to enforce count in the parser listener?


回答1:


what if I want the (rule2) to match 5 times?

Inside the grammar, there are 2 options:

1.

write it out 5 times:

rule1: 'text' '(' rule2 ')' '(' rule2 ')' '(' rule2 ')' '(' rule2 ')' '(' rule2 ')'

2.

or use a semantic predicate. See paragraph Using Context-Dependent Predicates from the ANTLR4 wiki about predicate

Are +,*,? the only count modifier supported for grammar

Yes, there is no (...){5} syntax to match exactly 5 times.

so I need to enforce count in the parser listener?

That would be the (IMO) best option: in the parser, just match ( '(' rule2 ')' )+, and in a listener/visitor validate after parsing.




回答2:


Yes, you need to specify * or + in the grammar, and then use a listener after the parse is complete to verify that it appeared exactly n times. The alternative is to expand the expression in the grammar, but this can have disastrous consequences on the ability of the grammar to cleanly recover from syntax errors.

// this is allowed, but not recommended as described in the text above
rule1
  : 'text'
    '(' rule2 ')'
    '(' rule2 ')'
    '(' rule2 ')'
    '(' rule2 ')'
    '(' rule2 ')'
  ;


来源:https://stackoverflow.com/questions/25212324/how-to-set-a-rule-option-count-in-antlr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!