diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e50acb8..b0afc62a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/pyqasm/expressions.py b/src/pyqasm/expressions.py index c6319f13..8f3c76bc 100644 --- a/src/pyqasm/expressions.py +++ b/src/pyqasm/expressions.py @@ -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 @@ -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 + @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. @@ -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) ) diff --git a/src/pyqasm/modules/base.py b/src/pyqasm/modules/base.py index cafd509f..06e54f2d 100644 --- a/src/pyqasm/modules/base.py +++ b/src/pyqasm/modules/base.py @@ -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: diff --git a/src/pyqasm/modules/qasm2.py b/src/pyqasm/modules/qasm2.py index 3bb366d2..73b4baff 100644 --- a/src/pyqasm/modules/qasm2.py +++ b/src/pyqasm/modules/qasm2.py @@ -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, @@ -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]: diff --git a/src/pyqasm/modules/qasm3.py b/src/pyqasm/modules/qasm3.py index f9bb0b59..47c675b1 100644 --- a/src/pyqasm/modules/qasm3.py +++ b/src/pyqasm/modules/qasm3.py @@ -23,11 +23,13 @@ from openqasm3.ast import ( BinaryExpression, BinaryOperator, + IntegerLiteral, Pragma, Program, QASMNode, QuantumGate, QuantumPhase, + UnaryExpression, ) from openqasm3.printer import Printer, PrinterState @@ -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 @@ -46,10 +61,19 @@ 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. @@ -57,12 +81,17 @@ def __init__( 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.""" @@ -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: @@ -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. @@ -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. diff --git a/src/pyqasm/visitor.py b/src/pyqasm/visitor.py index 09f36c37..9d7da902 100644 --- a/src/pyqasm/visitor.py +++ b/src/pyqasm/visitor.py @@ -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: diff --git a/tests/qasm3/resources/qasm/custom_gate_nested.qasm b/tests/qasm3/resources/qasm/custom_gate_nested.qasm index 918c5d99..472a3e30 100644 --- a/tests/qasm3/resources/qasm/custom_gate_nested.qasm +++ b/tests/qasm3/resources/qasm/custom_gate_nested.qasm @@ -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]; diff --git a/tests/qasm3/test_expressions.py b/tests/qasm3/test_expressions.py index b0c9cb04..fb993b9e 100644 --- a/tests/qasm3/test_expressions.py +++ b/tests/qasm3/test_expressions.py @@ -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(): @@ -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)