开发者

Extra right brace in yacc output

My lex file has:

word [^{}"=,\t\n@\\ ]+

\{  {
    return(LBRACE);
}

\}  {
    return(RBRACE);
}

{word}  {
     yylval = yytext; printf("WORD=%s",yytext); return(WORD);
}

My yacc file has:

phrase: LBRACE WORD RBRACE  {printf("LBRACE %s RBRACE\n",$2);};

On inputting:

{FooBar}

I get:

WORD=FooBar
LBRACE FooBar} RBRACE

I'm unsure why I'm getting th开发者_JAVA百科e extra right brace even though I'm printing only $2, which should ideal


Here:

{word}  {
     yylval = yytext; printf("WORD=%s",yytext); return(WORD);
}

The value of yytext is only valid while you are handling this lexeme. Once you move to the next lexeme the content of the bufffer may be overwritten. Thus saving the yytext pointer is not going to do you any good. You need to copy the token out of the buffer.

{word}   {  yylval = (char*)calloc(yylen+1, sizeof(char));
            strncpy(yylval, yytext, yylen); // Remember you need to free this.
            return WORD;
         }


It's up to you to store the value of yytext (via yylval) in the WORD production. It's just a pointer into the working space of lex. You're seeing the working space change after it parses RBRACE. Imagine a yacc rule like LBRACE WORD COMMA WORD LBRACE and what would be going on there.

If you don't want to have a separate production I think you can do LBRACE WORD { code to strdup yylval } RBRACE { ... }

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜