简体   繁体   English

BYACCJ:如何在错误消息中包含行号?

[英]BYACCJ: How do I include line number in my error message?

This is my current error handling function:这是我当前的错误处理 function:

public void yyerror(String error) {
    System.err.println("Error: "+ error);
}

This is the default error function I found on the BYACC/J homepage .这是我在 BYACC/J主页上找到的默认错误 function。 I can't find any way to add the line number.我找不到任何方法来添加行号。 My question is similar to this question .我的问题类似于这个问题 But the solution to it doesn't work here.但它的解决方案在这里不起作用。

For my lexer I am using a JFlex file.对于我的词法分析器,我使用的是 JFlex 文件。

It's not that different from the bison/flex solution proposed in the question you link.这与您链接的问题中提出的 bison/flex 解决方案没有什么不同。 At least, the principle is the same.至少,原理是一样的。 Only the details differ.只有细节不同。

The key fact is that it is the scanner, not the parser, which needs to count lines, because it is the scanner which converts the input text into tokens.关键事实是扫描器而不是解析器需要计算行数,因为扫描器将输入文本转换为标记。 The parser knows nothing about the original text;解析器对原始文本一无所知; it just receives a sequence of nicely-processed tokens.它只是接收一系列处理良好的令牌。

So we have to scour the documentation for JFlex to figure out how to get it to track line numbers, and then we find the following in the section on options and declarations:所以我们必须搜索 JFlex 的文档来弄清楚如何让它跟踪行号,然后我们在选项和声明部分找到以下内容:

  • %line

    Turns line counting on.打开行计数。 The int member variable yyline contains the number of lines (starting with 0) from the beginning of input to the beginning of the current token. int 成员变量yyline包含从输入开头到当前标记开头的行数(从 0 开始)。

The JFlex manual doesn't mention that yyline is a private member variable, so in order to get at it from the parser you need to add something like the following to your JFlex file: JFlex 手册没有提到yyline是一个私有成员变量,因此为了从解析器中获取它,您需要在 JFlex 文件中添加如下内容:

%line
{
    public int GetLine() { return yyline + 1; }
    // ...

}

You can then add a call to GetLine in the error function:然后您可以在错误 function 中添加对GetLine的调用:

public void yyerror (String error) {
  System.err.println ("Error at line " + lexer.GetLine() + ": " + error);
}

That will sometimes produce confusing error messages, because by the time yyerror is called, the parser has already requested the lookahead token, which may be on the line following the error or even separated from the error by several lines of comments.这有时会产生令人困惑的错误消息,因为在调用yyerror时,解析器已经请求了前瞻标记,该标记可能位于错误之后的行上,甚至与错误相隔几行注释。 (This problem often shows up when the error is a missing statement terminator.) But it's a good start. (当错误是缺少语句终止符时,通常会出现此问题。)但这是一个好的开始。

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

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