问题
I want the output as:
a=3 mov a,3
a=fs mov b,fs
b=32 mov b,32
Program for 3 address intermediate code generation - the lex file written for lexical analysis reads the input from command line and passes tokens:
%{
#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;}
%%
The corresponding yacc file:
%{
#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);
}
The output of running the above code (after linking between lex and yacc):
dsa=32
MOV dsa, 32 // 3 address code generated
ds=342 // but does not parse this line why??
syntax error
How do I get the output in the desired format?
回答1:
Your grammar only reads a single line
Maybe you wanted:
start : line
| start line
;
回答2:
Not clear exactly what you want. Do you want a single call of yyparse
to parse multiple lines (everything until you get an EOF)? If so, rici's answer is what you want. Or do you want yyparse
to parse a single line and return, after which you can call it again to parse another line? If that's what you want, you need to have your lexer recognize newlines and return an EOF for them:
[\n] return -1;
However, with your current grammar, this will give you syntax errors for blank lines, which may or may not be what you want.
来源:https://stackoverflow.com/questions/12956358/how-to-read-multiple-lines-of-input-in-lex-and-yacc