parsing - yacc/lex 的基本问题

标签 parsing yacc lexer

我在使用一个非常简单的 yacc/lex 程序时遇到一些问题。我可能忘记了一些基本步骤(我已经很长时间没有使用这些工具了)。

在我的 lex 程序中,我给出了一些基本值,例如:

word    [a-zA-Z][a-zA-Z]*
%%
":"    return(PV);
{word}  { 
            yylval = yytext;
            printf("yylval = %s\n",yylval);
            return(WORD);
       }
"\n"    return(ENDLINE);

在我的 yacc 程序中,我的语法的开头是(其中 TranslationUnit 是我的 %start):

TranslationUnit:
               /* Nothing */
              | InfoBlock Data
              ;

InfoBlock:
           /* Nothing */
         | InfoBlock InfoExpression {}
         ;

InfoExpression:
             WORD PV WORD ENDLINE { printf("$1 = %s\n",$1);
 printf("$2 = %s\n",$2);
 printf("$3 = %s\n",$3);
 printf("$4 = %s\n",$4);
                                  }
            | ... /* other things */
            ;

Data:
    ... /* other things */

当我使用输入运行程序时:

keyword : value

我认为我至少会得到:

$1 = keyword
$2 = keyword // yylval not changed for token PV
$3 = value
$4 = value // yylval not changed for token ENDLINE

实际上我明白:

$1 = keyword : value
$2 = keyword : value
$3 = value
$4 = value

我不明白这个结果。我前段时间学过语法,即使我现在不记得所有内容,我也没有发现任何重要错误......

预先感谢您的帮助。

最佳答案

问题在于,除非您保存 token ,否则 Lex/Yacc 会继续覆盖该空间,或指向不同的空间等。因此,您需要在修改之前存储对您至关重要的信息。您在 Lex 代码中的打印应该表明,在调用词法分析器(词法分析器)时,yylval 值是准确的。

另请参阅SO 2696470遇到并诊断出相同的基本问题。

关于parsing - yacc/lex 的基本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3344267/

相关文章:

javascript - 使用javascript在html中获取子节点和子节点

json - 使用 Json.Net 解析两个语义相同的层次结构文档并失败

c - lextestpass.l :384: error: expected expression before ‘int’

java - 了解 ANTLR4 代币

javascript - 是否总是可以从 AST 转到原始源代码?

android无法解析单个json元素

java - 日期解析魔法

c - Bison 递归在链表中表现异常

grammar - 为什么这个简单的语法会有移位/归约冲突?