diff options
author | Jo-Philipp Wich <jo@mein.io> | 2020-09-17 13:57:22 +0200 |
---|---|---|
committer | Jo-Philipp Wich <jo@mein.io> | 2020-09-20 20:45:26 +0200 |
commit | 9a74b811f007986a3e6015af0c06b33147d05951 (patch) | |
tree | 43e794cb1f35582c98eab8f8a1f4d54299cf2557 /eval.c | |
parent | 2601b1e17f5ba2e15fb16e126ec5d22a39246649 (diff) |
eval: implement -m option to preload modules
The -m option instructs the interpreter to automatically require the named
module and to register the module context as global variable.
The following two commands are equivalent, with the former one serving as
a shortcut for the latter:
utpl -m fs -s '{{ fs.open("test.txt").read("all") }}'
utpl -s '{% fs = require("fs"); print(fs.open("test.txt").read("all")) %}'
Signed-off-by: Jo-Philipp Wich <jo@mein.io>
Diffstat (limited to 'eval.c')
-rw-r--r-- | eval.c | 20 |
1 files changed, 19 insertions, 1 deletions
@@ -1557,10 +1557,11 @@ ut_register_variable(struct json_object *scope, const char *key, struct json_obj } enum ut_error_type -ut_run(struct ut_state *state, struct json_object *env) +ut_run(struct ut_state *state, struct json_object *env, struct json_object *modules) { struct ut_op *op = ut_get_op(state, state->main); struct json_object *entry, *scope, *args, *rv; + size_t i; if (!op || op->type != T_FUNC) { ut_exception(state, state->main, "Runtime error: Invalid root operation in AST"); @@ -1589,6 +1590,23 @@ ut_run(struct ut_state *state, struct json_object *env) ut_lib_init(state, scope); args = json_object_new_array(); + + if (modules) { + for (i = 0; i < json_object_array_length(modules); i++) { + json_object_array_put_idx(args, 0, json_object_get(json_object_array_get_idx(modules, i))); + + rv = ut_invoke(state, state->main, NULL, + json_object_object_get(scope, "require"), + args); + + ut_register_variable(scope, + json_object_get_string(json_object_array_get_idx(modules, i)), + rv); + } + + json_object_array_del_idx(args, 0, 1); + } + rv = ut_invoke(state, state->main, NULL, entry, args); json_object_put(entry); |