问题
I have tried a lot of solutions given online. One of the solutions i have tried is from this link: Flex yylineno set to 1
But none of them seem to work for my code of producing a symbol table.
The yylineno
value doesn't change. It keeps on showing 1
The input I provided in the input file was:
main()
while
varrrr
if
This is my code snippet:
%%
{pound}{includekey}{openarrow}{alpha}+{closearrow}
{printf("\n %s : Preprocessor Directive at line no: %d!", yytext, yylineno); newfunction(yytext,"Preprocessor",yyleng);}
{mainkey}{openpara}{closepara} {printf("\n %s : Main function found at line no: %d! ", yytext, yylineno); newfunction(yytext,"main",yyleng);}
{alpha}[{underkey}|{alpha}|{digit}]+{openpara}{closepara} {printf("\n %s : Userdefined function without parameters found at line no: %d!", yytext, yylineno);newfunction(yytext, "function",yyleng);}
{conditional} {printf("\n %s : If statement encountered at line no: %d!", yytext, yylineno);newfunction(yytext,"if", yyleng);}
{control} {printf("\n %s : Control statement encountered at line no: %d!", yytext, yylineno);newfunction(yytext,"control", yyleng);}
{datatypes} {printf("\n %s : Datatype found at line no: %d!", yytext, yylineno);newfunction(yytext, "datatype", yyleng);}
{alpha}* {printf("\n %s : Variable found at line no: %d!", yytext, yylineno);newfunction(yytext, "variable", yyleng);}
{operators} {printf("\n Operator %s found at line no: %d!", yytext, yylineno );}
\n { }
. {printf("\n Unexpected character!");}
%%
Also, I am talking in terms of lex, not yacc. Although similar, I have tried yylineno has always the same value in yacc file but the solution didn't work for me!
回答1:
Other questions indicate that Flex has the ability to manage yylineno
automatically via the %option yylineno
directive. That is, however, an extension in Flex compared with classic Lex.
Assuming that you cannot upgrade to Flex, you probably need to replace your rule
\n { }
with
\n { yylineno++; }
As an aside, printing works best with newlines at the end of the format string. The buffered output is normally flushed when the newline is 'printed' — so the output won't necessarily appear until you print the newline after it. Plan to write newlines at the end of the format string unless you have an incomplete line. Newlines at the beginning are only needed when you need to double-space the output (or you are concerned that someone else has been sloppy about ending the output with a newline).
来源:https://stackoverflow.com/questions/31524630/lex-yylineno-returning-1