2015-07-20 99 views
1

我已经尝试了很多网上给出的解决方案。我试过的解决方案之一是从这个链接:Flex yylineno set to 1LEX- yylineno返回1

但他们都没有为我的代码生成符号表的工作。 yylineno值不会更改。它使上显示1

我在输入文件提供的输入是:

main() 

while 

varrrr 

if 

这是我的代码片段:

%% 

{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!");} 


%% 

而且,我说的就lex而言,不是yacc。虽然相似,但我试过yylineno has always the same value in yacc file 但该解决方案对我无效!

+2

当你觉得合适的时候,你的责任是提高线数! –

+0

@KerrekSB没有定义任何自动函数来扫描行号并将其返回给我们? – Rubal

+0

您可能需要将'\ n {}'替换为\ n {yylineno ++; }'。此外,打印效果最好,最后使用换行符(缓冲输出通常在换行符被打印时刷新 - 所以输出不一定会出现,直到您在后面打印新行)。 –

回答

2

其他问题表明Flex有能力通过%option yylineno指令自动管理yylineno。然而,这是Flex与经典Lex相比的一个扩展。

假设你不能升级到Flex中, 你可能需要更换您的规则

\n { } 

\n { yylineno++; } 

顺便说一句,印刷效果最好换行末的格式字符串。当换行符被“打印”时,缓冲输出通常被刷新 - 所以输出不一定会出现,直到你在后面打印新行。计划在格式字符串的末尾写入换行符,除非您有不完整的行。换句话说,只有在需要对输出进行双倍空间处理时才需要换行符(或者您担心其他人对使用换行符结束输出的操作一直很sl))。