diff --git a/CHANGELOG.md b/CHANGELOG.md index dac9966..c7a31af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ Types of changes: ### Removed ### Fixed +- 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 statement and its source span. - 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)) - Fixed `reset` on a physical qubit rewriting the operand to the internal pulse register, e.g. `reset $2;` unrolled to `reset __PYQASM_QUBITS__[2];`. That names a register the program never declares, so the unrolled output did not round-trip through `dumps()`/`loads()`, and the qubit was never registered (a program whose only operation was `reset $3;` reported `num_qubits == 0`). Physical qubits are now kept as-is in plain QASM programs, matching how gate and measurement operands already treat them; the rename is still applied for OpenPulse programs, where the pulse visitor expects it. ([#325](https://github.com/qBraid/pyqasm/pull/325)) diff --git a/src/pyqasm/modules/qasm2.py b/src/pyqasm/modules/qasm2.py index f4b0de9..cd3eac4 100644 --- a/src/pyqasm/modules/qasm2.py +++ b/src/pyqasm/modules/qasm2.py @@ -23,7 +23,7 @@ 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 @@ -53,6 +53,13 @@ def __init__(self, name: str, program: Program): qasm3_ast.QuantumReset, qasm3_ast.QuantumBarrier, } + # the QASM 2.0 production: a gate application, a measurement or a reset. + # only these may be the body of an 'if'. + self._qop_statements = ( + qasm3_ast.QuantumGate, + qasm3_ast.QuantumMeasurementStatement, + qasm3_ast.QuantumReset, + ) def _filter_statements(self): """Filter statements according to the whitelist""" @@ -60,8 +67,34 @@ 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, self._qop_statements): + continue + if isinstance(inner_stmt, qasm3_ast.BranchingStatement): + self._filter_branch_body(inner_stmt) + continue + name = "barrier" if isinstance(inner_stmt, qasm3_ast.QuantumBarrier) else None + 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..fb252ca --- /dev/null +++ b/tests/qasm2/test_conditional_body.py @@ -0,0 +1,78 @@ +# 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", + [ + "delay[10ns] q;", + "box {x q[0];}", + ], +) +def test_conditional_non_qop_rejected(operation): + """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.""" + module = loads(QASM2_PREAMBLE + f"if(m==1) {operation}\n") + with pytest.raises(ValidationError, match="body of an 'if'"): + module.validate() + + +@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()