首页 > 解决方案 > flex bison:创建多个字符变量

问题描述

我想创建一种由多个字符变量组成的编程语言(例如 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", $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: %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 种单字符变量。如何创建多个字符变量而且我还想检查它是否已经声明?

标签: bisonflex-lexer

解决方案


这与野牛或弹性几乎没有关系。事实上,您的 flex 模式已经识别多字符标识符(只要它们是纯字母的),但该操作会忽略第一个之后的字符。

您需要的是某种关联容器,例如哈希表,您可以将其用作符号表而不是向量sym

Bison 手册包括一些小的示例计算器程序。例如,参见 mfcalc,它包括一个符号表,实现为一个简单的线性关联列表。


推荐阅读