如何读取lex和yacc中的多行输入? [英] How to read multiple lines of input in lex and yacc?
本文介绍了如何读取lex和yacc中的多行输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望输出为:
a=3 mov a,3
a=fs mov b,fs
b=32 mov b,32
3地址中间代码生成程序-为词法分析编写的 lex 文件从命令行读取输入并传递标记:
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;}
%%
对应的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);
}
运行上述代码的输出(在lex和yacc链接之后):
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?
推荐答案
你的语法只读取一行 line
也许你想要:
start : line
| start line
;
这篇关于如何读取lex和yacc中的多行输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文