Python 2.7 &ANTLR4:使 ANTLR 对无效输入抛出异常 [英] Python 2.7 & ANTLR4 : Make ANTLR throw exceptions on invalid input

查看:28
本文介绍了Python 2.7 &ANTLR4:使 ANTLR 对无效输入抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕捉诸如

line 1:1 extraneous input '\r\n' expecting {':', '/',}

line 1:1 mismatched input 'Vaasje' expecting 'Tafel'

我尝试将我的函数包装在 try-catch 中,但正如预期的那样,这些错误只是打印语句而不是异常.我在 .g4 文件中看到了一些打开错误的例子,但所有的例子都是针对 Java 的,我似乎无法让它工作.

I tried wrapping my functions in try-catch but, as expected, these errors are just print statement and not exceptions. I've seen some examples of switching on errors in the .g4 file, but all the examples are for Java, and I can't seem to get it working.

Python 中的 ANTLR4 是否可能抛出我可以捕获的异常?

Is it possible for ANTLR4 in Python to throw exceptions which I can catch?

推荐答案

我浏览了 python 类,注意到它们没有 java 类用于添加和删除错误侦听器的方法,这可能是一个错误ANTLR,但是python是python,您可以修改成员而无需像以下示例中那样的setter:

I have looked through the python classes and noticed that they dont have the methods that the java one has for adding and removing a error listener, this maybe a bug in ANTLR, however python being python you are allowed to modify the members without requiring a setter as such like in the following example:

我通过执行 antlr4 -Dlanguage=Python2AlmostEmpty.g4 然后输入 main.py 来运行示例

I run the example by performing a : antlr4 -Dlanguage=Python2 AlmostEmpty.g4 and then by typing in main.py

AlmostEmpty.g4

AlmostEmpty.g4

grammar AlmostEmpty;

animals: (CAT | DOG | SHEEP ) EOF;

WS: [ \n\r]+ -> skip;
CAT: [cC] [aA] [tT];
DOG: [dD] [oO] [gG];
SHEEP: [sS] [hH] [eE] [pP];

<小时>

main.py


main.py

from antlr4 import *
import sys
from AlmostEmptyLexer import AlmostEmptyLexer
from AlmostEmptyParser import AlmostEmptyParser
from antlr4.error.ErrorListener import ErrorListener

class MyErrorListener( ErrorListener ):

    def __init__(self):
        super(MyErrorListener, self).__init__()

    def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
        raise Exception("Oh no!!")

    def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs):
        raise Exception("Oh no!!")

    def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs):
        raise Exception("Oh no!!")

    def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs):
        raise Exception("Oh no!!")

if __name__ == "__main__":
    inputStream = StdinStream( )
    lexer = AlmostEmptyLexer(inputStream)
    # Add your error listener to the lexer if required
    #lexer.removeErrorListeners()
    #lexer._listeners = [ MyErrorListener() ]
    stream = CommonTokenStream(lexer)
    parser = AlmostEmptyParser(stream)
    # As mentioned in the comments by @Tim Stewart instead of doing this:
    # parser._listeners = [ MyErrorListener() ]
    # you can do this:
    parser.addErrorListener( MyErrorListener() )
    tree = parser.animals()

这篇关于Python 2.7 &amp;ANTLR4:使 ANTLR 对无效输入抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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