简体   繁体   English

Bison:语法错误处理,意外和未定义<token>

[英]Bison: Syntax Error processing, unexpected and undefined<token>

I want to process undefined and unexpected token error in yyerror func (or maybe by another func if it's possible) for example, i get a error message from Bison例如,我想在 yyerror func 中处理未定义和意外的令牌错误(或者如果可能的话,可能由另一个 func 处理),我从 Bison 收到一条错误消息

... 
LAC: checking lookahead EXECSQL: S4
Error: popping nterm component_list ()
Stack now 0
Cleanup: discarding lookahead token $undefined ()
Stack now 0
  ERRSTAT = "%X0000002C"

But I want to print which token hasn't been founded and the line number.但我想打印尚未建立的令牌和行号。 Is it possible to implement it in Bison and how?是否可以在 Bison 中实现它以及如何实现?

The special token $undefined is reported when yylex returns a token number which doesn't appear in any parser rule.yylex返回一个没有出现在任何解析器规则中的标记号时,会报告特殊标记$undefined Most of the time, that's the result of the lexer fallback rule:大多数时候,这是词法分析器回退规则的结果:

.        { return yytext[0]; }

But it can also happen if you declare a token in your parser file, and the lexer returns that token, but the token is never actually used in any rule.但是,如果您在解析器文件中声明一个标记,并且词法分析器返回该标记,但该标记实际上从未在任何规则中使用,也会发生这种情况。

Unused tokens don't have names, in the sense that the array of names which Bison includes in your parser doesn't include unused tokens, and so there's no way to look up what the token name originally was.未使用的标记没有名称,因为 Bison 包含在您的解析器中的名称数组不包含未使用的标记,因此无法查找最初的标记名称。 You can, however, often get the token number from the variable yychar .但是,您通常可以从变量yychar获取令牌编号。 If that number is greater than 0 and less than 256, then the token is probably a single-character token, and you could use that to print an additional error message.如果该数字大于 0 且小于 256,则该标记可能是单字符标记,您可以使用它来打印附加错误消息。 However, there's no simple way to modify the error message generated by Bison's verbose error messages;但是,没有简单的方法可以修改由 Bison 的冗长错误消息生成的错误消息; if you're using that feature, you'll still see the invalid token message.如果您正在使用该功能,您仍会看到无效令牌消息。

In order to print line numbers, you only need to enable line number counting in the lexical scanner, using为了打印行号,你只需要在词法扫描器中启用行号计数,使用

%option yylineno

in your Flex ( .l ) file.在您的 Flex ( .l ) 文件中。 Then you can print the value of yylineno in yyerror .然后你可以在yyerror打印yylineno的值。 (If you're using a "pure" (reentrant) scanner, then yylineno will be in the scanner_t object. In the normal use case where that object is an extra parser argument, it will also be available inside yyerror .) (如果您使用的是“纯”(可重入)扫描仪,则yylineno将位于scanner_t对象中。在该对象是额外解析器参数的正常用例中,它也将在yyerror可用。)

I know that the above is a bit confusing because there are a lot of different code-generation options with slightly different behaviours.我知道上面的内容有点令人困惑,因为有很多不同的代码生成选项,它们的行为略有不同。 You didn't specify the particular options you're using, so the answer is a bit generic.您没有指定正在使用的特定选项,因此答案有点笼统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM