bison - 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 种单字符变量。如何创建多个字符变量而且我还想检查它是否已经声明?
解决方案
这与野牛或弹性几乎没有关系。事实上,您的 flex 模式已经识别多字符标识符(只要它们是纯字母的),但该操作会忽略第一个之后的字符。
您需要的是某种关联容器,例如哈希表,您可以将其用作符号表而不是向量sym
。
Bison 手册包括一些小的示例计算器程序。例如,参见 mfcalc,它包括一个符号表,实现为一个简单的线性关联列表。
推荐阅读
- r - 通过灵活的调用将具有不同宽度的数据从宽转向长(在循环中使用)
- python - 如何检查python环境是否稳定一致
- azure - 我们可以在不使用 Azure Active Directory 的情况下在 Azure 中配置 SSO(单点登录)吗?
- java - 尝试在开源 Conversations 应用程序上使用 gradle 运行 SonarScanner
- arrays - 在以下情况下,对数组进行排序所需的最小操作数是多少:-
- ruby-on-rails - 如何根据参数连接不同的表
- android - android简单的JSON有效负载到websocket
- angular - 输入'{文本:字符串;}' 不可分配给类型“TitleObject”。在高图表中
- javascript - MOUSEOVER:如何启动一个函数并让它一直播放到最后而不一遍又一遍地启动它?
- php - 使用 WriteHTML 函数时的 mPDF 分页问题