flex bison:创建多字符变量
flex bison : creating multiple character variable
我想创建一种包含多个字符变量(例如 abc=10、num=120)的编程语言。我能够创建单字符变量。 .y 代码是:
%{
#include <stdio.h>
//char sym[1000];
//int x=0;
int sym[26];
%}
%token NUMBER ADD SUB MUL DIV ABS EOL ID ASS
%%
calclist :
| calclist exp EOL { printf("= %d\n", ); }
| ID ASS exp EOL { sym[] = ;
}
;
exp: factor { $$=; }
| exp ADD factor { $$ = + ; }
| exp SUB factor { $$ = - ; }
;
factor : term { $$=; }
| factor MUL term { $$ = * ; }
| factor DIV term { $$ = / ; }
;
term : NUMBER { $$=; }
;
%%
int main(int argc, char **argv)
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}
.l 代码是:
%{
# include "P3.tab.h"
#include <stdio.h>
#include <stdlib.h>
extern int yylval;
//int m=0;
%}
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"=" { return ASS; }
[a-z]+ { yylval= *yytext - 'a' ;
return ID ; }
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. { printf("Mystery character %c\n", *yytext); }
%%
int yywrap()
{
return 1;
}
因此,使用这段代码,我只能创建 a=10,x=90 种单字符变量。如何创建多字符变量并且我还想检查它是否已经声明?
这与 bison 或 flex 关系不大。事实上,您的 flex 模式已经可以识别多字符标识符(只要它们是纯字母),但是该操作会忽略第一个字符之后的字符。
您需要的是某种关联容器,例如散列 table,您可以将其用作符号 table 而不是向量 sym
.
Bison 手册包括许多小型计算器程序示例。参见,例如,mfcalc,其中包含一个实现为简单线性关联列表的符号 table。
我想创建一种包含多个字符变量(例如 abc=10、num=120)的编程语言。我能够创建单字符变量。 .y 代码是:
%{
#include <stdio.h>
//char sym[1000];
//int x=0;
int sym[26];
%}
%token NUMBER ADD SUB MUL DIV ABS EOL ID ASS
%%
calclist :
| calclist exp EOL { printf("= %d\n", ); }
| ID ASS exp EOL { sym[] = ;
}
;
exp: factor { $$=; }
| exp ADD factor { $$ = + ; }
| exp SUB factor { $$ = - ; }
;
factor : term { $$=; }
| factor MUL term { $$ = * ; }
| factor DIV term { $$ = / ; }
;
term : NUMBER { $$=; }
;
%%
int main(int argc, char **argv)
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}
.l 代码是:
%{
# include "P3.tab.h"
#include <stdio.h>
#include <stdlib.h>
extern int yylval;
//int m=0;
%}
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"=" { return ASS; }
[a-z]+ { yylval= *yytext - 'a' ;
return ID ; }
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. { printf("Mystery character %c\n", *yytext); }
%%
int yywrap()
{
return 1;
}
因此,使用这段代码,我只能创建 a=10,x=90 种单字符变量。如何创建多字符变量并且我还想检查它是否已经声明?
这与 bison 或 flex 关系不大。事实上,您的 flex 模式已经可以识别多字符标识符(只要它们是纯字母),但是该操作会忽略第一个字符之后的字符。
您需要的是某种关联容器,例如散列 table,您可以将其用作符号 table 而不是向量 sym
.
Bison 手册包括许多小型计算器程序示例。参见,例如,mfcalc,其中包含一个实现为简单线性关联列表的符号 table。