简体   繁体   English

在ANTLR中需要匹配的括号

[英]Requiring matching parentheses in ANTLR

I know that in ANTLR4 I can use ? 我知道在ANTLR4中可以使用吗? for 0 or 1 times. 0或1次。 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) . 解析器将允许诸如'(x' or 'y)'语句,而不是要求(x) Is there a way to require matching parentheses when defining your grammar in ANTLR4 在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规则的一部分来处理:

expression
    : identifier
    | '(' expression ')'
    | // other types of expression
    ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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