Skip to content

Commit

Permalink
feat: Return already-compiled hugrs from GuppyModule.compile (#247)
Browse files Browse the repository at this point in the history
Closes #246 

I'm not sure where to add a test for this, as it's not integration nor
error testing.
  • Loading branch information
aborgna-q authored Jun 18, 2024
1 parent e0b40fb commit 9d01eae
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
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()

0 comments on commit 9d01eae

Please sign in to comment.