1

I know that in ANTLR4 I can use ? for 0 or 1 times. But For example for identifiers, the user may or may not use parentheses. But if I do this

'('? identifier ')'?

The parser will allow statements like : '(x' or 'y)' instead of requiring (x). Is there a way to require matching parentheses when defining your grammar in ANTLR4

Michael
  • 41,989
  • 11
  • 82
  • 128
Pape Traore
  • 83
  • 2
  • 9

2 Answers2

1

You can define an alternative with both parentheses and an alternative without any, e.g.

expression: 
    '(' identifier ')'
    | identifier
;
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
1

If you want to allow identifiers either between '(' and ')' or without parentheses, you could simply use two alternatives for that instead of the ? operator:

'(' identifier ')' | identifier

Note that this will only allow one set of parentheses. To allow an arbitrary number, you'd use a recursive rule like this:

identfiierWithParens
    : '(' identifierWithParens ')'
    | identifier
    ;

Since in most languages, arbitrary expressions can be enclosed in parentheses (and identifiers only can when they're used as expressions or other entities that can be parenthesized like this), you'd usually handle this as part of your expression rule instead:

expression
    : identifier
    | '(' expression ')'
    | // other types of expression
    ;
sepp2k
  • 363,768
  • 54
  • 674
  • 675