Skip to content

Commit

Permalink
feat: restrict result tag sizes to 256 bytes (#596)
Browse files Browse the repository at this point in the history
Closes #595
  • Loading branch information
ss2165 authored Oct 28, 2024
1 parent 242fa44 commit 4e8e00f
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
8 changes: 8 additions & 0 deletions guppylang/prelude/_internal/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,10 @@ def check(self, args: list[ast.expr], ty: Type) -> tuple[ast.expr, Subst]:
raise InternalGuppyError(f"Invalid array type args: {type_args}")


#: Maximum length of a tag in the `result` function.
TAG_MAX_LEN = 200


class ResultChecker(CustomCallChecker):
"""Call checker for the `result` function."""

Expand All @@ -241,6 +245,10 @@ def synthesize(self, args: list[ast.expr]) -> tuple[ast.expr, Type]:
[tag, value] = args
if not isinstance(tag, ast.Constant) or not isinstance(tag.value, str):
raise GuppyTypeError("Expected a string literal", tag)
if len(tag.value.encode("utf-8")) > TAG_MAX_LEN:
raise GuppyTypeError(
f"Tag is too long, limited to {TAG_MAX_LEN} bytes", tag
)
value, ty = ExprSynthesizer(self.ctx).synthesize(value)
# We only allow numeric values or vectors of numeric values
err = (
Expand Down
7 changes: 7 additions & 0 deletions tests/error/misc_errors/result_tag_too_big.err
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Guppy compilation failed. Error in file $FILE:11

9: def foo(y: bool) -> None:
10: # each tick or cross is 3 bytes. The cross sends the tag over the limit.
11: result("✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅❌", y)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
GuppyTypeError: Tag is too long, limited to 200 bytes
11 changes: 11 additions & 0 deletions tests/error/misc_errors/result_tag_too_big.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from guppylang.prelude.builtins import result, py
from tests.util import compile_guppy

# TODO use this once https://github.com/CQCL/guppylang/issues/599 lands
# from guppylang.prelude._internal.checker import TAG_MAX_LEN
# BIG_TAG = "a" * (TAG_MAX_LEN + 1)

@compile_guppy
def foo(y: bool) -> None:
# each tick or cross is 3 bytes. The cross sends the tag over the limit.
result("✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅❌", y)

0 comments on commit 4e8e00f

Please sign in to comment.