diff --git a/CHANGELOG.md b/CHANGELOG.md index 74581b8..bcc32f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ Types of changes: - Fixed `remove_idle_qubits()` and `reverse_qubit_order()` ignoring statements nested inside `box` and `if` blocks. Top-level operands were rewritten while nested ones kept their old indices, so the result silently addressed the wrong qubits — and when a nested index fell outside the shrunken register, the output was not a loadable program at all. Both passes now walk nested bodies, as do `has_measurements()` / `remove_measurements()` and `has_barriers()` / `remove_barriers()`; a box left empty by a removal is dropped, since pyqasm rejects a box with no statements. Two consequences of the same blind spot are fixed alongside: a qubit operated on only inside an `if` block no longer counts as idle, and `remove_idle_qubits()` no longer raises `AssertionError` on a program that mixes physical qubits with declared registers. ([#345](https://github.com/qBraid/pyqasm/pull/345)) - Fixed `unroll(consolidate_qubits=True)` raising `AttributeError: 'str' object has no attribute 'name'` for any gate applied to a physical qubit, e.g. `h $1;`. Consolidation assumed every gate operand was an `IndexedIdentifier`, but a physical qubit survives unrolling as `Identifier("$1")`. Physical qubits are absolute hardware indices belonging to no declared register, so they are now left as written — matching how `measure`, `reset` and `barrier` already treat them. ([#344](https://github.com/qBraid/pyqasm/pull/344)) - Fixed `unroll()` and `rebase()` emitting statements that share operand AST nodes: gate decompositions passed the same `IndexedIdentifier` objects into every statement they emitted, so transformations that rewrite qubit indices in place mutated a shared node once per referencing statement. This crashed `reverse_qubit_order()` (`KeyError: -1`) and `remove_idle_qubits()` (`KeyError`, [#331](https://github.com/qBraid/pyqasm/issues/331)) on any decomposed gate (e.g. `crz`) whenever the remap was not the identity. Statement constructors in `maps/gates.py` and `Decomposer` now copy their qubit operands so every emitted statement owns its nodes. ([#333](https://github.com/qBraid/pyqasm/issues/333)) +- Fixed statements that OpenQASM 2 cannot condition being accepted as the body of a classical conditional. The QASM 2 grammar admits only a `` — a gate application, a measurement or a reset — as the body of an `if`. `barrier` is a separate production, and `delay`/`box` have no QASM 2 syntax at all, yet `if(m==1) barrier q;`, `if(m==1) delay[10ns] q;` and `if(m==1) box {...}` all validated and were emitted unchanged, producing output that QASM 2 parsers reject. Conditional bodies are now filtered against the `` whitelist at any nesting depth, raising a `ValidationError` that names the offending keyword and its source span. ([#339](https://github.com/qBraid/pyqasm/pull/339)) - Fixed `remove_idle_qubits(in_place=False)` updating the qubit count on the wrong module: the original module's `num_qubits` was decremented while the returned copy kept the stale pre-removal count. The copy's AST was already correct; only the counters were swapped. ([#336](https://github.com/qBraid/pyqasm/pull/336)) - Fixed `remove_idle_qubits()` raising `KeyError` when the unrolled AST contains operand nodes shared across multiple statements (e.g. the `crz` decomposition) and an idle lower-indexed qubit shifts the register indices. `_remap_qubits` now remaps each operand node exactly once instead of once per statement that references it. ([#332](https://github.com/qBraid/pyqasm/pull/332)) - Fixed `box` duration validation summing `delay` durations across all qubits instead of tracking each qubit's timeline. Delays on disjoint qubits run in parallel, so `box[300ns] { delay[200ns] q[0]; delay[200ns] q[1]; }` was rejected while the identical schedule written as a broadcast delay (`delay[200ns] q;`) was accepted. Delays are now accumulated per qubit and the box is validated against the busiest single timeline; the error message names the offending qubit. Nested boxes now also contribute their declared duration to the enclosing box's timelines (previously the accumulator was reset when an inner box closed, dropping all inner delay accounting). ([#330](https://github.com/qBraid/pyqasm/pull/330)) diff --git a/src/pyqasm/modules/qasm2.py b/src/pyqasm/modules/qasm2.py index f4b0de9..bba821e 100644 --- a/src/pyqasm/modules/qasm2.py +++ b/src/pyqasm/modules/qasm2.py @@ -23,10 +23,26 @@ from openqasm3.ast import Include, Program from openqasm3.printer import dumps -from pyqasm.exceptions import ValidationError +from pyqasm.exceptions import ValidationError, raise_qasm3_error from pyqasm.modules.base import QasmModule from pyqasm.modules.qasm3 import Qasm3Module +# the QASM 2.0 production: a gate application, a measurement or a reset. +# only these may be the body of an 'if'. +_QOP_STATEMENTS = ( + qasm3_ast.QuantumGate, + qasm3_ast.QuantumMeasurementStatement, + qasm3_ast.QuantumReset, +) + +# statements the user can write in a conditional body that QASM 2.0 has no form for, +# named by the keyword they wrote rather than by the AST class they parsed into +_NON_QOP_KEYWORDS = { + qasm3_ast.QuantumBarrier: "barrier", + qasm3_ast.DelayInstruction: "delay", + qasm3_ast.Box: "box", +} + class Qasm2Module(QasmModule): """ @@ -60,8 +76,44 @@ def _filter_statements(self): stmt_type = type(stmt) if stmt_type not in self._whitelist_statements: raise ValidationError(f"Statement of type {stmt_type} not supported in QASM 2.0") + if isinstance(stmt, qasm3_ast.BranchingStatement): + self._filter_branch_body(stmt) # TODO: add more filtering here if needed + def _filter_branch_body(self, statement: qasm3_ast.BranchingStatement): + """Filter the body of a conditional against what QASM 2.0 allows there. + + The QASM 2.0 grammar admits only a ```` as the body of an ``if`` -- + a gate application, a measurement or a reset. Everything else, ``barrier`` + included, belongs to a different production and cannot be conditioned. The + parser does not enforce that, so it is enforced here as a whitelist: a + blacklist would let through whatever statement kinds it had not enumerated. + """ + for inner_stmt in [*statement.if_block, *statement.else_block]: + if isinstance(inner_stmt, _QOP_STATEMENTS): + continue + if isinstance(inner_stmt, qasm3_ast.BranchingStatement): + self._filter_branch_body(inner_stmt) + continue + if isinstance(inner_stmt, qasm3_ast.QuantumPhase): + # not something the user wrote: rzz/rxx decompose to a global phase, so this + # is only reachable by re-filtering an already-unrolled body (see issue #351) + raise_qasm3_error( + "Global phase is not representable in QASM 2.0, so it cannot appear in " + "a conditional body; it is introduced by unrolling gates such as 'rzz' " + "and 'rxx'", + error_node=inner_stmt, + span=inner_stmt.span, + ) + name = _NON_QOP_KEYWORDS.get(type(inner_stmt)) + described = f"'{name}'" if name else f"statement of type {type(inner_stmt).__name__}" + raise_qasm3_error( + f"{described} is not supported as the body of an 'if' in QASM 2.0, which " + "allows only a gate, measurement or reset there", + error_node=inner_stmt, + span=inner_stmt.span, + ) + def _format_declarations(self, qasm_str): """Format the unrolled qasm for declarations in openqasm 2.0 format""" for declaration_type, replacement_type in [("qubit", "qreg"), ("bit", "creg")]: diff --git a/tests/qasm2/test_conditional_body.py b/tests/qasm2/test_conditional_body.py new file mode 100644 index 0000000..b093a2d --- /dev/null +++ b/tests/qasm2/test_conditional_body.py @@ -0,0 +1,90 @@ +# Copyright 2025 qBraid +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Module containing unit tests for what OpenQASM 2.0 allows as a conditional body + +""" + +import pytest + +from pyqasm.entrypoint import loads +from pyqasm.exceptions import ValidationError + +QASM2_PREAMBLE = """OPENQASM 2.0; +include "qelib1.inc"; +qreg q[2]; +creg m[1]; +creg c[1]; +measure q[0] -> m[0]; +""" + + +@pytest.mark.parametrize("operation", ["barrier q;", "barrier q[0];", "barrier q[0], q[1];"]) +def test_conditional_barrier_rejected(operation): + """Test that a barrier is rejected as the body of a conditional. The QASM 2 grammar + admits only a there, and barrier is a separate production.""" + module = loads(QASM2_PREAMBLE + f"if(m==1) {operation}\n") + with pytest.raises(ValidationError, match="barrier"): + module.validate() + + +def test_conditional_barrier_rejected_when_nested(): + """Test that a barrier reached only through a nested conditional is also rejected, + exercising the recursive descent rather than just the outer body""" + module = loads(QASM2_PREAMBLE + "if(m==1) if(m==0) barrier q;\n") + with pytest.raises(ValidationError, match="barrier"): + module.validate() + + +@pytest.mark.parametrize( + "operation, keyword", + [ + ("delay[10ns] q;", "'delay'"), + ("box {x q[0];}", "'box'"), + ], +) +def test_conditional_non_qop_rejected(operation, keyword): + """Test that any statement which is not a is rejected as a conditional body, + not just barrier. These parse but have no QASM 2 syntax at all, and the error names + the keyword the user wrote rather than the AST class it parsed into.""" + module = loads(QASM2_PREAMBLE + f"if(m==1) {operation}\n") + with pytest.raises(ValidationError, match=f"{keyword} is not supported as the body of an 'if'"): + module.validate() + + +def test_conditional_global_phase_reports_global_phase(): + """Test that the QuantumPhase unrolling introduces for rzz/rxx is reported as global + phase rather than as an AST class name. Reachable only by re-filtering an already + unrolled body, which remove_idle_qubits/reverse_qubit_order do (issue #351).""" + module = loads(QASM2_PREAMBLE + "if(m==1) rzz(0.3) q[0], q[1];\n") + module.unroll() + module.reverse_qubit_order() + with pytest.raises(ValidationError, match="Global phase is not representable in QASM 2.0"): + module.remove_idle_qubits() + + +@pytest.mark.parametrize( + "operation", ["x q[1];", "reset q[1];", "measure q[1] -> c[0];", "cx q[0], q[1];"] +) +def test_conditional_qop_accepted(operation): + """Test that the operations QASM 2 does allow as a conditional body still validate""" + module = loads(QASM2_PREAMBLE + f"if(m==1) {operation}\n") + module.validate() + + +def test_unconditional_barrier_accepted(): + """Test that a barrier outside a conditional is unaffected""" + module = loads(QASM2_PREAMBLE + "barrier q;\n") + module.validate()