【问题标题】:A parser program for the following grammar以下语法的解析器程序
【发布时间】:2015-01-21 06:41:50
【问题描述】:

编写一个使用以下产生式和动作的解析器(Yacc 和 Lex 文件):

S -> cSS    {print “x”}  
S -> a  {print “y”}  
S -> b  {print “z”}  

表示当输入为cacba时将打印的字符串。

我收到这个错误:当我给它输入时,它说输入有效并且还说语法错误。

我的扫描仪代码是这个

%{
   #include "prac.h"
%}
%%

[c] {return C; }
[a] {return A; }
[b] {return B;  }
[ \t]   ;
\n  { return 0; }
.   { return yytext[0]; }
%%

int yywrap(void) {
    return 1;
}

我的 yacc 代码是这样的:

%{
   #include <stdio.h>
%}
%token A B C
%%
statement: S    {printf("Valid Input"); }
;
S: C S S        {printf("Print x\n");} 
| A     {printf("Print y\n");} 
| B     {printf("Print z\n");} 
;
%%
int main()
{
    return yyparse();
}

yyerror(char *s)
{
    printf("\n%s\n",s);
    printf("Invalid Input");
    fprintf(stderr,"At line %d %s ",s,yylineno);
}

我该如何解决这个问题?

【问题讨论】:

  • 你给它什么输入?
  • 最好的猜测——你在 Windows 上运行,所以你在导致错误的换行符之前得到一个 \r(回车)字符。尝试将 \r 添加到 [ \t] 模式以忽略它。
  • 我删除了我的答案,因为它似乎不适合你。仍然将您的 fprintf() 语句更改为 fprintf(stderr, "At line %d %s", yylineno, s); 并不是说​​它会解决您的问题。
  • @rici 我给它输入 cacba 但它说 syantax 错误
  • @UsamaLucky - 我可以向您发送对我有用的完整代码,遗憾的是,有些人很快就拒绝了 =( 是的,您可以按照我在 lex 中展示的方式使用正则表达式,但是有些人....

标签: regex compiler-construction yacc lex


【解决方案1】:

(Comments converted to an answer)

@ChrisDodd 写道:

最好的猜测——你在 Windows 上运行,所以你在导致错误的换行符之前得到一个 \r(回车)字符。尝试将\r 添加到[ \t] 模式以忽略它。

@Cyclone 写道:

将您的 fprintf() 语句更改为 fprintf(stderr, "At line %d %s", yylineno, s); 并不是说​​它会解决您的问题。

OP 写道:

您的意思是我应该将 \r 添加到 \t 中,这样新的正则表达式将是 [\r\t] 对吗?

@rici 写道:

@chris 建议[ \r\t]。如果你在循环中的某个地方有 Windows,我同意。

【讨论】:

    猜你喜欢
    • 2015-06-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多