diff --git a/src/kirin/ir/group.py b/src/kirin/ir/group.py index b97ac7502..e9e72aba9 100644 --- a/src/kirin/ir/group.py +++ b/src/kirin/ir/group.py @@ -22,9 +22,10 @@ from kirin.ir.method import Method from kirin.ir.traits import SymbolTable, SymbolOpInterface from kirin.ir.exception import CompilerError, ValidationError +from kirin.serialization.jsonserializer import get_json_serializer if TYPE_CHECKING: - from kirin.ir import Dialect, Statement + from kirin.ir import Method, Dialect, Statement from kirin.lowering import Python from kirin.registry import Registry from kirin.serialization.base.serializer import Serializer @@ -330,6 +331,14 @@ def decode(self, encoded: "SerializationModule") -> Method: deserializer = Deserializer(dialect_group=self) return deserializer.decode(encoded) + def encode_json(self, program: Method) -> str: + encoded_module = self.encode(program) + return get_json_serializer().encode(encoded_module) + + def decode_json(self, json_str: str) -> Method: + decoded_module = get_json_serializer().decode(json_str) + return self.decode(decoded_module) + def dialect_group( dialects: Iterable[Union["Dialect", ModuleType]], diff --git a/src/kirin/serialization/jsonserializer.py b/src/kirin/serialization/jsonserializer.py index db737d828..a173b0d8b 100644 --- a/src/kirin/serialization/jsonserializer.py +++ b/src/kirin/serialization/jsonserializer.py @@ -1,5 +1,5 @@ import json -from typing import Any +from typing import Any, Optional from kirin.serialization.core.serializationunit import SerializationUnit from kirin.serialization.core.serializationmodule import SerializationModule @@ -74,3 +74,14 @@ def decode(self, data: str) -> SerializationModule: if not isinstance(result, SerializationModule): raise TypeError("decoded payload is not a SerializationModule") return result + + +_json_serializer_instance: Optional[JSONSerializer] = None + + +def get_json_serializer() -> JSONSerializer: + """Lazily return a single JSONSerializer instance (module-level singleton).""" + global _json_serializer_instance + if _json_serializer_instance is None: + _json_serializer_instance = JSONSerializer() + return _json_serializer_instance