2
votes

In the ANTLRv4 grammar that one can find in the grammars-v4 repository (https://github.com/antlr/grammars-v4/blob/master/antlr4/ANTLRv4Parser.g4) the optional rule ebnfSuffix is:

  • sometimes matched using ebnfSuffix?, see lexerElement
  • sometimes matched using (ebnfSuffix | ), see element.

I was indeed asking to myself, and here as well, if the two have slightly different meaning.

The grammars-v4 repository has another example in https://github.com/antlr/grammars-v4/blob/master/cql3/CqlParser.g4 of the same two patterns with respect to beginBatch rule used has optional element or together with an empty alternative.

EDIT: I've added here the part of the grammar I'm referring to as suggested:

lexerElement
   : labeledLexerElement ebnfSuffix?   <-- case 1: optional rule
   | lexerAtom ebnfSuffix?
   | lexerBlock ebnfSuffix?
   | actionBlock QUESTION?
   ;

element
   : labeledElement (ebnfSuffix |)   <-- case 2: block with empty alternative
   | atom (ebnfSuffix |)
   | ebnf
   | actionBlock QUESTION?
   ;
1
Read the body of the question please, in the title I've put just an example with the element "abc". In particular I refer to 2 grammars from the grammars-v4 repository as real examples.mar9000
Interesting, so what's the difference between "ebnfSuffix?" and "(ebnfSuffix | )"?mar9000
Ok, I will post part of the gramar.mar9000
Ah, ok I see what you mean. I thought abc? was a regex, but you mean a rule. Right, got it.Bart Kiers

1 Answers

1
votes

Both ebnfSuffix? and (ebnfSuffix | ) result in exactly the same behaviour: they (greedily) optionally match ebnfSuffix.

The fact that they're both being used in a grammar could be because it was translated from some spec (or other grammar) that used that notation and that notation didn't have the ? operator, but that's just guessing.

Personally I'd just use ebnfSuffix?.