From b05a419e08dfcccf10fa081a22fc83af0d11502b Mon Sep 17 00:00:00 2001 From: tatiana-s Date: Thu, 19 Dec 2024 11:33:19 +0000 Subject: [PATCH] feat: Add `StringVal` to hugr-py (#1818) Closes #1817 Enables strings in Guppy, see CQCL/guppylang#695 --- hugr-py/src/hugr/std/prelude.py | 34 +++++++++++++++++++++++++++++++++ hugr-py/tests/test_prelude.py | 8 ++++++++ 2 files changed, 42 insertions(+) create mode 100644 hugr-py/src/hugr/std/prelude.py create mode 100644 hugr-py/tests/test_prelude.py diff --git a/hugr-py/src/hugr/std/prelude.py b/hugr-py/src/hugr/std/prelude.py new file mode 100644 index 000000000..efa17a955 --- /dev/null +++ b/hugr-py/src/hugr/std/prelude.py @@ -0,0 +1,34 @@ +"""HUGR prelude values.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from hugr import val +from hugr.std import _load_extension + +PRELUDE_EXTENSION = _load_extension("prelude") + +STRING_T_DEF = PRELUDE_EXTENSION.types["string"] + +STRING_T = STRING_T_DEF.instantiate([]) + + +@dataclass +class StringVal(val.ExtensionValue): + """Custom value for a string.""" + + v: str + + def to_value(self) -> val.Extension: + name = "ConstString" + payload = {"value": self.v} + return val.Extension( + name, + typ=STRING_T, + val=payload, + extensions=[PRELUDE_EXTENSION.name], + ) + + def __str__(self) -> str: + return f"{self.v}" diff --git a/hugr-py/tests/test_prelude.py b/hugr-py/tests/test_prelude.py new file mode 100644 index 000000000..a0f47ac5a --- /dev/null +++ b/hugr-py/tests/test_prelude.py @@ -0,0 +1,8 @@ +from hugr.std.prelude import STRING_T, StringVal + + +def test_string_val(): + ext_val = StringVal("test").to_value() + assert ext_val.name == "ConstString" + assert ext_val.typ == STRING_T + assert ext_val.val == {"value": "test"}