ANTLR 对等号的容忍度太高
ANTLR is too tolerant for the equals sign
我有一个非常基本的 ANTLR 配置来解析表达式。它可以解析像 12 + myVariable.myAttribute == myResult(myParameter)
这样的东西。但是,当涉及到运算符处的 =
符号时,它似乎有点过于宽容。例如,即使我没有指定 +=
运算符,它也不会在写入 1 += 2
时发现任何错误。 1 !== 2
或 1 and= 2
也是如此。就好像第一个 =
会使运算符在一个原本有效的运算符被完全忽略之后无效。我做错了什么?
我的配置(complete repository on Github):
grammar MyGrammar;
/*
* Parser rules
*/
expression: operation ( ( operator operation)*) EOF;
operation: operationWithBrackets | operationWithoutBrackets;
operationWithBrackets:
'(' operation (( operator operation)*) ')';
operationWithoutBrackets: primitive ( ( operator operation)*);
primitive: string | bool | number | nil | variable;
string: SINGLE_STRING | DOUBLE_STRING;
nil: NIL;
bool: BOOLEAN;
param: operation;
variable:
variablePart (
(
( '.' variablePart)
| ( '[' bracketOperation ']')
| ( callStart ( param ( ( ',' param)*))? callEnd)
)*
);
callStart: '(';
callEnd: ')';
variablePart: VARIABLE_PART;
bracketOperation: operation;
number: NUMBER;
operator: OPERATOR;
/*
* Lexer rules
*/
OPERATOR:
'+'
| '-'
| '/'
| '*'
| '=='
| '!='
| '<='
| '>='
| '<'
| '>'
| 'and'
| 'or'
| 'then'
| 'else';
SINGLE_STRING: '\'' ~('\'')* '\'';
DOUBLE_STRING: '"' ~('"')* '"';
NUMBER: '-'? [0-9]+ ('.' [0-9]+)?;
WHITE_SPACE: [ \t\r\n]+ -> skip;
IF: 'if' -> skip;
BOOLEAN: 'true' | 'false';
NIL: 'null';
VARIABLE_DOT_SEPARATOR: '.';
VARIABLE_PART: ([a-zA-Z0-9] | '\.' | '-' | '_')+;
正如@sepp2k 在上面的评论中指出的那样,这是一个无法正确识别的词法分析器错误。
我有一个非常基本的 ANTLR 配置来解析表达式。它可以解析像 12 + myVariable.myAttribute == myResult(myParameter)
这样的东西。但是,当涉及到运算符处的 =
符号时,它似乎有点过于宽容。例如,即使我没有指定 +=
运算符,它也不会在写入 1 += 2
时发现任何错误。 1 !== 2
或 1 and= 2
也是如此。就好像第一个 =
会使运算符在一个原本有效的运算符被完全忽略之后无效。我做错了什么?
我的配置(complete repository on Github):
grammar MyGrammar;
/*
* Parser rules
*/
expression: operation ( ( operator operation)*) EOF;
operation: operationWithBrackets | operationWithoutBrackets;
operationWithBrackets:
'(' operation (( operator operation)*) ')';
operationWithoutBrackets: primitive ( ( operator operation)*);
primitive: string | bool | number | nil | variable;
string: SINGLE_STRING | DOUBLE_STRING;
nil: NIL;
bool: BOOLEAN;
param: operation;
variable:
variablePart (
(
( '.' variablePart)
| ( '[' bracketOperation ']')
| ( callStart ( param ( ( ',' param)*))? callEnd)
)*
);
callStart: '(';
callEnd: ')';
variablePart: VARIABLE_PART;
bracketOperation: operation;
number: NUMBER;
operator: OPERATOR;
/*
* Lexer rules
*/
OPERATOR:
'+'
| '-'
| '/'
| '*'
| '=='
| '!='
| '<='
| '>='
| '<'
| '>'
| 'and'
| 'or'
| 'then'
| 'else';
SINGLE_STRING: '\'' ~('\'')* '\'';
DOUBLE_STRING: '"' ~('"')* '"';
NUMBER: '-'? [0-9]+ ('.' [0-9]+)?;
WHITE_SPACE: [ \t\r\n]+ -> skip;
IF: 'if' -> skip;
BOOLEAN: 'true' | 'false';
NIL: 'null';
VARIABLE_DOT_SEPARATOR: '.';
VARIABLE_PART: ([a-zA-Z0-9] | '\.' | '-' | '_')+;
正如@sepp2k 在上面的评论中指出的那样,这是一个无法正确识别的词法分析器错误。