Bison 错误输出

标签 bison

我正在使用 Bison 并且生成了一个非常复杂的语法。问题是我的第一个测试用例失败了——但 Bison 只会说“语法错误”。有什么办法可以让Bison输出匹配失败的规则和有问题的token吗?我用了

%define parse.trace true

但仍然只能得到syntax error作为输出。

最佳答案

当出现问题时,没有一个基于 Yacc 的解析器比“语法错误”做得更好;这在很大程度上取决于您的改进。

有几件事你可以很容易地做。

一种是检测您的词法分析器,以便它打印出它找到的标记,并将它们返回给正确的解析器。这会告诉您语法失败的标记,以及预先提供的标记。

另一种是在启用Yacc调试的情况下进行编译,然后将其打开。这需要 -DYYDEBUG=1并设置变量 yydebug到非零值(通常为 1)。第一步将额外信息编译成语法;第二步启用输出。

来自 Bison 2.4.3 手册:

§8.2 Tracing Your Parser

If a Bison grammar compiles properly but doesn’t do what you want when it runs, the yydebug parser-trace feature can help you figure out why.

There are several means to enable compilation of trace facilities:

  • the macro YYDEBUG

    Define the macro YYDEBUG to a nonzero value when you compile the parser. This is compliant with POSIX Yacc. You could use -DYYDEBUG=1 as a compiler option or you could put #define YYDEBUG 1 in the prologue of the grammar file (see Section 3.1.1 [The Prologue], page 47).

  • the option -t, --debug

    Use the -t option when you run Bison (see Chapter 9 [Invoking Bison], page 117). This is POSIX compliant too.

  • the directive %debug

    Add the %debug directive (see Section 3.7.12 [Bison Declaration Summary], page 72). This is a Bison extension, which will prove useful when Bison will output parsers for languages that don’t use a preprocessor. Unless POSIX and Yacc portability matter to you, this is the preferred solution.

We suggest that you always enable the debug option so that debugging is always possible.

The trace facility outputs messages with macro calls of the form YYFPRINTF (stderr, format, args) where format and args are the usual printf format and variadic arguments. If you define YYDEBUG to a nonzero value but do not define YYFPRINTF, <stdio.h> is automatically included and YYFPRINTF is defined to fprintf.

Once you have compiled the program with trace facilities, the way to request a trace is to store a nonzero value in the variable yydebug. You can do this by making the C code do it (in main, perhaps), or you can alter the value with a C debugger.

Each step taken by the parser when yydebug is nonzero produces a line or two of trace information, written on stderr. The trace messages tell you these things:

  • Each time the parser calls yylex, what kind of token was read.
  • Each time a token is shifted, the depth and complete contents of the state stack (see Section 5.5 [Parser States], page 95).
  • Each time a rule is reduced, which rule it is, and the complete contents of the state stack afterward.

关于 Bison 错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6948948/

相关文章:

c++ - 使用 Bison/Antlr/Packrat/Elkhound/编写的 LLVM JIT 解析器

c++ - 当我在 yacc 中引入一个 Action 时 Shift/Reduce 冲突

Bison 转移减少冲突 - 无法解决

c - 从电子邮件地址中检索字符串

g++ - 对 'yylex()' 的 undefined reference

c - 运行时公式评估

c++ - 来自字符串 vector 的 Bison 输入

c++ - Bison 中无用的规则

c++ - Bison 不解析多行?

bison - 警告 Bison 编译