diff --git a/.github/requirements/openqasm3-1.0.1.in b/.github/requirements/openqasm3-1.0.1.in new file mode 100644 index 00000000..f337bb0f --- /dev/null +++ b/.github/requirements/openqasm3-1.0.1.in @@ -0,0 +1 @@ +openqasm3[parser]==1.0.1 diff --git a/.github/requirements/openqasm3-1.0.1.txt b/.github/requirements/openqasm3-1.0.1.txt new file mode 100644 index 00000000..63fe3df2 --- /dev/null +++ b/.github/requirements/openqasm3-1.0.1.txt @@ -0,0 +1,10 @@ +# This file was autogenerated by uv via the following command: +# uv pip compile --universal --generate-hashes --python-version 3.10 .github/requirements/openqasm3-1.0.1.in -o .github/requirements/openqasm3-1.0.1.txt +antlr4-python3-runtime==4.13.2 \ + --hash=sha256:909b647e1d2fc2b70180ac586df3933e38919c85f98ccc656a96cd3f25ef3916 \ + --hash=sha256:fe3835eb8d33daece0e799090eda89719dbccee7aa39ef94eed3818cafa5a7e8 + # via openqasm3 +openqasm3==1.0.1 \ + --hash=sha256:0d3a1ebe3465e3ea619bcaa369858bba8944cbb0c49604b24f94662d3ec41d41 \ + --hash=sha256:c589dc05d4ced50ca24167d14e0f2c916e717499ba0442e0ff2a3030ef312d0a + # via -r .github/requirements/openqasm3-1.0.1.in diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 96ae8c1a..00a2294f 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -171,4 +171,10 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} fail_ci_if_error: false files: ./build/coverage/coverage.xml - verbose: true \ No newline at end of file + verbose: true + + # keeps the openqasm3 1.0.1 code paths tested until pyqasm requires 1.0.2 + - name: Test against openqasm3 1.0.1 + run: | + python -m pip install --require-hashes -r .github/requirements/openqasm3-1.0.1.txt + python -m pytest tests/ -q \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 05478ef7..2f0397f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ Types of changes: ### Removed ### Fixed +- `loads()` works with `openqasm3` 1.0.2 again, and still with 1.0.1. OpenQASM 2 programs load instead of failing with `program reports being unsupported version '2.0'`, syntax errors name the offending token instead of `parse failed`, and `nop` unrolls to one `nop` per operand qubit as before, also inside gate definitions (`nop;` to nothing). A measurement call such as `measure_iq q[0]`, which 1.0.2 parses, raises `ValidationError`. Known issue: openpulse 1.0.1 cannot parse an assignment in a `cal` or `defcal` block with openqasm3 1.0.2, and pyqasm now raises a `ValidationError` that names this cause instead of an `AttributeError` ([#475](https://github.com/qBraid/pyqasm/pull/475), [#472](https://github.com/qBraid/pyqasm/issues/472)). - `unroll()` now broadcasts a gate over register operands element by element, as the spec defines. `cx a, b` on two registers became `cx a[0], a[1]; cx b[0], b[1];` instead of `cx a[0], b[0]; cx a[1], b[1];`, and slices, aliases, subroutine register arguments and `ctrl @` did the same. A register beside single-qubit operands (`cx q, r[0]`) now repeats the single qubit instead of raising, and register operands of different lengths raise `ValidationError` ([#462](https://github.com/qBraid/pyqasm/pull/462), [#384](https://github.com/qBraid/pyqasm/issues/384)). - Decompose `p`, `phaseshift`, and `u1` (`U1`) gates into a single `rz(theta)` rotation instead of `h; rx(theta); h` ([#470](https://github.com/qBraid/pyqasm/pull/470), [#469](https://github.com/qBraid/pyqasm/issues/469)). - Fixed `rebase` failing on `ccx`, `id`, and the `p` gates produced by unrolling `c3x` for the `ROTATIONAL_CX` / `CLIFFORD_T` basis sets ([#468](https://github.com/qBraid/pyqasm/pull/468), [#467](https://github.com/qBraid/pyqasm/issues/467)). diff --git a/src/pyqasm/entrypoint.py b/src/pyqasm/entrypoint.py index 90fb8524..4623b647 100644 --- a/src/pyqasm/entrypoint.py +++ b/src/pyqasm/entrypoint.py @@ -19,6 +19,7 @@ from __future__ import annotations +import inspect import os from typing import TYPE_CHECKING @@ -36,6 +37,13 @@ if TYPE_CHECKING: import openqasm3.ast +# openqasm3 1.0.2 parses only OpenQASM 3 unless told otherwise; pyqasm checks the version itself +_PARSE_KWARGS = ( + {"ignore_version": True} + if "ignore_version" in inspect.signature(openqasm3.parse).parameters + else {} +) + # maps each documented loads() kwarg to the module attribute that stores it _LOADS_KWARG_ATTRS = { "device_qubits": "_device_qubits", @@ -181,7 +189,7 @@ 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) + program = openqasm3.parse(program, **_PARSE_KWARGS) except (openqasm3.parser.QASM3ParsingError, AttributeError) as err: # openqasm3 can raise AttributeError on empty/whitespace-only input raise ValidationError( diff --git a/src/pyqasm/exceptions.py b/src/pyqasm/exceptions.py index 45aa89e7..7b75f0bb 100644 --- a/src/pyqasm/exceptions.py +++ b/src/pyqasm/exceptions.py @@ -140,18 +140,15 @@ def raise_qasm3_error( def describe_parse_error(err: Exception) -> str: """Describe an ``openqasm3`` parse failure, recovering the location it leaves out. - ``openqasm3.parse`` raises ``QASM3ParsingError()`` with no message for syntax errors and - keeps the offending ANTLR token on the chained ``ParseCancellationException``. Columns - are reported 1-based, as editors show them. + For syntax errors ``openqasm3.parse`` raises ``QASM3ParsingError`` with no message (1.0.1) + or with ``"parse failed"`` (1.0.2), and keeps the offending ANTLR token on the chained + ``ParseCancellationException``. Columns are reported 1-based, as editors show them. """ - message = str(err) - if message: - return message cause = err.__cause__ recognition = cause.args[0] if cause is not None and cause.args else None token = getattr(recognition, "offendingToken", None) if token is None: - return "invalid OpenQASM syntax" + return str(err) or "invalid OpenQASM syntax" where = f"at line {token.line}, column {token.column + 1}" if token.text == "": return f"syntax error: unexpected end of program {where}" diff --git a/src/pyqasm/printer.py b/src/pyqasm/printer.py index 95a0b9aa..5ce17eaf 100644 --- a/src/pyqasm/printer.py +++ b/src/pyqasm/printer.py @@ -97,7 +97,9 @@ def _collapse_broadcast_measurement( """ pairs = [] for statement in body: - if not isinstance(statement, qasm3_ast.QuantumMeasurementStatement): + if not isinstance(statement, qasm3_ast.QuantumMeasurementStatement) or not isinstance( + statement.measure, qasm3_ast.QuantumMeasurement + ): return None qubit = _single_index(statement.measure.qubit) target = _single_index(statement.target) diff --git a/src/pyqasm/transformer.py b/src/pyqasm/transformer.py index d2eaa1c1..9e35e67d 100644 --- a/src/pyqasm/transformer.py +++ b/src/pyqasm/transformer.py @@ -21,6 +21,7 @@ from typing import Any, NamedTuple, Optional, Sequence, cast import numpy as np +import openqasm3.ast as qasm3_ast from openqasm3.ast import ( BinaryExpression, BinaryOperator, @@ -456,6 +457,47 @@ def broadcast_operands( for i in range(size) ] + @staticmethod + def nop_as_gate_calls(statement: Any) -> list[QuantumGate]: + """Turn a ``nop`` statement into one ``nop`` gate call per operand. + + This is the form older openqasm3 versions parse, so the operands are validated and + broadcast like any gate operand and the unrolled program is unchanged. A ``nop`` + with no operands has no effect and gives no call. + + Args: + statement (QuantumNop): The nop statement. + + Returns: + list[QuantumGate]: One ``nop`` gate call per operand. + """ + calls = [] + for operand in statement.operands: + gate = QuantumGate(modifiers=[], name=Identifier("nop"), arguments=[], qubits=[operand]) + gate.span = statement.span + calls.append(gate) + return calls + + @staticmethod + def expand_nop_statements(statements: list) -> list: + """Replace each ``nop`` statement in a gate body by its ``nop`` gate calls. + + Args: + statements (list[Statement]): The statements of a gate body. + + Returns: + list[Statement]: The same statements with each ``nop`` statement expanded. + """ + if hasattr(qasm3_ast, "QuantumNop"): + expanded = [] + for statement in statements: + if isinstance(statement, qasm3_ast.QuantumNop): + expanded.extend(Qasm3Transformer.nop_as_gate_calls(statement)) + else: + expanded.append(statement) + return expanded + return statements + @classmethod def transform_function_qubits( cls, diff --git a/src/pyqasm/visitor.py b/src/pyqasm/visitor.py index 707d1158..867ae2bd 100644 --- a/src/pyqasm/visitor.py +++ b/src/pyqasm/visitor.py @@ -189,7 +189,7 @@ def _init_utilities(self): class_obj.set_visitor_obj(self) def _construct_visit_map(self): - return { + visit_map = { qasm3_ast.Include: self._visit_include, # No operation qasm3_ast.QuantumMeasurementStatement: self._visit_measurement, qasm3_ast.QuantumReset: self._visit_reset, @@ -220,6 +220,25 @@ def _construct_visit_map(self): qasm3_ast.CalibrationStatement: self._visit_calibration_statement, qasm3_ast.CalibrationGrammarDeclaration: self._visit_calibration_grammar_declaration, } + # openqasm3 1.0.2 parses `nop` as its own statement, older versions as a gate call + if hasattr(qasm3_ast, "QuantumNop"): + visit_map[qasm3_ast.QuantumNop] = self._visit_nop + return visit_map + + def _visit_nop(self, statement: Any) -> list[qasm3_ast.Statement]: + """Visit a ``nop`` statement as one ``nop`` gate call per operand. + + Args: + statement (QuantumNop): The nop statement to visit. + + Returns: + list[Statement]: One ``nop`` gate per operand qubit, or an empty list if + self._check_only is True. + """ + result: list[qasm3_ast.Statement] = [] + for gate in Qasm3Transformer.nop_as_gate_calls(statement): + result.extend(self._visit_generic_gate_operation(gate)) + return result def _visit_quantum_register( self, register: qasm3_ast.QubitDeclaration @@ -326,7 +345,7 @@ def _get_op_bits( if isinstance(operation, qasm3_ast.QuantumMeasurementStatement): if qubits: - bit_list = [operation.measure.qubit] + bit_list = [cast(qasm3_ast.QuantumMeasurement, operation.measure).qubit] else: assert operation.target is not None bit_list = [operation.target] @@ -638,7 +657,15 @@ def _visit_measurement( # pylint: disable=too-many-locals,too-many-branches,too """ logger.debug("Visiting measurement statement '%s'", str(statement)) - source = statement.measure.qubit + if not isinstance(statement.measure, qasm3_ast.QuantumMeasurement): + # openqasm3 1.0.2 parses calls such as `measure_iq $0` into QuantumCallExpression + raise_qasm3_error( + "Only 'measure' is supported as a measurement, not a call to a defcal", + error_node=statement, + span=statement.span, + ) + measurement = cast(qasm3_ast.QuantumMeasurement, statement.measure) + source = measurement.qubit target = statement.target if isinstance(source, qasm3_ast.Identifier): is_pulse_gate = False @@ -647,7 +674,7 @@ def _visit_measurement( # pylint: disable=too-many-locals,too-many-branches,too # OpenPulse program: rename to the internal virtual register used by the # pulse visitor, and validate the index is in range. is_pulse_gate = True - statement.measure.qubit.name = f"{INTERNAL_QUBIT_REGISTER}[{source.name[1:]}]" + measurement.qubit.name = f"{INTERNAL_QUBIT_REGISTER}[{source.name[1:]}]" if ( self._total_pulse_qubits <= 0 and sum(self._global_qreg_size_map.values()) == 0 @@ -663,7 +690,7 @@ def _visit_measurement( # pylint: disable=too-many-locals,too-many-branches,too self._register_physical_qubit(source.name) elif is_internal_qubit_register(source.name): is_pulse_gate = True - statement.measure.qubit.name = source.name + measurement.qubit.name = source.name if self._total_pulse_qubits <= 0 and sum(self._global_qreg_size_map.values()) == 0: raise_qasm3_error( "Invalid no of qubits in pulse level measurement", @@ -1365,7 +1392,9 @@ def _visit_custom_gate_operation( for formal_arg, actual_arg in zip(gate_definition.arguments, operation.arguments) } - gate_definition_ops = copy.deepcopy(gate_definition.body) + gate_definition_ops = Qasm3Transformer.expand_nop_statements( + copy.deepcopy(gate_definition.body) + ) if inverse: gate_definition_ops.reverse() @@ -3348,6 +3377,13 @@ def _visit_calibration_definition( str(err), ) raise ValidationError(f"Failed to parse OpenPulse string: {_error_line}") from err + except AttributeError as err: + # openpulse <= 1.0.1 bundles an older qasm3 grammar than openqasm3 1.0.2 parses with + raise ValidationError( + "Failed to parse OpenPulse string: openpulse failed inside the openqasm3 parser. " + "openpulse 1.0.1 with openqasm3 1.0.2 is a known cause " + "(openqasm/openpulse-python#42); install openqasm3 1.0.1 or a fixed openpulse." + ) from err result = [] if len(self._global_qreg_size_map) > 1: @@ -3498,6 +3534,13 @@ def _visit_calibration_statement( str(err), ) raise ValidationError(f"Failed to parse OpenPulse string: {_error_line}") from err + except AttributeError as err: + # openpulse <= 1.0.1 bundles an older qasm3 grammar than openqasm3 1.0.2 parses with + raise ValidationError( + "Failed to parse OpenPulse string: openpulse failed inside the openqasm3 parser. " + "openpulse 1.0.1 with openqasm3 1.0.2 is a known cause " + "(openqasm/openpulse-python#42); install openqasm3 1.0.1 or a fixed openpulse." + ) from err result = [] calibration_stmts: list[qasm3_ast.Statement] = block_body.body diff --git a/src/pyqasm/visualization.py b/src/pyqasm/visualization.py index 5567ab16..2d417265 100644 --- a/src/pyqasm/visualization.py +++ b/src/pyqasm/visualization.py @@ -22,7 +22,7 @@ from __future__ import annotations from pathlib import Path -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Any, Literal, cast from openqasm3 import ast @@ -218,7 +218,7 @@ def _compute_moments( for stmt in reversed(statements): if not isinstance(stmt, ast.QuantumMeasurementStatement): break - control_key = _identifier_to_key(stmt.measure.qubit) + control_key = _identifier_to_key(cast(ast.QuantumMeasurement, stmt.measure).qubit) if control_key not in seen_keys: seen_keys.add(control_key) final_measurements.append(stmt) @@ -240,7 +240,7 @@ def _compute_moments( for key in target_keys: depths[key] = depth elif isinstance(statement, ast.QuantumMeasurementStatement): - keys = [_identifier_to_key(statement.measure.qubit)] + keys = [_identifier_to_key(cast(ast.QuantumMeasurement, statement.measure).qubit)] if statement.target: target_key = _identifier_to_key(statement.target)[0], -1 keys.append(target_key) @@ -486,7 +486,7 @@ def _mpl_draw_statement( lines = [line_nums[_identifier_to_key(q)] for q in statement.qubits] _mpl_draw_gate(statement, args, lines, ax, x) elif isinstance(statement, ast.QuantumMeasurementStatement): - qubit_key = _identifier_to_key(statement.measure.qubit) + qubit_key = _identifier_to_key(cast(ast.QuantumMeasurement, statement.measure).qubit) if statement.target is None: _mpl_draw_measurement(line_nums[qubit_key], -1, -1, ax, x) return diff --git a/tests/qasm3/openpulse/test_general.py b/tests/qasm3/openpulse/test_general.py index 978f171d..2a8913b7 100644 --- a/tests/qasm3/openpulse/test_general.py +++ b/tests/qasm3/openpulse/test_general.py @@ -22,6 +22,7 @@ from pyqasm.entrypoint import loads from pyqasm.exceptions import ValidationError +from tests.utils import openpulse_parses_cal_assignments, xfail_on_cal_assignment_bug @pytest.mark.parametrize("expression", ["1 + 2;", "i;", "sin(1.0);"]) @@ -150,7 +151,7 @@ def test_unknown_expression_statement_call_raises_validation_error(operation: st r"Frequency argument 'ph1' must be a FloatType with same size in frame 'frame1'", r"Error at line 8, column 15", ), - ( + pytest.param( """ OPENQASM 3.0; defcalgrammar "openpulse"; @@ -163,6 +164,7 @@ def test_unknown_expression_statement_call_raises_validation_error(operation: st """, r"Variable 'freq' is constant, cannot be reassigned", r"Error at line 9, column 15", + marks=xfail_on_cal_assignment_bug, ), ( """ @@ -197,7 +199,7 @@ def test_unknown_expression_statement_call_raises_validation_error(operation: st r"Frame 'frame2' not found in openpulse scope", r"Error at line 9, column 15", ), - ( + pytest.param( """ OPENQASM 3.0; defcalgrammar "openpulse"; @@ -208,8 +210,9 @@ def test_unknown_expression_statement_call_raises_validation_error(operation: st """, r"Invalid return type 'IntType' for function 'gaussian'", r"Error at line 7, column 15", + marks=xfail_on_cal_assignment_bug, ), - ( + pytest.param( """ OPENQASM 3.0; defcalgrammar "openpulse"; @@ -227,6 +230,7 @@ def test_unknown_expression_statement_call_raises_validation_error(operation: st """, r"Invalid return type 'IntType' for function 'newframe'", r"Error at line 14, column 15", + marks=xfail_on_cal_assignment_bug, ), ( """ @@ -423,3 +427,17 @@ def test_frame_collision_error(qasm_code, error_message, error_span, caplog): loads(qasm_code).unroll() assert error_message in str(err.value) assert error_span in caplog.text + + +@pytest.mark.parametrize( + "block", + ["cal {\n int a = 1;\n a = 2;\n}", "defcal g $0 {\n int a = 1;\n a = 2;\n}"], +) +def test_cal_assignment_grammar_mismatch_names_the_cause(block): + """openpulse 1.0.1 with openqasm3 1.0.2 fails on assignments with a ValidationError.""" + module = loads(f'OPENQASM 3.0;\ndefcalgrammar "openpulse";\nqubit[1] q;\n{block}\n') + if openpulse_parses_cal_assignments(): + module.validate() + else: + with pytest.raises(ValidationError, match=r"openpulse 1\.0\.1 with openqasm3 1\.0\.2"): + module.validate() diff --git a/tests/qasm3/openpulse/test_pulse_examples.py b/tests/qasm3/openpulse/test_pulse_examples.py index 964435d3..282bbb5a 100644 --- a/tests/qasm3/openpulse/test_pulse_examples.py +++ b/tests/qasm3/openpulse/test_pulse_examples.py @@ -18,7 +18,7 @@ """ from pyqasm.entrypoint import dumps, loads -from tests.utils import check_unrolled_qasm +from tests.utils import check_unrolled_qasm, xfail_on_cal_assignment_bug def test_qubit_spectroscopy(): @@ -415,6 +415,7 @@ def test_neutral_atom_gate(): check_unrolled_qasm(dumps(module), expected_qasm) +@xfail_on_cal_assignment_bug def test_multiplexed_readout_and_capture(): qasm_str = """ OPENQASM 3.0; diff --git a/tests/qasm3/test_entrypoint.py b/tests/qasm3/test_entrypoint.py index 50233c2d..868fe125 100644 --- a/tests/qasm3/test_entrypoint.py +++ b/tests/qasm3/test_entrypoint.py @@ -104,7 +104,7 @@ def test_loads_parse_error_names_location(program, reason): def test_describe_parse_error_without_token(): """An empty parse error with no ANTLR cause still gets a non-empty reason.""" - assert describe_parse_error(QASM3ParsingError()) == "invalid OpenQASM syntax" + assert describe_parse_error(QASM3ParsingError("")) == "invalid OpenQASM syntax" def test_loads_header_only_module_ok(): diff --git a/tests/qasm3/test_gates.py b/tests/qasm3/test_gates.py index 60aa63bd..48121750 100644 --- a/tests/qasm3/test_gates.py +++ b/tests/qasm3/test_gates.py @@ -68,6 +68,46 @@ def test_single_qubit_qasm3_gates(circuit_name, request): check_single_qubit_gate_op(result.unrolled_ast, 5, qubit_list, gate_name) +@pytest.mark.parametrize( + "statement, expected", + [ + ("nop q[1];", ["nop q[1];"]), + ("nop q;", ["nop q[0];", "nop q[1];"]), + ("nop q[0], r[0];", ["nop q[0];", "nop r[0];"]), + ("nop q[0], q[0];", ["nop q[0];", "nop q[0];"]), + ("gate g a { nop a; }\ng q[0];", ["nop q[0];"]), + ("gate g a, b { nop a, b; x b; }\ng q[0], r[0];", ["nop q[0];", "nop r[0];", "x r[0];"]), + ], +) +def test_nop_unrolls_per_operand(statement, expected): + """A nop unrolls to one nop per operand qubit, also inside a gate definition. + + openqasm3 1.0.1 parses these as nop gate calls and 1.0.2 as nop statements, and both + give the same unrolled program. + """ + header = 'OPENQASM 3.0;\ninclude "stdgates.inc";\nqubit[2] q;\nqubit[1] r;\n' + module = loads(header + statement) + module.unroll() + check_unrolled_qasm(dumps(module), header + "\n".join(expected)) + + +@pytest.mark.skipif( + not hasattr(qasm3_ast, "QuantumNop"), reason="openqasm3 < 1.0.2 does not parse a bare nop" +) +def test_nop_without_operands_unrolls_to_nothing(): + """A nop with no operands has no effect.""" + header = 'OPENQASM 3.0;\ninclude "stdgates.inc";\nqubit[2] q;\n' + module = loads(header + "nop;") + module.unroll() + check_unrolled_qasm(dumps(module), header) + + +def test_nop_out_of_range_operand_raises(): + """A nop operand is validated like a gate operand.""" + with pytest.raises(ValidationError): + loads('OPENQASM 3.0;\ninclude "stdgates.inc";\nqubit[2] q;\nnop q[2];').validate() + + @pytest.mark.parametrize("circuit_name", double_op_tests) def test_two_qubit_qasm3_gates(circuit_name, request): qubit_list = [[0, 1], [0, 1]] diff --git a/tests/qasm3/test_measurement.py b/tests/qasm3/test_measurement.py index 3d8da1fe..fbde7582 100644 --- a/tests/qasm3/test_measurement.py +++ b/tests/qasm3/test_measurement.py @@ -17,6 +17,7 @@ """ +import openqasm3.ast as qasm3_ast import pytest from pyqasm.entrypoint import dumps, loads @@ -456,3 +457,15 @@ def test_incorrect_measure(qasm3_code, error_message, line_num, col_num, err_lin assert f"Error at line {line_num}, column {col_num}" in caplog.text assert err_line in caplog.text + + +@pytest.mark.skipif( + not hasattr(qasm3_ast, "QuantumCallExpression"), + reason="openqasm3 < 1.0.2 does not parse measurement calls", +) +@pytest.mark.parametrize("statement", ["c[0] = measure_iq q[0];", "measure_iq q[0] -> c[0];"]) +def test_measurement_call_raises(statement): + """A measurement other than `measure`, such as a defcal call, raises a ValidationError.""" + qasm3_string = f"OPENQASM 3.0;\nqubit[1] q;\nbit[1] c;\n{statement}" + with pytest.raises(ValidationError, match="Only 'measure' is supported as a measurement"): + loads(qasm3_string).validate() diff --git a/tests/utils.py b/tests/utils.py index 464ca2a6..77864322 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -19,7 +19,9 @@ import numpy as np import openqasm3.ast as qasm3_ast +import pytest +from pyqasm.exceptions import ValidationError from pyqasm.maps.expressions import CONSTANTS_MAP CONTROLLED_ROTATION_TEST_ANGLE = 0.5 @@ -584,3 +586,26 @@ def check_custom_qasm_gate_op_with_external_gates(unrolled_ast, test_type): check_two_qubit_gate_op(unrolled_ast, 1, [[0, 1]], "cx") else: raise ValueError(f"Unknown test type {test_type}") + + +def openpulse_parses_cal_assignments() -> bool: + """Whether the installed openpulse can parse an assignment inside a cal block.""" + try: + from openpulse.parser import parse_openpulse # pylint: disable=import-outside-toplevel + except ImportError: + return True + try: + parse_openpulse("int a = 1; a = 2;", in_defcal=False, permissive=False) + except AttributeError: + return False + return True + + +# openpulse 1.0.1 has an older copy of the qasm3 grammar than openqasm3 1.0.2 parses with +# (openqasm/openpulse#42), so every assignment in a cal block fails with a ValidationError. +xfail_on_cal_assignment_bug = pytest.mark.xfail( + not openpulse_parses_cal_assignments(), + reason="openpulse 1.0.1 cannot parse assignments in cal blocks with openqasm3 1.0.2", + raises=(ValidationError, AssertionError), + strict=True, +)