Antlr4, How to report specific syntax error

自古美人都是妖i 提交于 2019-12-11 13:36:41

问题


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

The grammar itself is constructed by functions.

ie

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

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.


回答1:


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.



来源:https://stackoverflow.com/questions/18941263/antlr4-how-to-report-specific-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!