Skip to content

Commit 7e05f4c

Browse files
fix: reject barrier as an OpenQASM 2 conditional body (#339)
* test: cover barrier as an OpenQASM 2 conditional body The QASM 2 grammar admits only a <qop> as the body of an `if`: <if> := if ( <id> == <nninteger> ) <qop> <qop> := <uop> | 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 <qop> in a conditional body, and an unconditional barrier. * fix: reject barrier as an OpenQASM 2 conditional body `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 <qop>, and only a <qop> may follow an `if`. Filtering now recurses into conditional bodies (both blocks, at any depth) and raises a ValidationError naming the offending statement. * 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. * fix: whitelist the QASM 2 <qop> 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 <qop> production itself (QuantumGate, QuantumMeasurementStatement, QuantumReset), with branching statements recursed into as before. Barrier keeps its specific message; anything else is named by node type. * review: hoist qop constant, name keywords, report global phase honestly - _qop_statements becomes a module-level _QOP_STATEMENTS; it is a fixed grammar production, not per-instance state (L1) - non-qop bodies report the keyword the user wrote via _NON_QOP_KEYWORDS, so a delay body says 'delay' rather than 'statement of type DelayInstruction' (L2) - QuantumPhase gets its own message naming global phase and the rzz/rxx decomposition that introduces it, instead of an AST class name; the underlying gphase gap is tracked in #351 (M1 mitigation) --------- Co-authored-by: TheGupta2012 <harshit.11235@gmail.com>
1 parent 8a4eac2 commit 7e05f4c

3 files changed

Lines changed: 144 additions & 1 deletion

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Types of changes:
2929
- 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))
3030
- 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))
3131
- 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))
32+
- Fixed statements that OpenQASM 2 cannot condition being accepted as the body of a classical conditional. The QASM 2 grammar admits only a `<qop>` — 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 `<qop>` 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))
3233
- 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))
3334
- 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))
3435
- 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))

src/pyqasm/modules/qasm2.py

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,26 @@
2323
from openqasm3.ast import Include, Program
2424
from openqasm3.printer import dumps
2525

26-
from pyqasm.exceptions import ValidationError
26+
from pyqasm.exceptions import ValidationError, raise_qasm3_error
2727
from pyqasm.modules.base import QasmModule
2828
from pyqasm.modules.qasm3 import Qasm3Module
2929

30+
# the QASM 2.0 <qop> production: a gate application, a measurement or a reset.
31+
# only these may be the body of an 'if'.
32+
_QOP_STATEMENTS = (
33+
qasm3_ast.QuantumGate,
34+
qasm3_ast.QuantumMeasurementStatement,
35+
qasm3_ast.QuantumReset,
36+
)
37+
38+
# statements the user can write in a conditional body that QASM 2.0 has no form for,
39+
# named by the keyword they wrote rather than by the AST class they parsed into
40+
_NON_QOP_KEYWORDS = {
41+
qasm3_ast.QuantumBarrier: "barrier",
42+
qasm3_ast.DelayInstruction: "delay",
43+
qasm3_ast.Box: "box",
44+
}
45+
3046

3147
class Qasm2Module(QasmModule):
3248
"""
@@ -60,8 +76,44 @@ def _filter_statements(self):
6076
stmt_type = type(stmt)
6177
if stmt_type not in self._whitelist_statements:
6278
raise ValidationError(f"Statement of type {stmt_type} not supported in QASM 2.0")
79+
if isinstance(stmt, qasm3_ast.BranchingStatement):
80+
self._filter_branch_body(stmt)
6381
# TODO: add more filtering here if needed
6482

83+
def _filter_branch_body(self, statement: qasm3_ast.BranchingStatement):
84+
"""Filter the body of a conditional against what QASM 2.0 allows there.
85+
86+
The QASM 2.0 grammar admits only a ``<qop>`` as the body of an ``if`` --
87+
a gate application, a measurement or a reset. Everything else, ``barrier``
88+
included, belongs to a different production and cannot be conditioned. The
89+
parser does not enforce that, so it is enforced here as a whitelist: a
90+
blacklist would let through whatever statement kinds it had not enumerated.
91+
"""
92+
for inner_stmt in [*statement.if_block, *statement.else_block]:
93+
if isinstance(inner_stmt, _QOP_STATEMENTS):
94+
continue
95+
if isinstance(inner_stmt, qasm3_ast.BranchingStatement):
96+
self._filter_branch_body(inner_stmt)
97+
continue
98+
if isinstance(inner_stmt, qasm3_ast.QuantumPhase):
99+
# not something the user wrote: rzz/rxx decompose to a global phase, so this
100+
# is only reachable by re-filtering an already-unrolled body (see issue #351)
101+
raise_qasm3_error(
102+
"Global phase is not representable in QASM 2.0, so it cannot appear in "
103+
"a conditional body; it is introduced by unrolling gates such as 'rzz' "
104+
"and 'rxx'",
105+
error_node=inner_stmt,
106+
span=inner_stmt.span,
107+
)
108+
name = _NON_QOP_KEYWORDS.get(type(inner_stmt))
109+
described = f"'{name}'" if name else f"statement of type {type(inner_stmt).__name__}"
110+
raise_qasm3_error(
111+
f"{described} is not supported as the body of an 'if' in QASM 2.0, which "
112+
"allows only a gate, measurement or reset there",
113+
error_node=inner_stmt,
114+
span=inner_stmt.span,
115+
)
116+
65117
def _format_declarations(self, qasm_str):
66118
"""Format the unrolled qasm for declarations in openqasm 2.0 format"""
67119
for declaration_type, replacement_type in [("qubit", "qreg"), ("bit", "creg")]:
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# Copyright 2025 qBraid
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""
16+
Module containing unit tests for what OpenQASM 2.0 allows as a conditional body
17+
18+
"""
19+
20+
import pytest
21+
22+
from pyqasm.entrypoint import loads
23+
from pyqasm.exceptions import ValidationError
24+
25+
QASM2_PREAMBLE = """OPENQASM 2.0;
26+
include "qelib1.inc";
27+
qreg q[2];
28+
creg m[1];
29+
creg c[1];
30+
measure q[0] -> m[0];
31+
"""
32+
33+
34+
@pytest.mark.parametrize("operation", ["barrier q;", "barrier q[0];", "barrier q[0], q[1];"])
35+
def test_conditional_barrier_rejected(operation):
36+
"""Test that a barrier is rejected as the body of a conditional. The QASM 2 grammar
37+
admits only a <qop> there, and barrier is a separate production."""
38+
module = loads(QASM2_PREAMBLE + f"if(m==1) {operation}\n")
39+
with pytest.raises(ValidationError, match="barrier"):
40+
module.validate()
41+
42+
43+
def test_conditional_barrier_rejected_when_nested():
44+
"""Test that a barrier reached only through a nested conditional is also rejected,
45+
exercising the recursive descent rather than just the outer body"""
46+
module = loads(QASM2_PREAMBLE + "if(m==1) if(m==0) barrier q;\n")
47+
with pytest.raises(ValidationError, match="barrier"):
48+
module.validate()
49+
50+
51+
@pytest.mark.parametrize(
52+
"operation, keyword",
53+
[
54+
("delay[10ns] q;", "'delay'"),
55+
("box {x q[0];}", "'box'"),
56+
],
57+
)
58+
def test_conditional_non_qop_rejected(operation, keyword):
59+
"""Test that any statement which is not a <qop> is rejected as a conditional body,
60+
not just barrier. These parse but have no QASM 2 syntax at all, and the error names
61+
the keyword the user wrote rather than the AST class it parsed into."""
62+
module = loads(QASM2_PREAMBLE + f"if(m==1) {operation}\n")
63+
with pytest.raises(ValidationError, match=f"{keyword} is not supported as the body of an 'if'"):
64+
module.validate()
65+
66+
67+
def test_conditional_global_phase_reports_global_phase():
68+
"""Test that the QuantumPhase unrolling introduces for rzz/rxx is reported as global
69+
phase rather than as an AST class name. Reachable only by re-filtering an already
70+
unrolled body, which remove_idle_qubits/reverse_qubit_order do (issue #351)."""
71+
module = loads(QASM2_PREAMBLE + "if(m==1) rzz(0.3) q[0], q[1];\n")
72+
module.unroll()
73+
module.reverse_qubit_order()
74+
with pytest.raises(ValidationError, match="Global phase is not representable in QASM 2.0"):
75+
module.remove_idle_qubits()
76+
77+
78+
@pytest.mark.parametrize(
79+
"operation", ["x q[1];", "reset q[1];", "measure q[1] -> c[0];", "cx q[0], q[1];"]
80+
)
81+
def test_conditional_qop_accepted(operation):
82+
"""Test that the operations QASM 2 does allow as a conditional body still validate"""
83+
module = loads(QASM2_PREAMBLE + f"if(m==1) {operation}\n")
84+
module.validate()
85+
86+
87+
def test_unconditional_barrier_accepted():
88+
"""Test that a barrier outside a conditional is unaffected"""
89+
module = loads(QASM2_PREAMBLE + "barrier q;\n")
90+
module.validate()

0 commit comments

Comments
 (0)