From ddb79e40eb0b15ef69c0d6af0bc68a9146ae3aba Mon Sep 17 00:00:00 2001 From: Ryan Hill Date: Fri, 31 Jul 2026 12:48:27 -0500 Subject: [PATCH 1/4] test: cover barrier as an OpenQASM 2 conditional body The QASM 2 grammar admits only a as the body of an `if`: := if ( == ) := | measure ... | reset ... `barrier` is a separate production, so `if(m==1) barrier q;` is not a valid QASM 2 program. pyqasm accepts it and emits it unchanged, which downstream QASM 2 parsers reject. Tests assert the rejection, alongside cases pinning down what must keep validating: every operation that *is* a in a conditional body, and an unconditional barrier. --- tests/qasm2/test_conditional_body.py | 69 ++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 tests/qasm2/test_conditional_body.py diff --git a/tests/qasm2/test_conditional_body.py b/tests/qasm2/test_conditional_body.py new file mode 100644 index 0000000..8857390 --- /dev/null +++ b/tests/qasm2/test_conditional_body.py @@ -0,0 +1,69 @@ +# 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 nested deeper inside a conditional body is also rejected""" + qasm2_string = """OPENQASM 2.0; + include "qelib1.inc"; + qreg q[2]; + creg m[2]; + measure q[0] -> m[0]; + if(m==1) barrier q; + """ + module = loads(qasm2_string) + with pytest.raises(ValidationError, match="barrier"): + 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() From 3ca979d0ce925a0ab117108158f4099cf3bfbd9e Mon Sep 17 00:00:00 2001 From: Ryan Hill Date: Fri, 31 Jul 2026 12:49:12 -0500 Subject: [PATCH 2/4] fix: reject barrier as an OpenQASM 2 conditional body MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Qasm2Module._filter_statements` checked only the type of each top-level statement, so nothing inspected what a `BranchingStatement` carried in its body. A conditional barrier passed validation and was serialized verbatim as `if (m == 1) barrier q[0], q[1];`, which QASM 2 parsers reject — barrier is not a , and only a may follow an `if`. Filtering now recurses into conditional bodies (both blocks, at any depth) and raises a ValidationError naming the offending statement. --- CHANGELOG.md | 1 + src/pyqasm/modules/qasm2.py | 22 +++++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dac9966..0441b58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ Types of changes: ### Removed ### Fixed +- Fixed `barrier` being accepted as the body of a classical conditional in OpenQASM 2 programs. 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, so `if(m==1) barrier q;` is not a valid program. pyqasm passed it through unvalidated and emitted it unchanged, producing output that QASM 2 parsers reject. It now raises a `ValidationError` naming the offending statement, including when the barrier is nested deeper inside the conditional. - 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..e7f93ef 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 @@ -60,8 +60,28 @@ 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. ``barrier`` is a separate + production, so it cannot be conditioned. + """ + for inner_stmt in [*statement.if_block, *statement.else_block]: + if isinstance(inner_stmt, qasm3_ast.QuantumBarrier): + raise_qasm3_error( + "'barrier' 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, + ) + if isinstance(inner_stmt, qasm3_ast.BranchingStatement): + self._filter_branch_body(inner_stmt) + 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")]: From 7c769c06f1f39cbd38fc64548c8747ea1ff9d367 Mon Sep 17 00:00:00 2001 From: Ryan Hill Date: Fri, 31 Jul 2026 13:50:46 -0500 Subject: [PATCH 3/4] test: cover non-qop conditional bodies, make nested test actually nest Review feedback on #339. `test_conditional_barrier_rejected_when_nested` claimed to exercise the recursive descent but its program had no nesting -- it duplicated the `barrier q;` parametrized case, so dropping the recursion left every test green. It now nests (`if(m==1) if(m==0) barrier q;`), verified to fail when the recursion is removed. Adds failing tests for the wider hole behind that one: filtering blacklists `barrier` alone, so any other non-qop body the parser accepts validates cleanly and is emitted as invalid QASM 2. `delay` and `box` bodies both do this today -- neither has any QASM 2 syntax, and `delay` is even rejected at the top level by the existing whitelist. --- tests/qasm2/test_conditional_body.py | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/tests/qasm2/test_conditional_body.py b/tests/qasm2/test_conditional_body.py index 8857390..fb252ca 100644 --- a/tests/qasm2/test_conditional_body.py +++ b/tests/qasm2/test_conditional_body.py @@ -41,19 +41,28 @@ def test_conditional_barrier_rejected(operation): def test_conditional_barrier_rejected_when_nested(): - """Test that a barrier nested deeper inside a conditional body is also rejected""" - qasm2_string = """OPENQASM 2.0; - include "qelib1.inc"; - qreg q[2]; - creg m[2]; - measure q[0] -> m[0]; - if(m==1) barrier q; - """ - module = loads(qasm2_string) + """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];"] ) From 785b20f1070bbaf047f483ceeaca7a7cf329c4f8 Mon Sep 17 00:00:00 2001 From: Ryan Hill Date: Fri, 31 Jul 2026 13:51:42 -0500 Subject: [PATCH 4/4] fix: whitelist the QASM 2 production for conditional bodies Review feedback on #339. Filtering blacklisted `barrier` alone, so every other non-qop body the parser accepts still validated and was emitted verbatim. `delay` and `box` bodies both did this -- neither has any QASM 2 syntax, and `delay` is already rejected by the top-level whitelist, so a conditional was the one place it could slip through. Conditional bodies are now checked against the production itself (QuantumGate, QuantumMeasurementStatement, QuantumReset), with branching statements recursed into as before. Barrier keeps its specific message; anything else is named by node type. --- CHANGELOG.md | 2 +- src/pyqasm/modules/qasm2.py | 31 ++++++++++++++++++++++--------- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0441b58..c7a31af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,7 +25,7 @@ Types of changes: ### Removed ### Fixed -- Fixed `barrier` being accepted as the body of a classical conditional in OpenQASM 2 programs. 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, so `if(m==1) barrier q;` is not a valid program. pyqasm passed it through unvalidated and emitted it unchanged, producing output that QASM 2 parsers reject. It now raises a `ValidationError` naming the offending statement, including when the barrier is nested deeper inside the conditional. +- 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 e7f93ef..cd3eac4 100644 --- a/src/pyqasm/modules/qasm2.py +++ b/src/pyqasm/modules/qasm2.py @@ -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""" @@ -68,19 +75,25 @@ 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. ``barrier`` is a separate - production, so it cannot be conditioned. + 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, qasm3_ast.QuantumBarrier): - raise_qasm3_error( - "'barrier' 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, - ) + 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"""