我正在使用Jison开发一种语言,而我遇到的一个问题是操作符优先。我希望比较运算符是第一个要计算的运算符,例如,1 + 2 < 3 - 3 * 4将变成(1+2) < (3 - (3 * 4))。
我现在的规矩是:
expression
: expression OP_COMPARISON expression
{ $$ = { type: "Comparison", operator: $2, args: [$1, $3], location: locationFromObject(@$) } }
| literal
{ $$ = $literal; }
| NAME
{ $$ = { type: "Variable", variable: $1, location: locationFromObject(@$) }; }
| field
{ $$ = { type: "Field", field: $field, location: locationFromObject(@$) }; }
| '(' ':' typename ')' expression
{ $$ = { type: "Cast", cast_type: $typename, expression: $expression, location: locationFromObject(@$) }; }
| function_call
{ $$ = $function_call; $$.type = "FunctionCall"; }
| method_call
{ $$ = $method_call; $$.type = "FunctionCall"; }
| '(' expression ')'
{ $$ = { type: "Grouped", expression: $expression, location: locationFromObject(@$) }; }
| OP_PREPOSTFIX expression
{ $$ = { type: "Prefix", operator: $1, arg: $expression, location: locationFromObject(@$) }; }
| expression OP_PREPOSTFIX
{ $$ = { type: "Postfix", operator: $2, arg: $expression, location: locationFromObject(@$) }; }
| expression OP_ARITHMETIC expression
{
if($1.type == "Arithmetic"){
$$ = $1;
$$.args.push($3);
$$.operators.push($2);
$$.location = locationFromObject(@$);
}else{
$$ = { type: "Arithmetic", operators: [$2], args: [$1, $3], location: locationFromObject(@$) };
}
}
| expression OP_LOGICAL expression
{
if($1.type == "Logical"){
$$ = $1;
$$.args.push($3);
$$.operators.push($2);
$$.location = locationFromObject(@$);
}else{
$$ = { type: "Logical", operators: [$2], args: [$1, $3], location: locationFromObject(@$) };
}
}
| '!' expression
{ $$ = {type: "LogicalNot", arg: $expression, location: locationFromObject(@$) }; }
;任何帮助都将受到极大的感谢
发布于 2014-12-27 22:36:21
使运算符优先进入上下文无关文法的最佳方法是使用指示优先级级别的几个规则。例如,使用简单的算术:
expression : expression PLUS term
| expression MINUS term
| term
;
term : term MULTIPLY factor
| term DIVIDE factor
| factor
;
factor : IDENTIFIER
| CONSTANT
| LEFT expression RIGHT
;利用该层次结构实现了BODMAS算法规则。
您可以使用语法做类似的事情:分解成几个表示不同优先级层的规则。
(有关更多细节,请参见编写计算机科学文本的标准编译器)
https://stackoverflow.com/questions/27493202
复制相似问题