Antlr4,如何报告特定的语法错误 [英] Antlr4, How to report specific syntax error

查看:31
本文介绍了Antlr4,如何报告特定的语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 antlr4 为我的简单语法编写一些错误检查.

I am trying to use antlr4 to write some error checking for my simple grammar.

语法本身是由函数构造的.

The grammar itself is constructed by functions.

FUNCTION hello (n){
    ......
}
FUNCTION main (n) {
    ......
}

我不确定它是如何捕捉特定错误的,例如缺少函数名称缺少主函数

I am not sure how it suppose to catch specific errors such as missing function name, or missing main function

这是我的 ErrorListener 的样子

Here is what my ErrorListener looks like

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;

public class SimpleErrorListener extends BaseErrorListener {
    @Override
    public void syntaxError(Recognizer<?, ?> recognizer,
            Object offendingSymbol,
            int line,
            int charPositionInLine,
            String msg,
            RecognitionException e) {
        List<String> stack = ((Parser) recognizer.getRuleInvocationStack();
        Collections.reverse(stack);
        System.err.println("rule stack: " + stack);
        System.err.println("line" + line + ":" + 
            charPositionInLine + "at" + offendingSymbol + ": " + msg);
    }
}

我也删除了控制台错误监听器并添加了这个,但我不知道如何处理那些特定的错误.任何建议表示赞赏.非常感谢.

I also removed the console error listener and add this one, but I don't know how to deal with those specific errors. Any suggestions appreciated. Thanks a lot.

推荐答案

一般来说,报告语义错误比报告语法错误要容易得多.如果您想要自定义语法错误报告,则需要更改语法,使这些语法错误成为语义错误.例如,如果您当前像这样解析您的函数:

Reporting semantic errors is much easier in general than reporting syntax errors. If you want custom reporting of syntax errors, you need to alter your grammar so those syntax errors become semantic errors. For example, if you currently parse your function like this:

function : FUNCTION ID '(' ...

然后您可以使用以下规则之一将缺少函数名称"变成语法错误:

Then you can turn "Missing function name" into a syntax error by using one of the following rules instead:

function : FUNCTION ID? '(' ...

// alternate
function : FUNCTION (ID | /*missing function name; reported in listener*/) '(' ...

请注意,随着您添加越来越多的特殊情况,您的语法将很快变得难以管理.

Note that your grammar will quickly become unmanageable as you add more and more special cases.

这篇关于Antlr4,如何报告特定的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆