guppylang
guppylang copied to clipboard
feat: Inout arguments
This is the dev branch for the inout argument feature (tracked by #282).
The idea is to allow explicit @inout annotations on function arguments that "give back" the passed value after the function returns:
@guppy
def foo(q: qubit @inout) -> None: ...
@guppy
def bar(q1: qubit @inout, q2: qubit @inout) -> bool: ...
@guppy
def main() -> None:
q1, q2 = qubit(), qubit()
foo(q1) # Desugars to `q1 = foo(q1)`
x = bar(q1, q2) # Desugars to `q1, q2, x = bar(q1, q2)`
y = bar(q1, q1) # Error: Linearity violation, q1 used twice
To enable this, we need to enforce that @inout arguments are not moved in the body of the function (apart from passing them in another @inout position). This means that the argument will always be bound to the same name and never aliased which allows us to desugar @inout functions like
@guppy
def bar(q1: qubit, q2: qubit) -> bool:
[body]
return [expr]
into
@guppy
def bar(q1: qubit, q2: qubit) -> tuple[qubit, qubit, bool]:
[body]
return q1, q2, [expr] # Linearity checker needs to ensure that q1, q2 are unused
Note that we only allow @inout annotations on linear types, since they would be useless for classical ones (unless we also implement an ownership system for classical values). Supporting them would make the checking logic more complicated without providing any meaningful benefit.
Tracked PRs:
- #315
- #316
- #349
- #344
- #321
- #331
- #350
- #339
- #340
- #351
Codecov Report
Attention: Patch coverage is 98.00797% with 5 lines in your changes missing coverage. Please review.
Project coverage is 92.50%. Comparing base (
536abf9) to head (288146b).
| Files | Patch % | Lines |
|---|---|---|
| guppylang/tys/parsing.py | 91.37% | 5 Missing :warning: |
Additional details and impacted files
@@ Coverage Diff @@
## main #311 +/- ##
==========================================
+ Coverage 92.32% 92.50% +0.18%
==========================================
Files 48 48
Lines 5014 5177 +163
==========================================
+ Hits 4629 4789 +160
- Misses 385 388 +3
:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.