在ANTLR4中强制语义错误(失败的谓词)

时间:2013-10-02 14:13:57

标签: antlr antlr4

基本上,我已经扩展了BaseErrorListener,我需要知道错误何时是语义错误,何时是语法错误。所以我希望以下内容给我一个失败的谓词异常,但我得到一个NoViableAltException(我知道计数正在起作用,因为我可以打印出things的值,这是正确的)。有没有办法让我可以重新做它我想做的事情?在下面的示例中,如果我们最终得到6 things,我希望有一个失败的谓词异常。

grammar Test;

@parser::members {
    int things = 0;
}
.
.
.
samplerule : THING { things++; } ;
.
.
.
// Want this to be a failed predicate instead of NoViableAltException
anotherrule : ENDTOKEN { things == 6 }? ;
.
.
.

我已经正确地使用以下内容获得失败的谓词异常(针对不同的场景):

somerule : { Integer.valueOf(getCurrentToken().getText()) < 256 }? NUMBER ;
.
.
.
NUMBER : [0-9]+ ;

2 个答案:

答案 0 :(得分:0)

在ANTLR 4中,谓词用于输入导致两个不同的可能解析树(模糊语法)并且默认处理产生错误的解析树的情况。您应该创建一个侦听器或访问器实现,其中包含用于源的语义验证的逻辑。

答案 1 :(得分:0)

由于280Z28's答案以及谓词不应该用于我试图做的事实,我走了一条不同的路线。

如果你知道你在寻找什么,那么ANTLR4的文档实际上非常有用 - 访问Parser.getCurrentToken()的文档并进一步探讨,看看你还能做些什么以下实施。

我的司机最终看起来像以下内容:

// NameOfMyGrammar.java
public class NameOfMyGrammar {

    public static void main(String[] args) throws Exception {

        String inputFile = args[0];

        try {
            ANTLRInputStream input = new ANTLRFileStream(inputFile);

            NameOfMyGrammarLexer lexer = new NameOfMyGrammarLexer(input);

            CommonTokenStream tokens = new CommonTokenStream(lexer);

            MyCustomParser parser = new MyCustomParser(tokens);

            try {
                // begin parsing at "start" rule
                ParseTree tree = parser.start();
                // can print out parse tree if you want..
            } catch (RuntimeException e) {
                // Handle errors if you want..
            }
        } catch (IOException e) {
            System.err.println("Error: " + e);
        }   
    }

    // extend ANTLR-generated parser
    private static class MyCustomParser extends NameOfMyGrammarParser {

        // Constructor (my understanding is that you DO need this)
        public MyCustomParser(TokenStream input) {
            super(input);
        }

        @Override
        public Token getCurrentToken() {
            // Do your semantic checking as you encounter tokens here..
            // Depending on how you want to handle your errors, you can
            // throw exceptions, print out errors, etc.

            // Make sure you end by returning the current token
            return _input.LT(1);
        }
    }
}
相关问题