Handle empty defmain args

Closes hylang/hy#1707.
This commit is contained in:
Brandon T. Willard 2018-11-26 13:17:32 -06:00
parent 9efd2a9d61
commit b8b02c9df9
2 changed files with 37 additions and 7 deletions

View File

@ -223,11 +223,17 @@ Such 'o!' params are available within `body` as the equivalent 'g!' symbol."
(defmacro defmain [args &rest body]
"Write a function named \"main\" and do the 'if __main__' dance"
(setv retval (gensym))
"Write a function named \"main\" and do the 'if __main__' dance.
The symbols in `args` are bound to the elements in `sys.argv`, which means that
the first symbol in `args` will always take the value of the script/executable
name (i.e. `sys.argv[0]`).
"
(setv retval (gensym)
restval (gensym))
`(when (= --name-- "__main__")
(import sys)
(setv ~retval ((fn [~@args] ~@body) #* sys.argv))
(setv ~retval ((fn [~@(or args `[&rest ~restval])] ~@body) #* sys.argv))
(if (integer? ~retval)
(sys.exit ~retval))))

View File

@ -325,14 +325,38 @@
(global --name--)
(setv oldname --name--)
(setv --name-- "__main__")
(defn main []
(print 'Hy)
42)
(defn main [x]
(print (integer? x))
x)
(try
(defmain [&rest args]
(main))
(main 42))
(assert False)
(except [e SystemExit]
(assert (= (str e) "42"))))
;; Try a `defmain` without args
(try
(defmain []
(main 42))
(assert False)
(except [e SystemExit]
(assert (= (str e) "42"))))
;; Try a `defmain` with only one arg
(import sys)
(setv oldargv sys.argv)
(try
(setv sys.argv [1])
(defmain [x]
(main x))
(assert False)
(except [e SystemExit]
(assert (= (str e) "1"))))
(setv sys.argv oldargv)
(setv --name-- oldname))
(defn test-macro-namespace-resolution []