Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<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))
- 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))
Expand Down
54 changes: 53 additions & 1 deletion src/pyqasm/modules/qasm2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <qop> 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):
"""
Expand Down Expand Up @@ -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):

@TheGupta2012 TheGupta2012 Aug 5, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[M1] QuantumPhase can reach a conditional body — this whitelist does not cover it — Implementation · Medium (pre-existing gap; not a blocker)

Rationale: the whitelist is the right shape, but the <qop> set is not quite the set of things that actually arrive here. Two legal qelib1 gates decompose to a body containing a QuantumPhase node:

if(m==1) rzz(0.3) q[0],q[1];
if(m==1) rxx(0.3) q[0],q[1];

Sweeping ~45 qelib1/pyqasm gate shapes as conditional bodies and inspecting the unrolled if_block node kinds: every other gate produced only QuantumGate, but these two produce ['QuantumPhase', 'QuantumGate', ...]. Two consequences on this branch:

1. The output-level hole this PR closes for barrier is still open here. After unroll(), dumps() emits:

if (m[0] == true) {
  gphase(-0.15) q[0], q[1];
  cx q[0], q[1];
  ...
}

gphase has no QASM 2 syntax at all — the same accept-then-emit-invalid pattern this PR is fixing, arriving from the unroller rather than from the source program. (The m[0] == true half of that line is #338's territory.)

2. A narrow regression. _filter_statements runs over self._statements, and remove_idle_qubits() / reverse_qubit_order() both reassign _statements = _unrolled_ast.statements. Since unroll() has no re-entry guard, a second pass filters the unrolled body and raises:

ValidationError: statement of type QuantumPhase is not supported as the body of an 'if'
in QASM 2.0, which allows only a gate, measurement or reset

naming an AST class for a program the user wrote as rzz. Diffing the reachable public-API sequences against main: reverse_qubit_order() then remove_idle_qubits() passes on main and raises here. The other sequences (remove_idle_qubits() then unroll(), etc.) already fail on main for an unrelated pre-existing reason (Index 1 out of range for register of size 1), and remove_idle_qubits() then dumps() is fine on both.

Attribution: the underlying gap is pre-existing, not introduced here. QuantumPhase is absent from _whitelist_statements too, so unconditional rzz(0.3) q[0],q[1]; followed by remove_idle_qubits() + unroll() already raises Statement of type <class 'openqasm3.ast.QuantumPhase'> not supported in QASM 2.0 on main. This PR extends the same gap into conditional bodies, which is consistent — it just widens where it surfaces by one construct.

Change requested: not a blocker, and not worth growing the diff for. Please file a follow-up for QASM 2 global-phase handling — either the unroller should not emit gphase for a Qasm2Module, or _qasm_ast_to_str should fold/drop it — and reference it here. As a cheap in-PR mitigation, giving QuantumPhase its own message (global phase is not representable in QASM 2, rather than statement of type QuantumPhase) would keep the user-facing error honest in the meantime.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up filed as #351, referenced here and in the code. Kept the diff out of the underlying gap as you asked.

Reproduced first: if(m==1) rzz(0.3) q[0],q[1]; unrolls to ['QuantumPhase', 'QuantumGate', ...] and emits gphase(-0.15) q[0], q[1];, and reverse_qubit_order() then remove_idle_qubits() raises here where it passes on main. #351 covers both routes to a fix (unroller not emitting gphase for a Qasm2Module, or _qasm_ast_to_str folding it) and notes the _whitelist_statements half.

Took the cheap in-PR mitigation you suggested — QuantumPhase now gets its own message:

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'

test_conditional_global_phase_reports_global_phase pins it via the reverse_qubit_order() + remove_idle_qubits() sequence you found.

"""Filter the body of a conditional against what QASM 2.0 allows there.

The QASM 2.0 grammar admits only a ``<qop>`` 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")]:
Expand Down
90 changes: 90 additions & 0 deletions tests/qasm2/test_conditional_body.py
Original file line number Diff line number Diff line change
@@ -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 <qop> 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 <qop> 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()
Loading