Skip to content
Open
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ Types of changes:
### Removed

### Fixed
- `/` between integer operands, meaning integer literals and `int` or `uint` variables, is now integer division, truncated toward zero, as the spec defines (`b / a; // 1`). This also changes angles: `rx(1 / 2)` is now `rx(0)`, was `rx(0.5)`, `rx(3 / 4 * pi)` is now `rx(0.0)`, was `rx(2.356194490192345)`, and with `int[32] a = 2; int[32] b = 3;`, `rx(b / a)` is now `rx(1)`, was `rx(1.5)`. Gate parameters are angles and keep real division (`g(3)` with `rx(t / 2)` in the body is still `rx(1.5)`). OpenQASM 2 has no integer type, so its programs keep real division, also after `to_qasm3()`, which writes `1/2` as `1.0 / 2.0` ([#474](https://github.com/qBraid/pyqasm/pull/474)).
- `unroll()` accepts `inv @` on a custom gate whose body contains `nop`, and keeps each `nop` in the inverted body. Before, it raised `ValidationError: Unsupported / undeclared QASM operation: nop` ([#485](https://github.com/qBraid/pyqasm/pull/485), [#477](https://github.com/qBraid/pyqasm/issues/477)).
- `publish-lab-env.yml` files a publish request before it approves the environment. Since qBraid/qbraid-api#1334 the server approves only an environment with an open request, so every run failed at approve with `Environment must have status REQUESTED or PENDING to publish`. The request counts toward the API key owner's publish quota and notifies the platform admins ([#491](https://github.com/qBraid/pyqasm/pull/491), [#490](https://github.com/qBraid/pyqasm/issues/490)).


### Dependencies

### Other
Expand Down
31 changes: 30 additions & 1 deletion src/pyqasm/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
IntegerLiteral,
)
from openqasm3.ast import IntType as Qasm3IntType
from openqasm3.ast import SizeOf, Statement, StretchType, UnaryExpression
from openqasm3.ast import SizeOf, Statement, StretchType, UintType, UnaryExpression

from pyqasm.analyzer import Qasm3Analyzer
from pyqasm.elements import Variable
Expand Down Expand Up @@ -142,6 +142,29 @@ def _check_var_type(cls, var_name, reqd_type, expression):
span=expression.span,
)

@classmethod
def _is_integer_typed(cls, expression) -> bool:
"""Whether an expression is built only from integer literals and int or uint variables."""
if isinstance(expression, IntegerLiteral):
# OpenQASM 2 has no integer type: every classical expression is real
assert cls.visitor_obj
return not cls.visitor_obj._module._real_literal_division
if isinstance(expression, Identifier):
assert cls.visitor_obj
var = cls.visitor_obj._scope_manager.get_from_visible_scope(expression.name)
return (
var is not None
and not var.dims
and isinstance(var.base_type, (Qasm3IntType, UintType))
)
if isinstance(expression, UnaryExpression):
return expression.op.name == "-" and cls._is_integer_typed(expression.expression)
if isinstance(expression, BinaryExpression):
return expression.op.name in ("+", "-", "*", "/", "%") and all(
cls._is_integer_typed(operand) for operand in (expression.lhs, expression.rhs)
)
return False
Comment on lines +146 to +166

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.

[H1] Integer literals must divide as integers in this PR — Implementation · High

Impact: rx(1 / 2), rx(b / 2) and rx(3 / a) still give 0.5, 1.5 and 1.5. The spec gives 0, 1 and 1. So / stays inconsistent on integer operands: b / a is 1, but b / 2 is 1.5.

Rationale

Integer literals are integers (spec types.rst, "Literals"). / on integer types is integer division (classical.rst, "Integers": b / a; // 1). So every + - * / % tree of integer literals and int/uint variables is integer-typed. The decision for this PR is to include literals now, not in a follow-up.

A prototype that marks IntegerLiteral as integer-typed shows three places where a Python int reaches the evaluator but is not an OpenQASM integer:

Input Naive literal rule Correct Why
gate g(t) r { rx(t / 2) r; } then g(3) q[0]; (or g(n)) rx(1) rx(1.5) Gate parameters are angle (gates.rst). transform_gate_params substitutes IntegerLiteral(3) for t.
OpenQASM 2: rx(1/2) q[0]; rx(0) rx(0.5) OpenQASM 2 has no integer type; every classical expression is real.
OpenQASM 2 rx(1/2) through to_qasm3(), then unroll() rx(0) rx(0.5) to_qasm3() keeps rx(1 / 2) verbatim and relabels the program as 3.0.

Durations already behave: delay[d / 2] stays 500.5ns.

Change requested:

  1. In _is_integer_typed, treat IntegerLiteral as integer-typed only for OpenQASM 3 modules. A Qasm2Module must keep true division. The prototype gated on cls.visitor_obj._module.original_program.version.
  2. Bind gate parameters as reals in QasmVisitor._visit_custom_gate_operation (visitor.py, param_map), so transform_gate_params substitutes a FloatLiteral:
    param_map = {}
    for formal_arg, actual_arg in zip(gate_definition.arguments, operation.arguments):
        value = Qasm3ExprEvaluator.evaluate_expression(actual_arg)[0]
        # gate parameters are angles: an int argument must not divide as an integer
        param_map[formal_arg.name] = float(value) if isinstance(value, int) else value
    Visible side effect: gate g(t) r { rx(t) r; } with g(3) dumps rx(3.0) instead of rx(3). No existing test changes because of it.
  3. Make to_qasm3() keep OpenQASM 2 semantics. For example, emit integer literals inside classical expressions as float literals (1.0 / 2).
  4. Update tests/qasm3/resources/qasm/custom_gate_nested.qasm:17 (2 + 3 - 1/5). Either write 1.0/5 and keep 4.8 in tests/utils.py:548,550, or expect 5.
  5. In this test: flip the three literal rows to rx(0), rx(1) and rx(1). Add rx(3 / 4 * pi) → rx(0), an OpenQASM 2 rx(1/2) → rx(0.5) row, and a to_qasm3() row. Keep both g(3) and g(n) rows at 1.5.
  6. Reword the CHANGELOG entry, which says "between two int or uint variables". Call out the user-visible changes rx(1/2) → rx(0) and 3/4*pi → 0.

The prototype of steps 1 and 2 leaves the suite at 1059 passed and 4 failed. The 4 failures are exactly the updates in steps 4 and 5.

Completed when: with openqasm3 1.0.1, rx(1 / 2) → rx(0), rx(b / 2) → rx(1), g(3) with rx(t / 2) → rx(1.5), OpenQASM 2 rx(1/2) and its to_qasm3() output → rx(0.5), and the full suite passes.

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.

[L1] Other integer-typed operands still true-divide — Implementation · Low

Impact: int[32](f) / a (with f = 7.9), arr[0] / a on an int[32] array, (b | 4) / a and an int[32]-returning def call divided by a all give 3.5. The spec gives 3. The PR description lists these as intended true division.

Rationale

Casts to int/uint, elements of integer arrays, bitwise and shift results on integers, int ** int, and subroutines returning int/uint are all integer-typed in the spec. They are less common than literals, so a follow-up is proportionate.

Change requested: open a follow-up issue that lists these operands, and link it from the PR description instead of listing them as intended behavior.

Completed when: the issue exists and the PR description links it.


@classmethod
def _check_var_initialized(cls, var_name, var_value, expression):
"""Checks if a variable is initialized and raises an error if it is not.
Expand Down Expand Up @@ -471,6 +494,12 @@ def _get_external_function_return_type(expression):
return (None, [])

statements.extend(rhs_statements)
if expression.op.name == "/" and cls._is_integer_typed(expression):
# int / int is integer division, truncated toward zero as in C99
quotient = abs(lhs_value) // abs(rhs_value)
return _check_and_return_value(
quotient if (lhs_value < 0) == (rhs_value < 0) else -quotient
)
return _check_and_return_value(
qasm3_expression_op_map(expression.op.name, lhs_value, rhs_value)
)
Expand Down
2 changes: 2 additions & 0 deletions src/pyqasm/modules/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,8 @@ def __init__(self, name: str, program: Program):
self._frame_limit_per_port: Optional[int] = None
self._play_in_cal: Optional[bool] = True
self._compact_gate_arguments: bool = False
# OpenQASM 2 has no integer type, so its integer literals divide as reals
self._real_literal_division: bool = False

@property
def name(self) -> str:
Expand Down
9 changes: 8 additions & 1 deletion src/pyqasm/modules/qasm2.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class Qasm2Module(QasmModule):
def __init__(self, name: str, program: Program) -> None:
super().__init__(name, program)
self._unrolled_ast = Program(statements=[], version="2.0")
self._real_literal_division = True
self._whitelist_statements = {
qasm3_ast.BranchingStatement,
qasm3_ast.QubitDeclaration,
Expand Down Expand Up @@ -172,9 +173,15 @@ def to_qasm3(self, as_str: bool = False) -> str | Qasm3Module:
break
qasm_program.version = "3.0"
if as_str:
return dumps(qasm_program, compact_gate_arguments=self._compact_gate_arguments)
return dumps(
qasm_program,
compact_gate_arguments=self._compact_gate_arguments,
real_literal_division=True,
)
module = Qasm3Module(self._name, qasm_program)
module.compact_gate_arguments = self._compact_gate_arguments
# the program is still OpenQASM 2 arithmetic under an OpenQASM 3 header
module._real_literal_division = True
return module

def finalize(self, statements: list[qasm3_ast.Statement]) -> list[qasm3_ast.Statement]:
Expand Down
58 changes: 55 additions & 3 deletions src/pyqasm/modules/qasm3.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@
from openqasm3.ast import (
BinaryExpression,
BinaryOperator,
IntegerLiteral,
Pragma,
Program,
QASMNode,
QuantumGate,
QuantumPhase,
UnaryExpression,
)
from openqasm3.printer import Printer, PrinterState

Expand All @@ -36,8 +38,21 @@
_COMPACT_OPERATORS = frozenset({BinaryOperator["*"], BinaryOperator["/"], BinaryOperator["**"]})


def _int_literal_arithmetic(expression: QASMNode) -> bool:
"""Whether an expression combines only integer literals with + - * / % **."""
if isinstance(expression, IntegerLiteral):
return True
if isinstance(expression, UnaryExpression):
return expression.op.name == "-" and _int_literal_arithmetic(expression.expression)
if isinstance(expression, BinaryExpression):
return expression.op.name in ("+", "-", "*", "/", "%", "**") and all(
_int_literal_arithmetic(operand) for operand in (expression.lhs, expression.rhs)
)
return False


class Qasm3Printer(Printer):
"""OpenQASM 3 printer with two changes to the upstream printer.
"""OpenQASM 3 printer with three changes to the upstream printer.

Pragmas are written in their '#pragma' form. The upstream printer emits the bare
'pragma' keyword. Both forms parse, but tools consuming the output (e.g. Amazon
Expand All @@ -46,23 +61,37 @@ class Qasm3Printer(Printer):
With ``compact_gate_arguments``, gate arguments are written without spaces around
'*', '/' and '**': ``rx(pi/2)`` instead of ``rx(pi / 2)``. Some vendors (e.g. Diraq)
match rotation angles textually and only accept the compact spelling.

With ``real_literal_division``, a division between integer literals is written with
float literals: ``rx(1.0 / 2.0)`` instead of ``rx(1 / 2)``. A program converted from
OpenQASM 2, which has no integer type, keeps its real division this way.
"""

def __init__(
self, stream: io.TextIOBase, *, compact_gate_arguments: bool = False, **kwargs: Any
self,
stream: io.TextIOBase,
*,
compact_gate_arguments: bool = False,
real_literal_division: bool = False,
**kwargs: Any,
) -> None:
"""Create a printer.

Args:
stream (io.TextIOBase): The stream to write to.
compact_gate_arguments (bool): Drop the spaces around '*', '/' and '**' in gate
arguments. Defaults to False.
real_literal_division (bool): Write the integer literals of a division between
integer literals as floats. Defaults to False.
**kwargs (Any): Printer options, forwarded to `openqasm3.printer.Printer`.
"""
super().__init__(stream, **kwargs)
self.compact_gate_arguments = compact_gate_arguments
# true only while a gate call prints, so classical expressions keep their spacing
self._printing_gate_expr = False
self.real_literal_division = real_literal_division
# true only while a division between integer literals prints
self._printing_real_division = False

def visit_QuantumGate(self, node: QuantumGate, context: PrinterState) -> None:
"""Write a gate call, marking its expressions as gate arguments."""
Expand All @@ -85,6 +114,18 @@ def visit_BinaryExpression(self, node: BinaryExpression, context: PrinterState)

Mirrors the upstream method, which hardcodes the spaces around the operator.
"""
if (
self.real_literal_division
and not self._printing_real_division
and node.op.name == "/"
and _int_literal_arithmetic(node)
):
self._printing_real_division = True
try:
self.visit_BinaryExpression(node, context)
finally:
self._printing_real_division = False
return
our_precedence = properties.precedence(node)
# All AST nodes that are built into BinaryExpression are currently left associative.
if properties.precedence(node.lhs) < our_precedence:
Expand All @@ -106,6 +147,13 @@ def visit_BinaryExpression(self, node: BinaryExpression, context: PrinterState)
else:
self.visit(node.rhs, context)

def visit_IntegerLiteral(self, node: IntegerLiteral, context: PrinterState) -> None:
"""Write an integer literal, as a float inside a division that stays real."""
if self._printing_real_division:
self.stream.write(str(float(node.value)))
else:
super().visit_IntegerLiteral(node, context)

def visit_Pragma(self, node: Pragma, context: PrinterState) -> None:
"""Write a pragma node, keeping the '#' that the upstream printer drops.

Expand Down Expand Up @@ -151,7 +199,11 @@ def _qasm_ast_to_str(self, qasm_ast: Program) -> str:
"""Convert the qasm AST to a string."""
# set the version to 3.0
qasm_ast.version = "3.0"
return dumps(qasm_ast, compact_gate_arguments=self._compact_gate_arguments)
return dumps(
qasm_ast,
compact_gate_arguments=self._compact_gate_arguments,
real_literal_division=self._real_literal_division,
)

def accept(self, visitor: QasmVisitor) -> None:
"""Accept a visitor for the module.
Expand Down
9 changes: 5 additions & 4 deletions src/pyqasm/visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1395,10 +1395,11 @@ def _visit_custom_gate_operation(
formal_arg.name: actual_arg
for formal_arg, actual_arg in zip(gate_definition.qubits, op_qubits)
}
param_map = {
formal_arg.name: Qasm3ExprEvaluator.evaluate_expression(actual_arg)[0]
for formal_arg, actual_arg in zip(gate_definition.arguments, operation.arguments)
}
param_map: dict[str, int | float | bool] = {}
for formal_arg, actual_arg in zip(gate_definition.arguments, operation.arguments):
value = Qasm3ExprEvaluator.evaluate_expression(actual_arg)[0]
# gate parameters are angles: an int argument must not divide as an integer
param_map[formal_arg.name] = float(value) if isinstance(value, int) else value

gate_definition_ops = copy.deepcopy(gate_definition.body)
if inverse:
Expand Down
2 changes: 1 addition & 1 deletion tests/qasm3/resources/qasm/custom_gate_nested.qasm
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ gate custom(a,b,c) p, q{
}

qubit[2] q;
custom(2 + 3 - 1/5, 0.1, 0.3) q[0], q[1];
custom(2 + 3 - 1.0/5, 0.1, 0.3) q[0], q[1];
72 changes: 70 additions & 2 deletions tests/qasm3/test_expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,14 @@
import openqasm3.ast as qasm3_ast
import pytest

from pyqasm.entrypoint import loads
from pyqasm.entrypoint import dumps, loads
from pyqasm.exceptions import ValidationError
from tests.utils import check_measure_op, check_single_qubit_gate_op, check_single_qubit_rotation_op
from tests.utils import (
check_measure_op,
check_single_qubit_gate_op,
check_single_qubit_rotation_op,
check_unrolled_qasm,
)


def test_correct_expressions():
Expand Down Expand Up @@ -205,3 +210,66 @@ def test_unknown_gate_reports_its_name_before_checking_operands(

with pytest.raises(ValidationError, match=error):
getattr(module, operation)()


@pytest.mark.parametrize(
"statements, expected",
[
("if (b / a == 1) x q[0];\nif (b / a == 1.5) x q[1];", "x q[0];"),
("x q[b / a];", "x q[1];"),
("rx(b / a) q[0];", "rx(1) q[0];"),
("int[32] n = -3;\nif (n / a == -1) x q[0];", "x q[0];"),
("int[32] m = -2;\nif (b / m == -1) x q[0];", "x q[0];"),
("uint[8] u = 7;\nuint[8] w = 2;\nrx(u / w) q[0];", "rx(3) q[0];"),
("const int[32] k = 7;\nconst int[32] m = 2;\nrx(k / m) q[0];", "rx(3) q[0];"),
("for int i in [3:3] { rx(i / a) q[0]; }", "rx(1) q[0];"),
("ry(pi * (b / a)) q[0];", "ry(3.141592653589793) q[0];"),
("rx(1 / 2) q[0];", "rx(0) q[0];"),
("rx(b / 2) q[0];", "rx(1) q[0];"),
("rx(3 / a) q[0];", "rx(1) q[0];"),
("rx(3 / 4 * pi) q[0];", "rx(0.0) q[0];"),
# gate parameters are angles and other types keep true division
("gate g(t) r { rx(t / 2) r; }\ng(3) q[0];", "rx(1.5) q[0];"),
("gate g(t) r { rx(t / 2) r; }\nint[32] n = 3;\ng(n) q[0];", "rx(1.5) q[0];"),
("ry(3.0 / a) q[0];", "ry(1.5) q[0];"),
("duration d = 1001ns;\nduration h = d / a;\ndelay[h] q[0];", "delay[500.5ns] q[0];"),
],
)
def test_integer_division_of_int_variables(statements, expected):
"""Integer literals and int and uint variables divide as integers; other operands keep true
division."""
qasm_str = f"""OPENQASM 3.0;
include "stdgates.inc";
qubit[2] q;
int[32] a = 2;
int[32] b = 3;
{statements}
"""
result = loads(qasm_str)
result.unroll()
check_unrolled_qasm(
dumps(result), f'OPENQASM 3.0;\ninclude "stdgates.inc";\nqubit[2] q;\n{expected}'
)


@pytest.mark.parametrize("to_qasm3", [False, True])
def test_openqasm2_division_stays_real(to_qasm3):
"""OpenQASM 2 has no integer type, so 1/2 stays 0.5, also after to_qasm3()."""
module = loads('OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[1];\nrx(1/2) q[0];\n')
if to_qasm3:
module = module.to_qasm3()
module.unroll()
assert "rx(0.5) q[0];" in dumps(module)


def test_to_qasm3_writes_literal_division_as_real():
"""The OpenQASM 3 text of an OpenQASM 2 program keeps 1/2 real when it is loaded again."""
module = loads(
'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[1];\nrx(1/2) q[0];\nrz(pi/2) q[0];\n'
)
text = module.to_qasm3(as_str=True)
assert "rx(1.0 / 2.0) q[0];" in text and "rz(pi / 2) q[0];" in text
assert dumps(module.to_qasm3()) == text
reloaded = loads(text)
reloaded.unroll()
assert "rx(0.5) q[0];" in dumps(reloaded)
Loading