From 2e3efb4f7e4ca65f7f277655c6f391423773aff6 Mon Sep 17 00:00:00 2001 From: gilch Date: Mon, 21 Oct 2024 19:48:39 -0600 Subject: [PATCH] Harmonize readerless env resolution Now uses _resolve_env() to walk up the stack like macroexpand and friends, and like evaluate/execute. It no longer makes an empty environment, you'd have to pass it explicitly. --- src/hissp/compiler.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/hissp/compiler.py b/src/hissp/compiler.py index e444fcde..83a56358 100644 --- a/src/hissp/compiler.py +++ b/src/hissp/compiler.py @@ -653,23 +653,24 @@ def _pairs(it: Iterable[T]) -> Iterable[tuple[T, T]]: raise CompileError("incomplete pair") from None -def readerless(form: object, env: Env | None = None) -> str: - """Compile a Hissp form to Python without evaluating it. - Uses the current `ENV` for context, unless an alternative is provided. - (Creates a temporary environment if neither is available.) - Returns the Python in a string. - """ - if env is None and (env := ENV.get()) is None: - env = {"__name__": "__main__"} - return Compiler(env=env, evaluate=False).compile([form]) - - def _resolve_env(env: Env | None = None) -> Env: if env is not None or (env := ENV.get()) is not None: return env return inspect.currentframe().f_back.f_back.f_globals +def readerless(form: object, env: Env | None = None) -> str: + """Compile a Hissp form to Python without evaluating it. + + Returns the compiled Python in a string. + + Unless an alternative ``env`` is specified, uses the current `ENV` + (available in a `macro_context`) when available, otherwise uses the + calling frame's globals. + """ + return Compiler(env=_resolve_env(env), evaluate=False).compile([form]) + + def evaluate(form: object, env: Env | None = None): """Convenience function to evaluate a Hissp form.