From 5cedcac0b7b8d47dcdb8e461341cb4018dab00e9 Mon Sep 17 00:00:00 2001 From: Erik Davis Date: Fri, 2 Aug 2024 12:22:35 -0700 Subject: [PATCH 1/2] improve parser error messages --- source/openpulse/openpulse/parser.py | 9 ++++++++- source/openpulse/tests/test_openpulse_parser.py | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/source/openpulse/openpulse/parser.py b/source/openpulse/openpulse/parser.py index ab8bd0e..9ea7570 100644 --- a/source/openpulse/openpulse/parser.py +++ b/source/openpulse/openpulse/parser.py @@ -87,7 +87,14 @@ def parse_openpulse( try: tree = parser.calibrationBlock() except (RecognitionException, ParseCancellationException) as exc: - raise OpenPulseParsingError() from exc + msg = '' + # With BailErrorStrategy, we should be able to recover and report + # information about the offending token. + if isinstance(exc, ParseCancellationException) and exc.args: + tok = getattr(exc.args[0], 'offendingToken', None) + if tok is not None: + msg = f"Unexpected token '{tok.text}' at line {tok.line}, column {tok.start}." + raise OpenPulseParsingError(msg) from exc result = ( OpenPulseNodeVisitor(in_defcal).visitCalibrationBlock(tree) if tree.children diff --git a/source/openpulse/tests/test_openpulse_parser.py b/source/openpulse/tests/test_openpulse_parser.py index 555a509..b59836a 100644 --- a/source/openpulse/tests/test_openpulse_parser.py +++ b/source/openpulse/tests/test_openpulse_parser.py @@ -383,7 +383,7 @@ def test_permissive_parsing(capsys): captured = capsys.readouterr() assert captured.err.strip() == "line 2:9 no viable alternative at input 'int;'" - with pytest.raises(OpenPulseParsingError): + with pytest.raises(OpenPulseParsingError, match=r"Unexpected token ';' at line 2, column 10."): # This is stricter -- we fail as soon as ANTLR sees a problem parse(p) captured = capsys.readouterr() From a38b0f86ef6e1e9a4b4bd66b124de26d9c396118 Mon Sep 17 00:00:00 2001 From: Erik Davis Date: Fri, 2 Aug 2024 12:29:41 -0700 Subject: [PATCH 2/2] fix style --- source/openpulse/openpulse/parser.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/openpulse/openpulse/parser.py b/source/openpulse/openpulse/parser.py index 9ea7570..5f9c6d2 100644 --- a/source/openpulse/openpulse/parser.py +++ b/source/openpulse/openpulse/parser.py @@ -87,11 +87,11 @@ def parse_openpulse( try: tree = parser.calibrationBlock() except (RecognitionException, ParseCancellationException) as exc: - msg = '' + msg = "" # With BailErrorStrategy, we should be able to recover and report # information about the offending token. if isinstance(exc, ParseCancellationException) and exc.args: - tok = getattr(exc.args[0], 'offendingToken', None) + tok = getattr(exc.args[0], "offendingToken", None) if tok is not None: msg = f"Unexpected token '{tok.text}' at line {tok.line}, column {tok.start}." raise OpenPulseParsingError(msg) from exc