From 2ad2d5a41828a0c8d1f75f1488b7b47a540d8819 Mon Sep 17 00:00:00 2001 From: "Zack M. Davis" Date: Sun, 26 Apr 2015 15:57:08 -0700 Subject: [PATCH] fix keyword lambda values by retaining statements in Result MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As reported in issue #748, there was a bug in which passing a lambda as the value of a :keyword argument would fail— $ hy --spy hy 0.10.1 using CPython(default) 3.4.0 on Linux => (sorted (range 10) :key (fn [x] (- x))) from hy.core.language import range sorted(range(10), key=_hy_anon_fn_1) Traceback (most recent call last): File "", line 1, in NameError: name '_hy_anon_fn_1' is not defined The function call would appear in the generated AST without being preceded by the appropriate function definition corresponding to the anonymous function argument value in the Hy source, causing either a NameError (as in the example above), or erroneous reuse of whatever function was already pointed to by the `_hy_anon_fn_` name referenced in the list of keywords passed to `ast.Call`. This commit aims to fix the problem by handling it in same way that the expression/statement gap is bridged many other places in the compiler, by adding the compiled value of the keyword argument to the Result object being built during `_compile_collect`, with the understanding that any Python statements implied by the argument value will be appropriately preserved therein. --- hy/compiler.py | 1 + tests/native_tests/language.hy | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/hy/compiler.py b/hy/compiler.py index 8eb2291..50b2b7e 100644 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -462,6 +462,7 @@ class HyASTCompiler(object): raise HyCompileError(msg.format(kw=str(expr))) compiled_value = self.compile(value) + ret += compiled_value # no unicode for py2 in ast names keyword = str(expr[2:]) diff --git a/tests/native_tests/language.hy b/tests/native_tests/language.hy index d75e267..3fce18b 100644 --- a/tests/native_tests/language.hy +++ b/tests/native_tests/language.hy @@ -1140,7 +1140,8 @@ (assert (= (kwtest :key "value") {"key" "value"})) (assert (= (kwtest :key-with-dashes "value") {"key_with_dashes" "value"})) (assert (= (kwtest :result (+ 1 1)) {"result" 2})) - (assert (= (kwtest :key (kwtest :key2 "value")) {"key" {"key2" "value"}}))) + (assert (= (kwtest :key (kwtest :key2 "value")) {"key" {"key2" "value"}})) + (assert (= ((get (kwtest :key (fn [x] (* x 2))) "key") 3) 6))) (defmacro identify-keywords [&rest elts] `(list