简体   繁体   中英

Requiring matching parentheses in ANTLR

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

You can define an alternative with both parentheses and an alternative without any, eg

expression: 
    '(' identifier ')'
    | identifier
;

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
    ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM