YACC当表达式&&表达式错误!无法先读取第一个表达式

时间:2019-05-28 14:57:28

标签: compiler-construction expression yacc lex

我正在编写一个解析器,并且执行一些错误消息来检查。
但是当我进入
而(index <= n && index> 0)做...
我的语法很好。
但是根据我的跟踪,运行此行代码的过程,
它先跟踪表达式:index> 0,然后跟踪表达式&&表达式,
最后一个将是第一个表达式(index <= n)。但是为什么呢?
首先检查索引<= n,然后检查索引> 0,是否正确,最后一个是表达式&& expression?

在一种情况下就可以了。
例如: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;
        }

这些是我追踪的结果。...
    而
    '('
    ID:索引
    <=
    ID:n
    &&
    ID:索引
    '>'
    整数:0
    ')'

第16行:表达式> expression
行:16个表达式&&表达式
行:16个类型不匹配
行:16个操作员错误
行:16个表达式<=表达式
行:16个类型不匹配

1 个答案:

答案 0 :(得分:0)

您的precedence declarations不正确或丢失。

实际上看不到它们,因此很难提供更多信息,但是看起来您所有的运算符都具有相同的优先级和正确的关联性。

如果您收到有关解析冲突的警告,那么如果您提到该事实,那将很有用(甚至更好地解决了该问题)。

使用Bison的内置跟踪工具总是比尝试自己做要好。 Bison的功能更全面,更准确,并且工作量更少。请参阅Bison手册中的Debugging your Parser部分。

相关问题