From 2f7d40b409997c041d43914bfd01db1c59cd1983 Mon Sep 17 00:00:00 2001 From: Nicolas Dandrimont Date: Fri, 3 Jan 2014 21:41:14 +0100 Subject: [PATCH] Factor the calling-module-name function --- hy/core/language.hy | 28 ++++++++++++++++------------ tests/native_tests/language.hy | 6 ++++++ 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/hy/core/language.hy b/hy/core/language.hy index 0b8b0d3..bf4fa54 100644 --- a/hy/core/language.hy +++ b/hy/core/language.hy @@ -119,6 +119,14 @@ (finally (.release _gensym_lock))) new_symbol)) +(defn calling-module-name [&optional [n 1]] + "Get the name of the module calling `n` levels up the stack from the + `calling-module-name` function call (by default, one level up)" + (import inspect) + + (setv f (get (.stack inspect) (+ n 1) 0)) + (get f.f_globals "__name__")) + (defn inc [n] "Increment n by 1" (_numeric-check n) @@ -153,20 +161,16 @@ (defn macroexpand [form] "Return the full macro expansion of form" - (import inspect) (import hy.macros) - (setv f (get (get (.stack inspect) 1) 0)) - (setv name (get f.f_globals "__name__")) + (setv name (calling-module-name)) (hy.macros.macroexpand form name)) (defn macroexpand-1 [form] "Return the single step macro expansion of form" - (import inspect) (import hy.macros) - (setv f (get (get (.stack inspect) 1) 0)) - (setv name (get f.f_globals "__name__")) + (setv name (calling-module-name)) (hy.macros.macroexpand-1 form name)) (defn neg? [n] @@ -272,9 +276,9 @@ (_numeric_check n) (= n 0)) -(def *exports* '[cycle dec distinct drop drop-while empty? even? filter - flatten float? gensym inc instance? integer integer? - iterable? iterate iterator? macroexpand macroexpand-1 - neg? nil? none? nth numeric? odd? pos? remove repeat - repeatedly second string string? take take-nth - take-while zero?]) +(def *exports* '[calling-module-name cycle dec distinct drop + drop-while empty? even? filter flatten float? gensym + inc instance? integer integer? iterable? iterate + iterator? macroexpand macroexpand-1 neg? nil? none? + nth numeric? odd? pos? remove repeat repeatedly second + string string? take take-nth take-while zero?]) diff --git a/tests/native_tests/language.hy b/tests/native_tests/language.hy index 952dc49..7153337 100644 --- a/tests/native_tests/language.hy +++ b/tests/native_tests/language.hy @@ -862,3 +862,9 @@ "Test macroexpand-1 on ->" (assert (= (macroexpand-1 '(-> (a b) (-> (c d) (e f)))) '(-> (a b) (c d) (e f))))) + + +(defn test-calling-module-name [] + "NATIVE: Test the calling-module-name function" + (assert (= (calling-module-name -1) "hy.core.language")) + (assert (= (calling-module-name 0) "tests.native_tests.language")))