c++ - Bison C++ - 减法

标签 c++ bison

我正在使用 lex 和 bison 进行简单的计算。它应该做的是解析每个提到的减法 - 1 - -11- 11--1,最多的是什么重要:1-1。前三种情况有效,但在最后一种情况下,它看起来好像将句子分成数字 1-1 ,它们之间没有符号,这就是为什么有一个错误。 我阅读了有关优先级以及如何使用它的内容,但没有任何效果。

下面是我的缩短代码,准备复制:

.l文件

%{
#include "y.tab.h"

void yyerror (const char* s);
int yylex();
%}

%%
[-+*/%\^()\n] { return yytext[0]; }
[0] {yylval = 0; return number;}
[-]?[1-9][0-9]* {yylval = atoi(yytext); return number;}
%%

int yywrap(void) {return 1;}
void yyerror (const char* s) {;}

.y文件

%{
#include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>
#include <cmath>

void yyerror (const char*);
int yylex();
%}

%token number


%right NEG
%left '-'

%%
program: 
       | line program
       ;

line: '\n'
    | expression '\n' { std::cout << "Score: " << $1 << "\n";   }
    ;

expression: number { ; }
          | expression '-' expression { $$ = $1-$3; }
          | '-' expression %prec NEG { $$ = -$2; }
          ;
%% 

int main (void) {
    return yyparse();
}

输入输出:

1- - 1
  Score: 2
1--1
Score: 2
1-1
<here is an error>

最佳答案

您的优先级注释没有为您改变任何内容,因为 '-' expression 规则实际上并未在 1-1 中使用。该输入的问题是解析器只能看到两个整数标记,您在解析器中所做的任何事情都无法改变这一点。

相反,您需要让词法分析器为该输入生成三个标记,而不是两个。您只需从 number 标记的规则中删除 [-]? 即可。通过该更改,1-1 将被标记为 number, '-', number 并且您的解析器将工作。

请注意,这仍将允许负数,因为您的 '-' 表达式 规则会处理它 - 它不会将负数视为单个标记,这很好。

关于c++ - Bison C++ - 减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53307097/

相关文章:

c++ - 在不同的编译单元中使用不同的编译标志编译相同的 header

C++ 模板性能包含模型和内联模型

c++ - 是否可以使用带有 bison/yacc 的逆波兰符号为一种语言生成解析器?

c++ - 为什么循环是无限的?

c++ - Linux C++ 如何打开一个程序

bison - 使用 Bison 的 C++ GLR 解析器

c++ - Bison :轮类减少冲突

c++ - 使用机器学习自动更正自定义句子的应用程序 : how to begin?

c++ - 具有组件性能的 Entity Framework 实体

c - undefined reference 'yylex' bison 错误