【发布时间】:2018-03-13 07:46:09
【问题描述】:
我正在制作一个简单的计算器,可以打印后缀来学习野牛。我可以使后缀部分工作,但现在我需要对变量 (a-z) tex: a=3+2; 进行分配应该打印:a32+=;例如。我正在尝试修改我的工作后缀代码,以便也能够读取字符。 如果我理解正确,为了能够在 $$ 中放置不同的类型,我需要一个联合并制作节点,我应该使用结构,因为在我的情况下,'expr' 可以是 int 或 char。 这是我的解析器:
%code requires{
struct nPtr{
char *val;
int num;
};
}
%union {
int iValue;
char sIndex;
struct nPtr *e;
};
%token PLUS MINUS STAR LPAREN RPAREN NEWLINE DIV ID NUMBER POW EQL
%type <iValue> NUMBER
%type <sIndex> ID
%type <e> expr line
%left PLUS MINUS
%left STAR DIV
%left POW
%left EQL
%%
line : /* empty */
|line expr NEWLINE { printf("=\n%d\n", $2.num); }
expr : LPAREN expr RPAREN { $$.num = $2.num; }
| expr PLUS expr { $$.num = $1.num + $3.num; printf("+"); }
| expr MINUS expr { $$.num = $1.num - $3.num; printf("-"); }
| expr STAR expr { $$.num = $1.num * $3.num; printf("*"); }
| expr DIV expr { $$.num = $1.num / $3.num; printf("/");}
| expr POW expr { $$.num = pow($1.num, $3.num); printf("**");}
| NUMBER { $$.num = $1.num; printf("%d", yylval); }
| ID EQL expr { printf("%c", yylval); }
;
%%
我在 lex 中有这个来处理“=”和变量
"=" { return EQL; }
[a-z] { yylval.sIndex = strdup(yytext); return ID; }
我得到错误 警告键入的非终结符为空规则且无操作 我在这里找到的唯一答案是: Bison warning: Empty rule for typed nonterminal 它说只需删除 /* 空 */ 部分:
line: /* empty */
| line expr NEWLINE { printf("=\n%d\n", $2.num); }
当我这样做时,我会收到 3 个新警告:
warning 3 nonterminal useless in grammar
warning 10 rules useless in grammar
fatal error: start symbol line does not derive any sentence
例如,我用谷歌搜索并找到了一些解决方案,但这些解决方案却给我带来了其他问题。 当我改变时:
line:line expr NEWLINE { printf("=\n%d\n", $2.num); }
到
line:expr NEWLINE { printf("=\n%d\n", $2.num); }
bison 可以工作,但是当我尝试在 Visual Studio 中运行代码时出现很多错误,例如:
left of '.e' must have struct/union type
'pow': too few arguments for call
'=': cannot convert from 'int' to 'YYSTYPE'
就我所知。我找不到与我的需求相似的简单示例。我只是想让'expr'能够读取一个字符并打印它。如果有人可以检查我的代码并推荐一些更改。真的很感激。
【问题讨论】: