Syntax analyser to show success using flex and bison

我只是一个虾纸丫 提交于 2020-01-16 02:52:51

问题


I am trying to make a syntax analyzer that will recognize a valid statement and will print success upon doing so. However, after making the lex and yacc files, I keep getting errors in my yacc file which says:

In function 'yyparse'fofo.y: In function 'yyparse':
fofo.y:13:5: error: stray '\223' 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 '\224' in program

Here's my yacc file contents:

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

回答1:


The errors come from having some non ASCII characters in the text (which probably come from pasting text from a Word file), on line 13, as the error message indicated:

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

Note the quotation characters are different to the line above, and should be edited to be:

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

I also added some white space around your tokens. For example, on these lines:

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

which I changed to:

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

I also note you are calling the C function 'exit' but have not declared it properly. You need the following line in your header:

#include <stdlib.h>

It then seemed to build OK for me.



来源:https://stackoverflow.com/questions/33593974/syntax-analyser-to-show-success-using-flex-and-bison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!