Skip to content
Myr

Further module system revamp (fix #659)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

To import a module now use: # Import module.jq file: import "relative/path/to/module" as foo; # Use the module's defs as foo::<def-name> To import a JSON file: # Read file.json: import "relative/path/to/file" as $foo; # # Use as $foo::foo Using `-L` now drops the builtin library path and appends the requested path to the empty array (or the result of an earlier `-L`). Support for the `$JQ_LIBRARY_PATH` environment variable has been removed.

authored by Nicolas Williams · committed by Nicolas Williams · parent 7dc34b9 · Browse files · 13 files+347 added−203 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+347 added−203 removed

  • tests:+15 added−13 removed
  • other:+332 added−190 removed

13 files+347 added−203 removed

modified:docs/content/3.manual/manual.yml+66 added-36 removed
183 unmodified lines
184 awk's -f option. You can also use '#' to make comments.185186 * `-Ldirectory` / `-L directory`:187188 Add `directory` to the search list for modules. See the section189 on modules below.188 Prepend `directory` to the search list for modules. If this189 option is used then no builtin search list is used. See the190 section on modules below.191192 * `-e` / `--exit-status`:193194 Sets the exit status of jq to 0 if the last output values was
2279 unmodified lines
2474 - title: Modules2475 body: |24762477 jq has a library/module system. Modules are files whose names end2477 in `.jq`. Modules should (but don't have to) start with a2478 `module` directive. Programs and modules must `import` their2479 dependencies, if any.2478 in `.jq`.24792480 Modules imported by a program are searched for in a default search2481 path (see below). The `import` directive allows the importer to2482 alter this path.
13 unmodified lines
2496 Import directives can optionally specify a search path to which2497 the default is appended.24982499 The default search path is the search path given to the `-L`2501 command-line option, else the "$JQ_LIBRARY_PATH", if set in the2502 environment, else `["~/.jq", "$ORIGIN/../lib/jq"]` (on Unix) or2503 `["~/.jq", "$ORIGIN/lib"]` (on Windows).2500 command-line option, else `["~/.jq", "$ORIGIN/../lib/jq",2501 "$ORIGIN/../lib"]`.25022505 The `-L` argument's and "$JQ_LIBRARY_PATH" environment variable's2506 string values are split on ":" on Unix, or ";" on Windows.25072503 Null and empty string path elements terminate search path2504 processing.25052511 Modules may be organized into a hierarchy, with name components2512 separated by double-colons ("::"). For example: "foo::bar". Each2513 component in the name corresponds to a directory on the2514 filesystem.2506 A dependency with relative path "foo/bar" would be searched for in2507 "foo/bar.jq" and "foo/bar/bar.jq" in the given search path. This2508 is intended to allow modules to be placed in a directory along2509 with, for example, version control files, README files, and so on,2510 but also to allow for single-file modules.25112516 A module named "foo::bar" would be searched for in "foo/bar.jq"2517 and "foo/bar/bar.jq" in the given search path. This is intended to2518 allow modules to be placed in a directory along with, for example,2519 version control files, README files, and so on, but also to allow2520 for single-file modules.25212512 Consecutive components with the same name are not allowed to avoid2523 ambiguities (e.g., "foo::foo").2513 ambiguities (e.g., "foo/foo").25142515 For example, with `-L$HOME/.jq` a module `foo` can be found in2516 `$HOME/.jq/foo.jq` and `$HOME/.jq/foo/foo.jq`.25172518 If "$HOME/.jq" is a file, it is sourced into the main program.25192520 entries:2531 - title: "`module NAME {<metadata>};`"2521 - title: "`import RelativePathString as NAME;`"2522 body: |25232534 Defines a module named `NAME` with the given metadata. If2535 given it must be the first thing in the module. Programs also2536 may use this directive.2524 Imports a module found at the given path relative to a2525 directory in a search path. The module's symbols are prefixed2526 with "NAME::". A ".jq" suffix will be added to the relative2527 path string.25282529 - title: "`import RelativePathString as NAME {<metadata>};`"2530 body: |25312532 Imports a module found at the given path relative to a2533 directory in a search path. The module's symbols are prefixed2534 with "NAME::". A ".jq" suffix will be added to the relative2535 path string.25362537 The metadata must be a constant jq expression. It should be2539 an object with keys like "version", "repo", "URI", and so on.2540 At this time jq doesn't use this metadata, but it is made2541 available to users via the `modulemeta` builtin.2538 an object with keys like "homepage" and so on. At this time2539 jq only uses the "search" key/value of the metadate. The2540 metadata is also made available to users via the `modulemeta`2541 builtin.2542 2543 The "search" key in the metadata, if present, should have a2544 string or array value (array of strings); this is the search2545 path to be prefixed to the top-level search path.25462543 - title: "`import NAME {<metadata>};` `import NAME {<metadata>} as NAME;`"2547 - title: "`import RelativePathString as NAME;`"2548 body: |25492546 Imports a module named `NAME`. If the second form is used2547 then the module's symbols are prefixed with "NAME::".2550 Imports a JSON file found at the given path relative to a2551 directory in a search path. The file's data will be available2552 as `$NAME::NAME`. A ".json" suffix will be added to the2553 relative path string.25542555 - title: "`import RelativePathString as $NAME {<metadata>};`"2556 body: |25572558 Imports a JSON file found at the given path relative to a2559 directory in a search path. The file's data will be available2560 as `$NAME::NAME`. A ".json" suffix will be added to the2561 relative path string.25622563 The metadata must be a constant jq expression. It should be2550 an object with keys like "version", "repo", "URI", and so on.2564 an object with keys like "homepage" and so on. At this time2565 jq only uses the "search" key/value of the metadate. The2566 metadata is also made available to users via the `modulemeta`2567 builtin.2568 2569 The "search" key in the metadata, if present, should have a2570 string or array value (array of strings); this is the search2571 path to be prefixed to the top-level search path.25722573 - title: "`module {<metadata>};`"2574 body: |25752576 This directive is entirely optional. It's not required for2577 proper operation. It serves only the purpose of providing2578 metadata that can be read with the `modulemeta` builtin.25792580 The metadata must be a constant jq expression. It should be2581 an object with keys like "homepage". At this time jq doesn't2582 use this metadata, but it is made available to users via the2583 `modulemeta` builtin.25842585 - title: "`modulemeta`"2586 body: |25872559 Takes a module name as input and outputs the module's2560 metadata, with the module's imports (including metadata) as2561 the "deps" key.2588 Takes a module name as input and outputs the module's metadata2589 as an object, with the module's imports (including metadata)2590 as an array value for the "deps" key.25912592 Programs can use this to query a module's metadata, which they2593 could then use to, for example, search for, download, and2594 install missing dependencies.2595
modified:tests/modules/c/c.jq+9 added-7 removed
1module c {whatever:null};2import a as foo;3import d as d {search:"./"};4import d {search:"./"};5import e as e {search:"./../lib/jq"};6import f as f {search:"./../lib/jq"};1module {whatever:null};2import "a" as foo;3import "d" as d {search:"./"};4import "d" as d2{search:"./"};5import "e" as e {search:"./../lib/jq"};6import "f" as f {search:"./../lib/jq"};7import "data" as $d;8def a: 0;9def c:9 if meh != d::meh then error("import into namespace doesn't work")10 if $d::d[0] != {this:"is a test",that:"is too"} then error("data import is busted")11 elif d2::meh != d::meh then error("import twice doesn't work")12 elif foo::a != "a" then error("foo::a didn't work as expected")13 elif d::meh != "meh" then error("d::meh didn't work as expected")14 elif e::bah != "bah" then error("e::bah didn't work as expected")15 elif f::f != "f is here" then error("f::f didn't work as expected")
1 unmodified line
modified:tests/modules/a.jq+1 added-1 removed
1module a {version:1.7};1module {version:1.7};2def a: "a";
modified:tests/run+5 added-5 removed
157 unmodified lines
158 tail -1 $d/err | egrep -i 'assert|abort|core' && false159 fi160161 dd "if=tests/torture/input0.json" bs=$i count=1 2>/dev/null |162 $VALGRIND ./jq -cn --stream -L "$mods" 'import streaming; tovalues(inputs)' > $d/out1 2>$d/err || true162 $VALGRIND ./jq -cn --stream -L "$mods" 'import "streaming" as streaming; streaming::tovalues(inputs)' > $d/out1 2>$d/err || true163 if [ -n "$VALGRIND" ]; then164 grep '^==[0-9][0-9]*== ERROR SUMMARY: 0 errors' $d/err > /dev/null165 else166 tail -1 $d/err | egrep -i 'assert|abort|core' && false
32 unmodified lines
199 echo "Binding too many defs into program" 1>&2200 exit 1201fi202203if ! $VALGRIND $Q ./jq -ner -L "$mods" 'import a as foo; import b as bar; import a; def fooa: foo::a; [fooa, bar::a, bar::b, foo::a, a] | . == ["a","b","c","a","a"]' > /dev/null; then203if ! $VALGRIND $Q ./jq -ner -L "$mods" 'import "a" as foo; import "b" as bar; def fooa: foo::a; [fooa, bar::a, bar::b, foo::a] | . == ["a","b","c","a"]' > /dev/null; then204 echo "Module system appears to be broken" 1>&2205 exit 1206fi207208if ! $VALGRIND $Q ./jq -ner -L "$mods" 'import c as foo; [foo::a, foo::c] | . == [0,"acmehbah"]' > /dev/null; then208if ! $VALGRIND $Q ./jq -ner -L "$mods" 'import "c" as foo; [foo::a, foo::c] | . == [0,"acmehbah"]' > /dev/null; then209 echo "Module system appears to be broken" 1>&2210 exit 1211fi212213if [ "`$VALGRIND $Q ./jq -cner -L "$mods" '\"c\" | modulemeta'`" != '{"whatever":null,"name":"c","deps":[{"as":"foo","name":"a"},{"search":"./","as":"d","name":"d"},{"search":"./","name":"d"},{"search":"./../lib/jq","as":"e","name":"e"},{"search":"./../lib/jq","as":"f","name":"f"}]}' ]; then213if [ "`$VALGRIND $Q ./jq -cner -L "$mods" '\"c\" | modulemeta'`" != '{"whatever":null,"deps":[{"as":"foo","is_data":false,"relpath":"a"},{"search":"./","as":"d","is_data":false,"relpath":"d"},{"search":"./","as":"d2","is_data":false,"relpath":"d"},{"search":"./../lib/jq","as":"e","is_data":false,"relpath":"e"},{"search":"./../lib/jq","as":"f","is_data":false,"relpath":"f"},{"as":"d","is_data":true,"relpath":"data"}]}' ]; then214 echo "modulemeta builtin appears to be broken" 1>&2215 exit 1216fi217 218if $VALGRIND ./jq -ner -L "$mods" 'import syntaxerror; .' > $d/out 2>&1; then218if $VALGRIND ./jq -ner -L "$mods" 'import "syntaxerror" as e; .' > $d/out 2>&1; then219 echo "Module system appears to be broken" 1>&2220 exit 1221fi222if [ -n "$VALGRIND" ] && ! grep 'ERROR SUMMARY: 0 errors from 0 contexts' $d/out > /dev/null; then
32 unmodified lines
modified:builtin.c+18 added
822 unmodified lines
823 }824 return env;825}826827static jv f_get_search_list(jq_state *jq, jv input) {828 jv_free(input);829 return jq_get_lib_dirs(jq);830}831832static jv f_get_prog_origin(jq_state *jq, jv input) {833 jv_free(input);834 return jq_get_prog_origin(jq);835}836837static jv f_get_jq_origin(jq_state *jq, jv input) {838 jv_free(input);839 return jq_get_jq_origin(jq);840}841842static jv f_string_split(jq_state *jq, jv a, jv b) {843 if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING) {844 jv_free(a);845 jv_free(b);
105 unmodified lines
951 {(cfunction_ptr)f_max_by_impl, "_max_by_impl", 2},952 {(cfunction_ptr)f_error, "error", 2},953 {(cfunction_ptr)f_format, "format", 2},954 {(cfunction_ptr)f_env, "env", 1},955 {(cfunction_ptr)f_get_search_list, "get_search_list", 1},956 {(cfunction_ptr)f_get_prog_origin, "get_prog_origin", 1},957 {(cfunction_ptr)f_get_jq_origin, "get_jq_origin", 1},958 {(cfunction_ptr)f_match, "_match_impl", 4},959 {(cfunction_ptr)f_modulemeta, "modulemeta", 1},960 {(cfunction_ptr)f_input, "_input", 1},961 {(cfunction_ptr)f_debug, "debug", 1},
303 unmodified lines
modified:bytecode.c+1 added
7 unmodified lines
8// flags, length9#define NONE 0, 110#define CONSTANT OP_HAS_CONSTANT, 211#define VARIABLE (OP_HAS_VARIABLE | OP_HAS_BINDING), 312#define GLOBAL (OP_HAS_CONSTANT | OP_HAS_VARIABLE | OP_HAS_BINDING | OP_IS_CALL_PSEUDO), 413#define BRANCH OP_HAS_BRANCH, 214#define CFUNC (OP_HAS_CFUNC | OP_HAS_BINDING), 315#define UFUNC (OP_HAS_UFUNC | OP_HAS_BINDING | OP_IS_CALL_PSEUDO), 416#define DEFINITION (OP_IS_CALL_PSEUDO | OP_HAS_BINDING), 0
145 unmodified lines
modified:compile.c+41 added-18 removed
146 unmodified lines
147 i->imm.constant = constant;148 return inst_block(i);149}150151block gen_const_global(jv constant, const char *name) {152 assert((opcode_describe(STORE_GLOBAL)->flags & (OP_HAS_CONSTANT | OP_HAS_VARIABLE | OP_HAS_BINDING)) ==153 (OP_HAS_CONSTANT | OP_HAS_VARIABLE | OP_HAS_BINDING));154 inst* i = inst_new(STORE_GLOBAL);155 i->imm.constant = constant;156 i->symbol = strdup(name);157 return inst_block(i);158}159160int block_is_const(block b) {161 return (block_is_single(b) && b.first->op == LOADK);162}163
83 unmodified lines
247 }248 return 1;249}250251static int inst_is_binder(inst *i, int bindflags) {252 return !((opcode_describe(i->op)->flags & bindflags) != bindflags && i->op != MODULEMETA);253}254255int block_has_only_binders(block binders, int bindflags) {256 bindflags |= OP_HAS_BINDING;257 bindflags &= ~OP_BIND_WILDCARD;258 for (inst* curr = binders.first; curr; curr = curr->next) {
64 unmodified lines
323 // Check for break/break2/break3; see parser.y324 ((bindflags & OP_BIND_WILDCARD) && i->symbol[0] == '*' &&325 break_distance <= 3 && (i->symbol[1] == '1' + break_distance) &&326 i->symbol[2] == '\0'))) {314 if (bindflags & OP_BIND_WILDCARD) {315 jv_mem_free(i->symbol);316 i->symbol = strdup(binder.first->symbol);317 }327 // bind this instruction328 if (i->op == CALL_JQ && i->nactuals == -1)329 i->nactuals = block_count_actuals(i->arglist);330 if (i->nactuals == -1 || i->nactuals == binder.first->nformals) {
30 unmodified lines
361 return block_join(binder, body);362}363364block block_bind_library(block binder, block body, int bindflags, const char* libname) {356 assert(block_has_only_binders(binder, bindflags));365 bindflags |= OP_HAS_BINDING;366 int nrefs = 0;367 int matchlen = strlen(libname);368 char* matchname = calloc(1,matchlen+2+1);
1 unmodified line
370 strcpy(matchname,libname);371 strcpy(matchname+matchlen,"::");372 matchlen += 2;373 }374 assert(block_has_only_binders(binder, bindflags));375 for (inst *curr = binder.first; curr; curr = curr->next) {376 int bindflags2 = bindflags;377 char* cname = curr->symbol;378 char* tname = malloc(strlen(curr->symbol)+matchlen+1);379 strcpy(tname, matchname);380 strcpy(tname+matchlen,cname);381382 // Ew383 if ((opcode_describe(curr->op)->flags & (OP_HAS_VARIABLE | OP_HAS_CONSTANT)))384 bindflags2 = OP_HAS_VARIABLE | OP_HAS_BINDING;385386 // This mutation is ugly, even if we undo it387 curr->symbol = tname;372 nrefs += block_bind_subblock(inst_block(curr), body, bindflags, 0);388 nrefs += block_bind_subblock(inst_block(curr), body, bindflags2, 0);389 curr->symbol = cname;390 free(tname);391 }392 free(matchname);
62 unmodified lines
455jv block_take_imports(block* body) {456 jv imports = jv_array();457 458 inst* top = NULL;443 if (body->first->op == TOP) {459 if (body->first && body->first->op == TOP) {460 top = block_take(body);461 }462 while (body->first && (body->first->op == MODULEMETA || body->first->op == DEPS)) {463 inst* dep = block_take(body);464 if (dep->op == DEPS) {449 jv opts = jv_copy(dep->imm.constant);450 opts = jv_object_set(opts,jv_string("name"),jv_string(dep->symbol));451 imports = jv_array_append(imports, opts);465 imports = jv_array_append(imports, jv_copy(dep->imm.constant));466 }467 inst_free(dep);468 }469 if (top) {
1 unmodified line
471 }472 return imports;473}474461block gen_module(const char* name, block metadata) {475block gen_module(block metadata) {476 inst* i = inst_new(MODULEMETA);463 i->symbol = strdup(name);477 i->imm.constant = block_const(metadata);478 if (jv_get_kind(i->imm.constant) != JV_KIND_OBJECT)479 i->imm.constant = jv_object_set(jv_object(), jv_string("metadata"), i->imm.constant);467 i->imm.constant = jv_object_set(i->imm.constant, jv_string("name"), jv_string(name));480 block_free(metadata);481 return inst_block(i);482}483
2 unmodified lines
486 return jv_copy(b.first->imm.constant);487 return jv_null();488}489478block gen_import(const char* name, block metadata, const char* as) {490block gen_import(const char* name, block metadata, const char* as, int is_data) {491 assert(metadata.first == NULL || block_is_const(metadata));492 inst* i = inst_new(DEPS);481 i->symbol = strdup(name);493 jv meta;494 if (block_is_const(metadata))495 meta = block_const(metadata);496 else497 meta = jv_object();487 if (as)488 meta = jv_object_set(meta, jv_string("as"), jv_string(as));498 meta = jv_object_set(meta, jv_string("as"), jv_string(as));499 meta = jv_object_set(meta, jv_string("is_data"), is_data ? jv_true() : jv_false());500 meta = jv_object_set(meta, jv_string("relpath"), jv_string(name));501 i->imm.constant = meta;502 block_free(metadata);503 return inst_block(i);504}
303 unmodified lines
808 gen_const(jv_false())))));809}810811block gen_var_binding(block var, const char* name, block body) {812 // var bindings can be added after coding the program; leave the TOP first.813 block top = gen_noop();814 if (body.first && body.first->op == TOP)815 top = inst_block(block_take(&body));800 return BLOCK(gen_op_simple(DUP), var,816 return BLOCK(top, gen_op_simple(DUP), var,817 block_bind(gen_op_unbound(STOREV, name),818 body, OP_HAS_VARIABLE));819}820
278 unmodified lines
1099 assert(arg->op == CLOSURE_REF && arg->bound_by->op == CLOSURE_CREATE);1100 code[pos++] = nesting_level(bc, arg->bound_by);1101 code[pos++] = arg->bound_by->imm.intval | ARG_NEWCLOSURE;1102 }1103 } else if ((op->flags & OP_HAS_CONSTANT) && (op->flags & OP_HAS_VARIABLE)) {1104 // STORE_GLOBAL: constant global, basically1105 code[pos++] = jv_array_length(jv_copy(constant_pool));1106 constant_pool = jv_array_append(constant_pool, jv_copy(curr->imm.constant));1107 code[pos++] = nesting_level(bc, curr->bound_by);1108 uint16_t var = (uint16_t)curr->bound_by->imm.intval;1109 code[pos++] = var;1110 } else if (op->flags & OP_HAS_CONSTANT) {1111 code[pos++] = jv_array_length(jv_copy(constant_pool));1112 constant_pool = jv_array_append(constant_pool, jv_copy(curr->imm.constant));1113 } else if (op->flags & OP_HAS_VARIABLE) {
47 unmodified lines
modified:compile.h+3 added-2 removed
18 unmodified lines
19block gen_noop();20int block_is_noop(block b);21block gen_op_simple(opcode op);22block gen_const(jv constant);23block gen_const_global(jv constant, const char *name);24int block_is_const(block b);25jv_kind block_const_kind(block b);26jv block_const(block b);27block gen_op_target(opcode op, block target);28block gen_op_unbound(opcode op, const char* name);29block gen_op_bound(opcode op, block binder);30block gen_op_var_fresh(opcode op, const char* name);3131block gen_module(const char* name, block metadata);32block gen_module(block metadata);33jv block_module_meta(block b);33block gen_import(const char* name, block metadata, const char *as);34block gen_import(const char* name, block metadata, const char *as, int is_data);35block gen_function(const char* name, block formals, block body);36block gen_param_regular(const char* name);37block gen_param(const char* name);38block gen_lambda(block body);
59 unmodified lines
modified:execute.c+19 added
506 unmodified lines
507 *var = val;508 break;509 }510511 case STORE_GLOBAL: {512 // Get the constant513 jv val = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);514 assert(jv_is_valid(val));515516 // Store the var517 uint16_t level = *pc++;518 uint16_t v = *pc++;519 jv* var = frame_local_var(jq, v, level);520 if (jq->debug_trace_enabled) {521 printf("V%d = ", v);522 jv_dump(jv_copy(val), 0);523 printf(" (%d)\n", jv_get_refcnt(val));524 }525 jv_free(*var);526 *var = val;527 break;528 }529530 case PATH_BEGIN: {531 jv v = stack_pop(jq);532 stack_push(jq, jq->path);533
560 unmodified lines
modified:linker.c+147 added-97 removed
19 unmodified lines
20 char **names;21 block *defs;22 uint64_t ct;23};24static int load_library(jq_state *jq, jv lib_path, block *out_block, struct lib_loading_state *lib_state);24static int load_library(jq_state *jq, jv lib_path, int is_data, int raw,25 const char *as, block *out_block,26 struct lib_loading_state *lib_state);272829// Given a lib_path to search first, creates a chain of search paths30// in the following order:31// 1. lib_path29// 2. -L paths passed in on the command line (from jq_state*)30// 3. JQ_LIBRARY_PATH environment variable31jv build_lib_search_chain(jq_state *jq, jv search_path) {32// 2. -L paths passed in on the command line (from jq_state*) or builtin list33static jv build_lib_search_chain(jq_state *jq, jv search_path, jv jq_origin, jv lib_origin) {34 assert(jv_get_kind(search_path) == JV_KIND_ARRAY);35 jv expanded = jv_array();36 jv expanded_elt;37 jv_array_foreach(search_path, i, path) {35 path = expand_path(path);36 if (jv_is_valid(path))37 expanded = jv_array_append(expanded, expand_path(path));38 else39 jv_free(path);38 if (strcmp(".",jv_string_value(path)) == 0) {39 expanded_elt = jv_copy(path);40 } else if (jv_get_kind(lib_origin) == JV_KIND_STRING &&41 strncmp("./", jv_string_value(path),sizeof("./")-1) == 0) {42 expanded_elt = jv_string_fmt("%s/%s",43 jv_string_value(lib_origin),44 jv_string_value(path) + sizeof ("./") - 1);45 } else if (strncmp("$ORIGIN/",jv_string_value(path),sizeof("$ORIGIN/")-1) == 0) {46 expanded_elt = jv_string_fmt("%s/%s",47 jv_string_value(jq_origin),48 jv_string_value(path) + sizeof ("$ORIGIN/") - 1);49 } else {50 expanded_elt = expand_path(path);51 if (!jv_is_valid(expanded_elt)) {52 jv_free(search_path);53 jv_free(expanded);54 jv_free(path);55 return expanded_elt;56 }57 path = jv_invalid();58 }59 expanded = jv_array_append(expanded, expanded_elt);60 jv_free(path);61 }62 jv_free(jq_origin);63 jv_free(lib_origin);64 jv_free(search_path);42 expanded = jv_array_concat(expanded, jq_get_lib_dirs(jq));65 return expanded;66}6746static jv name2relpath(jv name) {47 jv components = jv_string_split(jv_copy(name), jv_string("::"));68// Doesn't actually check that name not be an absolute path; we could69// just always prepend "./"!70static jv validate_relpath(jv name) {71 const char *s = jv_string_value(name);72 if (strchr(s, '\\')) {73 jv res = jv_invalid_with_msg(jv_string_fmt("Modules must be named by relative paths using '/', not '\\' (%s)", s));74 jv_free(name);75 return res;76 }77 jv components = jv_string_split(jv_copy(name), jv_string("/"));78 jv rp = jv_array_get(jv_copy(components), 0);79 components = jv_array_slice(components, 1, jv_array_length(jv_copy(components)));80 jv_array_foreach(components, i, x) {81 if (!strcmp(jv_string_value(x), "..")) {82 jv_free(x);83 jv_free(rp);84 jv_free(components);85 jv res = jv_invalid_with_msg(jv_string_fmt("Relative paths to modules may not traverse to parent directories (%s)", s));86 jv_free(name);87 return res;88 }89 if (i > 0 && jv_equal(jv_copy(x), jv_array_get(jv_copy(components), i - 1))) {90 jv_free(x);91 jv_free(rp);92 jv_free(components);
8 unmodified lines
101 jv_free(name);102 return rp;103}10467static jv find_lib(jq_state *jq, jv lib_name, jv lib_search_path) {68 assert(jv_get_kind(lib_search_path) == JV_KIND_ARRAY);69 assert(jv_get_kind(lib_name) == JV_KIND_STRING);105// Assumes name has been validated106static jv jv_basename(jv name) {107 const char *s = jv_string_value(name);108 const char *p = strrchr(s, '/');109 if (!p)110 return name;111 jv res = jv_string_fmt("%s", p);112 jv_free(name);113 return res;114}11571 jv rel_path = name2relpath(jv_copy(lib_name));72 if (!jv_is_valid(rel_path)) {73 jv_free(lib_name);74 return rel_path;75 }116// Asummes validated relative path to module117static jv find_lib(jq_state *jq, jv rel_path, jv search, const char *suffix, jv jq_origin, jv lib_origin) {118 if (jv_get_kind(search) != JV_KIND_ARRAY)119 return jv_invalid_with_msg(jv_string_fmt("Module search path must be an array"));120 if (jv_get_kind(rel_path) != JV_KIND_STRING)121 return jv_invalid_with_msg(jv_string_fmt("Module path must be a string"));122123 struct stat st;124 int ret;12580 jv lib_search_paths = build_lib_search_chain(jq, lib_search_path);126 // Ideally we should cache this somewhere127 search = build_lib_search_chain(jq, search, jq_origin, lib_origin);128129 jv bname = jv_basename(jv_copy(rel_path));13082 jv_array_foreach(lib_search_paths, i, spath) {131 jv_array_foreach(search, i, spath) {132 if (jv_get_kind(spath) == JV_KIND_NULL) {133 jv_free(spath);134 break;135 }
1 unmodified line
137 strcmp(jv_string_value(spath), "") == 0) {138 jv_free(spath);139 continue; /* XXX report non-strings in search path?? */140 }141 // Try .../module/last/component.jq92 jv testpath = jq_realpath(jv_string_fmt("%s/%s.jq",142 jv testpath = jq_realpath(jv_string_fmt("%s/%s%s",143 jv_string_value(spath),94 jv_string_value(rel_path)));144 jv_string_value(rel_path),145 suffix));146 ret = stat(jv_string_value(testpath),&st);147 if (ret == -1 && errno == ENOENT) {148 jv_free(testpath);149 // Try .../module/last/component/component.jq98 testpath = jq_realpath(jv_string_fmt("%s/%s/%s.jq",150 testpath = jq_realpath(jv_string_fmt("%s/%s/%s%s",151 jv_string_value(spath),152 jv_string_value(rel_path),101 jv_string_value(lib_name)));153 jv_string_value(bname),154 suffix));155 ret = stat(jv_string_value(testpath),&st);156 }157 if (ret == 0) {105 jv_free(spath);158 jv_free(rel_path);107 jv_free(lib_name);108 jv_free(lib_search_paths);159 jv_free(search);160 jv_free(bname);161 jv_free(spath);162 return testpath;163 }164 jv_free(testpath);165 jv_free(spath);166 }114 jv output = jv_invalid_with_msg(jv_string_fmt("module not found: %s", jv_string_value(lib_name)));167 jv output = jv_invalid_with_msg(jv_string_fmt("module not found: %s", jv_string_value(rel_path)));168 jv_free(rel_path);116 jv_free(lib_name);117 jv_free(lib_search_paths);169 jv_free(search);170 jv_free(bname);171 return output;172}173121static int version_matches(jq_state *jq, block importer, block module) {122 return 1;123}124125static jv default_search(jv value) {174static jv default_search(jq_state *jq, jv value) {175 if (!jv_is_valid(value)) {176 // dependent didn't say; prepend . to system search path listj177 jv_free(value);128 return JV_ARRAY(jv_string("."), jv_string("$ORIGIN"));178 return jv_array_concat(JV_ARRAY(jv_string(".")), jq_get_lib_dirs(jq));179 }180 if (jv_get_kind(value) != JV_KIND_ARRAY)181 return JV_ARRAY(value);182 return value;
5 unmodified lines
188 block bk = *src_block;189 int nerrors = 0;190191 jv_array_foreach(deps, i, dep) {142 jv name = jv_object_get(jv_copy(dep), jv_string("name"));192 int is_data = jv_get_kind(jv_object_get(jv_copy(dep), jv_string("is_data"))) == JV_KIND_TRUE;193 int raw = 0;194 jv v = jv_object_get(jv_copy(dep), jv_string("raw"));195 if (jv_get_kind(v) == JV_KIND_TRUE)196 raw = 1;197 jv_free(v);198 jv relpath = validate_relpath(jv_object_get(jv_copy(dep), jv_string("relpath")));199 jv as = jv_object_get(jv_copy(dep), jv_string("as"));144 if (!jv_is_valid(as)) {145 jv_free(as);146 as = jv_string("");147 }148 jv search = default_search(jv_object_get(dep, jv_string("search")));149 jv_array_foreach(search, k, search_elt) {150 if (strcmp(".",jv_string_value(search_elt)) == 0) {151 jv tsearch = jv_copy(lib_origin);152 jv_free(search_elt);153 search = jv_array_set(search, k, tsearch);154 } else if (strncmp("./",jv_string_value(search_elt),sizeof("./")-1) == 0) {155 jv tsearch = jv_string_fmt("%s/%s",156 jv_string_value(lib_origin),157 jv_string_value(search_elt) + sizeof ("./") - 1);158 jv_free(search_elt);159 search = jv_array_set(search, k, tsearch);160 } else if (strncmp("$ORIGIN/",jv_string_value(search_elt),sizeof("$ORIGIN/")-1) == 0) {161 jv tsearch = jv_string_fmt("%s/%s",162 jv_string_value(jq_origin),163 jv_string_value(search_elt) + sizeof ("$ORIGIN/") - 1);164 jv_free(search_elt);165 search = jv_array_set(search, k, tsearch);166 } else {167 jv_free(search_elt);168 }169 }170 jv lib_path = find_lib(jq, name, search);200 assert(jv_is_valid(as) && jv_get_kind(as) == JV_KIND_STRING);201 jv search = default_search(jq, jv_object_get(dep, jv_string("search")));202 // dep is now freed; do not reuse203204 // find_lib does a lot of work that could be cached...205 jv resolved = find_lib(jq, relpath, search, is_data ? ".json" : ".jq", jv_copy(jq_origin), jv_copy(lib_origin));206 // XXX ...move the rest of this into a callback.172 if (!jv_is_valid(lib_path)) {173 jv emsg = jv_invalid_get_msg(lib_path);207 if (!jv_is_valid(resolved)) {208 jv emsg = jv_invalid_get_msg(resolved);209 jq_report_error(jq, jv_string_fmt("jq: error: %s\n",jv_string_value(emsg)));210 jv_free(emsg);211 jv_free(as);212 jv_free(deps);
2 unmodified lines
215 return 1;216 }217 uint64_t state_idx = 0;218 for (; state_idx < lib_state->ct; ++state_idx) {184 if (strcmp(lib_state->names[state_idx],jv_string_value(lib_path)) == 0)219 if (strcmp(lib_state->names[state_idx],jv_string_value(resolved)) == 0)220 break;221 }222 if (state_idx < lib_state->ct) { // Found188 // XXX Check version matching here!189 if (version_matches(jq, bk, lib_state->defs[state_idx]))190 bk = block_bind_library(lib_state->defs[state_idx], bk, OP_IS_CALL_PSEUDO, jv_string_value(as));191 else192 // XXX Would be nice to have the dependent's name here too193 jq_report_error(jq, jv_string_fmt("jq: error: version mismatch for %s", jv_string_value(name)));194 jv_free(lib_path);223 jv_free(resolved);224 // Bind the library to the program225 bk = block_bind_library(lib_state->defs[state_idx], bk, OP_IS_CALL_PSEUDO, jv_string_value(as));226 } else { // Not found. Add it to the table before binding.227 block dep_def_block = gen_noop();197 nerrors += load_library(jq, lib_path, &dep_def_block, lib_state);228 nerrors += load_library(jq, resolved, is_data, raw, jv_string_value(as), &dep_def_block, lib_state);229 // resolved has been freed230 if (nerrors == 0) {199 // XXX Check version matching here!200 if (version_matches(jq, bk, dep_def_block))201 bk = block_bind_library(dep_def_block, bk, OP_IS_CALL_PSEUDO, jv_string_value(as));202 else203 jq_report_error(jq, jv_string_fmt("jq: error: version mismatch for %s", jv_string_value(name)));231 // Bind the library to the program232 bk = block_bind_library(dep_def_block, bk, OP_IS_CALL_PSEUDO, jv_string_value(as));233 }234 }235 jv_free(as);236 }
4 unmodified lines
241}242243// Loads the library at lib_path into lib_state, putting the library's defs244// into *out_block216static int load_library(jq_state *jq, jv lib_path, block *out_block, struct lib_loading_state *lib_state) {245static int load_library(jq_state *jq, jv lib_path, int is_data, int raw, const char *as, block *out_block, struct lib_loading_state *lib_state) {246 int nerrors = 0;218 struct locfile* src;247 struct locfile* src = NULL;248 block program;249 jv data;250 if (is_data && !raw)251 data = jv_load_file(jv_string_value(lib_path), 0);252 else220 jv data = jv_load_file(jv_string_value(lib_path), 1);253 data = jv_load_file(jv_string_value(lib_path), 1);254 int state_idx;222 if (jv_is_valid(data)) {255 if (!jv_is_valid(data)) {256 if (jv_invalid_has_msg(jv_copy(data)))257 data = jv_invalid_get_msg(data);258 else259 data = jv_string("unknown error");260 jq_report_error(jq, jv_string_fmt("jq: error loading data file %s: %s\n", jv_string_value(lib_path), jv_string_value(data)));261 nerrors++;262 goto out;263 } else if (is_data) {264 // import "foo" as $bar;265 program = gen_const_global(jv_copy(data), as);266 } else {267 // import "foo" as bar;268 src = locfile_init(jq, jv_string_value(data), jv_string_length_bytes(jv_copy(data)));269 nerrors += jq_parse_library(src, &program);270 if (nerrors == 0) {226 state_idx = lib_state->ct++;227 lib_state->names = realloc(lib_state->names, lib_state->ct * sizeof(const char *));228 lib_state->defs = realloc(lib_state->defs, lib_state->ct * sizeof(block));229 lib_state->names[state_idx] = strdup(jv_string_value(lib_path));230 lib_state->defs[state_idx] = program;271 char *lib_origin = strdup(jv_string_value(lib_path));272 nerrors += process_dependencies(jq, jq_get_jq_origin(jq),273 jv_string(dirname(lib_origin)),234 &lib_state->defs[state_idx], lib_state);274 &program, lib_state);275 free(lib_origin);236 *out_block = lib_state->defs[state_idx];276 }238 locfile_free(src);277 }278 state_idx = lib_state->ct++;279 lib_state->names = realloc(lib_state->names, lib_state->ct * sizeof(const char *));280 lib_state->defs = realloc(lib_state->defs, lib_state->ct * sizeof(block));281 lib_state->names[state_idx] = strdup(jv_string_value(lib_path));282 lib_state->defs[state_idx] = program;283 *out_block = program;284 if (src)285 locfile_free(src);286out:287 jv_free(lib_path);288 jv_free(data);289 return nerrors;290}291292// FIXME It'd be nice to have an option to search the same search path293// as we do in process_dependencies.247jv load_module_meta(jq_state *jq, jv modname) {248 jv lib_path = find_lib(jq, modname, jv_array());294jv load_module_meta(jq_state *jq, jv mod_relpath) {295 // We can't know the caller's origin; we could though, if it was passed in296 jv lib_path = find_lib(jq, validate_relpath(mod_relpath), jq_get_lib_dirs(jq), ".jq", jq_get_jq_origin(jq), jv_null());297 if (!jv_is_valid(lib_path))298 return lib_path;299 jv meta = jv_null();300 jv data = jv_load_file(jv_string_value(lib_path), 1);301 if (jv_is_valid(data)) {302 block program;
24 unmodified lines
327 nerrors = process_dependencies(jq, jq_get_jq_origin(jq), jq_get_prog_origin(jq), &program, &lib_state);328 block libs = gen_noop();329 for (uint64_t i = 0; i < lib_state.ct; ++i) {330 free(lib_state.names[i]);281 if (nerrors == 0)331 if (nerrors == 0 && !block_is_const(lib_state.defs[i]))332 libs = block_join(libs, lib_state.defs[i]);333 else334 block_free(lib_state.defs[i]);335 }
9 unmodified lines
modified:main.c+5 added-17 removed
442 unmodified lines
443 if (options & ASCII_OUTPUT) dumpopts |= JV_PRINT_ASCII;444 if (options & COLOUR_OUTPUT) dumpopts |= JV_PRINT_COLOUR;445 if (options & NO_COLOUR_OUTPUT) dumpopts &= ~JV_PRINT_COLOUR;446447 char *penv = getenv("JQ_LIBRARY_PATH");448 if (penv && jv_get_kind(lib_search_paths) == JV_KIND_NULL) {449 // Use $JQ_LIBRARY_PATH450#ifdef WIN32451#define PATH_ENV_SEPARATOR ";"452#else453#define PATH_ENV_SEPARATOR ":"454#endif455 lib_search_paths = jv_array_concat(lib_search_paths,jv_string_split(jv_string(penv),jv_string(PATH_ENV_SEPARATOR)));456#undef PATH_ENV_SEPARATOR457 } else if (jv_get_kind(lib_search_paths) == JV_KIND_NULL) {458 // Use compiled-in default JQ_LIBRARY_PATH459#ifdef WIN32460 lib_search_paths = JV_ARRAY(jv_string("~/.jq"), jv_string("$ORIGIN/lib"));461#else462 lib_search_paths = JV_ARRAY(jv_string("~/.jq"), jv_string("$ORIGIN/../lib/jq"));463#endif447 if (jv_get_kind(lib_search_paths) == JV_KIND_NULL) {448 // Default search path list449 lib_search_paths = JV_ARRAY(jv_string("~/.jq"),450 jv_string("$ORIGIN/../lib/jq"),451 jv_string("$ORIGIN/lib"));452 }453 jq_set_attr(jq, jv_string("JQ_LIBRARY_PATH"), lib_search_paths);454455 char *origin = strdup(argv[0]);
159 unmodified lines
modified:opcode_list.h+1 added
4 unmodified lines
5OP(POP, NONE, 1, 0)6OP(LOADV, VARIABLE, 1, 1)7OP(LOADVN, VARIABLE, 1, 1)8OP(STOREV, VARIABLE, 1, 0)9OP(STORE_GLOBAL, GLOBAL, 0, 0)10OP(INDEX, NONE, 2, 1)11OP(INDEX_OPT, NONE, 2, 1)12OP(EACH, NONE, 1, 1)13OP(EACH_OPT, NONE, 1, 1)
31 unmodified lines
modified:parser.y+31 added-20 removed
278 unmodified lines
279Module:280%empty {281 $$ = gen_noop();282} |283"module" IDENT Exp ';' {284 if (!block_is_const($3)) {283"module" Exp ';' {284 if (!block_is_const($2)) {285 FAIL(@$, "Module metadata must be constant.");286 $$ = gen_noop();287 } else {288 $$ = gen_module(jv_string_value($2), $3);288 $$ = gen_module($2);289 }290 jv_free($2);290}291292Imports:293%empty {
183 unmodified lines
477 $$ = $1; 478}479480Import:482"import" IDENT ';' {483 $$ = gen_import(jv_string_value($2), gen_noop(), NULL);484 jv_free($2);481"import" String "as" '$' IDENT ';' {482 jv v = block_const($2);483 // XXX Make gen_import take only blocks and the int is_data so we484 // don't have to free so much stuff here485 $$ = gen_import(jv_string_value(v), gen_noop(), jv_string_value($5), 1);486 block_free($2);487 jv_free($5);488 jv_free(v);489} |490"import" String "as" IDENT ';' {491 jv v = block_const($2);492 $$ = gen_import(jv_string_value(v), gen_noop(), jv_string_value($4), 0);493 block_free($2);494 jv_free($4);495 jv_free(v);496} |486"import" IDENT Exp ';' {487 if (!block_is_const($3)) {497"import" String "as" IDENT Exp ';' {498 if (!block_is_const($5)) {499 FAIL(@$, "Module metadata must be constant.");500 $$ = gen_noop();501 } else {491 $$ = gen_import(jv_string_value($2), $3, NULL);502 jv v = block_const($2);503 $$ = gen_import(jv_string_value(v), $5, jv_string_value($4), 0);504 jv_free(v);505 }493 jv_free($2);494} |495"import" IDENT "as" IDENT ';' {496 $$ = gen_import(jv_string_value($2), gen_noop(), jv_string_value($4));497 jv_free($2);506 block_free($2);507 jv_free($4);508} |500"import" IDENT "as" IDENT Exp ';' {501 if (!block_is_const($5)) {509"import" String "as" '$' IDENT Exp ';' {510 if (!block_is_const($6)) {511 FAIL(@$, "Module metadata must be constant.");512 $$ = gen_noop();513 } else {514 jv v = block_const($2);505 $$ = gen_import(jv_string_value($2), $5, jv_string_value($4));515 $$ = gen_import(jv_string_value(v), $6, jv_string_value($5), 1);516 jv_free(v);517 }507 jv_free($2);508 jv_free($4);518 block_free($2);519 jv_free($5);520}521522FuncDef:523"def" IDENT ':' Exp ';' {
286 unmodified lines