Repository navigation
fix(expressions): divide int variables as integers - #474
HVSharma12 wants to merge 8 commits into
Conversation
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 reviewAuto-review is off for this repo. Tick the box below to run a review on this PR.
Estimated cost
Tip: you can also comment |
Signed-off-by: HVSharma12 <harshvardhan.sharma@suse.com>
|
Hi @HVSharma12 , thanks for making the changes! Could you please fix the CI failures before we start reviewing the code? |
|
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 |
There was a problem hiding this comment.
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 intdefcalls 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
mainsource: 9 failed (the integer cases), 7 passed (the true-division cases). - PR body reproducer
x q[b / a];:mainraisesKeyError: ('q', 1.5); PR head emitsx q[1];. rx(b / a):main1.5, PR head 1. Truncation toward zero:-3 / 2→ -1,3 / -2→ -1,-7 / 2→ -3.const int,for int,uintanddefint parameters also give integer results.- True division kept, as described:
1 / 2→ 0.5,b / 2→ 1.5,3 / a→ 1.5,g(3)withrx(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.
| 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 |
There was a problem hiding this comment.
[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:
- In
_is_integer_typed, treatIntegerLiteralas integer-typed only for OpenQASM 3 modules. AQasm2Modulemust keep true division. The prototype gated oncls.visitor_obj._module.original_program.version. - Bind gate parameters as reals in
QasmVisitor._visit_custom_gate_operation(visitor.py,param_map), sotransform_gate_paramssubstitutes aFloatLiteral:Visible side effect: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
gate g(t) r { rx(t) r; }withg(3)dumpsrx(3.0)instead ofrx(3). No existing test changes because of it. - Make
to_qasm3()keep OpenQASM 2 semantics. For example, emit integer literals inside classical expressions as float literals (1.0 / 2). - Update
tests/qasm3/resources/qasm/custom_gate_nested.qasm:17(2 + 3 - 1/5). Either write1.0/5and keep 4.8 intests/utils.py:548,550, or expect 5. - In this test: flip the three literal rows to
rx(0),rx(1)andrx(1). Addrx(3 / 4 * pi)→rx(0), an OpenQASM 2rx(1/2)→rx(0.5)row, and ato_qasm3()row. Keep bothg(3)andg(n)rows at 1.5. - Reword the CHANGELOG entry, which says "between two
intoruintvariables". Call out the user-visible changesrx(1/2)→rx(0)and3/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.
| return expression.op.name in ("+", "-", "*", "/", "%") and all( | ||
| cls._is_integer_typed(operand) for operand in (expression.lhs, expression.rhs) | ||
| ) | ||
| return False |
There was a problem hiding this comment.
[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>
|
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. |
| stmt.filename = "stdgates.inc" | ||
| break | ||
| qasm_program.version = "3.0" | ||
| _RealDivision().visit(qasm_program) |
There was a problem hiding this comment.
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>
|
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 Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Summary of changes
/between integers used Python true division. Reproducer, onmain: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
intoruintvariables, or+ - * / %of them. This coversfor intloop variables,const intanddefint parameters. Angles change too: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 g(t) r { rx(t / 2) r; }withg(3)is stillrx(1.5). The argument now binds as a float, sorx(t)in a body dumpsrx(3.0)instead ofrx(3).rx(1/2)staysrx(0.5), also afterto_qasm3(), which writes it asrx(1.0 / 2.0).3.0 / a,d / a).Casts to
int/uint, elements of integer arrays, bitwise and shift results,**andint-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.