我如何在python ANTLR生成的解析器中出现第一个语法错误的同时保留错误消息?

问题描述 投票:0回答:1

我正在将antlr.error.ErrorStrategy.BailErrorStrategy用于我的解析器。有时(取决于输入),它将报告语法错误的人类可读版本(例如line 2:3: mismatched input XXX expecting YYY),有时则不报告(只是没有line 2:3: some message的异常):

import pytest
import json
import sys
from antlr4 import *
from antlr4.error.ErrorStrategy import DefaultErrorStrategy, BailErrorStrategy

from sqliteparser.SQLiteLexer import SQLiteLexer
from sqliteparser.SQLiteParser import SQLiteParser


def test_create_table():
    input_stream = InputStream("\nCREATE OR REPLACE VIEW APPDELETIONS as (\n")
    lexer = SQLiteLexer(input_stream)
    def recover(self,re):
        raise re
    lexer.recover = recover
    stream = CommonTokenStream(lexer)
    parser = SQLiteParser(stream)
    parser._errHandler = BailErrorStrategy()
    tree = parser.parse()

是否有一种方法可以获得总是报告语法错误的文本表示的错误策略?

antlr antlr4
1个回答
0
投票

可以继承BailErrorStrategy并调用reportError

class MyErrorStrategy(BailErrorStrategy):
    def recover(self, recognizer:Parser, e:RecognitionException):
        recognizer._errHandler.reportError(recognizer,e)
        super().recover(recognizer,e)

然后简单地调用parser._errHandler = MyErrorStrategy()

这将确保将实际的语法错误(例如line 2:18 mismatched input 'VIEW' expecting K_TABLE)打印到控制台。您可以通过parser.addErrorListener(...)添加其他错误侦听器。

© www.soinside.com 2019 - 2024. All rights reserved.