blob: 3e667d7563889117286e769daf61472809bc764c [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.
330 uint8_t esc2[6];
331 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) {
336 // The UTF-8 encoding takes 3 bytes.
337 uint8_t esc3[6];
338 esc3[0] = 0xE0 | (uint8_t)((vbd >> 12));
339 esc3[1] = 0x80 | (uint8_t)((vbd >> 6) & 0x3F);
340 esc3[2] = 0x80 | (uint8_t)((vbd >> 0) & 0x3F);
341 TRY(write_dst(&esc3[0], 3));
342
343 } else {
344 return "main: unexpected Unicode code point";
Nigel Tao1b073492020-02-16 22:11:36 +1100345 }
Nigel Taob5461bd2020-02-21 14:13:37 +1100346
Nigel Tao1b073492020-02-16 22:11:36 +1100347 pt = parse_next_token();
348 if (pt.error_msg) {
349 return pt.error_msg;
350 }
351 }
352 TRY(write_dst("\"", 1));
353 return nullptr;
354}
355
356const char* main2() {
357 dec_status = dec.initialize(sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0);
358 if (!dec_status.is_ok()) {
359 return dec_status.message();
360 }
361 dec_status = dec.decode_tokens(&tok, &src);
362 dec_current_token_end_src_index = 0;
363
364 uint64_t depth = 0;
365 context ctx = context::none;
366
367continue_loop:
368 while (true) {
369 parsed_token pt = parse_next_token();
370 if (pt.error_msg) {
371 return pt.error_msg;
372 }
373 uint64_t vbc = pt.token.value_base_category();
374 uint64_t vbd = pt.token.value_base_detail();
375
376 // Handle ']' or '}'.
Nigel Tao9f7a2502020-02-23 09:42:02 +1100377 if ((vbc == WUFFS_BASE__TOKEN__VBC__STRUCTURE) &&
378 ((vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__POP) != 0)) {
Nigel Tao1b073492020-02-16 22:11:36 +1100379 if (depth <= 0) {
380 return "main: internal error: inconsistent depth";
381 }
382 depth--;
383
384 // Write preceding whitespace.
385 if ((ctx != context::in_list_after_bracket) &&
386 (ctx != context::in_dict_after_brace)) {
387 TRY(write_dst("\n", 1));
388 for (size_t i = 0; i < depth; i++) {
389 TRY(write_dst(INDENT_STRING, indent));
390 }
391 }
392
Nigel Tao9f7a2502020-02-23 09:42:02 +1100393 TRY(write_dst(
394 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST) ? "]" : "}", 1));
395 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
396 ? context::in_list_after_value
397 : context::in_dict_after_key;
Nigel Tao1b073492020-02-16 22:11:36 +1100398 goto after_value;
399 }
400
401 // Write preceding whitespace and punctuation, if it wasn't ']' or '}'.
402 if (ctx == context::in_dict_after_key) {
403 TRY(write_dst(": ", 2));
404 } else if (ctx != context::none) {
405 if ((ctx != context::in_list_after_bracket) &&
406 (ctx != context::in_dict_after_brace)) {
407 TRY(write_dst(",", 1));
408 }
409 TRY(write_dst("\n", 1));
410 for (size_t i = 0; i < depth; i++) {
411 TRY(write_dst(INDENT_STRING, indent));
412 }
413 }
414
415 // Handle the token itself: either a container ('[' or '{') or a simple
416 // value (number, string or literal).
417 switch (vbc) {
Nigel Tao9f7a2502020-02-23 09:42:02 +1100418 case WUFFS_BASE__TOKEN__VBC__STRUCTURE:
419 TRY(write_dst(
420 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST) ? "[" : "{", 1));
Nigel Tao1b073492020-02-16 22:11:36 +1100421 depth++;
Nigel Tao9f7a2502020-02-23 09:42:02 +1100422 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
423 ? context::in_list_after_bracket
424 : context::in_dict_after_brace;
Nigel Tao1b073492020-02-16 22:11:36 +1100425 goto continue_loop;
426
Nigel Tao9f7a2502020-02-23 09:42:02 +1100427 case WUFFS_BASE__TOKEN__VBC__NUMBER:
Nigel Tao8850d382020-02-19 12:25:00 +1100428 TRY(write_dst(pt.data.ptr, pt.data.len));
429 goto after_value;
430
Nigel Tao9f7a2502020-02-23 09:42:02 +1100431 case WUFFS_BASE__TOKEN__VBC__STRING:
Nigel Tao1b073492020-02-16 22:11:36 +1100432 TRY(handle_string(pt));
433 goto after_value;
434 }
435
436 // Return an error if we didn't match the (vbc, vbd) pair.
437 return "main: unexpected token";
438
439 // Book-keeping after completing a value (whether a container value or a
440 // simple value). Empty parent containers are no longer empty. If the
441 // parent container is a "{...}" object, toggle between keys and values.
442 after_value:
443 if (depth <= 0) {
Nigel Tao6b161af2020-02-24 11:01:48 +1100444 goto break_loop;
Nigel Tao1b073492020-02-16 22:11:36 +1100445 }
446 switch (ctx) {
447 case context::in_list_after_bracket:
448 ctx = context::in_list_after_value;
449 break;
450 case context::in_dict_after_brace:
451 ctx = context::in_dict_after_key;
452 break;
453 case context::in_dict_after_key:
454 ctx = context::in_dict_after_value;
455 break;
456 case context::in_dict_after_value:
457 ctx = context::in_dict_after_key;
458 break;
459 }
460 }
Nigel Tao6b161af2020-02-24 11:01:48 +1100461
462break_loop:
463 // Consume an optional whitespace trailer. This isn't part of the JSON spec,
464 // but it works better with line oriented Unix tools (such as "echo 123 |
465 // jsonptr" where it's "echo", not "echo -n") or hand-edited JSON files which
466 // can accidentally contain trailing whitespace.
467 //
468 // A whitespace trailer is zero or more ' ' and then zero or one '\n'.
469 while (true) {
470 if (src.meta.ri < src.meta.wi) {
471 uint8_t c = src.data.ptr[src.meta.ri];
472 if (c == ' ') {
473 src.meta.ri++;
474 continue;
475 } else if (c == '\n') {
476 src.meta.ri++;
477 break;
478 }
479 // The "exhausted the input" check below will fail.
480 break;
481 } else if (src.meta.closed) {
482 break;
483 }
484 TRY(read_src());
485 }
486
487 // Check that we've exhausted the input.
488 if ((src.meta.ri < src.meta.wi) || !src.meta.closed) {
489 return "main: valid JSON followed by further (unexpected) data";
490 }
491
492 // Check that we've used all of the decoded tokens, other than trailing
493 // filler tokens. For example, a bare `"foo"` string is valid JSON, but even
494 // without a trailing '\n', the Wuffs JSON parser emits a filler token for
495 // the final '\"'.
496 for (; tok.meta.ri < tok.meta.wi; tok.meta.ri++) {
497 if (tok.data.ptr[tok.meta.ri].value_base_category() !=
498 WUFFS_BASE__TOKEN__VBC__FILLER) {
499 return "main: internal error: decoded OK but unprocessed tokens remain";
500 }
501 }
502
503 return nullptr;
Nigel Tao1b073492020-02-16 22:11:36 +1100504}
505
506const char* main1(int argc, char** argv) {
507 dst = wuffs_base__make_io_buffer(
508 wuffs_base__make_slice_u8(dst_buffer, DST_BUFFER_SIZE),
509 wuffs_base__empty_io_buffer_meta());
510
511 src = wuffs_base__make_io_buffer(
512 wuffs_base__make_slice_u8(src_buffer, SRC_BUFFER_SIZE),
513 wuffs_base__empty_io_buffer_meta());
514
515 tok = wuffs_base__make_token_buffer(
516 wuffs_base__make_slice_token(tok_buffer, TOKEN_BUFFER_SIZE),
517 wuffs_base__empty_token_buffer_meta());
518
519 indent = 4;
520
521 TRY(main2());
522 TRY(write_dst("\n", 1));
523 return nullptr;
524}
525
Nigel Tao9cc2c252020-02-23 17:05:49 +1100526int compute_exit_code(const char* status_msg) {
527 if (!status_msg) {
528 return 0;
529 }
530 size_t n = strnlen(status_msg, 2047);
531 if (n >= 2047) {
532 status_msg = "main: internal error: error message is too long";
533 n = strnlen(status_msg, 2047);
534 }
535 fprintf(stderr, "%s\n", status_msg);
536 // Return an exit code of 1 for regular (forseen) errors, e.g. badly
537 // formatted or unsupported input.
538 //
539 // Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
540 // run-time checks found that an internal invariant did not hold.
541 //
542 // Automated testing, including badly formatted inputs, can therefore
543 // discriminate between expected failure (exit code 1) and unexpected failure
544 // (other non-zero exit codes). Specifically, exit code 2 for internal
545 // invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
546 // linux) for a segmentation fault (e.g. null pointer dereference).
547 return strstr(status_msg, "internal error:") ? 2 : 1;
548}
549
Nigel Tao1b073492020-02-16 22:11:36 +1100550int main(int argc, char** argv) {
551 const char* z0 = main1(argc, argv);
552 const char* z1 = flush_dst();
Nigel Tao9cc2c252020-02-23 17:05:49 +1100553 int exit_code = compute_exit_code(z0 ? z0 : z1);
554 return exit_code;
Nigel Tao1b073492020-02-16 22:11:36 +1100555}