开发者

yacc: can't get yytext value from lex to yacc

开发者 https://www.devze.com 2023-02-02 05:32 出处:网络
Lex file: {Id}{yylval.strVal=yytext; cout<<yytext<<endl; return Id;} Yacc file: %union{ int iVal;

Lex file:

{Id}    {yylval.strVal=yytext; cout<<yytext<<endl; return Id;}

Yacc file:

%union{
int iVal;  
float fVal;  
char * strVal;
}; 

%token NS  
%token  <开发者_StackOverflowstrVal>Id  
program : NS Id {cout<<$2;}

The Lex prints but the Yacc doesn't !!

ideas ppl ^_^


'yytext' is a static buffer that contains the current token. You are then passing a pointer into that buffer (as yylval) to the parser. This has the rather severe problem that if there are more tokens in your input, these later tokens may overwrite the same yytext buffer pointed at by an earlier token, so you will probably start seeing random garbage if you make your parser more complex. The trivial example here doesn't show this problem, as it doesn't try to read another token after seeing the 'Id' token.


To make the output appear in the Lex file, you'd add << endl between yytext and its following semi-colon. Otherwise, the output is buffered until a newline appears or the file is closed at the end of the program.

Your Lex code assigns to yylval.strVal, but your Yacc grammar doesn't define strVal as part of your %union. If the code is compiling, this indicates a disconnect somewhere in your use of headers. Your Lex code should be using the header generated by Yacc (yacc -d).


With the disconnect between the union resolved, and the confirmation that adding << endl to the Lex code showed that output, did you also think of adding << endl to the Yacc code? If not, do so! If you did, edit the code in the question to accurately reflect what you've got; we can't read your screen from this side of the Internet.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号