diff --git a/hy/core/macros.hy b/hy/core/macros.hy index 7634a37..c65233c 100644 --- a/hy/core/macros.hy +++ b/hy/core/macros.hy @@ -200,16 +200,14 @@ (defmacro defmain [args &rest body] "Write a function named \"main\" and do the if __main__ dance" - (let [[retval (gensym)]] - `(do - (defn main [~@args] - ~@body) - - (when (= --name-- "__main__") - (import sys) - (setv ~retval (apply main sys.argv)) - (if (integer? ~retval) - (sys.exit ~retval)))))) + (let [[retval (gensym)] + [mainfn `(fn [~@args] + ~@body)]] + `(when (= --name-- "__main__") + (import sys) + (setv ~retval (apply ~mainfn sys.argv)) + (if (integer? ~retval) + (sys.exit ~retval))))) (defmacro-alias [defn-alias defun-alias] [names lambda-list &rest body] diff --git a/tests/native_tests/native_macros.hy b/tests/native_tests/native_macros.hy index 9066f9b..018e019 100644 --- a/tests/native_tests/native_macros.hy +++ b/tests/native_tests/native_macros.hy @@ -259,3 +259,19 @@ (defn test-botsbuildbots [] (assert (> (len (first (Botsbuildbots))) 50))) + + +(defn test-defmain [] + "NATIVE: make sure defmain is clean" + (global --name--) + (setv oldname --name--) + (setv --name-- "__main__") + (defn main [] + (print 'Hy) + 42) + (try + (defmain [&rest args] + (main)) + (except [e SystemExit] + (assert (= (str e) "42")))) + (setv --name-- oldname))