guppylang icon indicating copy to clipboard operation
guppylang copied to clipboard

Borrow error when indexing with nat

Open doug-q opened this issue 1 month ago • 2 comments

@guppy.struct
class Iceberg(Generic[n]):
    top: qubit
    bottom: qubit
    block: array[qubit, n]

    @guppy
    def cx(self, q: nat) -> None:
        cx(self.bottom, self.block[q])

gives

Error: Not able to borrow subscripted elements (at /home/doug/code/iceberg-repro/repro.gpy.py:21:24)
   | 
19 |     @guppy
20 |     def cx(self, q: nat) -> None:
21 |         cx(self.bottom, self.block[q])
   |                         ^^^^^^^^^^^^^ Expression of type `array[qubit, n]` is not able to borrow
   |                                       subscripted elements

Help: Fix signature of method `array[qubit, n].__setitem__`:  Expected
`(array[qubit, n], nat, qubit @owned) -> None`, got `forall L, n: nat. (array[L,
n], int, L @owned) -> None`

changing q: nat to q: int fixes the problem.

doug-q avatar Nov 25 '25 13:11 doug-q

This seems to be a problem with checking that __setitem__ has the correct signature: Passing nat instead of int seems to confuse the checker...

mark-koch avatar Nov 25 '25 13:11 mark-koch

Smaller reproducer:

@guppy
def foo(xs: array[qubit, 10], i: nat) -> None:
    h(xs[i])

mark-koch avatar Nov 26 '25 12:11 mark-koch