-
Notifications
You must be signed in to change notification settings - Fork 27
fix: reject barrier as an OpenQASM 2 conditional body #339
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+144
−1
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ddb79e4
test: cover barrier as an OpenQASM 2 conditional body
ryanhill1 3ca979d
fix: reject barrier as an OpenQASM 2 conditional body
ryanhill1 7c769c0
test: cover non-qop conditional bodies, make nested test actually nest
ryanhill1 785b20f
fix: whitelist the QASM 2 <qop> production for conditional bodies
ryanhill1 6a919c4
Merge branch 'main' into fix-qasm2-conditional-barrier
ryanhill1 ae8fedc
review: hoist qop constant, name keywords, report global phase honestly
ryanhill1 50bca4b
Merge branch 'main' into fix-qasm2-conditional-barrier
TheGupta2012 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[M1]
QuantumPhasecan 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 aQuantumPhasenode:Sweeping ~45 qelib1/pyqasm gate shapes as conditional bodies and inspecting the unrolled
if_blocknode kinds: every other gate produced onlyQuantumGate, but these two produce['QuantumPhase', 'QuantumGate', ...]. Two consequences on this branch:1. The output-level hole this PR closes for
barrieris still open here. Afterunroll(),dumps()emits:gphasehas 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. (Them[0] == truehalf of that line is #338's territory.)2. A narrow regression.
_filter_statementsruns overself._statements, andremove_idle_qubits()/reverse_qubit_order()both reassign_statements = _unrolled_ast.statements. Sinceunroll()has no re-entry guard, a second pass filters the unrolled body and raises:naming an AST class for a program the user wrote as
rzz. Diffing the reachable public-API sequences againstmain:reverse_qubit_order()thenremove_idle_qubits()passes onmainand raises here. The other sequences (remove_idle_qubits()thenunroll(), etc.) already fail onmainfor an unrelated pre-existing reason (Index 1 out of range for register of size 1), andremove_idle_qubits()thendumps()is fine on both.Attribution: the underlying gap is pre-existing, not introduced here.
QuantumPhaseis absent from_whitelist_statementstoo, so unconditionalrzz(0.3) q[0],q[1];followed byremove_idle_qubits()+unroll()already raisesStatement of type <class 'openqasm3.ast.QuantumPhase'> not supported in QASM 2.0onmain. 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
gphasefor aQasm2Module, or_qasm_ast_to_strshould fold/drop it — and reference it here. As a cheap in-PR mitigation, givingQuantumPhaseits own message (global phase is not representable in QASM 2, rather thanstatement of type QuantumPhase) would keep the user-facing error honest in the meantime.There was a problem hiding this comment.
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 emitsgphase(-0.15) q[0], q[1];, andreverse_qubit_order()thenremove_idle_qubits()raises here where it passes onmain. #351 covers both routes to a fix (unroller not emittinggphasefor aQasm2Module, or_qasm_ast_to_strfolding it) and notes the_whitelist_statementshalf.Took the cheap in-PR mitigation you suggested —
QuantumPhasenow gets its own message:test_conditional_global_phase_reports_global_phasepins it via thereverse_qubit_order()+remove_idle_qubits()sequence you found.