hy

Require macros from the same file in another macro


In the following code, given that hy seem to give a NameError when not explicitly requiring a macro's dependent macros, how do I require a macro in the same file in another macro?

(defmacro with-cwd [#* body] `(do ~@body))
(defmacro let-cwd [vars #* body] `(let ~vars (with-cwd ~@body)))

In a package called oreo, in a file called oreo.hy, I tried the following methods using (require oreo.oreo [with-cwd]), and none worked:

(defmacro let-cwd [vars #* body] (require oreo.oreo [with-cwd]) `(let ~vars (with-cwd ~@body)))

(defmacro let-cwd [vars #* body] `(let ~vars (require oreo.oreo [with-cwd]) (with-cwd ~@body)))

(defmacro let-cwd [vars #* body] `(let ~vars ~(require oreo.oreo [with-cwd]) (with-cwd ~@body)))

(defmacro let-cwd [vars #* body] `(do (require oreo.oreo [with-cwd]) (let ~vars (with-cwd ~@body))))

(defmacro let-cwd [vars #* body] `(do ~(require oreo.oreo [with-cwd]) (let ~vars (with-cwd ~@body))))

UPDATE: Upon request, I have modified the code to the point where the original problem still remains, but the code itself is significantly shorter.


Solution

  • The fourth version works, as noted by Kodiologist in their comment here; the final versions of two test files are therefore:

    ;; a.hy
    (defmacro with-cwd [#* body] `(do ~@body))
    (defmacro let-cwd [vars #* body] `(do (require oreo.oreo [with-cwd]) (let ~vars (with-cwd ~@body))))
    

    And:

    ;; b.hy
    (require a [let-cwd])
    (let-cwd [ string "Hello!" ] (print string))
    

    The second file then outputs Hello!.