Debian Codegraph @

easel/esl_json.c

raw symbols SCIP
1 /* esl_json : JSON data file parsing
2 *
3 * Inspired by Serge Zaitsev's Jasmine parser, https://github.com/zserge/jsmn
4 *
5 * Contents:
6 * 1. Full or incremental JSON parsing
7 * 2. ESL_JSON: a JSON parse tree
8 * 3. ESL_JSON_PARSER: precise state at each input byte
9 * 4. Accessing tokenized data
10 * 5. Debugging, development tools
11 * 6. Internal functions
12 * 7. Unit tests
13 * 8. Test driver
14 * 9. Example
15 *
16 * References:
17 * www.json.org
18 * tools.ietf.org/html/rfc8259
19 */
20 #include <esl_config.h>
21
22 #include <stdio.h>
23 #include <ctype.h>
24 #include <limits.h>
25 #include <string.h>
26
27 #include "easel.h"
28 #include "esl_buffer.h"
29 #include "esl_mem.h"
30 #include "esl_random.h"
31 #include "esl_stack.h"
32 #include "esl_json.h"
33
34 static int new_token(ESL_JSON_PARSER *parser, ESL_JSON *pi, enum esl_json_type_e type, esl_pos_t startpos);
35 static void add_dirty_unicode(ESL_RANDOMNESS *rng, char *b, int n, int *ret_nadd);
36
37
38
39 /*****************************************************************
40 * 1. Full or incremental JSON parsing
41 *****************************************************************/
42
43 /* Function: esl_json_Parse()
44 * Synopsis: Parse a complete JSON data object
45 * Incept: SRE, Sun 29 Jul 2018 [IB 6165 Madrid-Boston]
46 *
47 * Purpose: Given an open input buffer <bf>, read the next
48 * complete JSON data object from it. Return the
49 * parse tree thru <*ret_pi>.
50 *
51 * Upon successful return, the buffer <bf>'s point is
52 * sitting precisely on the next byte following the closing
53 * brace of the JSON object.
54 *
55 * Args: bf - open buffer for reading
56 * ret_pi - RETURN: JSON parse tree
57 *
58 * Returns: <eslOK> on success, and <*ret_pi> points
59 * to the parse tree.
60 *
61 * <eslEFORMAT> if the JSON data string is
62 * invalid. <bf->errbuf> is set to a user-friendly
63 * error message indicating why. <*ret_pi> is <NULL>.
64 *
65 * Throws: <eslEMEM> on allocation failure.
66 *
67 * On these exceptions, <*ret_pi> is returned <NULL>.
68 */
69 int
70 esl_json_Parse(ESL_BUFFER *bf, ESL_JSON **ret_pi)
71 {
72 ESL_JSON_PARSER *parser = esl_json_parser_Create();
73 ESL_JSON *pi = esl_json_Create();
74 char *s = NULL;
75 esl_pos_t n = 0;
76 esl_pos_t pos0 = esl_buffer_GetOffset(bf);
77 esl_pos_t nused;
78 int status = eslOK;
79
80 if (parser == NULL || pi == NULL) { status = eslEMEM; goto ERROR; }
81
82 esl_buffer_SetAnchor(bf, pos0);
83 while (status == eslOK && esl_buffer_Get(bf, &s, &n) == eslOK)
84 {
85 status = esl_json_PartialParse(parser, pi, s, n, &nused, bf->errmsg);
86 if (status != eslOK && status != eslEOD) goto ERROR;
87
88 esl_buffer_Set(bf, s, nused);
89 }
90 esl_buffer_RaiseAnchor(bf, pos0);
91
92 esl_json_parser_Destroy(parser);
93 *ret_pi = pi;
94 return eslOK;
95
96 ERROR:
97 esl_json_parser_Destroy(parser);
98 esl_json_Destroy(pi);
99 return status;
100 }
101
102
103 /* Function: esl_json_PartialParse()
104 * Synopsis: Incremental parse of a chunk of JSON data string.
105 * Incept: SRE, Sun 29 Jul 2018 [IB 6165 Madrid-Boston]
106 *
107 * Purpose: Parse a chunk of input JSON data string <s> of length <n>,
108 * adding incrementally to a parse tree <pi>. A <parser>
109 * keeps precise byte-by-byte state information, enabling
110 * parsing to stop and start across different chunks.
111 *
112 * At the first chunk, caller provides a freshly created
113 * <ESL_JSON_PARSER> as <parser>. At subsequent chunks,
114 * caller provides the parser state from the previous call.
115 *
116 * If a complete JSON object is finished in this chunk,
117 * return <eslEOD>, and <*nused> is the number of bytes
118 * that were consumed (inclusive of the closing brace),
119 * <nused> $\leq$ <n>.
120 *
121 * Args: parser - parser state information from previous chunk
122 * pi - incremental JSON parse tree - updated upon success
123 * s - next chunk of JSON data byte array to parse. \0-termination isn't needed.
124 * n - length of <s>
125 * ret_nused - RETURN: number of bytes consumed from <s>.
126 * This is <n> on <eslOK>, $\leq$ <n> on <eslEOD>.
127 * errbuf - OPTIONAL: <eslERRBUFSIZE> buffer for an error message, or <NULL>
128 *
129 * Returns: <eslOK> on success, where the entire chunk was parsed
130 * without completing a JSON object, consuming all <n>
131 * bytes, so <*ret_nused> is <n>. <parser> is updated to
132 * hold the parser state after the last byte of <s>. Parse
133 * tree <pi> is incrementally updated. Caller can pass
134 * <parser>, <pi> to parse the next chunk.
135 *
136 * <eslEOD> on success, where a complete JSON data object
137 * ended in this chunk after consuming <*ret_nused> bytes,
138 * inclusive of closing brace. The <parser> state is
139 * <eslJSON_OBJ_NONE>, and its <pos>, <linenum>, and
140 * <linepos> are set to the byte immediately following the
141 * close brace, ready to parse another JSON object in the
142 * stream if it's a stream of concatenated objects.
143 * <pi> contains a complete JSON parse tree.
144 *
145 * <eslEFORMAT> on an invalid JSON string:
146 * <errbuf> contains a detailed (line/cpos) error message.
147 */
148 int
149 esl_json_PartialParse(ESL_JSON_PARSER *parser, ESL_JSON *pi, const char *s, esl_pos_t n, esl_pos_t *ret_nused, char *errbuf)
150 {
151 esl_pos_t i;
152 enum esl_json_type_e closed_value;
153
154 for (i = 0; i < n; i++, parser->pos++)
155 {
156 closed_value = eslJSON_UNKNOWN; // i.e. FALSE, we didn't close a value; changes to something if we do.
157 switch (parser->state) {
158 case eslJSON_OBJ_NONE: // Only at very beginning of parse: initialize with root object
159 if (s[i] == '{') { parser->state = eslJSON_OBJ_OPEN; new_token(parser, pi, eslJSON_OBJECT, parser->pos); }
160 else if (! isspace(s[i])) ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d). expected JSON object to start with {", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.1}
161 break;
162
163 case eslJSON_OBJ_OPEN:
164 if (s[i] == '"') { parser->state = eslJSON_KEY_OPEN; new_token(parser, pi, eslJSON_KEY, parser->pos+1); } // pos+1 because not including the quote
165 else if (s[i] == '}') closed_value = eslJSON_OBJECT;
166 else if (! isspace(s[i])) ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d). expected JSON object key, or closing }", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.3}
167 break;
168
169 case eslJSON_OBJ_COMMA:
170 if (s[i] == '"') { parser->state = eslJSON_KEY_OPEN; new_token(parser, pi, eslJSON_KEY, parser->pos+1); }
171 else if (! isspace(s[i])) ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d). expected JSON object key after comma", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.2}
172 break;
173
174 case eslJSON_OBJ_COLON:
175 case eslJSON_ARR_OPEN:
176 case eslJSON_ARR_COMMA:
177 if (s[i] == '"') { parser->state = eslJSON_STR_OPEN; new_token(parser, pi, eslJSON_STRING, parser->pos+1); }
178 else if (s[i] == '{') { parser->state = eslJSON_OBJ_OPEN; new_token(parser, pi, eslJSON_OBJECT, parser->pos); }
179 else if (s[i] == '[') { parser->state = eslJSON_ARR_OPEN; new_token(parser, pi, eslJSON_ARRAY, parser->pos); }
180 else if (s[i] == '-') { parser->state = eslJSON_NUM_SIGN; new_token(parser, pi, eslJSON_NUMBER, parser->pos); }
181 else if (s[i] == '0') { parser->state = eslJSON_NUM_ZERO; new_token(parser, pi, eslJSON_NUMBER, parser->pos); }
182 else if (isdigit(s[i])) { parser->state = eslJSON_NUM_NONZERO; new_token(parser, pi, eslJSON_NUMBER, parser->pos); }
183 else if (s[i] == 't') { parser->state = eslJSON_VAL_TRUE; new_token(parser, pi, eslJSON_BOOLEAN, parser->pos); }
184 else if (s[i] == 'f') { parser->state = eslJSON_VAL_FALSE; new_token(parser, pi, eslJSON_BOOLEAN, parser->pos); }
185 else if (s[i] == 'n') { parser->state = eslJSON_VAL_NULL; new_token(parser, pi, eslJSON_NULL, parser->pos); }
186 else if (! isspace(s[i])) ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d). expected JSON value", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.4}
187 break;
188
189 case eslJSON_STR_OPEN:
190 case eslJSON_STR_CHAR:
191 case eslJSON_STR_PROTECTED:
192 if ( s[i] == '\\' ) parser->state = eslJSON_STR_BACKSLASH;
193 else if ( s[i] == '"' ) closed_value = eslJSON_STRING;
194 else if (! iscntrl(s[i])) parser->state = eslJSON_STR_CHAR; // anything not forbidden is allowed: this will accept UTF-8 one byte at a time, though without validating that it's a valid UTF-8 byte sequence.
195 else ESL_FAIL(eslEFORMAT, errbuf, "invalid control char at line %d pos %d. expected JSON string character", parser->linenum, parser->linepos); // {jbad.5} (For god's sake don't try to print it.) In emacs: C-q <key> to insert, for instance DEL.
196 break;
197
198 case eslJSON_KEY_OPEN:
199 case eslJSON_KEY_CHAR:
200 case eslJSON_KEY_PROTECTED:
201 if ( s[i] == '\\' ) parser->state = eslJSON_KEY_BACKSLASH;
202 else if ( s[i] == '"' ) closed_value = eslJSON_KEY;
203 else if (! iscntrl(s[i])) parser->state = eslJSON_KEY_CHAR;
204 else ESL_FAIL(eslEFORMAT, errbuf, "invalid control char at line %d pos %d. expected JSON key character", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.6}
205 break;
206
207 case eslJSON_STR_BACKSLASH:
208 if ( strchr("\"\\/bfnrt", s[i]) != NULL) parser->state = eslJSON_STR_PROTECTED;
209 else if ( s[i] == 'u') parser->state = eslJSON_STR_UNICODE;
210 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d). After \\, valid JSON chars are \"\\/bfnrtu", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.7}
211 break;
212
213 case eslJSON_KEY_BACKSLASH:
214 if ( strchr("\"\\/bfnrt", s[i]) != NULL) parser->state = eslJSON_KEY_PROTECTED;
215 else if ( s[i] == 'u') parser->state = eslJSON_KEY_UNICODE;
216 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d). After \\, valid JSON chars are \"\\/bfnrtu", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.8}
217 break;
218
219 case eslJSON_STR_UNICODE:
220 if ( isxdigit(s[i])) parser->codelen++;
221 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d). In JSON unicode, expected hex digit", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.9}
222 if ( parser->codelen == 4) { parser->state = eslJSON_STR_PROTECTED; parser->codelen = 0; }
223 break;
224
225 case eslJSON_KEY_UNICODE:
226 if ( isxdigit(s[i])) parser->codelen++;
227 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d). In JSON unicode, expected hex digit", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.10}
228 if ( parser->codelen == 4) { parser->state = eslJSON_KEY_PROTECTED; parser->codelen = 0; }
229 break;
230
231 case eslJSON_NUM_SIGN:
232 if (s[i] == '0') parser->state = eslJSON_NUM_ZERO;
233 else if (isdigit(s[i])) parser->state = eslJSON_NUM_NONZERO;
234 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) in number after leading sign of JSON number", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.11}
235 break;
236
237 case eslJSON_NUM_ZERO:
238 if (s[i] == '.') parser->state = eslJSON_NUM_POINT;
239 else if (strchr("eE", s[i])) parser->state = eslJSON_NUM_EXP;
240 else if (strchr(",]}", s[i])) closed_value = eslJSON_NUMBER;
241 else if (isspace(s[i])) closed_value = eslJSON_NUMBER;
242 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) after leading zero of JSON number", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.12}
243 break;
244
245 case eslJSON_NUM_NONZERO:
246 case eslJSON_NUM_LEADDIGIT:
247 if (isdigit(s[i])) parser->state = eslJSON_NUM_LEADDIGIT;
248 else if (s[i] == '.') parser->state = eslJSON_NUM_POINT;
249 else if (strchr("eE", s[i])) parser->state = eslJSON_NUM_EXP;
250 else if (strchr(",]}", s[i])) closed_value = eslJSON_NUMBER;
251 else if (isspace(s[i])) closed_value = eslJSON_NUMBER;
252 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) after leading digit(s) of JSON number", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.13}
253 break;
254
255 case eslJSON_NUM_POINT:
256 if (isdigit(s[i])) parser->state = eslJSON_NUM_FRACDIGIT;
257 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) after decimal point of JSON number", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.14}
258 break;
259
260 case eslJSON_NUM_FRACDIGIT:
261 if (isdigit(s[i])) parser->state = eslJSON_NUM_FRACDIGIT;
262 else if (strchr("eE", s[i])) parser->state = eslJSON_NUM_EXP;
263 else if (strchr(",]}", s[i])) closed_value = eslJSON_NUMBER;
264 else if (isspace(s[i])) closed_value = eslJSON_NUMBER;
265 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) in fractional part of JSON number", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.15}
266 break;
267
268 case eslJSON_NUM_EXP:
269 if (isdigit(s[i])) parser->state = eslJSON_NUM_EXPDIGIT;
270 else if (strchr("+-", s[i])) parser->state = eslJSON_NUM_EXPSIGN;
271 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) in exponent of JSON number", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.16}
272 break;
273
274 case eslJSON_NUM_EXPSIGN:
275 if (isdigit(s[i])) parser->state = eslJSON_NUM_EXPDIGIT;
276 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) after exponent sign of JSON number", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.17}
277 break;
278
279 case eslJSON_NUM_EXPDIGIT:
280 if (isdigit(s[i])) parser->state = eslJSON_NUM_EXPDIGIT;
281 else if (strchr(",]}", s[i])) closed_value = eslJSON_NUMBER;
282 else if (isspace(s[i])) closed_value = eslJSON_NUMBER;
283 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) in exponent of JSON number", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.18}
284 break;
285
286 case eslJSON_VAL_TRUE:
287 if (s[i] != "true"[++parser->codelen]) ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) in JSON 'true'", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.19}
288 if (parser->codelen == 3) { parser->codelen = 0; closed_value = eslJSON_BOOLEAN; }
289 break;
290
291 case eslJSON_VAL_FALSE:
292 if (s[i] != "false"[++parser->codelen]) ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) in JSON 'false'", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.20}
293 if (parser->codelen == 4) { parser->codelen = 0; closed_value = eslJSON_BOOLEAN; }
294 break;
295
296 case eslJSON_VAL_NULL:
297 if (s[i] != "null"[++parser->codelen]) ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) in JSON 'null'", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.21}
298 if (parser->codelen == 3) { parser->codelen = 0; closed_value = eslJSON_NULL; }
299 break;
300
301 case eslJSON_VAL_INOBJ:
302 if (s[i] == ',') parser->state = eslJSON_OBJ_COMMA;
303 else if (s[i] == '}') closed_value = eslJSON_OBJECT;
304 else if (! isspace(s[i])) ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) after JSON object value", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.22}
305 break;
306
307 case eslJSON_VAL_INARR:
308 if (s[i] == ',') parser->state = eslJSON_ARR_COMMA;
309 else if (s[i] == ']') closed_value = eslJSON_ARRAY;
310 else if (! isspace(s[i])) ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) after JSON array value", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.23}
311 break;
312
313 case eslJSON_STR_ASKEY:
314 if (s[i] == ':') parser->state = eslJSON_OBJ_COLON;
315 else if (! isspace(s[i])) ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) after JSON key", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.24}
316 break;
317
318 default: esl_fatal("no such state");
319 } // end of the big switch for parsing one character given curr state
320
321 /* Solely for informative error messages, keep track of line number and position on line.
322 * Advance counters to what byte i+1 will be.
323 */
324 if (s[i] == '\n') { parser->linenum++; parser->linepos = 1; }
325 else { parser->linepos++; }
326
327 /* for number values, we didn't know whether we've closed the value
328 * until we saw a non-value character: whitespace, comma, or
329 * *another* close-value character ] or }. A ] or } means we're
330 * closing two values, not just one: we close the number here,
331 * and set state to the `if (ended_value)` block below closes the obj/arr.
332 */
333 if (closed_value == eslJSON_NUMBER)
334 {
335 pi->tok[parser->curridx].endpos = parser->pos-1;
336 esl_stack_IPop(parser->pda, &(parser->curridx));
337 closed_value = eslJSON_UNKNOWN;
338
339 if (pi->tok[parser->curridx].type == eslJSON_OBJECT)
340 {
341 if (s[i] == ',') parser->state = eslJSON_OBJ_COMMA;
342 else if (s[i] == '}') { parser->state = eslJSON_VAL_INOBJ; closed_value = eslJSON_OBJECT; }
343 else if (isspace(s[i])) parser->state = eslJSON_VAL_INOBJ;
344 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) after JSON number in key:value pair", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.25}
345 }
346 else if (pi->tok[parser->curridx].type == eslJSON_ARRAY)
347 {
348 if (s[i] == ',') parser->state = eslJSON_ARR_COMMA;
349 else if (s[i] == ']') { parser->state = eslJSON_VAL_INARR; closed_value = eslJSON_ARRAY; }
350 else if (isspace(s[i])) parser->state = eslJSON_VAL_INARR;
351 else ESL_FAIL(eslEFORMAT, errbuf, "invalid char `%c` (line %d pos %d) after JSON number in array", isprint(s[i]) ? s[i] : ' ', parser->linenum, parser->linepos); // {jbad.26}
352 }
353 else esl_fatal("doesn't happen");
354 }
355
356 /* for all other values but numbers (string, array, obj, true,
357 * false, null) we know when we've properly closed the
358 * value, on a character that we can consider to be part of
359 * the value itself. Now to figure out what state we've just
360 * moved to, when we close this value, we need to know
361 * whether this value was an obj key, obj value, array
362 * value, or the root object.
363 */
364 if (closed_value != eslJSON_UNKNOWN)
365 {
366 pi->tok[parser->curridx].endpos = ( (pi->tok[parser->curridx].type == eslJSON_STRING || pi->tok[parser->curridx].type == eslJSON_KEY) ? parser->pos-1 : parser->pos);
367 if ( esl_stack_IPop(parser->pda, &(parser->curridx)) == eslEOD)
368 { // if we have nothing to pop, we just closed the root object at i, parser->pos.
369 // advance to next byte, and reinitialize state
370 parser->curridx = -1; // no tokens are open.
371 parser->codelen = 0;
372 parser->state = eslJSON_OBJ_NONE;
373 parser->pos++;
374 i++;
375 break;
376 }
377 if (closed_value == eslJSON_KEY) parser->state = eslJSON_STR_ASKEY;
378 else if (pi->tok[parser->curridx].type == eslJSON_OBJECT) parser->state = eslJSON_VAL_INOBJ;
379 else if (pi->tok[parser->curridx].type == eslJSON_ARRAY) parser->state = eslJSON_VAL_INARR;
380 }
381 } // end loop over chars in s[0..n-1] string.
382 *ret_nused = i;
383 return (i < n ? eslEOD : eslOK);
384 }
385
386
387
388 /*****************************************************************
389 * 2. ESL_JSON : a JSON parse tree
390 *****************************************************************/
391
392 /* Function: esl_json_Create()
393 * Synopsis: Create a new, empty JSON parse tree object
394 * Incept: SRE, Tue 31 Jul 2018 [Clint Mansell, Moon]
395 *
396 * Throws: <NULL> on allocation failure.
397 */
398 ESL_JSON *
399 esl_json_Create(void)
400 {
401 ESL_JSON *pi = NULL;
402 int status;
403
404 ESL_ALLOC(pi, sizeof(ESL_JSON));
405 pi->tok = NULL;
406
407 ESL_ALLOC(pi->tok, sizeof (ESL_JSON_TOK) * 32);
408 pi->nalloc = 32;
409 pi->redline = 65536; // M ~= 2114 for HMMER profile parser; ~3.1M @48B/token. See HMMER h4_hmmfile.md if you change; xref SRE:H5/131.
410 pi->ntok = 0;
411 return pi;
412
413 ERROR:
414 esl_json_Destroy(pi);
415 return NULL;
416 }
417
418 /* Function: esl_json_Grow()
419 * Synopsis: Double the allocation in a parse tree.
420 */
421 int
422 esl_json_Grow(ESL_JSON *pi)
423 {
424 int status;
425 ESL_REALLOC(pi->tok, sizeof(ESL_JSON_TOK) * pi->nalloc * 2);
426 pi->nalloc *= 2;
427 return eslOK;
428
429 ERROR:
430 return status;
431 }
432
433 /* Function: esl_json_Sizeof()
434 * Synopsis: Returns allocated size of a parse tree, in bytes
435 */
436 size_t
437 esl_json_Sizeof(ESL_JSON *pi)
438 {
439 size_t n = 0;
440 n += sizeof(ESL_JSON);
441 n += sizeof(ESL_JSON_TOK) * pi->nalloc;
442 return n;
443 }
444
445 /* Function: esl_json_MinSizeof()
446 * Synopsis: Returns minimum size required for a parse tree, in bytes
447 */
448 size_t
449 esl_json_MinSizeof(ESL_JSON *pi)
450 {
451 size_t n = 0;
452 n += sizeof(ESL_JSON);
453 n += sizeof(ESL_JSON_TOK) * pi->ntok;
454 return n;
455 }
456
457 /* Function: esl_json_Reuse()
458 * Synopsis: Reinitialize an existing parse tree for reuse.
459 * Incept: SRE, Sun 05 Aug 2018 [Clint Mansell, Welcome to Lunar Industries]
460 */
461 int
462 esl_json_Reuse(ESL_JSON *pi)
463 {
464 int status;
465 if (pi->nalloc > pi->redline) {
466 ESL_REALLOC(pi->tok, sizeof(ESL_JSON_TOK) * pi->redline);
467 pi->nalloc = pi->redline;
468 }
469 pi->ntok = 0;
470 return eslOK;
471
472 ERROR:
473 return status;
474 }
475
476
477 /* Function: esl_json_Destroy()
478 * Synopsis: Free a parse tree.
479 */
480 void
481 esl_json_Destroy(ESL_JSON *pi)
482 {
483 if (pi)
484 {
485 free(pi->tok);
486 free(pi);
487 }
488 }
489
490 /*****************************************************************
491 * 3. ESL_JSON_PARSER : precise state at each input byte
492 *****************************************************************/
493
494 /* Function: esl_json_parser_Create()
495 * Synopsis: Create and initialize a new ESL_JSON_PARSER
496 * Incept: SRE, Tue 31 Jul 2018 [Clint Mansell, Moon]
497 *
498 * Throws: <NULL> on allocation failure.
499 */
500 ESL_JSON_PARSER *
501 esl_json_parser_Create(void)
502 {
503 ESL_JSON_PARSER *parser = NULL;
504 int status;
505
506 ESL_ALLOC(parser, sizeof(ESL_JSON_PARSER));
507 if (( parser->pda = esl_stack_ICreate()) == NULL) { status = eslEMEM; goto ERROR; }
508
509 parser->pos = 0;
510 parser->linenum = 1;
511 parser->linepos = 1;
512 parser->state = eslJSON_OBJ_NONE;
513 parser->curridx = -1;
514 parser->codelen = 0;
515 return parser;
516
517 ERROR:
518 esl_json_parser_Destroy(parser);
519 return NULL;
520 }
521
522
523 /* Function: esl_json_parser_Destroy()
524 * Synopsis: Frees an ESL_JSON_PARSER
525 */
526 void
527 esl_json_parser_Destroy(ESL_JSON_PARSER *parser)
528 {
529 if (parser)
530 {
531 esl_stack_Destroy(parser->pda);
532 free(parser);
533 }
534 }
535
536
537
538 /*****************************************************************
539 * 4. Accessing tokenized data in ESL_JSON
540 *****************************************************************/
541
542 char *
543 esl_json_GetMem(const ESL_JSON *pi, int idx, const ESL_BUFFER *bf)
544 {
545 return bf->mem + pi->tok[idx].startpos - bf->baseoffset;
546 }
547
548 esl_pos_t
549 esl_json_GetLen(const ESL_JSON *pi, int idx, const ESL_BUFFER *bf)
550 {
551 return pi->tok[idx].endpos - pi->tok[idx].startpos + 1;
552 }
553
554
555 /* Function: esl_json_ReadInt()
556 * Synopsis: Read an integer from a valid JSON number token.
557 * Incept: SRE, Tue 14 Aug 2018
558 *
559 * Purpose: Parse tree <pi> token <idx> is a validated JSON number
560 * in input buffer <bf>; return its value in <*ret_i>.
561 *
562 * JSON number format is a superset of the integers.
563 * Valid integers match <-?0 | -?[1-9][0-9]*>.
564 *
565 * Args: pi - JSON parse tree
566 * idx - index of token in <pi>
567 * bf - input buffer that <pi> is for
568 * ret_i - RETURN: integer value
569 *
570 * Returns: <eslOK> on success, and <*ret_i> contains the value.
571 *
572 * <eslEFORMAT> if the complete token isn't a valid integer,
573 * and <*ret_i> is 0.
574 *
575 * <eslERANGE> if the integer value overflows (underflows)
576 * INT_MAX (INT_MIN), and <*ret_i> is INT_MAX (INT_MIN).
577 *
578 * Throws: (no abnormal error conditions)
579 *
580 * Xref: Shares code with <esl_mem_strtoi()>. Less (and different)
581 * error checking, because we assume token has already been
582 * validated as a JSON number format, and we assume that
583 * the entire token consists of integer (no whitespace or
584 * trailing stuff), and it must be base 10.
585 */
586 int
587 esl_json_ReadInt(const ESL_JSON *pi, int idx, ESL_BUFFER *bf, int *ret_i)
588 {
589 char *p = esl_json_GetMem(pi, idx, bf);
590 esl_pos_t n = esl_json_GetLen(pi, idx, bf);
591 int val = 0;
592 esl_pos_t i = 0;
593 int sign = 1;
594 int digit = 0;
595
596 bf->errmsg[0] = '\0';
597
598 if (p[i] == '-') { sign = -1; i++; }
599 for (; i < n; i++)
600 { // don't have to check leading zero specially; JSON parser has already validated that it's not 00, 0a, or some such.
601 if (! isdigit(p[i])) { *ret_i = 0; ESL_FAIL(eslEFORMAT, bf->errmsg, "bad JSON integer format, contains nondigit"); } // only happens for .eE+-: components of a float
602 digit = p[i] - '0';
603
604 if (sign == 1 && val > (INT_MAX - digit) / 10) { *ret_i = INT_MAX; return eslERANGE; }
605 if (sign == -1 && val < (INT_MIN + digit) / 10) { *ret_i = INT_MIN; return eslERANGE; }
606 val = val * 10 + sign * digit;
607 }
608 *ret_i = val;
609 return eslOK;
610 }
611
612
613 /* Function: esl_json_ReadFloat()
614 * Synopsis: Read a float from a valid JSON number token.
615 * Incept: SRE, Tue 14 Aug 2018
616 *
617 * Purpose: Given a parse tree <pi>, where token <idx> is a validated
618 * JSON number in input buffer <bf>, convert the decimal
619 * string representation to a float; return the float in
620 * <*ret_x>.
621 *
622 * This function is adapted from <esl_mem_strtof()>.
623 * Because the input was already validated as a JSON
624 * number, and all JSON numbers are valid floating-point
625 * decimal string representations, so no error checking is
626 * needed, and the complete token is converted. JSON does
627 * not have a representation for "NaN" or "infinity".
628 *
629 * If the representation overflows (e.g. "1e999") the
630 * result is +/-infinity. If it underflows (e.g. "1e-999")
631 * the result is 0. These conversions still return
632 * <eslOK>.
633 *
634 * Like <esl_mem_strtof()>, this conversion incurs a small
635 * roundoff error (usually within +/-1 ulp) that a strictly
636 * correct <strtof()> implementation does not. See
637 * <esl_mem.md> for discussion.
638 *
639 * Returns: <eslOK>.
640 */
641 int
642 esl_json_ReadFloat(const ESL_JSON *pi, int idx, ESL_BUFFER *bf, float *ret_x)
643 {
644 esl_pos_t n = esl_json_GetLen(pi, idx, bf);
645 char *p = esl_json_GetMem(pi, idx, bf);
646 int i = 0;
647 float sign = 1.0;
648 float val = 0.0;
649 float frac = 0.1;
650 float expsign = 1.;
651 float exponent = 0.;
652
653 /* Parser already verified p[0..n-1] is valid JSON number, so we can
654 * use a stripped-down copy of esl_mem_strtof(); we don't need to
655 * check for inf|nan|infinity, for example. Large speed win.
656 */
657 if (p[i] == '-') { sign = -1.0; i++; }
658 while (i < n && isdigit(p[i])) val = 10. * val + (p[i++]-'0');
659 if (i < n && p[i] == '.')
660 while (++i < n && isdigit(p[i]))
661 {
662 val += (p[i]-'0') * frac;
663 frac *= 0.1; // this is a source of roundoff error.
664 }
665 if (i < n && (p[i] == 'e' || p[i] == 'E'))
666 {
667 i++;
668 if (p[i] == '-') { expsign = -1.; i++; }
669 else if (p[i] == '+') { expsign = 1.; i++; }
670 while (i < n && isdigit(p[i]))
671 exponent = 10.*exponent + (p[i++]-'0') ;
672
673 exponent = exponent * expsign;
674 if (isfinite(val)) while ( val >= 10. ) { exponent += 1.; val /= 10.; } // renormalization. (and another source of roundoff error)
675 if (val != 0.0) while ( val < 1. ) { exponent -= 1.; val *= 10.; }
676 }
677 ESL_DASSERT1(( i == n ));
678
679 *ret_x = sign * val * powf(10.,exponent); // range errors (over/underflow) aren't checked for; just let it go to +/-inf.
680 return eslOK;
681 }
682
683
684
685
686 /*****************************************************************
687 * 5. Debugging, development tools
688 *****************************************************************/
689
690 /* Function: esl_json_Validate()
691 * Synopsis: Validate a JSON parse tree structure
692 * Incept: SRE, Tue 31 Jul 2018 [Clint Mansell, Moon soundtrack]
693 *
694 * Purpose: Validate internals of JSON parse tree <pi>. If optional
695 * <bf> is provided, do additional validation that
696 * substrings of the parsed input appear to match what the
697 * parse tree says they should be. If all seems ok, return
698 * <eslOK>. If bad, return <eslFAIL> and (if optional
699 * <errbuf> is provided), put an informative user-directed
700 * error message in <errbuf>.
701 *
702 * Args: pi - parse tree to validate
703 * bf - optional - input buffer that <pi> corresponds to, or NULL
704 * errbuf - optional - informative error message on failure, or NULL
705 *
706 * Returns: <eslOK> on success. <errbuf>, if it was provided, is an empty string.
707 *
708 * <eslFAIL> on failure. <errbuf>, if it was provided, contains
709 * an informative error message.
710 */
711 int
712 esl_json_Validate(const ESL_JSON *pi, const ESL_BUFFER *bf, char *errbuf)
713 {
714 int i,n;
715 ESL_JSON_TOK *tok;
716 int cur, prv; // token indices, following linked list of children
717 esl_pos_t pos1, pos2; // start, end coords for a token, adjusted to bf->mem coords if <bf> is passed
718
719 if (errbuf) errbuf[0] = '\0';
720
721 for (i = 0; i < pi->ntok; i++)
722 {
723 tok = &(pi->tok[i]);
724 pos1 = (bf ? tok->startpos - bf->baseoffset : tok->startpos); // bf->mem[0] = s[baseoffset] in original input coords for <s>
725 pos2 = (bf ? tok->endpos - bf->baseoffset : tok->endpos);
726
727 if (pos1 < 0) ESL_FAIL(eslFAIL, errbuf, "bad start pos, tok %d", i);
728 if (pos2 < 0) ESL_FAIL(eslFAIL, errbuf, "bad end pos, tok %d", i);
729 if ((tok->type == eslJSON_KEY || tok->type == eslJSON_STRING))
730 { if (pos2 < pos1-1) ESL_FAIL(eslFAIL, errbuf, "bad end pos, string/key tok %d", i); } // a zero-length string or key has endpos = startpos-1
731 else
732 { if (pos2 < pos1) ESL_FAIL(eslFAIL, errbuf, "bad end pos, tok %d", i); }
733
734 /* integrity of child linked list */
735 for (cur = tok->firstchild, n=0, prv=-1; cur != -1; cur = pi->tok[cur].nextsib) { n++; prv = cur; }
736 if (tok->nchild > 0 && (tok->firstchild == -1 || tok->lastchild == -1)) ESL_FAIL(eslFAIL, errbuf, "bad child links, tok %d", i);
737 if (tok->nchild == 0 && (tok->firstchild != -1 || tok->lastchild != -1)) ESL_FAIL(eslFAIL, errbuf, "tok %d shouldn't have child links");
738 if (tok->nchild != n) ESL_FAIL(eslFAIL, errbuf, "bad number of children, tok %d", i);
739 if (tok->lastchild != prv) ESL_FAIL(eslFAIL, errbuf, "bad child linked list for tok %d", i);
740 /* optionally, if <bf> provided, partially validate each substring */
741 if (bf)
742 {
743 if (pos1 >= bf->n) ESL_FAIL(eslFAIL, errbuf, "bad start pos, tok %d", i);
744 if (pos2 >= bf->n) ESL_FAIL(eslFAIL, errbuf, "bad end pos, tok %d", i);
745
746 switch (tok->type) {
747 case eslJSON_OBJECT: if (bf->mem[pos1] != '{' || bf->mem[pos2] != '}') { ESL_FAIL(eslFAIL, errbuf, "object closing brackets missing, tok %d", i); } break;
748 case eslJSON_ARRAY: if (bf->mem[pos1] != '[' || bf->mem[pos2] != ']') { ESL_FAIL(eslFAIL, errbuf, "array closing brackets missing, tok %d", i); } break;
749 case eslJSON_KEY: if (bf->mem[pos1-1] != '"' || bf->mem[pos2+1] != '"') { ESL_FAIL(eslFAIL, errbuf, "key quotes missing, tok %d", i); } break;
750 case eslJSON_STRING: if (bf->mem[pos1-1] != '"' || bf->mem[pos2+1] != '"') { ESL_FAIL(eslFAIL, errbuf, "string quotes missing, tok %d", i); } break;
751 case eslJSON_NUMBER: if (! esl_mem_IsReal(bf->mem + pos1, pos2-pos1+1)) { ESL_FAIL(eslFAIL, errbuf, "number isn't a number, tok %d", i); } break;
752 case eslJSON_BOOLEAN: if (! esl_memstrcmp(bf->mem + pos1, pos2-pos1+1, "true") &&
753 ! esl_memstrcmp(bf->mem + pos1, pos2-pos1+1, "false")) { ESL_FAIL(eslFAIL, errbuf, "boolean isn't a boolean, tok %d", i); } break;
754 case eslJSON_NULL: if (! esl_memstrcmp(bf->mem + pos1, pos2-pos1+1, "null")) { ESL_FAIL(eslFAIL, errbuf, "null isn't null, tok %d", i); } break;
755 default: ESL_FAIL(eslFAIL, errbuf, "no such state type %d, tok %d", (int) tok->type, i);
756 }
757 }
758 }
759 return eslOK;
760 }
761
762
763
764 /* Function: esl_json_DecodeType()
765 * Synopsis: Returns printable string, given <esl_json_type_e> code.
766 */
767 char *
768 esl_json_DecodeType(enum esl_json_type_e type)
769 {
770 switch (type) {
771 case eslJSON_UNKNOWN: return "unknown";
772 case eslJSON_OBJECT: return "object";
773 case eslJSON_ARRAY: return "array";
774 case eslJSON_KEY: return "key";
775 case eslJSON_STRING: return "string";
776 case eslJSON_NUMBER: return "number";
777 case eslJSON_BOOLEAN: return "boolean";
778 case eslJSON_NULL: return "null";
779 default: return "??";
780 }
781 }
782
783
784 /* Function: esl_json_Dump()
785 * Synopsis: Dump contents of an ESL_JSON parse tree
786 */
787 int
788 esl_json_Dump(FILE *fp, ESL_JSON *pi)
789 {
790 int i;
791
792 esl_dataheader(fp, 5, "idx", 8, "type", 8, "startpos", 8, "endpos",
793 8, "linenum", 8, "linepos",
794 8, "nchild", 10, "firstchild", 10, "lastchild", 8, "nextsib", 0);
795 for (i = 0; i < pi->ntok; i++)
796 fprintf(fp, "%-5d %8s %8d %8d %8d %8d %8d %10d %10d %8d\n",
797 i, esl_json_DecodeType(pi->tok[i].type),
798 (int) pi->tok[i].startpos, (int) pi->tok[i].endpos,
799 pi->tok[i].linenum, pi->tok[i].linepos,
800 pi->tok[i].nchild, pi->tok[i].firstchild, pi->tok[i].lastchild, pi->tok[i].nextsib);
801 return eslOK;
802 }
803
804
805
806 /* Function: esl_json_SampleDirty()
807 * Synopsis: Generate a lawful evil JSON string for parser testing
808 * Incept: SRE, Tue 31 Jul 2018 [Hildur Gudnadottir, Baer]
809 *
810 * Purpose: Generate a syntactically valid random JSON string using
811 * random number generator <rng>. Return it in <*ret_s> and
812 * its length in bytes in <*ret_n>,
813 *
814 * The JSON string is UTF-8 encoded. JSON spec allows
815 * string values to contain "any" Unicode character. There
816 * are a lot of UNICODE chars, so for testing purposes
817 * (where we don't really want the string to look like
818 * *utter* noise), we generate 3 of them: the 2-byte
819 * <\u00B5> character $\mu$, the 3-byte <\u221E> character
820 * $\infty$, and the 4-byte <\U00010083> glyph for 'horse'
821 * in Linear B. Note that renderer support for Unicode is
822 * spotty, especially in the high range where Linear B
823 * lives.
824 *
825 * The string is \0-terminated for convenience, but the
826 * Easel JSON parser works on byte arrays and does not
827 * require NUL string termination.
828 *
829 * <*ret_s> is allocated here; caller frees.
830 *
831 * Args: rng - random number generator
832 * ret_s - RETURN: generated JSON string <s>. Caller frees.
833 * ret_n - RETURN: length of <s>
834 *
835 * Returns: <eslOK> on success. <*ret_s> and <*ret_n> are the result.
836 *
837 * Throws: <eslEMEM> on allocation failure.
838 * <*ret_s> is <NULL>, <*ret_n> is 0.
839 *
840 * Note: Parameter choices here are arbitrary, no special reason for
841 * them other than to make reasonable-length strings that
842 * are likely to exercise lots of possible JSON syntax.
843 */
844 int
845 esl_json_SampleDirty(ESL_RANDOMNESS *rng, char **ret_s, int *ret_n)
846 {
847 enum esl_json_state_e state = eslJSON_OBJ_NONE; // we start outside the root JSON object
848 ESL_STACK *pda = NULL; // keeps track of object and array internal nodes in progress
849 char *s = NULL; // string we're building
850 int n = 0; // current length of string
851 int nalloc = 256; // current allocation for string
852 int nbarrier = 10000; // this keeps string from blowing up infinitely. after n > nbarrier, create no new objects or arrays.
853 int roll; // random roll 0..99
854 int closedv; // eslJSON_UNKNOWN becomes a value (eslJSON_NUMBER, etc) when we close a value, and need to pop up to its parent to set state.
855 int nadd; // how many bytes got added for a random unicode char
856 int j; // counter over added bytes
857 int x; // when we pop from <pda>, values have to be ints, which we then cast to the <enum esl_json_state_e>
858 int status;
859
860 ESL_ALLOC(s, sizeof(char) * nalloc);
861 if ((pda = esl_stack_ICreate()) == NULL) { status = eslEMEM; goto ERROR; }
862
863 while (1) // each iteration, add 0..5 bytes to b. (0 when we close a number; 5 when we add a "false" value or a "\uxxxx" unicode)
864 {
865 if (n+4 >= nalloc) {
866 ESL_REALLOC(s, sizeof(char) * nalloc * 2); // make sure we can write to n..n+4 : up to 5 bytes.
867 nalloc *= 2;
868 }
869
870 roll = esl_rnd_Roll(rng, 100);
871 closedv = eslJSON_UNKNOWN; // when we close an Array or Object value, we have to do some bookkeeping, popping its parent off stack.
872 switch (state) { // state machine follows the JSON specification's generative grammar, adding random whitespace where it's allowed
873 case eslJSON_OBJ_NONE:
874 if (roll < 40) { s[n++] = " \t\n"[esl_rnd_Roll(rng, 3)]; }
875 else { state = eslJSON_OBJ_OPEN; s[n++] = '{'; esl_stack_IPush(pda, (int) eslJSON_UNKNOWN); } // UNKNOWN because root JSON object has no parent. When we pop this, we'll be done.
876 break;
877
878 case eslJSON_OBJ_OPEN:
879 if (roll < 40) { s[n++] = " \t\n"[esl_rnd_Roll(rng, 3)]; }
880 else if (roll < 95) { state = eslJSON_KEY_OPEN; s[n++] = '"'; }
881 else { closedv = eslJSON_OBJECT; s[n++] = '}'; }
882 break;
883
884 case eslJSON_OBJ_COMMA:
885 if (roll < 40) { s[n++] = " \t\n"[esl_rnd_Roll(rng, 3)]; }
886 else { state = eslJSON_KEY_OPEN; s[n++] = '"'; }
887 break;
888
889 case eslJSON_OBJ_COLON:
890 case eslJSON_ARR_OPEN:
891 case eslJSON_ARR_COMMA:
892 x = (int) (state == eslJSON_OBJ_COLON ? eslJSON_OBJECT : eslJSON_ARRAY); // hacky. if we don't choose to generate whitespace, we are going to push obj|arr onto pda. we have to make this decision now, before we change state.
893
894 if (roll < 40) { s[n++] = " \t\n"[esl_rnd_Roll(rng, 3)]; break; } // the break is so we don't push enclosing object to stack
895 else if (roll < 50 && n <= nbarrier) { state = eslJSON_OBJ_OPEN; s[n++] = '{'; } // checking maxdepth attempts to keep nesting from spinning out of control
896 else if (roll < 60 && n <= nbarrier) { state = eslJSON_ARR_OPEN; s[n++] = '['; }
897 else if (roll < 70) { state = eslJSON_STR_OPEN; s[n++] = '"'; }
898 else if (roll < 75) { state = eslJSON_NUM_SIGN; s[n++] = '-'; }
899 else if (roll < 80) { state = eslJSON_NUM_ZERO; s[n++] = '0'; }
900 else if (roll < 85) { state = eslJSON_NUM_NONZERO; s[n++] = "123456789"[esl_rnd_Roll(rng,9)]; }
901 else if (roll < 90) { closedv = eslJSON_BOOLEAN; s[n++] = 't'; s[n++] = 'r'; s[n++] = 'u'; s[n++] = 'e'; } // push all 4 chars of "true", and we don't need the eslJSON_VAL_TRUE state; we just close the value immediately.
902 else if (roll < 95) { closedv = eslJSON_BOOLEAN; s[n++] = 'f'; s[n++] = 'a'; s[n++] = 'l'; s[n++] = 's'; s[n++] = 'e'; } // ... ditto "false" and eslJSON_VAL_FALSE
903 else { closedv = eslJSON_NULL; s[n++] = 'n'; s[n++] = 'u'; s[n++] = 'l'; s[n++] = 'l'; } // ... ditto "null" and eslJSON_VAL_NULL. We can do this because we know we're allocated for up to 5 new bytes per iteration.
904
905 esl_stack_IPush(pda, x); // when we open a new value - i.e. on anything but whitespace - push parent object|array to stack
906 break;
907
908 case eslJSON_STR_OPEN:
909 case eslJSON_STR_CHAR:
910 case eslJSON_STR_PROTECTED:
911 if (roll < 5) { state = eslJSON_STR_BACKSLASH; s[n++] = '\\'; }
912 else if (roll < 20) { closedv = eslJSON_STRING; s[n++] = '"'; }
913 else { state = eslJSON_STR_CHAR; add_dirty_unicode(rng, s, n, &nadd); n += nadd; }
914 break;
915
916 case eslJSON_KEY_OPEN:
917 case eslJSON_KEY_CHAR:
918 case eslJSON_KEY_PROTECTED:
919 if (roll < 5) { state = eslJSON_KEY_BACKSLASH; s[n++] = '\\'; }
920 else if (roll < 20) { state = eslJSON_STR_ASKEY; s[n++] = '"'; }
921 else { state = eslJSON_KEY_CHAR; add_dirty_unicode(rng, s, n, &nadd); n += nadd; }
922 break;
923
924 case eslJSON_STR_BACKSLASH:
925 if (roll < 15) { state = eslJSON_STR_UNICODE; s[n++] = 'u'; }
926 else { state = eslJSON_STR_PROTECTED; s[n++] = "\"\\/bfnrt"[esl_rnd_Roll(rng, 8)]; }
927 break;
928
929 case eslJSON_KEY_BACKSLASH:
930 if (roll < 15) { state = eslJSON_KEY_UNICODE; s[n++] = 'u'; }
931 else { state = eslJSON_KEY_PROTECTED; s[n++] = "\"\\/bfnrt"[esl_rnd_Roll(rng, 8)]; }
932 break;
933
934 case eslJSON_STR_UNICODE:
935 state = eslJSON_STR_PROTECTED;
936 for (j = 0; j < 4; j++)
937 if (esl_rnd_Roll(rng, 2) == 0) s[n++] = "0123456789abcdef"[esl_rnd_Roll(rng, 16)]; // this will generate invalid unicode sequences too, but JSON parser spec simply says "four hexadecimal digits"
938 else s[n++] = "0123456789ABCDEF"[esl_rnd_Roll(rng, 16)]; // JSON ECMA-404 spec says either lower or upper case are ok
939 break;
940
941 case eslJSON_KEY_UNICODE:
942 state = eslJSON_KEY_PROTECTED;
943 for (j = 0; j < 4; j++)
944 if (esl_rnd_Roll(rng, 2) == 0) s[n++] = "0123456789abcdef"[esl_rnd_Roll(rng, 16)];
945 else s[n++] = "0123456789ABCDEF"[esl_rnd_Roll(rng, 16)];
946 break;
947
948 case eslJSON_NUM_SIGN:
949 if (roll < 10) { state = eslJSON_NUM_ZERO; s[n++] = '0'; }
950 else { state = eslJSON_NUM_NONZERO; s[n++] = "123456789"[esl_rnd_Roll(rng,9)]; }
951 break;
952
953 case eslJSON_NUM_ZERO:
954 if (roll < 20) { closedv = eslJSON_NUMBER; } // n did not advance!
955 else if (roll < 80) { state = eslJSON_NUM_POINT; s[n++] = '.'; }
956 else { state = eslJSON_NUM_EXP; s[n++] = "eE"[esl_rnd_Roll(rng, 2)]; }
957 break;
958
959 case eslJSON_NUM_NONZERO:
960 case eslJSON_NUM_LEADDIGIT:
961 if (roll < 50) { state = eslJSON_NUM_LEADDIGIT; s[n++] = "0123456789"[esl_rnd_Roll(rng,10)]; }
962 else if (roll < 75) { state = eslJSON_NUM_POINT; s[n++] = '.'; }
963 else { closedv = eslJSON_NUMBER; } // n did not advance
964 break;
965
966 case eslJSON_NUM_POINT:
967 state = eslJSON_NUM_FRACDIGIT; s[n++] = "0123456789"[esl_rnd_Roll(rng,10)];
968 break;
969
970 case eslJSON_NUM_FRACDIGIT:
971 if (roll < 50) { state = eslJSON_NUM_FRACDIGIT; s[n++] = "0123456789"[esl_rnd_Roll(rng,10)]; }
972 else if (roll < 75) { state = eslJSON_NUM_EXP; s[n++] = "eE"[esl_rnd_Roll(rng, 2)]; }
973 else closedv = eslJSON_NUMBER;
974 break;
975
976 case eslJSON_NUM_EXP:
977 if (roll < 60) { state = eslJSON_NUM_EXPDIGIT; s[n++] = "0123456789"[esl_rnd_Roll(rng,10)]; }
978 else { state = eslJSON_NUM_EXPSIGN; s[n++] = "+-"[esl_rnd_Roll(rng, 2)]; }
979 break;
980
981 case eslJSON_NUM_EXPSIGN:
982 state = eslJSON_NUM_EXPDIGIT; s[n++] = "0123456789"[esl_rnd_Roll(rng,10)];
983 break;
984
985 case eslJSON_NUM_EXPDIGIT:
986 if (roll < 20) { state = eslJSON_NUM_EXPDIGIT; s[n++] = "0123456789"[esl_rnd_Roll(rng,10)]; }
987 else { closedv = eslJSON_NUMBER; }
988
989 case eslJSON_VAL_TRUE:
990 case eslJSON_VAL_FALSE:
991 case eslJSON_VAL_NULL: // these don't occur, because we generate the whole value at once, not byte by byte
992 break;
993
994 case eslJSON_VAL_INOBJ:
995 if (roll < 30) { s[n++] = " \t\n"[esl_rnd_Roll(rng, 3)]; }
996 else if (roll < 85) { state = eslJSON_OBJ_COMMA; s[n++] = ','; }
997 else { closedv = eslJSON_OBJECT; s[n++] = '}'; }
998 break;
999
1000 case eslJSON_VAL_INARR:
1001 if (roll < 30) { s[n++] = " \t\n"[esl_rnd_Roll(rng, 3)]; }
1002 else if (roll < 85) { state = eslJSON_ARR_COMMA; s[n++] = ','; }
1003 else { closedv = eslJSON_ARRAY; s[n++] = ']'; }
1004 break;
1005
1006 case eslJSON_STR_ASKEY:
1007 if (roll < 30) { s[n++] = " \t\n"[esl_rnd_Roll(rng, 3)]; }
1008 else { state = eslJSON_OBJ_COLON; s[n++] = ':'; }
1009 break;
1010
1011 default: esl_fatal("no such state");
1012 } // end of big state machine switch for generating one char at a time
1013
1014 /* any time we close a value, we have to figure out whether its
1015 * parent was an object or an array. We deferred that step by
1016 * raising a <closedv> flag above (which could simply be a
1017 * TRUE|FALSE flag); now do that bookkeeping here with one chunk
1018 * of code.
1019 */
1020 if (closedv != eslJSON_UNKNOWN)
1021 {
1022 esl_stack_IPop( pda, &x); // interface requires an integer return arg
1023 if ((enum esl_json_type_e) x == eslJSON_OBJECT) state = eslJSON_VAL_INOBJ;
1024 else if ((enum esl_json_type_e) x == eslJSON_ARRAY) state = eslJSON_VAL_INARR;
1025 else if ((enum esl_json_type_e) x == eslJSON_UNKNOWN) break; // this is the only way out of the while(1) loop: we closed the root object
1026 }
1027 }
1028
1029 /* make sure we can write up to 4 more bytes, inclusive of \0 */
1030 if (n+4 > nalloc) {
1031 ESL_REALLOC(s, sizeof(char) * (n+4)); // make sure we can write to n..n+4 : up to 5 bytes.
1032 nalloc = n+4;
1033 }
1034
1035 /* add random whitespace */
1036 nadd = esl_rnd_Roll(rng, 3);
1037 for (j = 0; j < nadd; j++)
1038 s[n++] = " \t\n"[esl_rnd_Roll(rng, 3)];
1039
1040 /* NUL terminate without advancing n, so now n is JSON string length */
1041 s[n] = '\0';
1042
1043 esl_stack_Destroy(pda);
1044 *ret_s = s;
1045 *ret_n = n;
1046 return eslOK;
1047
1048 ERROR:
1049 esl_stack_Destroy(pda);
1050 free(s);
1051 *ret_s = NULL;
1052 *ret_n = 0;
1053 return status;
1054 }
1055
1056
1057 /*****************************************************************
1058 * 6. internal functions
1059 *****************************************************************/
1060
1061 static int
1062 new_token(ESL_JSON_PARSER *parser, ESL_JSON *pi, enum esl_json_type_e type, esl_pos_t startpos)
1063 {
1064 /* The parent is parser->curridx, which must be an object or array, or -1 if we're initializing root */
1065 int mom = parser->curridx; // -1, if this is the root object
1066 int sib = (mom == -1 ? -1 : pi->tok[mom].lastchild); // -1, if this is mom's first child
1067 int status;
1068
1069 ESL_DASSERT1(( mom == -1 || pi->tok[mom].type == eslJSON_OBJECT || pi->tok[mom].type == eslJSON_ARRAY ));
1070
1071 if (pi->ntok == pi->nalloc) {
1072 if ((status = esl_json_Grow(pi)) != eslOK) return status;
1073 }
1074
1075 parser->curridx = pi->ntok;
1076 pi->ntok++;
1077
1078 pi->tok[parser->curridx].type = type;
1079 pi->tok[parser->curridx].startpos = startpos;
1080 pi->tok[parser->curridx].endpos = -1;
1081 pi->tok[parser->curridx].nchild = 0;
1082 pi->tok[parser->curridx].nextsib = -1;
1083 pi->tok[parser->curridx].firstchild = -1;
1084 pi->tok[parser->curridx].lastchild = -1;
1085 pi->tok[parser->curridx].linenum = parser->linenum;
1086 pi->tok[parser->curridx].linepos = parser->linepos;
1087
1088 if (mom != -1)
1089 {
1090 if (sib == -1) pi->tok[mom].firstchild = parser->curridx;
1091 else pi->tok[sib].nextsib = parser->curridx;
1092 pi->tok[mom].lastchild = parser->curridx;
1093 pi->tok[mom].nchild++;
1094 esl_stack_IPush(parser->pda, mom);
1095 }
1096 return eslOK;
1097 }
1098
1099
1100 /* add_dirty_unicode()
1101 * Append a randomly chosen Unicode code unit to a growing UTF-8 encoded byte array
1102 * SRE, Tue 31 Jul 2018 [Hildur Gudnadottir, Rennur upp]
1103 *
1104 * Purpose: Given byte array <s> currently of length <n> and allocated
1105 * for at least 4 additional bytes; add a randomly chosen
1106 * UTF-8 encoded Unicode code unit, using random number
1107 * generator <rng>.
1108 *
1109 * The added code unit may consist of 1-4 bytes:
1110 * 1-byte units: any of the 95 printable ASCII char except \ or "
1111 * 2-byte unit: \u00B5, $\mu$ (UTF-8 encoded: \xc2\xb5)
1112 * 3-byte unit: \u221E, $\infty$ (UTF-8 encoded: \xe2\x88\x9e)
1113 * 4-byte unit: \U000010083, Linear B 'horse' (\xf0\x90\x82\x83)
1114 *
1115 * The number of bytes added is returned in <*ret_nadd>, and caller
1116 * can use it to increment <n>.
1117 */
1118 static void
1119 add_dirty_unicode(ESL_RANDOMNESS *rng, char *s, int n, int *ret_nadd)
1120 {
1121 int roll = esl_rnd_Roll(rng, 100);
1122 int nadd;
1123
1124 if (roll < 85) { nadd = 1; do { s[n] = 32 + esl_rnd_Roll(rng, 95); } while (s[n] == '"' || s[n] == '\\'); }
1125 else if (roll < 90) { nadd = 2; s[n] = '\xc2'; s[n+1] = '\xb5'; } // \mu
1126 else if (roll < 95) { nadd = 3; s[n] = '\xe2'; s[n+1] = '\x88'; s[n+2] = '\x9e'; } // \infty
1127 else { nadd = 4; s[n] = '\xf0'; s[n+1] = '\x90'; s[n+2] = '\x82'; s[n+3] = '\x83'; } // Linear B horse pictograph. RIP Alice Kober.
1128 *ret_nadd = nadd;
1129 }
1130
1131
1132 /*****************************************************************
1133 * 7. Unit tests
1134 *****************************************************************/
1135 #ifdef eslJSON_TESTDRIVE
1136
1137 static void
1138 utest_evil(ESL_RANDOMNESS *rng)
1139 {
1140 char msg[] = "json utest_evil failed";
1141 ESL_BUFFER *bf = NULL;
1142 ESL_JSON *pi = NULL;
1143 char *s = NULL;
1144 int n = 0;
1145 char errbuf[eslERRBUFSIZE];
1146 int status;
1147
1148 if (( status = esl_json_SampleDirty(rng, &s, &n)) != eslOK) esl_fatal(msg);
1149 if (( status = esl_buffer_OpenMem(s, n, &bf)) != eslOK) esl_fatal(msg);
1150 if (( status = esl_json_Parse(bf, &pi)) != eslOK) esl_fatal(msg);
1151 if (( status = esl_json_Validate(pi, bf, errbuf)) != eslOK) esl_fatal("%s:\n %s", msg, errbuf);
1152
1153 esl_json_Destroy(pi);
1154 esl_buffer_Close(bf);
1155 free(s);
1156 }
1157
1158 /* utest_read_int
1159 * Test esl_json_ReadInt() on extreme values.
1160 */
1161 static void
1162 utest_read_int(void)
1163 {
1164 char msg[] = "json utest_read_int failed";
1165 ESL_BUFFER *bf;
1166 ESL_JSON *pi;
1167 int val;
1168
1169 if ( esl_buffer_OpenMem("{ \"a\" : 42 }", -1, &bf) != eslOK) esl_fatal(msg);
1170 if ( esl_json_Parse(bf, &pi) != eslOK) esl_fatal(msg);
1171 if ( esl_json_ReadInt(pi, 2, bf, &val) != eslOK) esl_fatal(msg);
1172 if (val != 42) esl_fatal(msg);
1173 esl_buffer_Close(bf);
1174 esl_json_Destroy(pi);
1175
1176 if ( esl_buffer_OpenMem("{ \"a\" : 42.0 }", -1, &bf) != eslOK) esl_fatal(msg); // 42. isn't a valid JSON number, but 42.0 is.
1177 if ( esl_json_Parse(bf, &pi) != eslOK) esl_fatal(msg);
1178 if ( esl_json_ReadInt(pi, 2, bf, &val) != eslEFORMAT) esl_fatal(msg);
1179 if (val != 0) esl_fatal(msg);
1180 esl_buffer_Close(bf);
1181 esl_json_Destroy(pi);
1182
1183 if (INT_MAX == 2147483647) // rather than hassling with printing INT_MAX+1 more generally, when we may not be able to find an integer size that fits it.
1184 {
1185 if ( esl_buffer_OpenMem("{ \"a\" : 2147483647 }", -1, &bf) != eslOK) esl_fatal(msg);
1186 if ( esl_json_Parse(bf, &pi) != eslOK) esl_fatal(msg);
1187 if ( esl_json_ReadInt(pi, 2, bf, &val) != eslOK) esl_fatal(msg);
1188 if (val != INT_MAX) esl_fatal(msg);
1189 esl_buffer_Close(bf);
1190 esl_json_Destroy(pi);
1191
1192 if ( esl_buffer_OpenMem("{ \"a\" : 2147483648 }", -1, &bf) != eslOK) esl_fatal(msg);
1193 if ( esl_json_Parse(bf, &pi) != eslOK) esl_fatal(msg);
1194 if ( esl_json_ReadInt(pi, 2, bf, &val) != eslERANGE) esl_fatal(msg);
1195 if (val != INT_MAX) esl_fatal(msg);
1196 esl_buffer_Close(bf);
1197 esl_json_Destroy(pi);
1198
1199 if ( esl_buffer_OpenMem("{ \"a\" : -2147483648 }", -1, &bf) != eslOK) esl_fatal(msg);
1200 if ( esl_json_Parse(bf, &pi) != eslOK) esl_fatal(msg);
1201 if ( esl_json_ReadInt(pi, 2, bf, &val) != eslOK) esl_fatal(msg);
1202 if (val != INT_MIN) esl_fatal(msg);
1203 esl_buffer_Close(bf);
1204 esl_json_Destroy(pi);
1205
1206 if ( esl_buffer_OpenMem("{ \"a\" : -2147483649 }", -1, &bf) != eslOK) esl_fatal(msg);
1207 if ( esl_json_Parse(bf, &pi) != eslOK) esl_fatal(msg);
1208 if ( esl_json_ReadInt(pi, 2, bf, &val) != eslERANGE) esl_fatal(msg);
1209 if (val != INT_MIN) esl_fatal(msg);
1210 esl_buffer_Close(bf);
1211 esl_json_Destroy(pi);
1212 }
1213 }
1214
1215 static void
1216 utest_read_float(void)
1217 {
1218 char msg[] = "json utest_read_float failed";
1219 struct tests_s { char *json; float trueval; float rtol; float atol; int status; }
1220 tests[] = { { "{ \"a\" : 42 }", 42.0, 0.0, 0.0, eslOK },
1221 { "{ \"a\" : 42.12345 }", 42.12345, 1e-6, 0.0, eslOK },
1222 { "{ \"a\" : -42.12345 }", -42.12345, 1e-6, 0.0, eslOK },
1223 { "{ \"a\" : 42.12345e1 }", 421.2345, 1e-6, 0.0, eslOK },
1224 { "{ \"a\" : -42.12345e1 }", -421.2345, 1e-6, 0.0, eslOK },
1225 { "{ \"a\" : 42.12345e-1 }", 4.212345, 1e-6, 0.0, eslOK },
1226 { "{ \"a\" : -42.12345e-1 }", -4.212345, 1e-6, 0.0, eslOK },
1227 { "{ \"a\" : 3.4e38 }", 3.4e38, 1e-6, 0.0, eslOK },
1228 { "{ \"a\" : 3.5e38 }", eslINFINITY, 0.0, 0.0, eslOK }, // overflows. rtol = 0 leads to a inf==inf equality test below
1229 { "{ \"a\" : 1.1e-38 }", 1.1e-38, 1e-6, 0.0, eslOK },
1230 // { "{ \"a\" : 1.3e-38 }", 1.3e-38, 1e-6, 0.0, eslOK }, // denormal. removed test, because icc by default rounds denormals to 0.
1231 { "{ \"a\" : 1e-46 }", 0.0, 0.0, 0.0, eslOK }, // underflows denormals to 0.0
1232 { "{ \"a\" : 0.0001e39 }", 1e35, 1e-6, 0.0, eslOK }, // requires renormalization to get right
1233 { "{ \"a\" : 1000e-39 }", 1e-36, 1e-6, 0.0, eslOK }, // ... ditto
1234 { "{ \"a\" : 9999999999999999999999999999999999999999e-10 }", eslINFINITY, 0.0, 0.0, eslOK }, // a real strtof() gets this right: it's 1e30
1235 { "{ \"a\" : 0.0000000000000000000000000000000000000000000001e10 }", 0.0, 0.0, 0.0, eslOK }, // ... and this should be 1e-36
1236 { "{ \"a\" : -9999999999999999999999999999999999999999e-10 }", -eslINFINITY, 0.0, 0.0, eslOK }, // ... this, -1e30
1237 { "{ \"a\" : -0.0000000000000000000000000000000000000000000001e10 }", 0.0, 0.0, 0.0, eslOK }, // ... this, -1e-36
1238
1239 };
1240 int ntests = sizeof(tests) / sizeof(struct tests_s);
1241 ESL_BUFFER *bf;
1242 ESL_JSON *pi;
1243 float val;
1244 int i;
1245 int status;
1246
1247 for (i = 0; i < ntests; i++)
1248 {
1249 if ( esl_buffer_OpenMem(tests[i].json, -1, &bf) != eslOK) esl_fatal(msg);
1250 if ( esl_json_Parse(bf, &pi) != eslOK) esl_fatal(msg);
1251 if (( status = esl_json_ReadFloat(pi, 2, bf, &val)) != tests[i].status) esl_fatal(msg);
1252 if (tests[i].rtol == 0.0) {
1253 if (val != tests[i].trueval) esl_fatal(msg); // includes inf==inf test
1254 } else if (esl_FCompare(tests[i].trueval, val, tests[i].rtol, tests[i].atol) != eslOK) esl_fatal(msg);
1255
1256 esl_buffer_Close(bf);
1257 esl_json_Destroy(pi);
1258 }
1259 }
1260
1261
1262 /* utest_read_float_err()
1263 * Based on esl_mem.c::utest_mem_strtof_error().
1264 */
1265 static void
1266 utest_read_float_err(ESL_RANDOMNESS *rng, int allow_badluck)
1267 {
1268 char msg[] = "esl_json read_float_err unit test failed";
1269 char s[32]; // randomly generated decimal string rep of a float
1270 char sj[64]; // JSON string constructed from <s>, e.g. { "a" = 42.0 }
1271 ESL_BUFFER *bf; // input buffer
1272 ESL_JSON *pi; // JSON parse tree
1273 typedef union { float f; uint32_t rep; } flunion; // union gives us access to the IEEE754 binary representation
1274 flunion v1; // reference conversion from strtof()
1275 flunion v2; // conversion from esl_json_ReadFloat() for comparison
1276 int ulperr; // ulp error
1277 int trial;
1278
1279 if (! allow_badluck) esl_randomness_Init(rng, 42);
1280
1281 for (trial = 0; trial < 10000; trial++)
1282 {
1283 if ( esl_rnd_floatstring(rng, s) != eslOK) esl_fatal(msg);
1284 if ( snprintf(sj, 64, "{ \"a\" : %s }", s) < 0) esl_fatal(msg);
1285 if ( esl_buffer_OpenMem(sj, -1, &bf) != eslOK) esl_fatal(msg);
1286 if ( esl_json_Parse(bf, &pi) != eslOK) esl_fatal(msg);
1287 if ( esl_json_ReadFloat(pi, 2, bf, &(v2.f)) != eslOK) esl_fatal(msg);
1288
1289 v1.f = strtof(s, NULL);
1290 ulperr = (v1.rep & 0x7fffff) - (v2.rep & 0x7fffff);
1291
1292 if (ulperr > 4) esl_fatal(msg); // 4 ulp = up to 4 \epsilon ~ 5e-7 rel error.
1293
1294 esl_buffer_Close(bf);
1295 esl_json_Destroy(pi);
1296 }
1297 }
1298
1299
1300 #endif /* eslJSON_TESTDRIVE */
1301
1302 /*****************************************************************
1303 * 8. Test driver
1304 *****************************************************************/
1305 #ifdef eslJSON_TESTDRIVE
1306
1307 #include "esl_getopts.h"
1308
1309 static ESL_OPTIONS options[] = {
1310 /* name type default env range toggles reqs incomp help docgroup*/
1311 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1312 { "-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
1313 { "-x", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "allow bad luck (stochastic failures)", 0 },
1314 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1315 };
1316 static char usage[] = "[-options]";
1317 static char banner[] = "test driver for json module";
1318
1319 int
1320 main(int argc, char **argv)
1321 {
1322 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
1323 ESL_RANDOMNESS *rng = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
1324 int allow_badluck = esl_opt_GetBoolean(go, "-x"); // if a utest can fail just by chance, let it, instead of suppressing
1325
1326 fprintf(stderr, "## %s\n", argv[0]);
1327 fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(rng));
1328
1329 utest_evil(rng);
1330 utest_read_int();
1331 utest_read_float();
1332
1333 /* tests that can stochastically fail go last, because they reinit the RNG w/ fixed seed */
1334 utest_read_float_err(rng, allow_badluck);
1335
1336 fprintf(stderr, "# status = ok\n");
1337
1338 esl_randomness_Destroy(rng);
1339 esl_getopts_Destroy(go);
1340 return eslOK;
1341 }
1342 #endif /* eslJSON_TESTDRIVE */
1343
1344
1345
1346 /*****************************************************************
1347 * 9. Example
1348 *****************************************************************/
1349 #ifdef eslJSON_EXAMPLE
1350
1351 int
1352 main(int argc, char **argv)
1353 {
1354 char *filename = argv[1];
1355 ESL_BUFFER *bf = NULL;
1356 ESL_JSON *pi = NULL;
1357 int status;
1358
1359 status = esl_buffer_Open(filename, NULL, &bf);
1360 if (status == eslENOTFOUND) esl_fatal("open failed: %s", bf->errmsg);
1361 else if (status == eslFAIL) esl_fatal("gzip -dc failed: %s", bf->errmsg);
1362 else if (status != eslOK) esl_fatal("open failed with error code %d", status);
1363
1364 status = esl_json_Parse(bf, &pi);
1365 if (status != eslOK) esl_fatal("parse failed:\n %s\n", bf->errmsg);
1366
1367 esl_json_Dump(stdout, pi);
1368
1369 esl_buffer_Close(bf);
1370 esl_json_Destroy(pi);
1371 return eslOK;
1372 }
1373 #endif /* eslJSON_EXAMPLE */
1374