Cant understand this round bracket meaning. Its not necessary to write it, but sometimes it can produce left-recursion error. Where should we use it in grammar rules?
Asked
Active
Viewed 126 times
0
-
1It's called a ["grouping"](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form#Table_of_symbols). When you write a sequence of symbols enclosed in parentheses ("round brackets"), the sequence is treated as a single group that occurs before or after other symbols for a rule. For example "S : a (b | c)* d;" can denote the language { ad, abd, acd, abbd, accd, abcd, acbd, etc. }. You can always write an equivalent BNF grammar for an EBNF grammar, and would do so if you have problems with Antlr4 accepting your grammar--which is not often. – kaby76 Mar 03 '21 at 23:12
1 Answers
0
Its not necessary to write it,
That is correct, it is not necessary. Just remove them.
but sometimes it can produce left-recursion error.
If that really is the case, you can open an issue here: https://github.com/antlr/antlr4/issues
EDIT
Seeing kaby76's comment, just to make sure: you cannot just remove them from a grammar file regardless. They can be removed from your example rule.
When used like this:
rule
: ID '=' ( NUMBER | STRING ) // match either `ID '=' NUMBER`
// or `ID '=' STRING`
;
they cannot be removed because removing them wold result in:
rule
: ID '=' NUMBER | STRING // match either `ID '=' NUMBER`
// or `STRING`
;
Or with repetition:
rule
: ( ID STRING )+ // match: `ID STRING ID STRING ID STRING ...`
;
and this:
rule
: ID STRING+ // match: `ID STRING STRING STRING ...`
;

Bart Kiers
- 166,582
- 36
- 299
- 288