语法分析器显示使用 flex 和 bison 的成功

Syntax analyser to show success using flex and bison

我正在尝试制作一个语法分析器,它将识别有效的语句并在这样做时打印成功。但是,在创建 lex 和 yacc 文件后,我的 yacc 文件中不断出现错误,其中显示:

In function 'yyparse'fofo.y: In function 'yyparse':
fofo.y:13:5: error: stray '3' in program
fofo.y:13:5: error: stray '\' in program
fofo.y:13:16: error: 'n' undeclared (first use in this function)
fofo.y:13:16: note: each undeclared identifier is reported only once for each function it appears in
fofo.y:13:18: error: expected ')' before 'Invalid'
fofo.y:13:18: error: stray '\' in program
fofo.y:13:18: error: stray '4' in program

这是我的 yacc 文件内容:

%{
#include <stdio.h>
%}

%start Stmt_list
%token Id Num Relop Addop Mulop Assignop Not

%%
Stmt_list   : Stmt ';' '\n' {printf ("\n Success. \n"); exit(0);}
        | Stmt_list Stmt ';' '\n'   {printf ("\n Success. \n"); exit(0);}
        | error '\n'    {printf (“\n Invalid. \n”); exit(1);}
        ;

Stmt    : Variable Assignop Expression
    ;

Variable    : Id 
        | Id '['Expression']'
        ;

Expression  : Simple_expression 
        | Simple_expression Relop Simple_expression
        ;

Simple_expression   : Term 
            | Simple_expression Addop Term
            ;

Term    : Factor 
    | Term Mulop Factor
    ;

Factor  : Id 
    | Num 
    | '('Expression')' 
    | Id '['Expression']' 
    | Not Factor
    ;

%%

#include"lex.yy.c"

int main()  
{   
    yyparse();  
    yylex();

}  

yyerror(char *s)  
{  
 printf("\nError\n");  
}  

错误来自第 13 行的文本中的一些非 ASCII 字符(可能来自从 Word 文件粘贴文本),如错误消息所示:

        | error '\n'    {printf (“\n Invalid. \n”); exit(1);}
                                 ^              ^
                                 |              |
                                 `--------------`------------   The error is here!

注意引号字符与上面的行不同,应编辑为:

        | error '\n'    {printf ("\n Invalid. \n"); exit(1);}

我还在你的标记周围添加了一些白色 space。例如,在这些行中:

        | Id '['Expression']'
    | '('Expression')' 
    | Id '['Expression']'

我改成了:

        | Id '[' Expression ']'
    | '(' Expression ')' 
    | Id '[' Expression ']'

我还注意到您正在呼叫 C function 'exit' but have not declared it properly。您的 header 中需要以下行:

#include <stdlib.h>

然后它似乎对我来说还不错。