如何在lex和yacc中读取多行输入?

Anu*_*bha 2 compiler-construction yacc lex

我希望输出为

a=3   mov a,3
a=fs  mov b,fs
b=32  mov b,32
Run Code Online (Sandbox Code Playgroud)

用于生成3地址中间代码的程序:为词法分析编写的lex文件,从命令行读取输入并传递令牌:

%{
#include "y.tab.h"
#include "string.h"
#include <math.h>
%}
%%
[a-zA-Z]+ { yylval.var=(char *)malloc(sizeof(char *));
          strcpy(yylval.var,yytext);
         return ID;}
"="       return EQUALS;
[0-9]+    {yylval.num=atoi(yytext);return DIGIT;}


%%
Run Code Online (Sandbox Code Playgroud)

yacc文件:

%{

#include "stdio.h"

#include "string.h"

int yywrap()
{
return 1;
}
%}


%union
{char *var;
 int num;
}


%token <var> ID 
%token <num> EQUALS DIGIT




%%
start : line 

line : ID EQUALS DIGIT {printf("MOV %s, %d\n",$1, $3);}
     | ID EQUALS ID    {printf("MOV %s, %s\n",$1, $3);}
     ;


%%

main()

{

yyparse();

return 0;

}

int yyerror(char *s)

{
fprintf(stderr,"%s\n",s);

}
Run Code Online (Sandbox Code Playgroud)

现在作为运行上述代码的输出(在lex和yacc之间链接)

dsa=32                
MOV dsa, 32                // 3 address code generated

ds=342                     // but does not parse this line why??
syntax error
Run Code Online (Sandbox Code Playgroud)

ric*_*ici 5

您的语法只读一个 line

也许您想要:

start : line
      | start line
      ;
Run Code Online (Sandbox Code Playgroud)