Add Streaming parser (--stream)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Streaming means that outputs are produced as soon as possible. With the `foreach` syntax one can write programs which reduce portions of the streaming parse of a large input (reduce into proper JSON values, for example), and discard the rest, processing incrementally. This: $ jq -c --stream . should produce the same output as this: $ jq -c '. as $dot | path(..) as $p | $dot | getpath($p) | [$p,.]' The output of `jq --stream .` should be a sequence of`[[<path>],<leaf>]` and `[[<path>]]` values. The latter indicate that the array/object at that path ended. Scalars and empty arrays and objects are leaf values for this purpose. For example, a truncated input produces a path as soon as possible, then later the error: $ printf '[0,\n'|./jq -c --stream . [[0],0] parse error: Unfinished JSON term at EOF at line 3, column 0 $
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+480 added−80 removed
- tests:+15 added−3 removed
- other:+465 added−77 removed
Provenance
- Commit
5bfb978- Tree
a6c1a44- Author
Nicolas Williams <nico@cryptonector.com>- Committer
Nicolas Williams <nico@cryptonector.com>- Parent
906d253
10 files changed+480 added−80 removed
modified:docs/content/3.manual/manual.yml+34 added
101 unmodified lines102 warned about), discarding all subsequent input until the next103 RS. This more also parses the output of jq without the `--seq`104 option.105 106+ * `--stream`:107+108+ Parse the input in streaming fashion, outputing arrays of path109+ and leaf values (scalars and empty arrays or empty objects).110+ For example, `"a"` becomes `[[],"a"]`, and `[[],"a",["b"]]`111+ becomes `[[0],[]]`, `[[1],"a"]`, and `[[1,0],"b"]`.112+113+ This is useful for processing very large inputs. Use this in114+ conjunction with filtering and the `reduce` and `foreach` syntax115+ to reduce large inputs incrementally.116+117 * `--slurp`/`-s`:118 119 Instead of running the filter for each JSON object in the120 input, read the entire input stream into a large array and run2094 unmodified lines2215 [while(.<100; .*2)]'2216 input: '1'2217 output: ['[1,2,4,8,16,32,64]']2218 2219+ - title: 'I/O'2220+ body: |2221+2222+ At this time jq has minimal support for I/O, mostly in the2223+ form of control over when inputs are read. Two builtins functions2224+ are provided for this, `input` and `inputs`, that read from the2225+ same sources (e.g., `stdin`, files named on the command-line) as2226+ jq itself. These two builtins, and jq's own reading actions, can2227+ be interleaved with each other.2228+2229+ - title: "`input`"2230+ body: |2231+2232+ Outputs one new input.2233+2234+ - title: "`inputs`"2235+ body: |2236+2237+ Outputs all remaining inputs, one by one.2238+2239+ This is primarily useful for reductions over a program's2240+ inputs.2241+2242 - title: Assignment2243 body: |2244 2245 Assignment works a little differently in jq than in most218 unmodified linesadded:tests/torture/input0.json+7 added
12345670 12 true false null [] {} [{}] [[]][0,01,[12,22,[34,[45,56],7]],[]]{"a":[1]}{"a":[{}]}{"a":[{},[],[[]]]}{"a":[{"b":[]}]}{"a":[{"b":[]},{},[2]]}modified:tests/run+8 added-3 removed
18 unmodified lines19 echo "Your OS does not support mktemp(1) -d" 1>&220 exit 021 fi22 23-23 ## Test constant folding24 25 # String constant folding (addition only)26 n=`$VALGRIND $Q ./jq -n --debug-dump-disasm '"foo"' | wc -l`72 unmodified lines99 100 # Note that here jq sees no inputs at all but it still succeeds because101 # --seq ignores parse errors102 cat > $d/expected <<EOF104-ignoring parse error: Unfinished string103+ignoring parse error: Unfinished string at EOF at line 1, column 4104 EOF105 printf '"foo'|./jq -ce --seq . > $d/out 2>&1106 cmp $d/out $d/expected107 108 # Numeric values truncated by EOF are ignored109 cat > $d/expected <<EOF111-ignoring parse error: Potentially truncated top-level numeric value110+ignoring parse error: Potentially truncated top-level numeric value at EOF at line 1, column 1111 EOF112 printf '1'|./jq -ce --seq . > $d/out 2>&1113 cmp $d/out $d/expected114 1 unmodified line116 EOF117 printf '1\n'|./jq -ces --seq '. == [1]' >/dev/null 2> $d/out118 cmp $d/out $d/expected119 120+## Test streaming parser121+122+$VALGRIND $Q ./jq -c '. as $d|path(..) as $p|$d|getpath($p)|scalars_or_empty|[$p,.]' < "$PWD/tests/torture/input0.json" > $d/out0123+$VALGRIND $Q ./jq --stream -c '.|select(length==2)' < "$PWD/tests/torture/input0.json" > $d/out1124+diff $d/out0 $d/out1125+126 ## Test library/module system127 128 mods=$PWD/tests/modules129 60 unmodified linesmodified:builtin.c+14 added
860 unmodified lines861 }862 return load_module_meta(jq, a);863 }864 865+static jv f_input(jq_state *jq, jv input) {866+ jv_free(input);867+ jq_input_cb cb;868+ void *data;869+ jq_get_input_cb(jq, &cb, &data);870+ jv v = cb(jq, data);871+ if (jv_is_valid(v) || jv_invalid_has_msg(jv_copy(v)))872+ return v;873+ return jv_invalid_with_msg(jv_string("break"));874+}875 876+877+878 #define LIBM_DD(name) \879 {(cfunction_ptr)f_ ## name, "_" #name, 1},880 881 static const struct cfunction function_list[] = {41 unmodified lines923 {(cfunction_ptr)f_format, "format", 2},924 {(cfunction_ptr)f_env, "env", 1},925 {(cfunction_ptr)f_match, "_match_impl", 4},926 {(cfunction_ptr)f_modulemeta, "modulemeta", 1},927+ {(cfunction_ptr)f_input, "_input", 1},928 };929 #undef LIBM_DD930 931 struct bytecoded_builtin { const char* name; block code; };94 unmodified lines1026 "def strings: select(type == \"string\");",1027 "def nulls: select(type == \"null\");",1028 "def values: select(. != null);",1029 "def scalars: select(. == null or . == true or . == false or type == \"number\" or type == \"string\");",1030+ "def scalars_or_empty: select(. == null or . == true or . == false or type == \"number\" or type == \"string\" or ((type==\"array\" or type==\"object\") and length==0));",1031 "def leaf_paths: paths(scalars);",1032 "def join($x): reduce .[] as $i (\"\"; . + (if . == \"\" then $i else $x + $i end));",1033 "def flatten: reduce .[] as $i ([]; if $i | type == \"array\" then . + ($i | flatten) else . + [$i] end);",1034 "def flatten($x): reduce .[] as $i ([]; if $i | type == \"array\" and $x > 0 then . + ($i | flatten($x-1)) else . + [$i] end);",157 unmodified linesmodified:execute.c+12 added
37 unmodified lines38 int debug_trace_enabled;39 int initial_execution;40 41 jv attrs;42+ jq_input_cb input_cb;43+ void *input_cb_data;44 };45 46 struct closure {47 struct bytecode* bc; // jq bytecode990 unmodified lines1038 1039 void jq_dump_disassembly(jq_state *jq, int indent) {1040 dump_disassembly(indent, jq->bc);1041 }1042+1043+void jq_set_input_cb(jq_state *jq, jq_input_cb cb, void *data) {1044+ jq->input_cb = cb;1045+ jq->input_cb_data = data;1046+}1047+1048+void jq_get_input_cb(jq_state *jq, jq_input_cb *cb, void **data) {1049+ *cb = jq->input_cb;1050+ *data = jq->input_cb_data;1051+}modified:jq.h+4 added
20 unmodified lines21 void jq_start(jq_state *, jv value, int);22 jv jq_next(jq_state *);23 void jq_teardown(jq_state **);24 25+typedef jv (*jq_input_cb)(jq_state *, void *);26+void jq_set_input_cb(jq_state *, jq_input_cb, void *);27+void jq_get_input_cb(jq_state *, jq_input_cb *, void **);28+29 void jq_set_attrs(jq_state *, jv);30 jv jq_get_attrs(jq_state *);31 jv jq_get_jq_origin(jq_state *);32 jv jq_get_prog_origin(jq_state *);4 unmodified linesmodified:jv_parse.c+290 added-23 removed
15 unmodified lines16 #else17 #define pfunc presult18 #endif19 20+enum last_seen {21+ JV_LAST_NONE = 0,22+ JV_LAST_OPEN_ARRAY = '[',23+ JV_LAST_OPEN_OBJECT = '{',24+ JV_LAST_COLON = ':',25+ JV_LAST_COMMA = ',',26+ JV_LAST_VALUE = 'V',27+};28+29 struct jv_parser {30 const char* curr_buf;31 int curr_buf_length;32 int curr_buf_pos;1 unmodified line34 unsigned bom_strip_position;35 36 int flags;37 29- jv* stack;30- int stackpos;31- int stacklen;32- jv next;38+ jv* stack; // parser39+ int stackpos; // parser40+ int stacklen; // both (optimization; it's really pathlen for streaming)41+ jv path; // streamer42+ enum last_seen last_seen; // streamer43+ jv output; // streamer44+ jv next; // both45 46 char* tokenbuf;47 int tokenpos;48 int tokenlen;11 unmodified lines60 unsigned int last_ch_was_ws:1;61 };62 63 52-static void parser_init(struct jv_parser* p) {53- p->flags = 0;64+static void parser_init(struct jv_parser* p, int flags) {65+ p->flags = flags;66+ if ((p->flags & JV_PARSE_STREAMING)) {67+ p->path = jv_array();68+ } else {69+ p->path = jv_invalid();70+ p->flags &= ~(JV_PARSE_STREAM_ERRORS);71+ }72 p->stack = 0;73 p->stacklen = p->stackpos = 0;74+ p->last_seen = JV_LAST_NONE;75+ p->output = jv_invalid();76 p->next = jv_invalid();77 p->tokenbuf = 0;78 p->tokenlen = p->tokenpos = 0;79 p->st = JV_PARSER_NORMAL;5 unmodified lines85 jvp_dtoa_context_init(&p->dtoa);86 }87 88 static void parser_reset(struct jv_parser* p) {89+ if ((p->flags & JV_PARSE_STREAMING)) {90+ jv_free(p->path);91+ p->path = jv_array();92+ }93+ p->last_seen = JV_LAST_NONE;94+ jv_free(p->output);95+ p->output = jv_invalid();96 jv_free(p->next);97 p->next = jv_invalid();98 for (int i=0; i<p->stackpos; i++) 99 jv_free(p->stack[i]);3 unmodified lines103 }104 105 static void parser_free(struct jv_parser* p) {106 parser_reset(p);107+ jv_free(p->path);108 jv_mem_free(p->stack);109 jv_mem_free(p->tokenbuf);110 jvp_dtoa_context_free(&p->dtoa);111 }112 113 static pfunc value(struct jv_parser* p, jv val) {114+ if ((p->flags & JV_PARSE_STREAMING)) {115+ if (jv_is_valid(p->next) || p->last_seen == JV_LAST_VALUE)116+ return "Expected separator between values";117+ if (p->stacklen > 0)118+ p->last_seen = JV_LAST_VALUE;119+ else120+ p->last_seen = JV_LAST_NONE;121+ } else {86- if (jv_is_valid(p->next)) return "Expected separator between values";122+ if (jv_is_valid(p->next)) return "Expected separator between values";123+ }124 jv_free(p->next);125 p->next = val;126 return 0;127 }7 unmodified lines135 assert(p->stackpos < p->stacklen);136 p->stack[p->stackpos++] = v;137 }138 102-static pfunc token(struct jv_parser* p, char ch) {139+static pfunc parse_token(struct jv_parser* p, char ch) {140 switch (ch) {141 case '[':142 if (jv_is_valid(p->next)) return "Expected separator between values";143 push(p, jv_array());74 unmodified lines218 }219 return 0;220 }221 222+static pfunc stream_token(struct jv_parser* p, char ch) {223+ jv_kind k;224+ jv last;225 226+ switch (ch) {227+ case '[':228+ if (jv_is_valid(p->next))229+ return "Expected a separator between values";230+ p->path = jv_array_append(p->path, jv_number(0)); // push231+ p->last_seen = JV_LAST_OPEN_ARRAY;232+ p->stacklen++;233+ break;234+235+ case '{':236+ if (p->last_seen == JV_LAST_VALUE)237+ return "Expected a separator between values";238+ // Push object key: null, since we don't know it yet239+ p->path = jv_array_append(p->path, jv_null()); // push240+ p->last_seen = JV_LAST_OPEN_OBJECT;241+ p->stacklen++;242+ break;243+244+ case ':':245+ if (p->stacklen == 0 || jv_get_kind(jv_array_get(jv_copy(p->path), p->stacklen - 1)) == JV_KIND_NUMBER)246+ return "':' not as part of an object";247+ if (!jv_is_valid(p->next) || p->last_seen == JV_LAST_NONE)248+ return "Expected string key before ':'";249+ if (jv_get_kind(p->next) != JV_KIND_STRING)250+ return "Object keys must be strings";251+ if (p->last_seen != JV_LAST_VALUE)252+ return "':' should follow a key";253+ p->last_seen = JV_LAST_COLON;254+ p->path = jv_array_set(p->path, p->stacklen - 1, p->next);255+ p->next = jv_invalid();256+ break;257+258+ case ',':259+ if (p->last_seen != JV_LAST_VALUE)260+ return "Expected value before ','";261+ if (p->stacklen == 0)262+ return "',' not as part of an object or array";263+ last = jv_array_get(jv_copy(p->path), p->stacklen - 1);264+ k = jv_get_kind(last);265+ if (k == JV_KIND_NUMBER) {266+ int idx = jv_number_value(last);267+268+ if (jv_is_valid(p->next)) {269+ p->output = JV_ARRAY(jv_copy(p->path), p->next);270+ p->next = jv_invalid();271+ }272+ p->path = jv_array_set(p->path, p->stacklen - 1, jv_number(idx + 1));273+ p->last_seen = JV_LAST_COMMA;274+ } else if (k == JV_KIND_STRING) {275+ if (jv_is_valid(p->next)) {276+ p->output = JV_ARRAY(jv_copy(p->path), p->next);277+ p->next = jv_invalid();278+ }279+ p->path = jv_array_set(p->path, p->stacklen - 1, jv_true()); // ready for another name:value pair280+ p->last_seen = JV_LAST_COMMA;281+ } else {282+ assert(k == JV_KIND_NULL);283+ // this case hits on input like {,}284+ // make sure to handle input like {"a", "b"} and {"a":, ...}285+ jv_free(last);286+ return "Objects must consist of key:value pairs";287+ }288+ jv_free(last);289+ break;290+291+ case ']':292+ if (p->stacklen == 0)293+ return "Unmatched ']' at the top-level";294+ if (p->last_seen == JV_LAST_COMMA)295+ return "Expected another array element";296+ if (p->last_seen == JV_LAST_OPEN_ARRAY)297+ assert(!jv_is_valid(p->next));298+299+ last = jv_array_get(jv_copy(p->path), p->stacklen - 1);300+ k = jv_get_kind(last);301+ jv_free(last);302+303+ if (k != JV_KIND_NUMBER)304+ return "Unmatched ']' in the middle of an object";305+ if (jv_is_valid(p->next)) {306+ p->output = JV_ARRAY(jv_copy(p->path), p->next, jv_true());307+ p->next = jv_invalid();308+ } else if (p->last_seen != JV_LAST_OPEN_ARRAY) {309+ p->output = JV_ARRAY(jv_copy(p->path));310+ }311+312+ p->path = jv_array_slice(p->path, 0, --(p->stacklen)); // pop313+ //assert(!jv_is_valid(p->next));314+ jv_free(p->next);315+ p->next = jv_invalid();316+317+ if (p->last_seen == JV_LAST_OPEN_ARRAY)318+ p->output = JV_ARRAY(jv_copy(p->path), jv_array()); // Empty arrays are leaves319+320+ if (p->stacklen == 0)321+ p->last_seen = JV_LAST_NONE;322+ else323+ p->last_seen = JV_LAST_VALUE;324+ break;325+326+ case '}':327+ if (p->stacklen == 0)328+ return "Unmatched '}' at the top-level";329+ if (p->last_seen == JV_LAST_COMMA)330+ return "Expected another key:value pair";331+ if (p->last_seen == JV_LAST_OPEN_OBJECT)332+ assert(!jv_is_valid(p->next));333+334+ last = jv_array_get(jv_copy(p->path), p->stacklen - 1);335+ k = jv_get_kind(last);336+ jv_free(last);337+ if (k == JV_KIND_NUMBER)338+ return "Unmatched '}' in the middle of an array";339+340+ if (jv_is_valid(p->next)) {341+ if (k != JV_KIND_STRING)342+ return "Objects must consist of key:value pairs";343+ p->output = JV_ARRAY(jv_copy(p->path), p->next, jv_true());344+ p->next = jv_invalid();345+ } else {346+ // Perhaps {"a":[]}347+ if (p->last_seen == JV_LAST_COLON)348+ // Looks like {"a":}349+ return "Missing value in key:value pair";350+ if (p->last_seen == JV_LAST_COMMA)351+ // Looks like {"a":0,}352+ return "Expected another key-value pair";353+ if (p->last_seen == JV_LAST_OPEN_ARRAY)354+ return "Unmatched '}' in the middle of an array";355+ if (p->last_seen != JV_LAST_VALUE && p->last_seen != JV_LAST_OPEN_OBJECT)356+ return "Unmatched '}'";357+ if (p->last_seen != JV_LAST_OPEN_OBJECT)358+ p->output = JV_ARRAY(jv_copy(p->path));359+ }360+ p->path = jv_array_slice(p->path, 0, --(p->stacklen)); // pop361+ jv_free(p->next);362+ p->next = jv_invalid();363+364+ if (p->last_seen == JV_LAST_OPEN_OBJECT)365+ p->output = JV_ARRAY(jv_copy(p->path), jv_object()); // Empty arrays are leaves366+367+ if (p->stacklen == 0)368+ p->last_seen = JV_LAST_NONE;369+ else370+ p->last_seen = JV_LAST_VALUE;371+ break;372+ }373+ return 0;374+}375+376 static void tokenadd(struct jv_parser* p, char c) {377 assert(p->tokenpos <= p->tokenlen);378 if (p->tokenpos == p->tokenlen) {379 p->tokenlen = p->tokenlen*2 + 256;380 p->tokenbuf = jv_mem_realloc(p->tokenbuf, p->tokenlen);381 }382 assert(p->tokenpos < p->tokenlen);383 p->tokenbuf[p->tokenpos++] = c;384+ p->tokenbuf[p->tokenpos] = '\0'; // for debugging385 }386 387 static int unhex4(char* hex) {388 int r = 0;130 unmodified lines519 520 521 static const presult OK = "output produced";522 332-static int check_done(struct jv_parser* p, jv* out) {523+static int parse_check_done(struct jv_parser* p, jv* out) {524 if (p->stackpos == 0 && jv_is_valid(p->next)) {525 *out = p->next;526 p->next = jv_invalid();527 return 1;1 unmodified line529 return 0;530 }531 }532 533+static int stream_check_done(struct jv_parser* p, jv* out) {534+ if (p->stacklen == 0 && jv_is_valid(p->next)) {535+ *out = JV_ARRAY(jv_copy(p->path),p->next);536+ p->next = jv_invalid();537+ return 1;538+ } else if (jv_is_valid(p->output)) {539+ if (jv_array_length(jv_copy(p->output)) > 2) {540+ // At end of an array or object, necessitating one more output by541+ // which to indicate this542+ *out = jv_array_slice(jv_copy(p->output), 0, 2);543+ p->output = jv_array_slice(p->output, 0, 1); // arrange one more output544+ } else {545+ // No further processing needed546+ *out = p->output;547+ p->output = jv_invalid();548+ }549+ return 1;550+ } else {551+ return 0;552+ }553+}554+555+static int parse_check_truncation(struct jv_parser* p, jv out) {556+ return ((p->flags & JV_PARSE_SEQ) && !p->last_ch_was_ws && jv_get_kind(out) == JV_KIND_NUMBER);557+}558+559+static int stream_check_truncation(struct jv_parser* p, jv out) {560+ if (!jv_is_valid(out))561+ return 0;562+ jv v = jv_array_get(jv_copy(out), 1);563+ jv_kind k = jv_get_kind(v);564+ jv_free(v);565+ return (k == JV_KIND_NUMBER || k == JV_KIND_TRUE || k == JV_KIND_FALSE || k == JV_KIND_NULL);566+}567+568+#define check_done(p, out) \569+ (((p)->flags & JV_PARSE_STREAMING) ? stream_check_done((p), (out)) : parse_check_done((p), (out)))570+571+#define token(p, ch) \572+ (((p)->flags & JV_PARSE_STREAMING) ? stream_token((p), (ch)) : parse_token((p), (ch)))573+574+#define check_truncation(p, o) \575+ (((p)->flags & JV_PARSE_STREAMING) ? stream_check_truncation((p), (o)) : parse_check_truncation((p), (o)))576+577 static pfunc scan(struct jv_parser* p, char ch, jv* out) {578 p->column++;579 if (ch == '\n') {580 p->line++;1 unmodified line582 }583 if (ch == '\036' /* ASCII RS; see draft-ietf-json-sequence-07 */) {584 TRY(check_literal(p));585 if (p->st == JV_PARSER_NORMAL && check_done(p, out)) {351- if ((p->flags & JV_PARSE_SEQ) && !p->last_ch_was_ws && jv_get_kind(*out) == JV_KIND_NUMBER) {586+ if (check_truncation(p, *out)) {587 jv_free(*out);588 *out = jv_invalid();589 return "Potentially truncated top-level numeric value";590 }47 unmodified lines638 }639 640 struct jv_parser* jv_parser_new(int flags) {641 struct jv_parser* p = jv_mem_alloc(sizeof(struct jv_parser));407- parser_init(p);642+ parser_init(p, flags);643 p->flags = flags;644 return p;645 }646 3 unmodified lines650 }651 652 static const unsigned char UTF8_BOM[] = {0xEF,0xBB,0xBF};653 654+int jv_parser_remaining(struct jv_parser* p) {655+ if (p->curr_buf == 0)656+ return 0;657+ return (p->curr_buf_length - p->curr_buf_pos);658+}659+660 void jv_parser_set_buf(struct jv_parser* p, const char* buf, int length, int is_partial) {661 assert((p->curr_buf == 0 || p->curr_buf_pos == p->curr_buf_length)662 && "previous buffer not exhausted");663 while (length > 0 && p->bom_strip_position < sizeof(UTF8_BOM)) {17 unmodified lines681 p->curr_buf_pos = 0;682 p->curr_buf_is_partial = is_partial;683 }684 685+static jv make_error(struct jv_parser*, const char *, ...) JV_PRINTF_LIKE(2, 3);686+687+static jv make_error(struct jv_parser* p, const char *fmt, ...) {688+ va_list ap;689+ va_start(ap, fmt);690+ jv e = jv_string_vfmt(fmt, ap);691+ va_end(ap);692+ if ((p->flags & JV_PARSE_STREAM_ERRORS))693+ return JV_ARRAY(e, jv_copy(p->path));694+ return jv_invalid_with_msg(e);695+}696+697 jv jv_parser_next(struct jv_parser* p) {445- assert(p->curr_buf && "a buffer must be provided");698+ if (!p->curr_buf)699+ return jv_invalid(); // Need a buffer700 if (p->bom_strip_position == 0xff) return jv_invalid_with_msg(jv_string("Malformed BOM"));447- jv value;701+ jv value = jv_invalid();702+ if ((p->flags & JV_PARSE_STREAMING) && stream_check_done(p, &value))703+ return value;704 char ch;705 presult msg = 0;706 while (!msg && p->curr_buf_pos < p->curr_buf_length) {707 ch = p->curr_buf[p->curr_buf_pos++];3 unmodified lines711 }712 if (msg == OK) {713 return value;714 } else if (msg) {459- parser_reset(p);715 if (ch != '\036' && (p->flags & JV_PARSE_SEQ)) {716 // Skip to the next RS717 p->st = JV_PARSER_WAITING_FOR_RS;463- return jv_invalid_with_msg(jv_string_fmt("%s at line %d, column %d (need RS to resync)", msg, p->line, p->column));718+ value = make_error(p, "%s at line %d, column %d (need RS to resync)", msg, p->line, p->column);719+ parser_reset(p);720+ return value;721 }722+ value = make_error(p, "%s at line %d, column %d", msg, p->line, p->column);723+ parser_reset(p);724 if (!(p->flags & JV_PARSE_SEQ)) {725 // We're not parsing a JSON text sequence; throw this buffer away.726 p->curr_buf = 0;727 p->curr_buf_pos = 0;728 } // Else ch must be RS; don't clear buf so we can start parsing again after this ch470- return jv_invalid_with_msg(jv_string_fmt("%s at line %d, column %d", msg, p->line, p->column));729+ return value;730 } else if (p->curr_buf_is_partial) {731 assert(p->curr_buf_pos == p->curr_buf_length);732 // need another buffer733 return jv_invalid();1 unmodified line735 assert(p->curr_buf_pos == p->curr_buf_length);736 // at EOF737 if (p->st != JV_PARSER_WAITING_FOR_RS) {738 if (p->st != JV_PARSER_NORMAL) {739+ value = make_error(p, "Unfinished string at EOF at line %d, column %d", p->line, p->column);740 parser_reset(p);741 p->st = JV_PARSER_WAITING_FOR_RS;482- return jv_invalid_with_msg(jv_string("Unfinished string"));742+ return value;743 }744 if ((msg = check_literal(p))) {745+ value = make_error(p, "%s at EOF at line %d, column %d", msg, p->line, p->column);746 parser_reset(p);747 p->st = JV_PARSER_WAITING_FOR_RS;487- return jv_invalid_with_msg(jv_string(msg));748+ return value;749 }489- if (p->stackpos != 0) {750+ if (((p->flags & JV_PARSE_STREAMING) && p->stacklen != 0) ||751+ (!(p->flags & JV_PARSE_STREAMING) && p->stackpos != 0)) {752+ value = make_error(p, "Unfinished JSON term at EOF at line %d, column %d", p->line, p->column);753 parser_reset(p);754 p->st = JV_PARSER_WAITING_FOR_RS;492- return jv_invalid_with_msg(jv_string("Unfinished JSON term"));755+ return value;756 }757 }758 // p->next is either invalid (nothing here but no syntax error)759 // or valid (this is the value). either way it's the thing to return760+ if ((p->flags & JV_PARSE_STREAMING) && jv_is_valid(p->next)) {761+ value = JV_ARRAY(jv_copy(p->path), p->next); // except in streaming mode we've got to make it [path,value]762+ } else {497- value = p->next;763+ value = p->next;764+ }765 p->next = jv_invalid();766 if ((p->flags & JV_PARSE_SEQ) && !p->last_ch_was_ws && jv_get_kind(value) == JV_KIND_NUMBER) {767 jv_free(value);501- return jv_invalid_with_msg(jv_string("Potentially truncated top-level numeric value"));768+ return make_error(p, "Potentially truncated top-level numeric value at EOF at line %d, column %d", p->line, p->column);769 }770 return value;771 }772 }773 774 jv jv_parse_sized(const char* string, int length) {775 struct jv_parser parser;509- parser_init(&parser);776+ parser_init(&parser, 0);777 jv_parser_set_buf(&parser, string, length, 0);778 jv value = jv_parser_next(&parser);779 if (jv_is_valid(value)) {780 jv next = jv_parser_next(&parser);35 unmodified linesmodified:jv.h+6 added-1 removed
168 unmodified lines169 void jv_dump(jv, int flags);170 void jv_show(jv, int flags);171 jv jv_dump_string(jv, int flags);172 173-#define JV_PARSE_SEQ 1173+enum {174+ JV_PARSE_SEQ = 1,175+ JV_PARSE_STREAMING = 2,176+ JV_PARSE_STREAM_ERRORS = 4,177+};178 179 jv jv_parse(const char* string);180 jv jv_parse_sized(const char* string, int length);181 4 unmodified lines186 187 struct jv_parser;188 struct jv_parser* jv_parser_new(int);189 void jv_parser_set_buf(struct jv_parser*, const char*, int, int);190+int jv_parser_remaining(struct jv_parser*);191 jv jv_parser_next(struct jv_parser*);192 void jv_parser_free(struct jv_parser*);193 194 jv jv_get(jv, jv);35 unmodified linesmodified:lexer.l+1 added-1 removed
98 unmodified lines99 return QQSTRING_END;100 }101 (\\[^u(]|\\u[a-zA-Z0-9]{0,4})+ {102 /* pass escapes to the json parser */103- jv escapes = jv_string_fmt("\"%.*s\"", yyleng, yytext);103+ jv escapes = jv_string_fmt("\"%.*s\"", (int)yyleng, yytext);104 yylval->literal = jv_parse_sized(jv_string_value(escapes), jv_string_length_bytes(jv_copy(escapes)));105 jv_free(escapes);106 return QQSTRING_TEXT;107 }73 unmodified linesmodified:main.c+104 added-52 removed
147 unmodified lines148 jv_free(result);149 return ret;150 }151 152+// XXX Move all this into the next_input_state struct153 FILE* current_input;154 const char** input_filenames = NULL;155 int ninput_files;156 int next_input_idx;18 unmodified lines175 next_input_idx++;176 }177 }178 179+ buf[0] = 0;180 if (current_input) {181 if (!fgets(buf, size, current_input))182 buf[0] = 0;183 }184 return next_input_idx == ninput_files && (!current_input || feof(current_input));185 }186 187+struct next_input_state {188+ struct jv_parser *parser;189+ jv slurped;190+ char buf[4096];191+};192+193+// Blocks to read one more input from stdin and/or given files194+// When slurping, it returns just one value195+static jv next_input(jq_state *jq, void *data) {196+ struct next_input_state *state = data;197+ int is_last = 0;198+ jv value = jv_invalid(); // need more input199+ do {200+ if (options & RAW_INPUT) {201+ is_last = read_more(state->buf, sizeof(state->buf));202+ if (state->buf[0] == '\0')203+ continue;204+ int len = strlen(state->buf); // Raw input doesn't support NULs205+ if (len > 0) {206+ if (options & SLURP) {207+ state->slurped = jv_string_concat(state->slurped, jv_string(state->buf));208+ } else if (jv_is_valid(value)) {209+ if (state->buf[len-1] == '\n') {210+ // whole line211+ state->buf[len-1] = 0;212+ return jv_string_concat(value, jv_string(state->buf));213+ }214+ value = jv_string_concat(value, jv_string(state->buf));215+ }216+ }217+ } else {218+ if (jv_parser_remaining(state->parser) == 0) {219+ is_last = read_more(state->buf, sizeof(state->buf));220+ jv_parser_set_buf(state->parser, state->buf, strlen(state->buf), !is_last); // NULs also not supported here221+ }222+ value = jv_parser_next(state->parser);223+ if (options & SLURP) {224+ if (jv_is_valid(value)) {225+ state->slurped = jv_array_append(state->slurped, value);226+ value = jv_invalid();227+ } else if (jv_invalid_has_msg(jv_copy(value)))228+ return value;229+ } else if (jv_is_valid(value) || jv_invalid_has_msg(jv_copy(value))) {230+ return value;231+ }232+ }233+ } while (!is_last);234+ return value;235+}236+237 int main(int argc, char* argv[]) {238 jq_state *jq = NULL;239 int ret = 0;240 int compiled = 0;241+ int parser_flags = 0;242 char *t = NULL;243 244 if (argc) progname = argv[0];245 99 unmodified lines345 if (isoption(argv[i], 0, "seq", &short_opts)) {346 options |= SEQ;347 if (!short_opts) continue;348 }349+ if (isoption(argv[i], 0, "stream", &short_opts)) {350+ parser_flags |= JV_PARSE_STREAMING;351+ if (!short_opts) continue;352+ }353+ if (isoption(argv[i], 0, "stream-errors", &short_opts)) {354+ parser_flags |= JV_PARSE_STREAM_ERRORS;355+ if (!short_opts) continue;356+ }357 if (isoption(argv[i], 'e', "exit-status", &short_opts)) {358 options |= EXIT_STATUS;359 if (!short_opts) continue;360 }175 unmodified lines536 jq_dump_disassembly(jq, 0);537 printf("\n");538 }539 540+ // XXX Refactor this and input_filenames[] and related setup into a541+ // function to setup struct next_input_state.542+ if ((options & SEQ))543+ parser_flags |= JV_PARSE_SEQ;544+545+ struct next_input_state input_state;546+ input_state.parser = jv_parser_new(parser_flags);547+ if ((options & RAW_INPUT) && (options & SLURP))548+ input_state.slurped = jv_string("");549+ else if ((options & SLURP))550+ input_state.slurped = jv_array();551+ else552+ input_state.slurped = jv_invalid();553+554+ // Let jq program read from inputs555+ jq_set_input_cb(jq, next_input, &input_state);556+557 if (options & PROVIDE_NULL) {558 ret = process(jq, jv_null(), jq_flags);559 } else {482- jv slurped;483- if (options & SLURP) {484- if (options & RAW_INPUT) {485- slurped = jv_string("");486- } else {487- slurped = jv_array();560+ jv value;561+ while (jv_is_valid((value = next_input(jq, &input_state))) || jv_invalid_has_msg(jv_copy(value))) {562+ if (jv_is_valid(value)) {563+ ret = process(jq, value, jq_flags);564+ continue;565 }489- }490- struct jv_parser* parser = jv_parser_new((options & SEQ) ? JV_PARSE_SEQ : 0);491- char buf[4096];492- int is_last = 0;493- do {494- is_last = read_more(buf, sizeof(buf));495- if (options & RAW_INPUT) {496- int len = strlen(buf);497- if (len > 0) {498- if (options & SLURP) {499- slurped = jv_string_concat(slurped, jv_string(buf));500- } else {501- if (buf[len-1] == '\n') buf[len-1] = 0;502- ret = process(jq, jv_string(buf), jq_flags);503- }504- }505- } else {506- jv_parser_set_buf(parser, buf, strlen(buf), !is_last);507- jv value;508- while (jv_is_valid(value = jv_parser_next(parser)) || jv_invalid_has_msg(jv_copy(value))) {509- if (!jv_is_valid(value)) {510- jv msg = jv_invalid_get_msg(value);511- if (!(options & SEQ)) {512- // We used to treat parse errors as fatal...513- ret = 4;514- fprintf(stderr, "parse error: %s\n", jv_string_value(msg));515- jv_free(msg);516- break;566+567+ // Parse error568+ jv msg = jv_invalid_get_msg(value);569+ if (!(options & SEQ)) {570+ // --seq -> errors are not fatal571+ ret = 4;572+ fprintf(stderr, "parse error: %s\n", jv_string_value(msg));573+ jv_free(msg);574+ break;517- }518- fprintf(stderr, "ignoring parse error: %s\n", jv_string_value(msg));519- jv_free(msg);520- // ...but with --seq we attempt to recover.521- continue;522- }523- if (options & SLURP) {524- slurped = jv_array_append(slurped, value);525- } else {526- ret = process(jq, value, jq_flags);527- value = jv_invalid();528- }529- }575 }531- } while (!is_last);532- jv_parser_free(parser);533- if (ret != 0)534- goto out;576+ fprintf(stderr, "ignoring parse error: %s\n", jv_string_value(msg));577+ jv_free(msg);578+ }579 if (options & SLURP) {536- ret = process(jq, slurped, jq_flags);580+ ret = process(jq, input_state.slurped, jq_flags);581+ input_state.slurped = jv_invalid();582 }583 }584+585+ jv_free(input_state.slurped);586+ jv_parser_free(input_state.parser);587+588+ if (ret != 0)589+ goto out;590+591 if ((options & IN_PLACE)) {592 FILE *devnull;593 #ifdef WIN32594 devnull = freopen("NUL", "w+", stdout);22 unmodified lines