本文介绍了Bison/Flex 解析问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 bison 和 flex,目前遇到了一些问题.当前读取第一个字符并将其传递给 Bison,但立即抛出 yyerror().它应该打印 1,因为 'w' 是由我的 Flex 规则定义的 Ident.

I am working with bison and flex and am currently have some issues. Currently the first character is read and passed to Bison, but immediately yyerror() is thrown. It should print 1 as 'w' is an Ident defined by my Flex rules.

我无法确定问题的根源.我没有使用 Bison 的经验.

I cannot identify the source of the issue. I am inexperienced using Bison.

这是我的野牛解析规则:

Here are my bison parsing rules:

    %%

   Prog : StmtSeq               {printf("13");};
   StmtSeq : Stmt StmtSeq           {printf("12");};
   StmtSeq :                        {printf("11");};
   Stmt : Id ':' Expr       {printf("10");};
   Expr : Expr '+' Term     {printf("9");};
   Expr : Term                  {printf("8");};
   Term : Term '*' Factor   {printf("7");};
   Term : Factor                {printf("6");};
   Factor   : '(' Expr ')'          {printf("5");};
   Factor   : '{' Expr '}'          {printf("4");};
   Factor   : Id                    {printf("3");};
   Factor   : SetLit                {printf("2");};
   Id       : Ident                 {printf("1");};

   %%

这是我的 flex 语法:

Here is my flex grammar:

    {letter} {return Ident;}
    (\{\})|(\{{letter}(\,{letter})*\}) {return SetLit;}
    \( {return '(';}
    \) {return ')';}
    \* {return '*';}
    \+ {return '+';}
    \{ {return '{';}
    \} {return '}';}
    \: {return ':';}
    [ ]             {return;}
    \t              {return;}
    \r              {return;}
    \n              {return;}
    . {writeIndicator(getCurrentColumnNum()); writeMessage("Illegal Character in lex"); }

输入是一个 .txt 文件,其中包含:

The input is a .txt file that contains:

  w: {f,x,a,b,c,d,e}
  x: {f,a,b,c,d,e}
  y: {}
  z: {x}
  a: {f,x,a,b,c,d,e}
  b: {}

推荐答案

如果你想让 lex 忽略一个记号,匹配那个记号的模式应该什么都不做.return 什么都不做;它导致 yylex 返回.此外,这是未定义的行为,因为您没有指定 yylex 应该 return 的值.(使用 -Wall 编译可能会发现这个问题.)

If you want lex to ignore a token, the pattern which matches that token should do nothing. return does not do nothing; it causes yylex to return. Furthermore, it is undefined behaviour because you haven't specified the value yylex should return. (Compiling with -Wall might have caught this problem.)

因此,当扫描器读取一个空格时,它会向调用者返回一些未指定的值 (yyparse).当然,这不会按预期工作.

So when the scanner reads a space, it returns some unspecified value to the caller (yyparse). Naturally, this doesn't work as expected.

改变(例如)

[ ]             {return;}

[ ]             ;

或者,更好的是,用

[[:space:]]+    ;

这篇关于Bison/Flex 解析问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 20:11