c++ - How can I print whatever I see in Yacc/Bison? -
i have complicated yacc file bunch of rules, of them complicated, example:
start: program program: extern_list class class: t_class t_id t_lcb field_dec_list method_dec_list t_rcb the exact rules , actions take on them not important, because want seems simple: print out program appears in source file, using rules define other purposes. i'm surprised @ how difficult doing is.
first tried adding printf("%s%s", $1, $2) second rule above. produced "��@p�@". understand, parsed text available variable, yytext. added printf("%s", yytext) every rule in file , added extern char* yytext; top of file. produced (null){void)1133331122222210101010--552222202020202222;;;;||||&&&&;;;;;;;;;;}}}}}}}} valid file according language's syntax. finally, changed extern char* yytext; extern char yytext[], thinking not make difference. difference in output made best shown screenshot
i using bison 3.0.2 on xubuntu 14.04.
if want echo source output while parsing it, easiest in lexer. don't ware using lexer, mention yytext, used lex/flex, assume that.
when use flex recognize tokens, variable yytext refers internal buffer flex uses recognize tokens. within action of token, can used text of token, temporarily -- once action completes , next token read, no longer valid.
so if have flex rule like:
[a-za-z_][a-za-z_0-9]* { yylval.str = yytext, return t_id; } that won't work @ all, you'll have dangling pointers running around in program; source of random-looking outputs you're seeing. instead need make copy. if want output input unchanged, can here too:
[a-za-z_][a-za-z_0-9]* { yylval.str = strdup(yytext); echo; return t_id; } this uses flex macro echo equivalent fputs(yytext, yyout) -- copying input file * called yyout (which defaults stdout)
Comments
Post a Comment