【问题标题】:LEX- yylineno returning 1LEX- yylineno 返回 1
【发布时间】:2015-07-20 19:19:24
【问题描述】:

我尝试了很多在线给出的解决方案。我尝试过的解决方案之一来自此链接:Flex yylineno set to 1

但它们似乎都不适用于我生成符号表的代码。 yylineno 值不会改变。一直显示 1

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

main()

while

varrrr

if

这是我的代码 sn-p:

%%

{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 但解决方案对我不起作用!

【问题讨论】:

  • 您有责任在您认为合适的情况下推进线路计数器!
  • @KerrekSB 没有定义任何自动函数来扫描行号并将其返回给我们吗?
  • 您可能需要将\n { } 替换为\n { yylineno++; }。此外,在结尾处使用换行符打印效果最好(缓冲的输出通常在换行符被“打印”时被刷新——所以在你打印换行符之后输出不一定会出现)。
  • @Kay 我说的是 lex。虽然类似,但那里的解决方案对我不起作用
  • @JonathanLeffler 感谢您的建议!它有效。

标签: c lex


【解决方案1】:

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

假设您无法升级到 Flex, 你可能需要替换你的规则

\n { }

\n { yylineno++; }

顺便说一句,使用格式字符串末尾的换行符打印效果最好。当换行符被“打印”时,缓冲的输出通常会被刷新——所以输出不一定会出现,直到你在它之后打印换行符。除非您有不完整的行,否则计划在格式字符串的末尾写换行符。仅当您需要将输出加倍(或者您担心其他人草率地以换行符结束输出时)才需要开头的换行符。

【讨论】:

    猜你喜欢
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 2015-03-04
    • 2013-10-27
    • 2016-07-28
    相关资源
    最近更新 更多