-
Notifications
You must be signed in to change notification settings - Fork 14
feat: Expose BorrowArray
in hugr-py
#2425
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
"""Borrow array types and operations.""" | ||
|
||
from __future__ import annotations | ||
|
||
from dataclasses import dataclass | ||
from typing import cast | ||
|
||
import hugr.model as model | ||
from hugr import tys, val | ||
from hugr.std import _load_extension | ||
from hugr.utils import comma_sep_str | ||
|
||
EXTENSION = _load_extension("collections.borrow_arr") | ||
|
||
|
||
@dataclass(eq=False) | ||
class BorrowArray(tys.ExtType): | ||
"""Fixed `size` borrow array of `ty` elements.""" | ||
|
||
def __init__(self, ty: tys.Type, size: int | tys.TypeArg) -> None: | ||
if isinstance(size, int): | ||
size = tys.BoundedNatArg(size) | ||
|
||
err_msg = ( | ||
f"Borrow array size must be a bounded natural or a nat variable, not {size}" | ||
) | ||
match size: | ||
case tys.BoundedNatArg(_n): | ||
pass | ||
case tys.VariableArg(_idx, param): | ||
if not isinstance(param, tys.BoundedNatParam): | ||
raise ValueError(err_msg) # noqa: TRY004 | ||
case _: | ||
raise ValueError(err_msg) | ||
|
||
ty_arg = tys.TypeTypeArg(ty) | ||
|
||
self.type_def = EXTENSION.types["borrow_array"] | ||
self.args = [size, ty_arg] | ||
|
||
@property | ||
def ty(self) -> tys.Type: | ||
assert isinstance( | ||
self.args[1], tys.TypeTypeArg | ||
), "Borrow array elements must have a valid type" | ||
return self.args[1].ty | ||
|
||
@property | ||
def size(self) -> int | None: | ||
"""If the borrow array has a concrete size, return it. | ||
|
||
Otherwise, return None. | ||
""" | ||
if isinstance(self.args[0], tys.BoundedNatArg): | ||
return self.args[0].n | ||
return None | ||
|
||
def type_bound(self) -> tys.TypeBound: | ||
return tys.TypeBound.Linear | ||
|
||
|
||
# Note that only borrow array values with no elements borrowed should be emitted. | ||
@dataclass | ||
class BorrowArrayVal(val.ExtensionValue): | ||
"""Constant value for a statically sized borrow array of elements.""" | ||
|
||
v: list[val.Value] | ||
ty: BorrowArray | ||
|
||
def __init__(self, v: list[val.Value], elem_ty: tys.Type) -> None: | ||
self.v = v | ||
self.ty = BorrowArray(elem_ty, len(v)) | ||
|
||
def to_value(self) -> val.Extension: | ||
name = "BorrowArrayValue" | ||
# The value list must be serialized at this point, otherwise the | ||
# `Extension` value would not be serializable. | ||
vs = [v._to_serial_root() for v in self.v] | ||
element_ty = self.ty.ty._to_serial_root() | ||
serial_val = {"values": vs, "typ": element_ty} | ||
return val.Extension(name, typ=self.ty, val=serial_val) | ||
|
||
def __str__(self) -> str: | ||
return f"borrow_array({comma_sep_str(self.v)})" | ||
|
||
def to_model(self) -> model.Term: | ||
return model.Apply( | ||
"collections.borrow_array.const", | ||
[ | ||
model.Literal(len(self.v)), | ||
cast(model.Term, self.ty.ty.to_model()), | ||
model.List([value.to_model() for value in self.v]), | ||
], | ||
) |
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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wonder if there is any way this could be asserted in this code or tested below, maybe not? For me, not being familiar with this code, this comment makes me wonder what the restrictions mean concretely in the kind of code that I would be allowed to write. Might just be my ignorance though, so feel free to ignore :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, this is something that should be handled in the future in some form (#2437)