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 .github/requirements/openqasm3-1.0.1.in
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
openqasm3[parser]==1.0.1
10 changes: 10 additions & 0 deletions .github/requirements/openqasm3-1.0.1.txt

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 7 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -171,4 +171,10 @@ jobs:
token: ${{ secrets.CODECOV_TOKEN }}
fail_ci_if_error: false
files: ./build/coverage/coverage.xml
verbose: true
verbose: true

# keeps the openqasm3 1.0.1 code paths tested until pyqasm requires 1.0.2
- name: Test against openqasm3 1.0.1
run: |
python -m pip install --require-hashes -r .github/requirements/openqasm3-1.0.1.txt
python -m pytest tests/ -q
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:
### Removed

### Fixed
- `loads()` works with `openqasm3` 1.0.2 again, and still with 1.0.1. OpenQASM 2 programs load instead of failing with `program reports being unsupported version '2.0'`, syntax errors name the offending token instead of `parse failed`, and `nop` unrolls to one `nop` per operand qubit as before, also inside gate definitions (`nop;` to nothing). A measurement call such as `measure_iq q[0]`, which 1.0.2 parses, raises `ValidationError`. Known issue: openpulse 1.0.1 cannot parse an assignment in a `cal` or `defcal` block with openqasm3 1.0.2, and pyqasm now raises a `ValidationError` that names this cause instead of an `AttributeError` ([#475](https://github.com/qBraid/pyqasm/pull/475), [#472](https://github.com/qBraid/pyqasm/issues/472)).
- `unroll()` now broadcasts a gate over register operands element by element, as the spec defines. `cx a, b` on two registers became `cx a[0], a[1]; cx b[0], b[1];` instead of `cx a[0], b[0]; cx a[1], b[1];`, and slices, aliases, subroutine register arguments and `ctrl @` did the same. A register beside single-qubit operands (`cx q, r[0]`) now repeats the single qubit instead of raising, and register operands of different lengths raise `ValidationError` ([#462](https://github.com/qBraid/pyqasm/pull/462), [#384](https://github.com/qBraid/pyqasm/issues/384)).
- Decompose `p`, `phaseshift`, and `u1` (`U1`) gates into a single `rz(theta)` rotation instead of `h; rx(theta); h` ([#470](https://github.com/qBraid/pyqasm/pull/470), [#469](https://github.com/qBraid/pyqasm/issues/469)).
- Fixed `rebase` failing on `ccx`, `id`, and the `p` gates produced by unrolling `c3x` for the `ROTATIONAL_CX` / `CLIFFORD_T` basis sets ([#468](https://github.com/qBraid/pyqasm/pull/468), [#467](https://github.com/qBraid/pyqasm/issues/467)).
Expand Down
10 changes: 9 additions & 1 deletion src/pyqasm/entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from __future__ import annotations

import inspect
import os
from typing import TYPE_CHECKING

Expand All @@ -36,6 +37,13 @@
if TYPE_CHECKING:
import openqasm3.ast

# openqasm3 1.0.2 parses only OpenQASM 3 unless told otherwise; pyqasm checks the version itself
_PARSE_KWARGS = (
{"ignore_version": True}
if "ignore_version" in inspect.signature(openqasm3.parse).parameters
else {}
)
Comment thread
TheGupta2012 marked this conversation as resolved.
Resolved

# maps each documented loads() kwarg to the module attribute that stores it
_LOADS_KWARG_ATTRS = {
"device_qubits": "_device_qubits",
Expand Down Expand Up @@ -181,7 +189,7 @@ def loads(program: openqasm3.ast.Program | str, **kwargs) -> QasmModule:
# after include resolution, so an opaque in a vendor include is rewritten too
program, opaque_gates = rewrite_opaque_declarations(program)
try:
program = openqasm3.parse(program)
program = openqasm3.parse(program, **_PARSE_KWARGS)
except (openqasm3.parser.QASM3ParsingError, AttributeError) as err:
# openqasm3 can raise AttributeError on empty/whitespace-only input
raise ValidationError(
Expand Down
11 changes: 4 additions & 7 deletions src/pyqasm/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,18 +140,15 @@ def raise_qasm3_error(
def describe_parse_error(err: Exception) -> str:
"""Describe an ``openqasm3`` parse failure, recovering the location it leaves out.

``openqasm3.parse`` raises ``QASM3ParsingError()`` with no message for syntax errors and
keeps the offending ANTLR token on the chained ``ParseCancellationException``. Columns
are reported 1-based, as editors show them.
For syntax errors ``openqasm3.parse`` raises ``QASM3ParsingError`` with no message (1.0.1)
or with ``"parse failed"`` (1.0.2), and keeps the offending ANTLR token on the chained
``ParseCancellationException``. Columns are reported 1-based, as editors show them.
"""
message = str(err)
if message:
return message
cause = err.__cause__
recognition = cause.args[0] if cause is not None and cause.args else None
token = getattr(recognition, "offendingToken", None)
if token is None:
return "invalid OpenQASM syntax"
return str(err) or "invalid OpenQASM syntax"
where = f"at line {token.line}, column {token.column + 1}"
if token.text == "<EOF>":
return f"syntax error: unexpected end of program {where}"
Expand Down
4 changes: 3 additions & 1 deletion src/pyqasm/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ def _collapse_broadcast_measurement(
"""
pairs = []
for statement in body:
if not isinstance(statement, qasm3_ast.QuantumMeasurementStatement):
if not isinstance(statement, qasm3_ast.QuantumMeasurementStatement) or not isinstance(
statement.measure, qasm3_ast.QuantumMeasurement
):
return None
qubit = _single_index(statement.measure.qubit)
target = _single_index(statement.target)
Expand Down
42 changes: 42 additions & 0 deletions src/pyqasm/transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from typing import Any, NamedTuple, Optional, Sequence, cast

import numpy as np
import openqasm3.ast as qasm3_ast
from openqasm3.ast import (
BinaryExpression,
BinaryOperator,
Expand Down Expand Up @@ -456,6 +457,47 @@ def broadcast_operands(
for i in range(size)
]

@staticmethod
def nop_as_gate_calls(statement: Any) -> list[QuantumGate]:
"""Turn a ``nop`` statement into one ``nop`` gate call per operand.

This is the form older openqasm3 versions parse, so the operands are validated and
broadcast like any gate operand and the unrolled program is unchanged. A ``nop``
with no operands has no effect and gives no call.

Args:
statement (QuantumNop): The nop statement.

Returns:
list[QuantumGate]: One ``nop`` gate call per operand.
"""
calls = []
for operand in statement.operands:
gate = QuantumGate(modifiers=[], name=Identifier("nop"), arguments=[], qubits=[operand])
gate.span = statement.span
calls.append(gate)
return calls

@staticmethod
def expand_nop_statements(statements: list) -> list:
"""Replace each ``nop`` statement in a gate body by its ``nop`` gate calls.

Args:
statements (list[Statement]): The statements of a gate body.

Returns:
list[Statement]: The same statements with each ``nop`` statement expanded.
"""
if hasattr(qasm3_ast, "QuantumNop"):
expanded = []
for statement in statements:
if isinstance(statement, qasm3_ast.QuantumNop):
expanded.extend(Qasm3Transformer.nop_as_gate_calls(statement))
else:
expanded.append(statement)
return expanded
return statements

@classmethod
def transform_function_qubits(
cls,
Expand Down
55 changes: 49 additions & 6 deletions src/pyqasm/visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def _init_utilities(self):
class_obj.set_visitor_obj(self)

def _construct_visit_map(self):
return {
visit_map = {
qasm3_ast.Include: self._visit_include, # No operation
qasm3_ast.QuantumMeasurementStatement: self._visit_measurement,
qasm3_ast.QuantumReset: self._visit_reset,
Expand Down Expand Up @@ -220,6 +220,25 @@ def _construct_visit_map(self):
qasm3_ast.CalibrationStatement: self._visit_calibration_statement,
qasm3_ast.CalibrationGrammarDeclaration: self._visit_calibration_grammar_declaration,
}
# openqasm3 1.0.2 parses `nop` as its own statement, older versions as a gate call
if hasattr(qasm3_ast, "QuantumNop"):
visit_map[qasm3_ast.QuantumNop] = self._visit_nop
return visit_map

def _visit_nop(self, statement: Any) -> list[qasm3_ast.Statement]:
"""Visit a ``nop`` statement as one ``nop`` gate call per operand.

Args:
statement (QuantumNop): The nop statement to visit.

Returns:
list[Statement]: One ``nop`` gate per operand qubit, or an empty list if
self._check_only is True.
"""
result: list[qasm3_ast.Statement] = []
for gate in Qasm3Transformer.nop_as_gate_calls(statement):
result.extend(self._visit_generic_gate_operation(gate))
return result

def _visit_quantum_register(
self, register: qasm3_ast.QubitDeclaration
Expand Down Expand Up @@ -326,7 +345,7 @@ def _get_op_bits(

if isinstance(operation, qasm3_ast.QuantumMeasurementStatement):
if qubits:
bit_list = [operation.measure.qubit]
bit_list = [cast(qasm3_ast.QuantumMeasurement, operation.measure).qubit]
else:
assert operation.target is not None
bit_list = [operation.target]
Expand Down Expand Up @@ -638,7 +657,15 @@ def _visit_measurement( # pylint: disable=too-many-locals,too-many-branches,too
"""
logger.debug("Visiting measurement statement '%s'", str(statement))

source = statement.measure.qubit
if not isinstance(statement.measure, qasm3_ast.QuantumMeasurement):
# openqasm3 1.0.2 parses calls such as `measure_iq $0` into QuantumCallExpression
raise_qasm3_error(
"Only 'measure' is supported as a measurement, not a call to a defcal",
error_node=statement,
span=statement.span,
)
measurement = cast(qasm3_ast.QuantumMeasurement, statement.measure)
source = measurement.qubit
target = statement.target
if isinstance(source, qasm3_ast.Identifier):
is_pulse_gate = False
Expand All @@ -647,7 +674,7 @@ def _visit_measurement( # pylint: disable=too-many-locals,too-many-branches,too
# OpenPulse program: rename to the internal virtual register used by the
# pulse visitor, and validate the index is in range.
is_pulse_gate = True
statement.measure.qubit.name = f"{INTERNAL_QUBIT_REGISTER}[{source.name[1:]}]"
measurement.qubit.name = f"{INTERNAL_QUBIT_REGISTER}[{source.name[1:]}]"
if (
self._total_pulse_qubits <= 0
and sum(self._global_qreg_size_map.values()) == 0
Expand All @@ -663,7 +690,7 @@ def _visit_measurement( # pylint: disable=too-many-locals,too-many-branches,too
self._register_physical_qubit(source.name)
elif is_internal_qubit_register(source.name):
is_pulse_gate = True
statement.measure.qubit.name = source.name
measurement.qubit.name = source.name
if self._total_pulse_qubits <= 0 and sum(self._global_qreg_size_map.values()) == 0:
raise_qasm3_error(
"Invalid no of qubits in pulse level measurement",
Expand Down Expand Up @@ -1365,7 +1392,9 @@ def _visit_custom_gate_operation(
for formal_arg, actual_arg in zip(gate_definition.arguments, operation.arguments)
}

gate_definition_ops = copy.deepcopy(gate_definition.body)
gate_definition_ops = Qasm3Transformer.expand_nop_statements(
copy.deepcopy(gate_definition.body)
)
if inverse:
gate_definition_ops.reverse()

Expand Down Expand Up @@ -3348,6 +3377,13 @@ def _visit_calibration_definition(
str(err),
)
raise ValidationError(f"Failed to parse OpenPulse string: {_error_line}") from err
except AttributeError as err:
# openpulse <= 1.0.1 bundles an older qasm3 grammar than openqasm3 1.0.2 parses with
raise ValidationError(
"Failed to parse OpenPulse string: openpulse failed inside the openqasm3 parser. "
"openpulse 1.0.1 with openqasm3 1.0.2 is a known cause "
"(openqasm/openpulse-python#42); install openqasm3 1.0.1 or a fixed openpulse."
) from err

result = []
if len(self._global_qreg_size_map) > 1:
Expand Down Expand Up @@ -3498,6 +3534,13 @@ def _visit_calibration_statement(
str(err),
)
raise ValidationError(f"Failed to parse OpenPulse string: {_error_line}") from err
except AttributeError as err:
# openpulse <= 1.0.1 bundles an older qasm3 grammar than openqasm3 1.0.2 parses with
raise ValidationError(
"Failed to parse OpenPulse string: openpulse failed inside the openqasm3 parser. "
"openpulse 1.0.1 with openqasm3 1.0.2 is a known cause "
"(openqasm/openpulse-python#42); install openqasm3 1.0.1 or a fixed openpulse."
) from err

result = []
calibration_stmts: list[qasm3_ast.Statement] = block_body.body
Expand Down
8 changes: 4 additions & 4 deletions src/pyqasm/visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
from typing import TYPE_CHECKING, Any, Literal, cast

from openqasm3 import ast

Expand Down Expand Up @@ -218,7 +218,7 @@ def _compute_moments(
for stmt in reversed(statements):
if not isinstance(stmt, ast.QuantumMeasurementStatement):
break
control_key = _identifier_to_key(stmt.measure.qubit)
control_key = _identifier_to_key(cast(ast.QuantumMeasurement, stmt.measure).qubit)
if control_key not in seen_keys:
seen_keys.add(control_key)
final_measurements.append(stmt)
Expand All @@ -240,7 +240,7 @@ def _compute_moments(
for key in target_keys:
depths[key] = depth
elif isinstance(statement, ast.QuantumMeasurementStatement):
keys = [_identifier_to_key(statement.measure.qubit)]
keys = [_identifier_to_key(cast(ast.QuantumMeasurement, statement.measure).qubit)]
if statement.target:
target_key = _identifier_to_key(statement.target)[0], -1
keys.append(target_key)
Expand Down Expand Up @@ -486,7 +486,7 @@ def _mpl_draw_statement(
lines = [line_nums[_identifier_to_key(q)] for q in statement.qubits]
_mpl_draw_gate(statement, args, lines, ax, x)
elif isinstance(statement, ast.QuantumMeasurementStatement):
qubit_key = _identifier_to_key(statement.measure.qubit)
qubit_key = _identifier_to_key(cast(ast.QuantumMeasurement, statement.measure).qubit)
if statement.target is None:
_mpl_draw_measurement(line_nums[qubit_key], -1, -1, ax, x)
return
Expand Down
24 changes: 21 additions & 3 deletions tests/qasm3/openpulse/test_general.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

from pyqasm.entrypoint import loads
from pyqasm.exceptions import ValidationError
from tests.utils import openpulse_parses_cal_assignments, xfail_on_cal_assignment_bug


@pytest.mark.parametrize("expression", ["1 + 2;", "i;", "sin(1.0);"])
Expand Down Expand Up @@ -150,7 +151,7 @@ def test_unknown_expression_statement_call_raises_validation_error(operation: st
r"Frequency argument 'ph1' must be a FloatType with same size in frame 'frame1'",
r"Error at line 8, column 15",
),
(
pytest.param(
"""
OPENQASM 3.0;
defcalgrammar "openpulse";
Expand All @@ -163,6 +164,7 @@ def test_unknown_expression_statement_call_raises_validation_error(operation: st
""",
r"Variable 'freq' is constant, cannot be reassigned",
r"Error at line 9, column 15",
marks=xfail_on_cal_assignment_bug,
),
(
"""
Expand Down Expand Up @@ -197,7 +199,7 @@ def test_unknown_expression_statement_call_raises_validation_error(operation: st
r"Frame 'frame2' not found in openpulse scope",
r"Error at line 9, column 15",
),
(
pytest.param(
"""
OPENQASM 3.0;
defcalgrammar "openpulse";
Expand All @@ -208,8 +210,9 @@ def test_unknown_expression_statement_call_raises_validation_error(operation: st
""",
r"Invalid return type 'IntType' for function 'gaussian'",
r"Error at line 7, column 15",
marks=xfail_on_cal_assignment_bug,
),
(
pytest.param(
"""
OPENQASM 3.0;
defcalgrammar "openpulse";
Expand All @@ -227,6 +230,7 @@ def test_unknown_expression_statement_call_raises_validation_error(operation: st
""",
r"Invalid return type 'IntType' for function 'newframe'",
r"Error at line 14, column 15",
marks=xfail_on_cal_assignment_bug,
),
(
"""
Expand Down Expand Up @@ -423,3 +427,17 @@ def test_frame_collision_error(qasm_code, error_message, error_span, caplog):
loads(qasm_code).unroll()
assert error_message in str(err.value)
assert error_span in caplog.text


@pytest.mark.parametrize(
"block",
["cal {\n int a = 1;\n a = 2;\n}", "defcal g $0 {\n int a = 1;\n a = 2;\n}"],
)
def test_cal_assignment_grammar_mismatch_names_the_cause(block):
"""openpulse 1.0.1 with openqasm3 1.0.2 fails on assignments with a ValidationError."""
module = loads(f'OPENQASM 3.0;\ndefcalgrammar "openpulse";\nqubit[1] q;\n{block}\n')
if openpulse_parses_cal_assignments():
module.validate()
else:
with pytest.raises(ValidationError, match=r"openpulse 1\.0\.1 with openqasm3 1\.0\.2"):
module.validate()
3 changes: 2 additions & 1 deletion tests/qasm3/openpulse/test_pulse_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"""

from pyqasm.entrypoint import dumps, loads
from tests.utils import check_unrolled_qasm
from tests.utils import check_unrolled_qasm, xfail_on_cal_assignment_bug


def test_qubit_spectroscopy():
Expand Down Expand Up @@ -415,6 +415,7 @@ def test_neutral_atom_gate():
check_unrolled_qasm(dumps(module), expected_qasm)


@xfail_on_cal_assignment_bug
def test_multiplexed_readout_and_capture():
qasm_str = """
OPENQASM 3.0;
Expand Down
Loading
Loading