From daab4b3a3886fb1909e65204d2866e9c8515aef1 Mon Sep 17 00:00:00 2001 From: HVSharma12 Date: Sat, 14 Nov 2026 05:05:26 +0530 Subject: [PATCH 1/5] fix(expressions): divide int variables as integers b / a with int[32] b = 3 and a = 2 gave 1.5 where the spec gives 1. Truncate toward zero when both operands are declared int or uint variables, or arithmetic of them. Signed-off-by: HVSharma12 --- CHANGELOG.md | 1 + src/pyqasm/expressions.py | 27 ++++++++++++++++++- tests/qasm3/test_expressions.py | 47 +++++++++++++++++++++++++++++++-- 3 files changed, 72 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36bc5130..678b0d23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ Types of changes: ### Removed ### Fixed +- `/` between two `int` or `uint` variables is now integer division, truncated toward zero, as the spec defines (`b / a; // 1`). This also changes angles: with `int[32] a = 2; int[32] b = 3;`, `rx(b / a)` is now `rx(1)`, was `rx(1.5)`. - `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)). diff --git a/src/pyqasm/expressions.py b/src/pyqasm/expressions.py index c6319f13..f5600c47 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,25 @@ 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 declared int or uint variables.""" + 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 +490,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/tests/qasm3/test_expressions.py b/tests/qasm3/test_expressions.py index b0c9cb04..11c66d0e 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,41 @@ 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];"), + # literals, gate parameters and other types keep true division + ("rx(1 / 2) q[0];", "rx(0.5) q[0];"), + ("rx(b / 2) q[0];", "rx(1.5) q[0];"), + ("rx(3 / a) q[0];", "rx(1.5) q[0];"), + ("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): + """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}' + ) From fbd624cf9f472e2b1a44638554c686bd36535d99 Mon Sep 17 00:00:00 2001 From: HVSharma12 Date: Sat, 14 Nov 2026 13:46:48 +0530 Subject: [PATCH 2/5] docs(changelog): link the pull request Signed-off-by: HVSharma12 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 678b0d23..3f68d585 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ Types of changes: ### Removed ### Fixed -- `/` between two `int` or `uint` variables is now integer division, truncated toward zero, as the spec defines (`b / a; // 1`). This also changes angles: with `int[32] a = 2; int[32] b = 3;`, `rx(b / a)` is now `rx(1)`, was `rx(1.5)`. +- `/` between two `int` or `uint` variables is now integer division, truncated toward zero, as the spec defines (`b / a; // 1`). This also changes angles: with `int[32] a = 2; int[32] b = 3;`, `rx(b / a)` is now `rx(1)`, was `rx(1.5)` ([#474](https://github.com/qBraid/pyqasm/pull/474)). - `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)). From 1f1b8659b374ae53832e025da3df8746abf71f14 Mon Sep 17 00:00:00 2001 From: HVSharma12 Date: Wed, 18 Nov 2026 11:58:30 +0530 Subject: [PATCH 3/5] fix(expressions): divide integer literals as integers too Integer literals are integers in OpenQASM 3, so rx(1 / 2) is rx(0). Gate parameters bind as reals because they are angles, and OpenQASM 2 keeps real division, also through to_qasm3(). Signed-off-by: HVSharma12 --- CHANGELOG.md | 2 +- src/pyqasm/expressions.py | 6 +++- src/pyqasm/modules/qasm2.py | 33 +++++++++++++++++++ src/pyqasm/visitor.py | 9 ++--- .../resources/qasm/custom_gate_nested.qasm | 2 +- tests/qasm3/test_expressions.py | 22 ++++++++++--- 6 files changed, 62 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f68d585..e1bf9f16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ Types of changes: ### Removed ### Fixed -- `/` between two `int` or `uint` variables is now integer division, truncated toward zero, as the spec defines (`b / a; // 1`). This also changes angles: with `int[32] a = 2; int[32] b = 3;`, `rx(b / a)` is now `rx(1)`, was `rx(1.5)` ([#474](https://github.com/qBraid/pyqasm/pull/474)). +- `/` 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 now writes `1/2` as `1.0 / 2.0` ([#474](https://github.com/qBraid/pyqasm/pull/474)). - `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)). diff --git a/src/pyqasm/expressions.py b/src/pyqasm/expressions.py index f5600c47..141575eb 100644 --- a/src/pyqasm/expressions.py +++ b/src/pyqasm/expressions.py @@ -144,7 +144,11 @@ def _check_var_type(cls, var_name, reqd_type, expression): @classmethod def _is_integer_typed(cls, expression) -> bool: - """Whether an expression is built only from declared int or uint variables.""" + """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 cls.visitor_obj._module.original_program.version != "2.0" if isinstance(expression, Identifier): assert cls.visitor_obj var = cls.visitor_obj._scope_manager.get_from_visible_scope(expression.name) diff --git a/src/pyqasm/modules/qasm2.py b/src/pyqasm/modules/qasm2.py index 3bb366d2..f8ad9e35 100644 --- a/src/pyqasm/modules/qasm2.py +++ b/src/pyqasm/modules/qasm2.py @@ -22,6 +22,7 @@ import openqasm3.ast as qasm3_ast from openqasm3.ast import Include, Program +from openqasm3.visitor import QASMTransformer from pyqasm.exceptions import ValidationError, raise_qasm3_error from pyqasm.modules.base import QasmModule, QasmVisitor @@ -29,6 +30,37 @@ from pyqasm.printer import Qasm2Printer, validate_branch +def _int_literal_arithmetic(expression) -> bool: + """Whether an expression combines only integer literals with + - * / %.""" + if isinstance(expression, qasm3_ast.IntegerLiteral): + return True + if isinstance(expression, qasm3_ast.UnaryExpression): + return expression.op.name == "-" and _int_literal_arithmetic(expression.expression) + if isinstance(expression, qasm3_ast.BinaryExpression): + return expression.op.name in ("+", "-", "*", "/", "%") and all( + _int_literal_arithmetic(operand) for operand in (expression.lhs, expression.rhs) + ) + return False + + +class _RealDivision(QASMTransformer[bool]): + """Turn the integer literals of a literal-only division into floats, so that OpenQASM 3 + keeps the real division OpenQASM 2 gives it (``1/2`` becomes ``1.0 / 2.0``).""" + + def visit_BinaryExpression(self, node, context=False): # pylint: disable=invalid-name + """Mark the operands of a division between integer literals.""" + in_division = context or (node.op.name == "/" and _int_literal_arithmetic(node)) + return self.generic_visit(node, in_division) + + def visit_IntegerLiteral(self, node, context=False): # pylint: disable=invalid-name + """Replace an integer literal inside a marked division with a float literal.""" + if not context: + return node + literal = qasm3_ast.FloatLiteral(float(node.value)) + literal.span = node.span + return literal + + class Qasm2Module(QasmModule): """ A module representing an openqasm2 quantum program. @@ -171,6 +203,7 @@ def to_qasm3(self, as_str: bool = False) -> str | Qasm3Module: stmt.filename = "stdgates.inc" break qasm_program.version = "3.0" + _RealDivision().visit(qasm_program) if as_str: return dumps(qasm_program, compact_gate_arguments=self._compact_gate_arguments) module = Qasm3Module(self._name, qasm_program) diff --git a/src/pyqasm/visitor.py b/src/pyqasm/visitor.py index 707d1158..330593ea 100644 --- a/src/pyqasm/visitor.py +++ b/src/pyqasm/visitor.py @@ -1360,10 +1360,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 11c66d0e..2b92cde3 100644 --- a/tests/qasm3/test_expressions.py +++ b/tests/qasm3/test_expressions.py @@ -224,10 +224,11 @@ def test_unknown_gate_reports_its_name_before_checking_operands( ("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];"), - # literals, gate parameters and other types keep true division - ("rx(1 / 2) q[0];", "rx(0.5) q[0];"), - ("rx(b / 2) q[0];", "rx(1.5) q[0];"), - ("rx(3 / a) q[0];", "rx(1.5) 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];"), @@ -235,7 +236,8 @@ def test_unknown_gate_reports_its_name_before_checking_operands( ], ) def test_integer_division_of_int_variables(statements, expected): - """int and uint variables divide as integers; other operands keep true division.""" + """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; @@ -248,3 +250,13 @@ def test_integer_division_of_int_variables(statements, expected): 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) From 5f7f857f4804fbd6766241b817efe100b845919e Mon Sep 17 00:00:00 2001 From: HVSharma12 Date: Wed, 18 Nov 2026 14:47:37 +0530 Subject: [PATCH 4/5] fix(expressions): keep OpenQASM 2 division real in the evaluator to_qasm3() no longer walks the program to rewrite integer literals. The module it returns carries a flag the expression evaluator reads, as Qasm2Module does, so 1/2 stays 0.5. Signed-off-by: HVSharma12 --- CHANGELOG.md | 2 +- src/pyqasm/expressions.py | 2 +- src/pyqasm/modules/base.py | 2 ++ src/pyqasm/modules/qasm2.py | 36 +++--------------------------------- 4 files changed, 7 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e1bf9f16..a3c12e76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ 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 now writes `1/2` as `1.0 / 2.0` ([#474](https://github.com/qBraid/pyqasm/pull/474)). +- `/` 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 in the module that `to_qasm3()` returns ([#474](https://github.com/qBraid/pyqasm/pull/474)). - `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)). diff --git a/src/pyqasm/expressions.py b/src/pyqasm/expressions.py index 141575eb..8f3c76bc 100644 --- a/src/pyqasm/expressions.py +++ b/src/pyqasm/expressions.py @@ -148,7 +148,7 @@ def _is_integer_typed(cls, expression) -> bool: if isinstance(expression, IntegerLiteral): # OpenQASM 2 has no integer type: every classical expression is real assert cls.visitor_obj - return cls.visitor_obj._module.original_program.version != "2.0" + 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) 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 f8ad9e35..99d627eb 100644 --- a/src/pyqasm/modules/qasm2.py +++ b/src/pyqasm/modules/qasm2.py @@ -22,7 +22,6 @@ import openqasm3.ast as qasm3_ast from openqasm3.ast import Include, Program -from openqasm3.visitor import QASMTransformer from pyqasm.exceptions import ValidationError, raise_qasm3_error from pyqasm.modules.base import QasmModule, QasmVisitor @@ -30,37 +29,6 @@ from pyqasm.printer import Qasm2Printer, validate_branch -def _int_literal_arithmetic(expression) -> bool: - """Whether an expression combines only integer literals with + - * / %.""" - if isinstance(expression, qasm3_ast.IntegerLiteral): - return True - if isinstance(expression, qasm3_ast.UnaryExpression): - return expression.op.name == "-" and _int_literal_arithmetic(expression.expression) - if isinstance(expression, qasm3_ast.BinaryExpression): - return expression.op.name in ("+", "-", "*", "/", "%") and all( - _int_literal_arithmetic(operand) for operand in (expression.lhs, expression.rhs) - ) - return False - - -class _RealDivision(QASMTransformer[bool]): - """Turn the integer literals of a literal-only division into floats, so that OpenQASM 3 - keeps the real division OpenQASM 2 gives it (``1/2`` becomes ``1.0 / 2.0``).""" - - def visit_BinaryExpression(self, node, context=False): # pylint: disable=invalid-name - """Mark the operands of a division between integer literals.""" - in_division = context or (node.op.name == "/" and _int_literal_arithmetic(node)) - return self.generic_visit(node, in_division) - - def visit_IntegerLiteral(self, node, context=False): # pylint: disable=invalid-name - """Replace an integer literal inside a marked division with a float literal.""" - if not context: - return node - literal = qasm3_ast.FloatLiteral(float(node.value)) - literal.span = node.span - return literal - - class Qasm2Module(QasmModule): """ A module representing an openqasm2 quantum program. @@ -74,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, @@ -203,11 +172,12 @@ def to_qasm3(self, as_str: bool = False) -> str | Qasm3Module: stmt.filename = "stdgates.inc" break qasm_program.version = "3.0" - _RealDivision().visit(qasm_program) if as_str: return dumps(qasm_program, compact_gate_arguments=self._compact_gate_arguments) 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]: From 77f81aa6b52179ec6ad37516bdef14e4d6264381 Mon Sep 17 00:00:00 2001 From: HVSharma12 Date: Wed, 18 Nov 2026 14:50:57 +0530 Subject: [PATCH 5/5] fix(printer): write OpenQASM 2 literal divisions as floats in OpenQASM 3 The text of a program converted with to_qasm3() said rx(1 / 2), which OpenQASM 3 divides as integers. The printer now writes rx(1.0 / 2.0) for such a module while it prints, with no extra pass. Signed-off-by: HVSharma12 --- CHANGELOG.md | 2 +- src/pyqasm/modules/qasm2.py | 6 +++- src/pyqasm/modules/qasm3.py | 58 +++++++++++++++++++++++++++++++-- tests/qasm3/test_expressions.py | 13 ++++++++ 4 files changed, 74 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a3c12e76..1b37bc1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ 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 in the module that `to_qasm3()` returns ([#474](https://github.com/qBraid/pyqasm/pull/474)). +- `/` 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()` 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)). diff --git a/src/pyqasm/modules/qasm2.py b/src/pyqasm/modules/qasm2.py index 99d627eb..73b4baff 100644 --- a/src/pyqasm/modules/qasm2.py +++ b/src/pyqasm/modules/qasm2.py @@ -173,7 +173,11 @@ 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 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/tests/qasm3/test_expressions.py b/tests/qasm3/test_expressions.py index 2b92cde3..fb993b9e 100644 --- a/tests/qasm3/test_expressions.py +++ b/tests/qasm3/test_expressions.py @@ -260,3 +260,16 @@ def test_openqasm2_division_stays_real(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)