Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Types of changes:
### Removed

### Fixed
- Fixed parse failures producing `ValidationError` with an empty message. ANTLR diagnostics written to stderr are now included in the exception text. ([#452](https://github.com/qBraid/pyqasm/pull/452), [#436](https://github.com/qBraid/pyqasm/issues/436))

### Dependencies

Expand Down
11 changes: 9 additions & 2 deletions src/pyqasm/entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

from __future__ import annotations

import contextlib
import io
import os
from typing import TYPE_CHECKING

Expand Down Expand Up @@ -181,9 +183,14 @@ def loads(program: openqasm3.ast.Program | str, **kwargs) -> QasmModule:
# after include resolution, so an opaque in a vendor include is rewritten too
program, opaque_gates = rewrite_opaque_declarations(program)
try:
program = openqasm3.parse(program)
# openqasm3 writes ANTLR diagnostics to stderr and often raises
# QASM3ParsingError with an empty message; capture stderr for callers.
stderr_buf = io.StringIO()
with contextlib.redirect_stderr(stderr_buf):
program = openqasm3.parse(program)
except openqasm3.parser.QASM3ParsingError as err:
raise ValidationError(f"Failed to parse OpenQASM string: {err}") from err
detail = str(err).strip() or stderr_buf.getvalue().strip()
raise ValidationError(f"Failed to parse OpenQASM string: {detail}") from err
elif not isinstance(program, openqasm3.ast.Program):
raise TypeError("Input quantum program must be of type 'str' or 'openqasm3.ast.Program'.")
elif include_dir is not None:
Expand Down
21 changes: 19 additions & 2 deletions tests/qasm3/test_entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@
from pyqasm.exceptions import ValidationError
from tests.utils import check_unrolled_qasm

QASM_RESOURCES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "qasm")
QASM_RESOURCES_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "resources", "qasm"
)


def test_correct_file_read():
Expand Down Expand Up @@ -53,7 +55,8 @@ def test_incorrect_module_loading_file():

def test_incorrect_module_loading_program():
with pytest.raises(
TypeError, match="Input quantum program must be of type 'str' or 'openqasm3.ast.Program'."
TypeError,
match="Input quantum program must be of type 'str' or 'openqasm3.ast.Program'.",
):
loads(1)

Expand All @@ -70,6 +73,20 @@ def test_incorrect_qasm_version():
loads("OPENQASM 4.0;\n qubit q;")


def test_loads_parse_error_includes_antlr_diagnostic():
"""Parse failures should surface the ANTLR diagnostic in ValidationError."""
bad = "OPENQASM 3.0;\nqubit q;\nrx(pi / 2 q;\n"
with pytest.raises(
ValidationError, match=r"no viable alternative|Failed to parse"
) as exc_info:
loads(bad)
msg = str(exc_info.value)
assert "Failed to parse OpenQASM string:" in msg
# must not be an empty reason after the colon
assert msg.rstrip() != "Failed to parse OpenQASM string:"
assert len(msg.split(":", 1)[-1].strip()) > 0


def test_incorrect_module_unroll_raises_error():
with pytest.raises(ValidationError):
module = loads("OPENQASM 3.0;\n qubit q; h q[2]")
Expand Down
Loading