Skip to content
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

feat: Return already-compiled hugrs from GuppyModule.compile #247

Merged
merged 2 commits into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions guppylang/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ class GuppyModule:
# Whether the module has already been compiled
_compiled: bool

# If the hugr has already been compiled, keeps a reference that can be returned
# from `compile`.
_compiled_hugr: Hugr | None

# Map of raw definitions in this module
_raw_defs: dict[DefId, RawDef]
_raw_type_defs: dict[DefId, RawDef]
Expand All @@ -61,6 +65,7 @@ def __init__(self, name: str, import_builtins: bool = True):
self._imported_globals = Globals.default()
self._imported_compiled_globals = {}
self._compiled = False
self._compiled_hugr = None
self._instance_func_buffer = None
self._raw_defs = {}
self._raw_type_defs = {}
Expand Down Expand Up @@ -162,10 +167,11 @@ def _check_defs(
}

@pretty_errors
def compile(self) -> Hugr | None:
def compile(self) -> Hugr:
"""Compiles the module and returns the final Hugr."""
if self.compiled:
raise GuppyError("Module has already been compiled")
assert self._compiled_hugr is not None, "Module is compiled but has no Hugr"
return self._compiled_hugr

# Type definitions need to be checked first so that we can use them when parsing
# function signatures etc.
Expand Down Expand Up @@ -201,6 +207,7 @@ def compile(self) -> Hugr | None:
defn.compile_inner(graph, all_compiled_globals)

self._compiled = True
self._compiled_hugr = graph
return graph

def contains(self, name: str) -> bool:
Expand Down
13 changes: 13 additions & 0 deletions tests/integration/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,16 @@ def func_name() -> None: ...
if isinstance(n.op.root, ops.FuncDecl)
]
assert def_op.name == "func_name"


def test_compile_again():
module = GuppyModule("test")

@guppy(module)
def identity(x: int) -> int:
return x

hugr = module.compile()

# Compiling again should return the same Hugr
assert hugr is module.compile()
Loading