问题
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