1
0
mirror of https://github.com/janet-lang/janet synced 2024-11-28 11:09:54 +00:00

Add merge-module to core.

This is a little utility used for manually importing modules.
It is responsible for taking the output of dofile, run-context, or
require and merging into another environment as if import was called.
This commit is contained in:
Calvin Rose 2020-11-27 00:16:54 -06:00
parent ca7c5b8b10
commit bfd2845077
2 changed files with 14 additions and 4 deletions

View File

@ -2,6 +2,7 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
## Unreleased - ??? ## Unreleased - ???
- Add `merge-module` to core.
- During installation and release, merge janetconf.h into janet.h for easier install. - During installation and release, merge janetconf.h into janet.h for easier install.
- Add `upscope` special form. - Add `upscope` special form.
- `os/execute` and `os/spawn` can take streams for redirecting IO. - `os/execute` and `os/spawn` can take streams for redirecting IO.

View File

@ -2489,11 +2489,22 @@
[path & args] [path & args]
(require-1 path args (struct ;args))) (require-1 path args (struct ;args)))
(defn merge-module
"Merge a module source into the target environment with a prefix, as with the import macro.
This lets users emulate the behavior of import with a custom module table.
If export is truthy, then merged functions are not marked as private. Returns
the modified target environment."
[target source &opt prefix export]
(loop [[k v] :pairs source :when (symbol? k) :when (not (v :private))]
(def newv (table/setproto @{:private (not export)} v))
(put target (symbol prefix k) newv))
target)
(defn import* (defn import*
"Function form of import. Same parameters, but the path "Function form of import. Same parameters, but the path
and other symbol parameters should be strings instead." and other symbol parameters should be strings instead."
[path & args] [path & args]
(def env (fiber/getenv (fiber/current))) (def env (curenv))
(def kargs (table ;args)) (def kargs (table ;args))
(def {:as as (def {:as as
:prefix prefix :prefix prefix
@ -2503,9 +2514,7 @@
(and as (string as "/")) (and as (string as "/"))
prefix prefix
(string (last (string/split "/" path)) "/"))) (string (last (string/split "/" path)) "/")))
(loop [[k v] :pairs newenv :when (symbol? k) :when (not (v :private))] (merge-module env newenv prefix ep))
(def newv (table/setproto @{:private (not ep)} v))
(put env (symbol prefix k) newv)))
(undef require-1) (undef require-1)