c - 我在第二次输入语言时收到错误

标签 c bison yacc flex-lexer lex

从我的 bison/flex 文件生成的程序对于第一个输入(第一次运行 yyparse())运行良好,但当我尝试第二次运行它时会抛出错误。

例如:

chris@chris-Inspiron-1525:~/4850/hw$ ./calc
HORN 3+4*6-11+33*2 ?
=   82
HORN 1+1 ?
error: syntax error

基本上,命令存在于“HORN”和“?”之间

这是我的 .y 文件:

%{ 
#include <stdlib.h>
#include <stdio.h>
void yyerror(const char *str);


%}

%union 
{
    int ival; 
    float fval;
    char* word;
}
%start line
%type <word> wexp
%type <ival> iexp
%type <fval> fexp

%left PLUS MINUS
%left STAR DIV MOD
%left POW
%token GT
%token LT
%token ASGN
%token LP
%token RP
%token LB
%token RB
%token NOT
%token GTEQ
%token LTEQ
%token EQTO
%token NOTEQ
%token HORN
%token QMARK
%token <word> WORD
%token <fval> FLOAT
%token <ival> INTEGER


%%

line    : HORN wexp QMARK   {   printf("=\t%s\n", $2);  }
        | HORN iexp QMARK   {   printf("=\t%d\n", $2);  }
        | HORN fexp QMARK   {   printf("=\t%f\n", $2);  }
        ;

iexp    : iexp MINUS iexp   { $$ = $1 - $3;             }
        | iexp PLUS iexp    { $$ = $1 + $3;             }
        | iexp STAR iexp    { $$ = $1 * $3;             }
        | iexp DIV iexp     { $$ = $1 / $3;             }
        | INTEGER           { $$ = $1;                  }
        ;

fexp    : FLOAT             { $$ = $1;                  }
        ;

wexp    : WORD              { $$ = $1;                  }
        ;
%%


int main(){
     yyparse();
}

void yyerror(const char *str)
{
        printf("error: %s\n",str);
}

感谢您的任何意见!

最佳答案

你的 yacc 语法只声明一行。当您完成一行后,任何后续输入都是语法错误。

当前允许所需数量的行的方法是添加第一个规则,例如:

lines : line
      | lines line
      ;

假设您正确忽略了 lex 部分中的行尾...

关于c - 我在第二次输入语言时收到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26776230/

相关文章:

c++ - malloc() 和 realloc() 有什么区别?

c++ - Bison %prec 不起作用

c - yyparse 中对 `pow' 的 undefined reference

javascript - 编写野牛语法以识别javascript函数并忽略其他所有内容

c - C 程序中 undefined reference

c - 使用 strtok 函数删除制表符空间

c - 对 avltree_init 的 undefined reference

c - 用户在 flex 中输入后显示消息

c++ - Bison 解析器 : When do I need 'return' and when I don't?

c - Lex Yacc 解析器卡在 EOF