Repository navigation
feat: Shared index resolution in AbstractProgramContext - #420
Merged
speller26 merged 2 commits intoOct 29, 2026
Merged
Conversation
Merged
5 tasks done
Add `AbstractProgramContext.resolve_index(name, value, index=None)`, which resolves one index into a sized target the same way for the simulator and for any subclass. The target can be a bit register, a sized `int` or `uint`, an array (its first dimension), or a qubit register, and its size comes from the declared type. Scalars, such as an unsized `bit`, and arrays with any zero dimension cannot be indexed, so they raise an `IndexError`. Types with no size, such as `float`, `bool` or an unsized `int`, raise a `TypeError`. The caller passes the index already evaluated in its own context, so loop variables, `int` variables and arithmetic expressions work. A negative index counts back from the end of the target, as in OpenQASM 3. An integer outside the target raises an `IndexError`, and a non-integer value raises a `TypeError`. A value that is a symbol, such as an unbound `input int`, is returned as the unevaluated index expression, so a context that builds circuits rather than running them can keep it symbolic. It is first checked to reference only `int` or `uint` variables, so `input float f; c[f]` raises a `TypeError`. To make that check possible, an unbound `input` is now declared with its own type instead of a placeholder type, still with a symbol as its value. The interpreter now resolves negative, computed and symbolic indexed measurement destinations with the helper. `c[-1] = measure q[0];` and destinations such as `c[n - 1]` crashed with `AttributeError: 'UnaryExpression' object has no attribute 'value'` (or 'BinaryExpression'), and `c[k] = measure q[0];` with `int k = -1;` was rejected as out of range. A non-negative integer index, and any index into an undeclared destination, is passed to the context's `add_measure` as before, so each context keeps its own range check. `ProgramContext` checks those with the helper as well, so a simulated destination such as `b[0]` on a scalar `bit b` is now an error. It also uses the helper for indexed bit writes such as `c[-1] = 0;`.
jheckey
force-pushed
the
fix/shared-index-resolution
branch
from
October 28, 2026 21:14
70fa2f9 to
1da05d5
Compare
speller26
reviewed
Oct 28, 2026
speller26
left a comment
Member
There was a problem hiding this comment.
Looks good, just have some questions.
| raise IndexError(f"'{name}' is a scalar bit and cannot be indexed.") | ||
| case BitType(size=size) | IntType(size=size) | UintType(size=size) if size: | ||
| return self._declared_size(name, size) | ||
| case ArrayType(dimensions=dimensions) | ArrayReferenceType(dimensions=list(dimensions)): |
Member
There was a problem hiding this comment.
interesting, didn't know you could match like
ArrayReferenceType(dimensions=list(dimensions))
Member
There was a problem hiding this comment.
Oh, this is treating list as a class pattern
- Drop the unneeded deepcopy before visiting a measurement index; expression visitors do not mutate the node. - A negative or symbolic index into an undeclared measurement destination now raises a NameError naming the undeclared destination, since resolving it needs the declared size. - resolve_index takes only the evaluated value. A symbolic index is checked with the sympy expression itself: its free symbols must be declared int or uint and its constants must be integers, so c[n + 0.5] is rejected. An expression that simplifies to a number, such as n - n, is resolved as that integer.
speller26
approved these changes
Oct 28, 2026
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #420 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 50 50
Lines 5135 5194 +59
Branches 602 620 +18
=========================================
+ Hits 5135 5194 +59 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Issue #, if available:
Follow-up to review feedback on amazon-braket/qiskit-braket-provider#411.
Description of changes:
qiskit-braket-provider#411 fixed
if (c[-1])crashing qiskit-braket-provider's condition resolver. A reviewer there asked for negative-index handling to live in the default simulator's program-context interface, so the simulator and qiskit-braket-provider support the same OpenQASM features. This PR adds that shared helper and uses it in the simulator.New
AbstractProgramContext.resolve_index(name, value) -> int | SymbolLiteral. It resolves one index intoname. The caller passesvalue, the index already evaluated in its own context:Target and size. The size comes from the target's declared type:
bit[n];int[n]oruint[n], for bit access;ArrayTypeor a subroutine'sArrayReferenceType;A declared size must be an integer literal or the name of a constant; any other size expression raises a
TypeError.Targets that can't be indexed.
bit(declared without a size, so size 0) raisesIndexError: 'b' is a scalar bit and cannot be indexed.array[float[32], 0]orarray[int[8], 2, 0]) raisesIndexError: 'a' has size zero and cannot be indexed.for both non-negative and negative indices. So does abit[0]orqubit[0]register.float,bool,complex, unsizedint,angle) raisesTypeError: 'g' of type FloatType is not indexable: it has no declared size.Evaluating the index. Because the caller evaluates the index, a loop variable, an
intvariable or an arithmetic expression such asc[n - 1]works. It does not have to be a compile-time constant. The helper itself needs no evaluator, so it works for anyAbstractProgramContextsubclass. That includes the Braket SDK'sBraketProgramContext, which has none. A negative index counts back from the end, as OpenQASM 3 specifies.Concrete results. The value must be an
IntegerLiteral; anything else, such as a float or bool, raisesTypeError: Index into 'c' must evaluate to an integer, got FloatLiteral.An integer outside[-size, size)raisesIndexError: Index 3 is out of range for 'c', which has size 3.Symbolic results. If the index evaluates to a symbol, such as an unbound
input int n(orn - 1), every free symbol in its sympy expression must be declaredintoruint, and every constant in it must be an integer. If so,valuecomes back as is, so a context that builds circuits instead of running them (qiskit-braket-provider's_QiskitProgramContext) can emit a symbolic condition. Otherwise it raises aTypeError, for exampleinput float f; c[f]givesIndex into 'c' must be an integer, but 'f' has type FloatType., andc[n + 0.5]givesIndex into 'c' must be an integer, got n + 0.5.A symbolic index that simplifies to a number, such asn - n, is resolved as that integer. To make this check possible, an unboundinputis now declared with its own (unevaluated) type instead of a placeholderSymbolLiteraltype. Its value is still a symbol.Other changes.
Measurement destinations. The interpreter now resolves negative, computed and symbolic destination indices with
resolve_index, passing the value it evaluated, including each element of a discrete set. A negative or symbolic index into an undeclared destination raisesNameError: Measurement destination 'c' is not declared, so its index -1 cannot be resolved., since resolving it needs the declared size. This fixes:c[-1] = measure q[0];andc[n - 1] = measure q[0];, which crashed withAttributeError: 'UnaryExpression' object has no attribute 'value'(or'BinaryExpression');c[k] = measure q[0];withint k = -1;, andc[{-1, 0}] = measure q;, which were rejected as out of range.A non-negative integer index, or any index into an undeclared destination, still goes to the context's
add_measureas before, so each context keeps its own range check.ProgramContextchecks those indices with the helper as well. So in the simulator, an out-of-range destination raises the helper'sIndexError,b[0] = measure q;on a scalarbit bis now an error, and an unboundinputused as a destination index raises a clearTypeError.Indexed bit writes in
ProgramContext(c[-1] = 0;) also use the helper.Not changed: indexed reads in conditions and expressions (
if (c[-1]),int x = c[-1];). These already accept negative and computed indices throughget_elements, which follows Python indexing and so matches OpenQASM for valid indices. An out-of-range read still raises a plainIndexError: list index out of range. Reads use the same path for MCM-dependent and ordinary expressions, so moving only MCM conditions onto the helper would make the two disagree. Qubit operands (x q[-1];) also keep their existingQubitTableresolution. Routing them through the helper would mean moving resolution out ofQubitTableinto the context, which is more than a minimal change. The helper does support qubit registers for callers that need it.Follow-up: strict bounds checking for the Braket SDK's
BraketProgramContext. It currently accepts out-of-range destinations, and itstest_from_ir_with_measurerelies on that.With this change qiskit-braket-provider can replace its private
_resolve_register_indexwithresolve_index. It also gets the negative-destination fix without any code change, since that path is in the shared interpreter.Testing done:
New unit tests:
In
test_program_context.py, tests call the helper directly:c[-1],c[-3], positive indices unchanged, anintvariable, a negated variable,n - 3), into arrays (array[int[8], 3] a; a[-1]gives 2), into a subroutine array reference, into a qubit register, and into sizedintanduint;bit, and size-zeroarray[float[32], 0],array[int[8], 2, 0],bit[0]andqubit[0], each with[0]and[-1];float,bool, unsizedintandcomplex;input int m,m - 1andm + nreturned unevaluated;input float fandm - fraisingTypeError, as do non-integer constants:m + 0.5,m / 2, andm + gwith a boundfloat g;m - m,m - m - 1) resolved as integers;TypeError), and unbound inputs keeping their declared types.They also cover destinations (
c[-1],c[-3],c[n - 3],c[{-1, 0}], out of range, a scalarbit) and an out-of-range indexed write.In
test_mcm.py, end-to-end runs of the program below and of variants that measure intoc[-1]or testc[-1] == 1; every shot measures11. There are also MCM conditions indexed by a loop variable,-i, anint, a negativeint,c[n - 1],c[n - 3] == 1, and an index computed from a measured value on each path, plus negative and computed destinations.In
test_interpreter.py, an undeclared destination with a non-negative index (c[1]) still reports the context's error, a negative index into one (c[-1],c[-2]) raises theNameErrorabove, a symbolicinput floatdestination index raisesTypeError, and a symbolicinput intdestination raises a clearTypeErrorin the simulator.tox -e clean,unit-tests,coverage-check: 2143 passed, 71 xfailed, 100% coverage.tox -e linters_check: "All checks passed!"ruff format --check .is clean. That needed a one-character fix to trailing whitespace already onmainin aprogram_context.pydocstring.Downstream checks against this branch:
circuits,devicesandparametricall pass. The rest of the suite has the same 16 failures and 2 errors underbraket/awsas againstmain, which come from the environment and are unrelated.Merge Checklist
Put an
xin the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request.General
Tests
By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.