yacc - 使用带括号的括号 - 减少/移位

时间:2017-07-10 15:55:29

标签: yacc parentheses

我试图使用括号'()'在yacc语法定义中。

这条线运作良好:

x == 1 && y == 0

但是这行不能被解析:

(x == 1) && (y == 0)

当我编译时,我有1个冲突并且在解析时出错:

冲突:1班/减少

语法错误(105; 264)之前&&

这是我使用的语法的一部分。

%type <node> full_expression signed_expression boolean_term boolean_expression expression term factor
%type <nodeList> dst_list dst
%nonassoc EQ NEQ GE GT LE LT
%left '=' '(' ')' '+' '-' '*' '/' OR AND
%right '?' ':' 

boolean_expression:
boolean_term
  { $$ = $1;}
| '(' boolean_term ')'
  { $$ = $2;}
;

boolean_term:
expression EQ expression
   { $$ = buildAndPrintBinaryOperator ($1, $3, "EqualityComparator"); }
| boolean_term AND boolean_term
   { $$ = buildAndPrintLogicalOperator ($1, $3, "And");}
| boolean_term OR boolean_term
   { $$ = buildAndPrintLogicalOperator ($1, $3, "Or");};

expression:
term
| signed_expression '+' term
  { $$ = buildAndPrintBinaryOperator ($1, $3, "Adder");}
| signed_expression '-' term
  { $$ = buildAndPrintBinaryOperator ($1, $3, "Subtractor");};

term:
factor
| term '*' factor
   { $$ = buildAndPrintBinaryOperator ($1, $3, "Multiplier"); }
| term '/' factor
   { $$ = buildAndPrintBinaryOperator ($1, $3, "Divider");};

factor:
INT
{
  $$ = (node*) malloc (sizeof (node));
  $$->isNumber = 1;
  $$->ref.value = $1;
}
| DOUBLE
{
  $$ = (node*) malloc (sizeof (node));
  $$->isNumber = 1;
  $$->ref.value = $1;
}
;

问题似乎出在&#39;(&#39; boolean_term&#39;)&#39; 行。然后解析器到达此行:解析错误。

我不明白我应该怎样做才能消除心机并解决我的问题。它似乎适用于其他例子吗?

任何想法?

问候

2 个答案:

答案 0 :(得分:1)

嗯,语法错误是因为您缺少解析带括号的表达式的规则。您可能想要添加:

factor: '(' expression ')'

为此。目前尚不清楚转移/减少冲突的来源,因为您发布的代码中没有。尝试查看从yacc -v获得的y.output文件 - 这将告诉您涉及哪个州,并查看相关州将告诉您涉及哪些规则。

答案 1 :(得分:0)

我终于找到了我的错误。这是语法本身。 在 AND OR

的情况下,我将 boolean_term 替换为 boolean_expression
boolean_expression:
boolean_term
  { $$ = $1;}
| '(' boolean_term ')'
  { $$ = $2;}
;

boolean_term:
expression EQ expression
   { $$ = buildAndPrintBinaryOperator ($1, $3, "EqualityComparator"); }
| boolean_expression AND boolean_expression
   { $$ = buildAndPrintLogicalOperator ($1, $3, "And");}
| boolean_expression OR boolean_expression
   { $$ = buildAndPrintLogicalOperator ($1, $3, "Or");};