From 7c203abe4d6d4225e5ef87e7c77891e7f42991df Mon Sep 17 00:00:00 2001 From: Kodi Arfer Date: Sat, 25 Mar 2017 18:07:45 -0700 Subject: [PATCH] Fix bug with unset __name__ of one-line functions The bug was a regression that I introduced in #1228. I've created a new special form named `fn*` that works like the old `fn` (that is, it always creates a `FunctionDef`). Since this is intended only for internal use, like `with*`, I haven't documented it. --- hy/compiler.py | 8 ++++++-- hy/core/bootstrap.hy | 2 +- tests/native_tests/language.hy | 13 +++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/hy/compiler.py b/hy/compiler.py index 63254a7..88c6ec7 100644 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -2297,9 +2297,13 @@ class HyASTCompiler(object): return ret @builds("fn") + @builds("fn*") + # The starred version is for internal use (particularly, in the + # definition of `defn`). It ensures that a FunctionDef is + # produced rather than a Lambda. @checkargs(min=1) def compile_function_def(self, expression): - expression.pop(0) + force_functiondef = expression.pop(0) == "fn*" arglist = expression.pop(0) if not isinstance(arglist, HyList): @@ -2376,7 +2380,7 @@ class HyASTCompiler(object): defaults=defaults) body = self._compile_branch(expression) - if not body.stmts: + if not force_functiondef and not body.stmts: ret += ast.Lambda( lineno=expression.start_line, col_offset=expression.start_column, diff --git a/hy/core/bootstrap.hy b/hy/core/bootstrap.hy index 4b07e91..f33de9b 100644 --- a/hy/core/bootstrap.hy +++ b/hy/core/bootstrap.hy @@ -46,7 +46,7 @@ (macro-error name "defn takes a name as first argument")) (if (not (isinstance lambda-list hy.HyList)) (macro-error name "defn takes a parameter list as second argument")) - `(setv ~name (fn ~lambda-list ~@body))) + `(setv ~name (fn* ~lambda-list ~@body))) (defmacro if-python2 [python2-form python3-form] "If running on python2, execute python2-form, else, execute python3-form" diff --git a/tests/native_tests/language.hy b/tests/native_tests/language.hy index c4ae6e0..013ef1e 100644 --- a/tests/native_tests/language.hy +++ b/tests/native_tests/language.hy @@ -900,6 +900,19 @@ (assert (= 43 (my-fun 42)))) +(defn test-defn-dunder-name [] + "NATIVE: test that defn preserves __name__" + + (defn phooey [x] + (+ x 1)) + (assert (= phooey.__name__ "phooey")) + + (defn mooey [x] + (+= x 1) + x) + (assert (= mooey.__name__ "mooey"))) + + (defn test-mangles [] "NATIVE: test mangles" (assert (= 2 ((fn [] (+ 1 1))))))