blob: 783faa242540dcea7e8321de640290e00bf75bfa [file] [log] [blame]
Nigel Tao1b073492020-02-16 22:11:36 +11001// Copyright 2020 The Wuffs Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// ----------------
16
17/*
18jsonptr is a JSON formatter (pretty-printer).
19
Nigel Taoc5b3a9e2020-02-24 11:54:35 +110020As of 2020-02-24, this program passes all 318 "test_parsing" cases from the
21JSON test suite (https://github.com/nst/JSONTestSuite), an appendix to the
22"Parsing JSON is a Minefield" article (http://seriot.ch/parsing_json.php) that
23was first published on 2016-10-26 and updated on 2018-03-30.
24
Nigel Tao1b073492020-02-16 22:11:36 +110025This example program differs from most other example Wuffs programs in that it
26is written in C++, not C.
27
28$CXX jsonptr.cc && ./a.out < ../../test/data/github-tags.json; rm -f a.out
29
30for a C++ compiler $CXX, such as clang++ or g++.
Nigel Tao569a2942020-02-23 23:13:51 +110031
32After modifying this program, run "build-example.sh example/jsonptr/" and then
33"script/run-json-test-suite.sh" to catch correctness regressions.
Nigel Tao1b073492020-02-16 22:11:36 +110034*/
35
36#include <inttypes.h>
37#include <stdio.h>
Nigel Tao9cc2c252020-02-23 17:05:49 +110038#include <string.h>
Nigel Tao1b073492020-02-16 22:11:36 +110039
40// Wuffs ships as a "single file C library" or "header file library" as per
41// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
42//
43// To use that single file as a "foo.c"-like implementation, instead of a
44// "foo.h"-like header, #define WUFFS_IMPLEMENTATION before #include'ing or
45// compiling it.
46#define WUFFS_IMPLEMENTATION
47
48// Defining the WUFFS_CONFIG__MODULE* macros are optional, but it lets users of
49// release/c/etc.c whitelist which parts of Wuffs to build. That file contains
50// the entire Wuffs standard library, implementing a variety of codecs and file
51// formats. Without this macro definition, an optimizing compiler or linker may
52// very well discard Wuffs code for unused codecs, but listing the Wuffs
53// modules we use makes that process explicit. Preprocessing means that such
54// code simply isn't compiled.
55#define WUFFS_CONFIG__MODULES
56#define WUFFS_CONFIG__MODULE__BASE
57#define WUFFS_CONFIG__MODULE__JSON
58
59// If building this program in an environment that doesn't easily accommodate
60// relative includes, you can use the script/inline-c-relative-includes.go
61// program to generate a stand-alone C++ file.
62#include "../../release/c/wuffs-unsupported-snapshot.c"
63
64#ifndef DST_BUFFER_SIZE
65#define DST_BUFFER_SIZE (32 * 1024)
66#endif
67#ifndef SRC_BUFFER_SIZE
68#define SRC_BUFFER_SIZE (32 * 1024)
69#endif
70#ifndef TOKEN_BUFFER_SIZE
71#define TOKEN_BUFFER_SIZE (4 * 1024)
72#endif
73
74uint8_t dst_buffer[DST_BUFFER_SIZE];
75uint8_t src_buffer[SRC_BUFFER_SIZE];
76wuffs_base__token tok_buffer[TOKEN_BUFFER_SIZE];
77
78wuffs_base__io_buffer dst;
79wuffs_base__io_buffer src;
80wuffs_base__token_buffer tok;
81
82wuffs_json__decoder dec;
83wuffs_base__status dec_status;
84
85// dec_current_token_end_src_index is the src.data.ptr index of the end of the
86// current token. An invariant is that (dec_current_token_end_src_index <=
87// src.meta.ri).
88size_t dec_current_token_end_src_index;
89
90#define MAX_INDENT 8
91#define INDENT_STRING " "
92size_t indent;
93
94#define TRY(error_msg) \
95 do { \
96 const char* z = error_msg; \
97 if (z) { \
98 return z; \
99 } \
100 } while (false)
101
102// ----
103
104const char* read_src() {
Nigel Taoa8406922020-02-19 12:22:00 +1100105 if (src.meta.closed) {
Nigel Tao9cc2c252020-02-23 17:05:49 +1100106 return "main: internal error: read requested on a closed source";
Nigel Taoa8406922020-02-19 12:22:00 +1100107 }
Nigel Tao1b073492020-02-16 22:11:36 +1100108 src.compact();
109 if (src.meta.wi >= src.data.len) {
110 return "main: src buffer is full";
111 }
112 size_t n = fread(src.data.ptr + src.meta.wi, sizeof(uint8_t),
113 src.data.len - src.meta.wi, stdin);
114 src.meta.wi += n;
Nigel Tao67306562020-02-19 14:04:49 +1100115 src.meta.closed = feof(stdin);
116 if ((n == 0) && !src.meta.closed) {
Nigel Taoa8406922020-02-19 12:22:00 +1100117 return "main: read error";
Nigel Tao1b073492020-02-16 22:11:36 +1100118 }
119 return nullptr;
120}
121
122const char* flush_dst() {
123 size_t n = dst.meta.wi - dst.meta.ri;
124 if (n > 0) {
125 size_t i = fwrite(dst.data.ptr + dst.meta.ri, sizeof(uint8_t), n, stdout);
126 dst.meta.ri += i;
127 if (i != n) {
128 return "main: write error";
129 }
130 dst.compact();
131 }
132 return nullptr;
133}
134
135const char* write_dst(const void* s, size_t n) {
136 const uint8_t* p = static_cast<const uint8_t*>(s);
137 while (n > 0) {
138 size_t i = dst.writer_available();
139 if (i == 0) {
140 const char* z = flush_dst();
141 if (z) {
142 return z;
143 }
144 i = dst.writer_available();
145 if (i == 0) {
146 return "main: dst buffer is full";
147 }
148 }
149
150 if (i > n) {
151 i = n;
152 }
153 memcpy(dst.data.ptr + dst.meta.wi, p, i);
154 dst.meta.wi += i;
155 p += i;
156 n -= i;
157 }
158 return nullptr;
159}
160
161// ----
162
163enum class context {
164 none,
165 in_list_after_bracket,
166 in_list_after_value,
167 in_dict_after_brace,
168 in_dict_after_key,
169 in_dict_after_value,
170};
171
172// parsed_token is a result type, combining a wuffs_base_token and an error.
173// For the parsed_token returned by make_parsed_token, it also contains the src
174// data bytes for the token. This slice is just a view into the src_buffer
175// array, and its contents may change on the next call to parse_next_token.
176//
177// An invariant is that (token.length() == data.len).
178typedef struct {
179 const char* error_msg;
180 wuffs_base__token token;
181 wuffs_base__slice_u8 data;
182} parsed_token;
183
184parsed_token make_pt_error(const char* error_msg) {
185 parsed_token p;
186 p.error_msg = error_msg;
187 p.token = wuffs_base__make_token(0);
188 p.data = wuffs_base__make_slice_u8(nullptr, 0);
189 return p;
190}
191
192parsed_token make_pt_token(uint64_t token_repr,
193 uint8_t* data_ptr,
194 size_t data_len) {
195 parsed_token p;
196 p.error_msg = nullptr;
197 p.token = wuffs_base__make_token(token_repr);
198 p.data = wuffs_base__make_slice_u8(data_ptr, data_len);
199 return p;
200}
201
202parsed_token parse_next_token() {
203 while (true) {
204 // Return a previously produced token, if one exists.
205 //
206 // We do this before checking dec_status. This is analogous to Go's
207 // io.Reader's documented idiom, when processing io.Reader.Read's returned
208 // (n int, err error), to "process the n > 0 bytes returned before
209 // considering the error err. Doing so correctly handles I/O errors that
210 // happen after reading some bytes".
211 if (tok.meta.ri < tok.meta.wi) {
212 wuffs_base__token t = tok.data.ptr[tok.meta.ri++];
213
214 uint64_t n = t.length();
215 if ((src.meta.ri - dec_current_token_end_src_index) < n) {
216 return make_pt_error("main: internal error: inconsistent src indexes");
217 }
218 dec_current_token_end_src_index += n;
219
220 // Filter out any filler tokens (e.g. whitespace).
Nigel Tao6b161af2020-02-24 11:01:48 +1100221 if (t.value_base_category() == WUFFS_BASE__TOKEN__VBC__FILLER) {
Nigel Tao1b073492020-02-16 22:11:36 +1100222 continue;
223 }
224
225 return make_pt_token(
226 t.repr, src.data.ptr + dec_current_token_end_src_index - n, n);
227 }
228
229 // Now consider dec_status.
230 if (dec_status.repr == nullptr) {
231 return make_pt_error("main: internal error: parser stopped");
232
233 } else if (dec_status.repr == wuffs_base__suspension__short_read) {
234 if (dec_current_token_end_src_index != src.meta.ri) {
235 return make_pt_error("main: internal error: inconsistent src indexes");
236 }
237 const char* z = read_src();
238 if (z) {
239 return make_pt_error(z);
240 }
241 dec_current_token_end_src_index = src.meta.ri;
242
243 } else if (dec_status.repr == wuffs_base__suspension__short_write) {
244 tok.compact();
245
246 } else {
247 return make_pt_error(dec_status.message());
248 }
249
250 // Retry a "short read" or "short write" suspension.
251 dec_status = dec.decode_tokens(&tok, &src);
252 }
253}
254
255// ----
256
Nigel Taob5461bd2020-02-21 14:13:37 +1100257uint8_t hex_digit(uint8_t nibble) {
258 nibble &= 0x0F;
259 if (nibble <= 9) {
260 return '0' + nibble;
261 }
262 return ('A' - 10) + nibble;
263}
264
Nigel Tao1b073492020-02-16 22:11:36 +1100265const char* handle_string(parsed_token pt) {
Nigel Tao0711f232020-02-17 13:17:06 +1100266 TRY(write_dst("\"", 1));
Nigel Tao1b073492020-02-16 22:11:36 +1100267 while (true) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100268 uint64_t vbc = pt.token.value_base_category();
269 uint64_t vbd = pt.token.value_base_detail();
270
Nigel Tao9f7a2502020-02-23 09:42:02 +1100271 if (vbc == WUFFS_BASE__TOKEN__VBC__STRING) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100272 TRY(write_dst(pt.data.ptr, pt.data.len));
Nigel Tao9f7a2502020-02-23 09:42:02 +1100273 if ((vbd & WUFFS_BASE__TOKEN__VBD__STRING__INCOMPLETE) == 0) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100274 break;
275 }
276
Nigel Tao9f7a2502020-02-23 09:42:02 +1100277 } else if (vbc != WUFFS_BASE__TOKEN__VBC__UNICODE_CODE_POINT) {
278 return "main: unexpected token";
279
Nigel Taob5461bd2020-02-21 14:13:37 +1100280 } else if (vbd < 0x0020) {
281 switch (vbd) {
282 case '\b':
283 TRY(write_dst("\\b", 2));
284 break;
285 case '\f':
286 TRY(write_dst("\\f", 2));
287 break;
288 case '\n':
289 TRY(write_dst("\\n", 2));
290 break;
291 case '\r':
292 TRY(write_dst("\\r", 2));
293 break;
294 case '\t':
295 TRY(write_dst("\\t", 2));
296 break;
297 default: {
298 // Other bytes less than 0x0020 are valid UTF-8 but not valid in a
299 // JSON string. They need to remain escaped.
300 uint8_t esc6[6];
301 esc6[0] = '\\';
302 esc6[1] = 'u';
303 esc6[2] = '0';
304 esc6[3] = '0';
305 esc6[4] = hex_digit(vbd >> 4);
306 esc6[5] = hex_digit(vbd >> 0);
307 TRY(write_dst(&esc6[0], 6));
308 break;
309 }
310 }
311
312 } else if (vbd <= 0x007F) {
313 switch (vbd) {
314 case '\"':
315 TRY(write_dst("\\\"", 2));
316 break;
317 case '\\':
318 TRY(write_dst("\\\\", 2));
319 break;
320 default: {
321 // The UTF-8 encoding takes 1 byte.
322 uint8_t esc0 = (uint8_t)(vbd);
323 TRY(write_dst(&esc0, 1));
324 break;
325 }
326 }
327
328 } else if (vbd <= 0x07FF) {
329 // The UTF-8 encoding takes 2 bytes.
Nigel Tao16b0c462020-02-24 23:12:39 +1100330 uint8_t esc2[2];
Nigel Taob5461bd2020-02-21 14:13:37 +1100331 esc2[0] = 0xC0 | (uint8_t)((vbd >> 6));
332 esc2[1] = 0x80 | (uint8_t)((vbd >> 0) & 0x3F);
333 TRY(write_dst(&esc2[0], 2));
334
335 } else if (vbd <= 0xFFFF) {
Nigel Tao16b0c462020-02-24 23:12:39 +1100336 if ((0xD800 <= vbd) && (vbd <= 0xDFFF)) {
337 return "main: unexpected Unicode surrogate";
338 }
Nigel Taob5461bd2020-02-21 14:13:37 +1100339 // The UTF-8 encoding takes 3 bytes.
Nigel Tao16b0c462020-02-24 23:12:39 +1100340 uint8_t esc3[3];
Nigel Taob5461bd2020-02-21 14:13:37 +1100341 esc3[0] = 0xE0 | (uint8_t)((vbd >> 12));
342 esc3[1] = 0x80 | (uint8_t)((vbd >> 6) & 0x3F);
343 esc3[2] = 0x80 | (uint8_t)((vbd >> 0) & 0x3F);
344 TRY(write_dst(&esc3[0], 3));
345
Nigel Tao16b0c462020-02-24 23:12:39 +1100346 } else if (vbd <= 0x10FFFF) {
347 // The UTF-8 encoding takes 4 bytes.
348 uint8_t esc4[4];
349 esc4[0] = 0xF0 | (uint8_t)((vbd >> 18));
350 esc4[1] = 0x80 | (uint8_t)((vbd >> 12) & 0x3F);
351 esc4[2] = 0x80 | (uint8_t)((vbd >> 6) & 0x3F);
352 esc4[3] = 0x80 | (uint8_t)((vbd >> 0) & 0x3F);
353 TRY(write_dst(&esc4[0], 4));
354
Nigel Taob5461bd2020-02-21 14:13:37 +1100355 } else {
356 return "main: unexpected Unicode code point";
Nigel Tao1b073492020-02-16 22:11:36 +1100357 }
Nigel Taob5461bd2020-02-21 14:13:37 +1100358
Nigel Tao1b073492020-02-16 22:11:36 +1100359 pt = parse_next_token();
360 if (pt.error_msg) {
361 return pt.error_msg;
362 }
363 }
364 TRY(write_dst("\"", 1));
365 return nullptr;
366}
367
368const char* main2() {
369 dec_status = dec.initialize(sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0);
370 if (!dec_status.is_ok()) {
371 return dec_status.message();
372 }
373 dec_status = dec.decode_tokens(&tok, &src);
374 dec_current_token_end_src_index = 0;
375
376 uint64_t depth = 0;
377 context ctx = context::none;
378
379continue_loop:
380 while (true) {
381 parsed_token pt = parse_next_token();
382 if (pt.error_msg) {
383 return pt.error_msg;
384 }
385 uint64_t vbc = pt.token.value_base_category();
386 uint64_t vbd = pt.token.value_base_detail();
387
388 // Handle ']' or '}'.
Nigel Tao9f7a2502020-02-23 09:42:02 +1100389 if ((vbc == WUFFS_BASE__TOKEN__VBC__STRUCTURE) &&
390 ((vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__POP) != 0)) {
Nigel Tao1b073492020-02-16 22:11:36 +1100391 if (depth <= 0) {
392 return "main: internal error: inconsistent depth";
393 }
394 depth--;
395
396 // Write preceding whitespace.
397 if ((ctx != context::in_list_after_bracket) &&
398 (ctx != context::in_dict_after_brace)) {
399 TRY(write_dst("\n", 1));
400 for (size_t i = 0; i < depth; i++) {
401 TRY(write_dst(INDENT_STRING, indent));
402 }
403 }
404
Nigel Tao9f7a2502020-02-23 09:42:02 +1100405 TRY(write_dst(
406 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST) ? "]" : "}", 1));
407 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
408 ? context::in_list_after_value
409 : context::in_dict_after_key;
Nigel Tao1b073492020-02-16 22:11:36 +1100410 goto after_value;
411 }
412
413 // Write preceding whitespace and punctuation, if it wasn't ']' or '}'.
414 if (ctx == context::in_dict_after_key) {
415 TRY(write_dst(": ", 2));
416 } else if (ctx != context::none) {
417 if ((ctx != context::in_list_after_bracket) &&
418 (ctx != context::in_dict_after_brace)) {
419 TRY(write_dst(",", 1));
420 }
421 TRY(write_dst("\n", 1));
422 for (size_t i = 0; i < depth; i++) {
423 TRY(write_dst(INDENT_STRING, indent));
424 }
425 }
426
427 // Handle the token itself: either a container ('[' or '{') or a simple
428 // value (number, string or literal).
429 switch (vbc) {
Nigel Tao9f7a2502020-02-23 09:42:02 +1100430 case WUFFS_BASE__TOKEN__VBC__STRUCTURE:
431 TRY(write_dst(
432 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST) ? "[" : "{", 1));
Nigel Tao1b073492020-02-16 22:11:36 +1100433 depth++;
Nigel Tao9f7a2502020-02-23 09:42:02 +1100434 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
435 ? context::in_list_after_bracket
436 : context::in_dict_after_brace;
Nigel Tao1b073492020-02-16 22:11:36 +1100437 goto continue_loop;
438
Nigel Tao9f7a2502020-02-23 09:42:02 +1100439 case WUFFS_BASE__TOKEN__VBC__NUMBER:
Nigel Tao8850d382020-02-19 12:25:00 +1100440 TRY(write_dst(pt.data.ptr, pt.data.len));
441 goto after_value;
442
Nigel Tao9f7a2502020-02-23 09:42:02 +1100443 case WUFFS_BASE__TOKEN__VBC__STRING:
Nigel Tao1b073492020-02-16 22:11:36 +1100444 TRY(handle_string(pt));
445 goto after_value;
446 }
447
448 // Return an error if we didn't match the (vbc, vbd) pair.
449 return "main: unexpected token";
450
451 // Book-keeping after completing a value (whether a container value or a
452 // simple value). Empty parent containers are no longer empty. If the
453 // parent container is a "{...}" object, toggle between keys and values.
454 after_value:
455 if (depth <= 0) {
Nigel Tao6b161af2020-02-24 11:01:48 +1100456 goto break_loop;
Nigel Tao1b073492020-02-16 22:11:36 +1100457 }
458 switch (ctx) {
459 case context::in_list_after_bracket:
460 ctx = context::in_list_after_value;
461 break;
462 case context::in_dict_after_brace:
463 ctx = context::in_dict_after_key;
464 break;
465 case context::in_dict_after_key:
466 ctx = context::in_dict_after_value;
467 break;
468 case context::in_dict_after_value:
469 ctx = context::in_dict_after_key;
470 break;
471 }
472 }
Nigel Tao6b161af2020-02-24 11:01:48 +1100473
474break_loop:
475 // Consume an optional whitespace trailer. This isn't part of the JSON spec,
476 // but it works better with line oriented Unix tools (such as "echo 123 |
477 // jsonptr" where it's "echo", not "echo -n") or hand-edited JSON files which
478 // can accidentally contain trailing whitespace.
479 //
480 // A whitespace trailer is zero or more ' ' and then zero or one '\n'.
481 while (true) {
482 if (src.meta.ri < src.meta.wi) {
483 uint8_t c = src.data.ptr[src.meta.ri];
484 if (c == ' ') {
485 src.meta.ri++;
486 continue;
487 } else if (c == '\n') {
488 src.meta.ri++;
489 break;
490 }
491 // The "exhausted the input" check below will fail.
492 break;
493 } else if (src.meta.closed) {
494 break;
495 }
496 TRY(read_src());
497 }
498
499 // Check that we've exhausted the input.
500 if ((src.meta.ri < src.meta.wi) || !src.meta.closed) {
501 return "main: valid JSON followed by further (unexpected) data";
502 }
503
504 // Check that we've used all of the decoded tokens, other than trailing
505 // filler tokens. For example, a bare `"foo"` string is valid JSON, but even
506 // without a trailing '\n', the Wuffs JSON parser emits a filler token for
507 // the final '\"'.
508 for (; tok.meta.ri < tok.meta.wi; tok.meta.ri++) {
509 if (tok.data.ptr[tok.meta.ri].value_base_category() !=
510 WUFFS_BASE__TOKEN__VBC__FILLER) {
511 return "main: internal error: decoded OK but unprocessed tokens remain";
512 }
513 }
514
515 return nullptr;
Nigel Tao1b073492020-02-16 22:11:36 +1100516}
517
518const char* main1(int argc, char** argv) {
519 dst = wuffs_base__make_io_buffer(
520 wuffs_base__make_slice_u8(dst_buffer, DST_BUFFER_SIZE),
521 wuffs_base__empty_io_buffer_meta());
522
523 src = wuffs_base__make_io_buffer(
524 wuffs_base__make_slice_u8(src_buffer, SRC_BUFFER_SIZE),
525 wuffs_base__empty_io_buffer_meta());
526
527 tok = wuffs_base__make_token_buffer(
528 wuffs_base__make_slice_token(tok_buffer, TOKEN_BUFFER_SIZE),
529 wuffs_base__empty_token_buffer_meta());
530
531 indent = 4;
532
533 TRY(main2());
534 TRY(write_dst("\n", 1));
535 return nullptr;
536}
537
Nigel Tao9cc2c252020-02-23 17:05:49 +1100538int compute_exit_code(const char* status_msg) {
539 if (!status_msg) {
540 return 0;
541 }
542 size_t n = strnlen(status_msg, 2047);
543 if (n >= 2047) {
544 status_msg = "main: internal error: error message is too long";
545 n = strnlen(status_msg, 2047);
546 }
547 fprintf(stderr, "%s\n", status_msg);
548 // Return an exit code of 1 for regular (forseen) errors, e.g. badly
549 // formatted or unsupported input.
550 //
551 // Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
552 // run-time checks found that an internal invariant did not hold.
553 //
554 // Automated testing, including badly formatted inputs, can therefore
555 // discriminate between expected failure (exit code 1) and unexpected failure
556 // (other non-zero exit codes). Specifically, exit code 2 for internal
557 // invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
558 // linux) for a segmentation fault (e.g. null pointer dereference).
559 return strstr(status_msg, "internal error:") ? 2 : 1;
560}
561
Nigel Tao1b073492020-02-16 22:11:36 +1100562int main(int argc, char** argv) {
563 const char* z0 = main1(argc, argv);
564 const char* z1 = flush_dst();
Nigel Tao9cc2c252020-02-23 17:05:49 +1100565 int exit_code = compute_exit_code(z0 ? z0 : z1);
566 return exit_code;
Nigel Tao1b073492020-02-16 22:11:36 +1100567}