首页 > 解决方案 > YACC时表达式&&表达式错误!无法先读取第一个表达式

问题描述

我正在写一个解析器,我做了一些错误信息来检查。
但是当我进入像
while ( index<=n && index > 0 ) 这样的循环时...
我的语法很好。
但是运行这行代码的过程,根据我的跟踪,
它首先跟踪表达式:index>0,然后跟踪表达式&&表达式,
最后一个将是第一个表达式(索引<=n)。但为什么?
先检查 index <=n,然后检查 index >0,最后一个将是表达式 && 表达式是不是正确的?

只有一种情况,会好的。
例如: while (index<=n) do
但是如果是组合条件,就会出错。

这是我的部分代码

    expr: expr LE expr
          {<br/>
           Trace("expression <= expression");
           if ($1->type != $3->type) yyerror("type not match"); 
           if ($1->type != intType && $1->type != realType) yyerror("operator error"); 
           idInfo *info = new idInfo();
           info->attribute = 2; //variable type
           info->type = boolType;
           $$ = info;
          }<br/>
         |expr AND expr
         {
          Trace("expression && expression");
          if ($1->type != $3->type) yyerror("type not match"); 
          if ($1->type != boolType) yyerror("operator error"); 
          idInfo *info = new idInfo();
          info->attribute = 2; //variable type
          info->type = boolType;
          $$ = info;
         }
        |expr GG expr
        {<br/>
         Trace("expression > expression");
         if ($1->type != $3->type) yyerror("type not match"); 
         if ($1->type != intType && $1->type != realType) yyerror("operator error"); 
         idInfo *info = new idInfo();
         info->attribute = 2; //variable type
         info->type = boolType;
         $$ = info;
        }

这些是根据我的跟踪的结果....
while
'('
ID:index
<=
ID:n
&&
ID:index
'>'
INTEGER:0
')'

行:16 表达式 > 表达式
行:16 表达式 && 表达式
行:16 类型不匹配
行:16 运算符错误
行:16 表达式 <= 表达式
行:16 类型不匹配

标签: compiler-constructionexpressionyacclex

解决方案


您的优先声明不正确或缺失。

如果没有实际看到它们,很难提供更多信息,但看起来您的所有运算符都具有相同的优先级和右关联性。

如果您收到有关解析冲突的警告,那么如果您提到这个事实(如果您解决了这个问题会更好)。

使用 Bison 的内置跟踪工具几乎总是比尝试自己做要好。Bison的功能更全面,更准确,工作量也少很多。请参阅 Bison 手册中的调试解析器部分。


推荐阅读