yacc/lex的基本问题 [英] Basic problem with yacc/lex

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

问题描述

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

I have some problems with a very simple yacc/lex program. I have maybe forgotten some basic steps (it's been a long time since I've used these tools).

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

In my lex program I give some basic values like :

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):

In my yacc program the beginning of my grammar is (where TranslationUnit is my %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 */

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

When I run my program with input :

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

我不明白这个结果.我前一段时间学习语法,即使我现在不记得所有内容,也看不到任何重要的错误...

I do not understand this result. I have studied grammars some time ago and even if I don't remember everything right now, I do not see any important mistake...

预先感谢您的帮助.

推荐答案

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

The trouble is that unless you save the token, Lex/Yacc goes on to over-write the space, or point to different space, etc. So you need to stash the information that's crucial to you before it gets modified. Your printing in the Lex code should have showed you that the yylval values were accurate at the point when the lexer (lexical analyzer) was called.

另请参见 SO 2696470 ,其中遇到并诊断出相同的基本问题

See also SO 2696470 where the same basic problem was encountered and diagnosed.

这篇关于yacc/lex的基本问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆