Skip to content

Instantly share code, notes, and snippets.

@sogaiu
Last active February 25, 2022 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sogaiu/8af89626f45420ef6b8add42778b5957 to your computer and use it in GitHub Desktop.
Save sogaiu/8af89626f45420ef6b8add42778b5957 to your computer and use it in GitHub Desktop.
Janet Module Loader Notes

Janet Module Loader Notes

Links Between JANET_PATH and import*

module/paths

@[(<function is-cached> :preload <function check-is-dep>)
  (":cur:/:all:.jimage" :image <function check-relative>)
  (":cur:/:all:.janet" :source <function check-relative>)
  (":cur:/:all:/init.janet" :source <function check-relative>)
  (":cur:/:all::native:" :native <function check-relative>)
  (":sys:/:all:.jimage" :image <function check-is-dep>)
  (":sys:/:all:.janet" :source <function check-is-dep>)
  (":sys:/:all:/init.janet" :source <function check-is-dep>)
  (":sys:/:all::native:" :native <function check-is-dep>)
  (".:all:.jimage" :image <function check-project-relative>)
  (".:all:.janet" :source <function check-project-relative>)
  (".:all:/init.janet" :source <function check-project-relative>)
  (".:all::native:" :native <function check-project-relative>)]

Some examples:

repl:1:> (module/expand-path "hello" ":cur:/:all:.janet")
@"hello.janet"
repl:2:> (module/expand-path "hello" ":sys:/:all:.janet")
@"/home/user/.local/lib/janet/hello.janet"
repl:3:> (module/expand-path "hello" ":sys:/:dir:.janet")
@"/home/user/.local/lib/janet/.janet"
repl:4:> (module/expand-path "hello" ":sys:/:name:.janet")
@"/home/user/.local/lib/janet/hello.janet"
repl:5:> (module/expand-path "hello" "./:name:.janet")
@"hello.janet"
repl:6:> (module/expand-path "hello" "./:name::native:")
@"hello.so"

See janet_core_expand_path in corelib.c for more details.

The check-* functions:

(defn- check-relative [x]
  (if (string/has-prefix? "." x)
    x))

(defn- check-is-dep [x]
  (unless (or (string/has-prefix? "/" x) 
              (string/has-prefix? "." x))
    x))

(defn- check-project-relative [x]
  (if (string/has-prefix? "/" x)
    x))

module/loaders

(def module/loaders
  `A table of loading method names to loading functions.
  This table lets require and import load many different kinds
  of files as modules.`
  @{:native (fn native-loader [path &] (native path (make-env)))
    :source (fn source-loader [path args]
              (put module/loading path true)
              (defer (put module/loading path nil)
                (dofile path ;args)))
    :preload (fn preload-loader [path & args]
               (when-let [m (in module/cache path)]
                 (if (function? m)
                   (set (module/cache path) (m path ;args))
                   m)))
    :image (fn image-loader [path &] (load-image (slurp path)))})

Examples

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment