Skip to content

fix(expressions): divide int variables as integers - #474

Open
HVSharma12 wants to merge 8 commits into
qBraid:mainfrom
HVSharma12:bugfix-integer-division
Open

HVSharma12 wants to merge 8 commits into
qBraid:mainfrom
HVSharma12:bugfix-integer-division

Conversation

@HVSharma12

@HVSharma12 HVSharma12 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary of changes

/ between integers used Python true division. Reproducer, on main:

OPENQASM 3.0;
include "stdgates.inc";
qubit[2] q;
int[32] a = 2;
int[32] b = 3;
x q[b / a];   // KeyError: ('q', 1.5)

The spec defines / on integers as integer division (language/classical.rst, "Integers": b / a; // 1), and integer literals are integers (language/types.rst, "Literals").

The evaluator now truncates toward zero when both operands are integer literals or declared int or uint variables, or + - * / % of them. This covers for int loop variables, const int and def int parameters. Angles change too:

Input Before After
rx(1 / 2) rx(0.5) rx(0)
rx(3 / 4 * pi) rx(2.356194490192345) rx(0.0)
rx(b / 2), rx(3 / a) rx(1.5) rx(1)
rx(b / a) rx(1.5) rx(1)

Real division stays where the operands are not OpenQASM integers:

  • gate parameters, which are angles. gate g(t) r { rx(t / 2) r; } with g(3) is still rx(1.5). The argument now binds as a float, so rx(t) in a body dumps rx(3.0) instead of rx(3).
  • OpenQASM 2, which has no integer type. rx(1/2) stays rx(0.5), also after to_qasm3(), which writes it as rx(1.0 / 2.0).
  • floats and durations (3.0 / a, d / a).

Casts to int/uint, elements of integer arrays, bitwise and shift results, ** and int-returning subroutines are integer-typed too but still true-divide. That is tracked in #480.

The nested custom-gate fixture now writes 1.0/5, so its expected 4.8 stays.

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 <harshvardhan.sharma@suse.com>
@argus-eye

argus-eye Bot commented Nov 14, 2026

Copy link
Copy Markdown

Argus review

Auto-review is off for this repo. Tick the box below to run a review on this PR.

  • Trigger Argus review

Estimated cost

  • Files changed: 3
  • Diff lines (±): 75
  • Historical avg: ~337.1k tokens · ~$1.17 · across last 18 review(s)

Tip: you can also comment @argus-eye review at any time.

Signed-off-by: HVSharma12 <harshvardhan.sharma@suse.com>
@TheGupta2012

Copy link
Copy Markdown
Member

Hi @HVSharma12 , thanks for making the changes! Could you please fix the CI failures before we start reviewing the code?

@HVSharma12

Copy link
Copy Markdown
Contributor Author

Thanks for looking at it. The red jobs fail the same way on main and do not come from this change. openqasm3 1.0.2 came out on Nov 11 and rejects every OpenQASM 2 program (#472), which fails 126 tests. It also changed QASM3ParsingError, which causes the pylint error. The macos-14 job never started because GitHub retired that runner on Nov 2. I opened #475 to support openqasm3 1.0.2 and to move that job to macos-15. Once it is merged I'll update this branch and CI should pass.

@TheGupta2012 TheGupta2012 left a comment •

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.

Changes requested

Integer division for int/uint variables is correct and well tested. Integer literals must follow the same rule in this PR.

Findings

All findings are posted inline on the relevant lines. Checklist:

  • H1 — Integer literals must divide as integers; gate parameters and OpenQASM 2 stay real
  • L1 — Casts, int array elements, bitwise, ** and int def calls still true-divide

How it was tested

Python 3.13, openqasm3 1.0.1, openpulse 1.0.1, throwaway venv.

  • Full suite: main (d8680f7) 1047 passed, 3 skipped. PR head (fbd624c) 1063 passed, 3 skipped.
  • The new tests against main source: 9 failed (the integer cases), 7 passed (the true-division cases).
  • PR body reproducer x q[b / a];: main raises KeyError: ('q', 1.5); PR head emits x q[1];.
  • rx(b / a): main 1.5, PR head 1. Truncation toward zero: -3 / 2 → -1, 3 / -2 → -1, -7 / 2 → -3. const int, for int, uint and def int parameters also give integer results.
  • True division kept, as described: 1 / 2 → 0.5, b / 2 → 1.5, 3 / a → 1.5, g(3) with rx(t / 2) → 1.5, 3.0 / a → 1.5, d / a → 500.5ns.
  • Prototype of H1 (literal rule plus real-valued gate parameters): 1059 passed, 4 failed. All 4 are the expected-value updates listed in H1.

Next steps

Address H1 in this PR. L1 can go to a follow-up issue. Rebase after #475 merges; the red CI comes from openqasm3 1.0.2 (#472), not from this change.

Comment thread src/pyqasm/expressions.py
Comment on lines +146 to +162
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

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.

Comment thread src/pyqasm/expressions.py
return expression.op.name in ("+", "-", "*", "/", "%") and all(
cls._is_integer_typed(operand) for operand in (expression.lhs, expression.rhs)
)
return False

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.

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 <harshvardhan.sharma@suse.com>
@HVSharma12

Copy link
Copy Markdown
Contributor Author

Thanks, integer literals now divide as integers in OpenQASM 3, while gate parameters and OpenQASM 2 stay real. One small thing is that rx(3 / 4 * pi) prints as rx(0.0) since 0 * pi is a float. I opened #480 for the remaining cases.

Comment thread src/pyqasm/modules/qasm2.py Outdated
stmt.filename = "stdgates.inc"
break
qasm_program.version = "3.0"
_RealDivision().visit(qasm_program)

@TheGupta2012 TheGupta2012 Nov 18, 2026 •

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.

This visit is parsing the whole AST again, can you please find a better approach to handle this ? I believe updating the expression evaluator would be the way to go

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 <harshvardhan.sharma@suse.com>
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 <harshvardhan.sharma@suse.com>
@HVSharma12

Copy link
Copy Markdown
Contributor Author

Done, to_qasm3() no longer walks the program a second time and the expression evaluator handles it as you suggested, so 1/2 still unrolls to 0.5. I also made one small change in the printer so the converted text says 1.0 / 2.0 and keeps its meaning when loaded again, and I can drop that commit if you prefer.

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.87234% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/pyqasm/modules/qasm3.py 95.23% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants