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

查看:403
本文介绍了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天全站免登陆