我想创建一种由多个字符变量组成的编程语言(例如abc=10,num=120(。我能够创建单字符变量。y.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("= %dn", $2); }
| ID ASS exp EOL { sym[$1] = $3;
}
;
exp: factor { $$=$1; }
| exp ADD factor { $$ = $1 + $3; }
| exp SUB factor { $$ = $1 - $3; }
;
factor : term { $$=$1; }
| factor MUL term { $$ = $1 * $3; }
| factor DIV term { $$ = $1 / $3; }
;
term : NUMBER { $$=$1; }
;
%%
int main(int argc, char **argv)
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %sn", 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 %cn", *yytext); }
%%
int yywrap()
{
return 1;
}
因此,使用这段代码,我只能创建一个=10,x=90的单字符变量。我如何创建多字符变量?我还想检查它是否已经声明?
这与bison或flex几乎没有关系。事实上,您的flex模式已经识别多字符标识符(只要它们是纯字母的(,但该操作会忽略第一个字符之后的字符。
您需要的是某种关联容器,如哈希表,可以将其用作符号表,而不是向量sym
。
Bison手册包括一些小的计算器程序示例。例如,请参阅mfcalc,其中包括一个实现为简单线性关联列表的符号表。