blob: c4f849b8d33c771730122d5a34202ec275107db7 [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
Nigel Tao2cf76db2020-02-27 22:42:01 +110064#define TRY(error_msg) \
65 do { \
66 const char* z = error_msg; \
67 if (z) { \
68 return z; \
69 } \
70 } while (false)
71
72static const char* eod = "main: end of data";
73
74// ----
75
76#define MAX_INDENT 8
77#define INDENT_STRING " "
78size_t indent;
79
Nigel Tao1b073492020-02-16 22:11:36 +110080#ifndef DST_BUFFER_SIZE
81#define DST_BUFFER_SIZE (32 * 1024)
82#endif
83#ifndef SRC_BUFFER_SIZE
84#define SRC_BUFFER_SIZE (32 * 1024)
85#endif
86#ifndef TOKEN_BUFFER_SIZE
87#define TOKEN_BUFFER_SIZE (4 * 1024)
88#endif
89
Nigel Tao2cf76db2020-02-27 22:42:01 +110090uint8_t dst_array[DST_BUFFER_SIZE];
91uint8_t src_array[SRC_BUFFER_SIZE];
92wuffs_base__token tok_array[TOKEN_BUFFER_SIZE];
Nigel Tao1b073492020-02-16 22:11:36 +110093
94wuffs_base__io_buffer dst;
95wuffs_base__io_buffer src;
96wuffs_base__token_buffer tok;
97
Nigel Tao2cf76db2020-02-27 22:42:01 +110098// curr_token_end_src_index is the src.data.ptr index of the end of the current
99// token. An invariant is that (curr_token_end_src_index <= src.meta.ri).
100size_t curr_token_end_src_index;
101
Nigel Tao2cf76db2020-02-27 22:42:01 +1100102uint64_t depth;
103
104enum class context {
105 none,
106 in_list_after_bracket,
107 in_list_after_value,
108 in_dict_after_brace,
109 in_dict_after_key,
110 in_dict_after_value,
111} ctx;
112
Nigel Tao1b073492020-02-16 22:11:36 +1100113wuffs_json__decoder dec;
Nigel Tao1b073492020-02-16 22:11:36 +1100114
Nigel Tao2cf76db2020-02-27 22:42:01 +1100115const char* //
116initialize_globals(int argc, char** argv) {
117 indent = 4;
Nigel Tao1b073492020-02-16 22:11:36 +1100118
Nigel Tao2cf76db2020-02-27 22:42:01 +1100119 dst = wuffs_base__make_io_buffer(
120 wuffs_base__make_slice_u8(dst_array, DST_BUFFER_SIZE),
121 wuffs_base__empty_io_buffer_meta());
Nigel Tao1b073492020-02-16 22:11:36 +1100122
Nigel Tao2cf76db2020-02-27 22:42:01 +1100123 src = wuffs_base__make_io_buffer(
124 wuffs_base__make_slice_u8(src_array, SRC_BUFFER_SIZE),
125 wuffs_base__empty_io_buffer_meta());
126
127 tok = wuffs_base__make_token_buffer(
128 wuffs_base__make_slice_token(tok_array, TOKEN_BUFFER_SIZE),
129 wuffs_base__empty_token_buffer_meta());
130
131 curr_token_end_src_index = 0;
132
Nigel Tao2cf76db2020-02-27 22:42:01 +1100133 depth = 0;
134
135 ctx = context::none;
136
137 return dec.initialize(sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0)
138 .message();
139}
Nigel Tao1b073492020-02-16 22:11:36 +1100140
141// ----
142
Nigel Tao2914bae2020-02-26 09:40:30 +1100143const char* //
144read_src() {
Nigel Taoa8406922020-02-19 12:22:00 +1100145 if (src.meta.closed) {
Nigel Tao9cc2c252020-02-23 17:05:49 +1100146 return "main: internal error: read requested on a closed source";
Nigel Taoa8406922020-02-19 12:22:00 +1100147 }
Nigel Tao1b073492020-02-16 22:11:36 +1100148 src.compact();
149 if (src.meta.wi >= src.data.len) {
150 return "main: src buffer is full";
151 }
152 size_t n = fread(src.data.ptr + src.meta.wi, sizeof(uint8_t),
153 src.data.len - src.meta.wi, stdin);
154 src.meta.wi += n;
Nigel Tao67306562020-02-19 14:04:49 +1100155 src.meta.closed = feof(stdin);
156 if ((n == 0) && !src.meta.closed) {
Nigel Taoa8406922020-02-19 12:22:00 +1100157 return "main: read error";
Nigel Tao1b073492020-02-16 22:11:36 +1100158 }
159 return nullptr;
160}
161
Nigel Tao2914bae2020-02-26 09:40:30 +1100162const char* //
163flush_dst() {
Nigel Tao1b073492020-02-16 22:11:36 +1100164 size_t n = dst.meta.wi - dst.meta.ri;
165 if (n > 0) {
166 size_t i = fwrite(dst.data.ptr + dst.meta.ri, sizeof(uint8_t), n, stdout);
167 dst.meta.ri += i;
168 if (i != n) {
169 return "main: write error";
170 }
171 dst.compact();
172 }
173 return nullptr;
174}
175
Nigel Tao2914bae2020-02-26 09:40:30 +1100176const char* //
177write_dst(const void* s, size_t n) {
Nigel Tao1b073492020-02-16 22:11:36 +1100178 const uint8_t* p = static_cast<const uint8_t*>(s);
179 while (n > 0) {
180 size_t i = dst.writer_available();
181 if (i == 0) {
182 const char* z = flush_dst();
183 if (z) {
184 return z;
185 }
186 i = dst.writer_available();
187 if (i == 0) {
188 return "main: dst buffer is full";
189 }
190 }
191
192 if (i > n) {
193 i = n;
194 }
195 memcpy(dst.data.ptr + dst.meta.wi, p, i);
196 dst.meta.wi += i;
197 p += i;
198 n -= i;
199 }
200 return nullptr;
201}
202
203// ----
204
Nigel Tao2914bae2020-02-26 09:40:30 +1100205uint8_t //
206hex_digit(uint8_t nibble) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100207 nibble &= 0x0F;
208 if (nibble <= 9) {
209 return '0' + nibble;
210 }
211 return ('A' - 10) + nibble;
212}
213
Nigel Tao2914bae2020-02-26 09:40:30 +1100214const char* //
Nigel Tao3b486982020-02-27 15:05:59 +1100215handle_unicode_code_point(uint32_t ucp) {
216 if (ucp < 0x0020) {
217 switch (ucp) {
218 case '\b':
219 return write_dst("\\b", 2);
220 case '\f':
221 return write_dst("\\f", 2);
222 case '\n':
223 return write_dst("\\n", 2);
224 case '\r':
225 return write_dst("\\r", 2);
226 case '\t':
227 return write_dst("\\t", 2);
228 default: {
229 // Other bytes less than 0x0020 are valid UTF-8 but not valid in a
230 // JSON string. They need to remain escaped.
231 uint8_t esc6[6];
232 esc6[0] = '\\';
233 esc6[1] = 'u';
234 esc6[2] = '0';
235 esc6[3] = '0';
236 esc6[4] = hex_digit(ucp >> 4);
237 esc6[5] = hex_digit(ucp >> 0);
238 return write_dst(&esc6[0], 6);
239 }
240 }
241
242 } else if (ucp <= 0x007F) {
243 switch (ucp) {
244 case '\"':
245 return write_dst("\\\"", 2);
246 case '\\':
247 return write_dst("\\\\", 2);
248 default: {
249 // The UTF-8 encoding takes 1 byte.
250 uint8_t esc0 = (uint8_t)(ucp);
251 return write_dst(&esc0, 1);
252 }
253 }
254
255 } else if (ucp <= 0x07FF) {
256 // The UTF-8 encoding takes 2 bytes.
257 uint8_t esc2[2];
258 esc2[0] = 0xC0 | (uint8_t)((ucp >> 6));
259 esc2[1] = 0x80 | (uint8_t)((ucp >> 0) & 0x3F);
260 return write_dst(&esc2[0], 2);
261
262 } else if (ucp <= 0xFFFF) {
263 if ((0xD800 <= ucp) && (ucp <= 0xDFFF)) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100264 return "main: internal error: unexpected Unicode surrogate";
Nigel Tao3b486982020-02-27 15:05:59 +1100265 }
266 // The UTF-8 encoding takes 3 bytes.
267 uint8_t esc3[3];
268 esc3[0] = 0xE0 | (uint8_t)((ucp >> 12));
269 esc3[1] = 0x80 | (uint8_t)((ucp >> 6) & 0x3F);
270 esc3[2] = 0x80 | (uint8_t)((ucp >> 0) & 0x3F);
271 return write_dst(&esc3[0], 3);
272
273 } else if (ucp <= 0x10FFFF) {
274 // The UTF-8 encoding takes 4 bytes.
275 uint8_t esc4[4];
276 esc4[0] = 0xF0 | (uint8_t)((ucp >> 18));
277 esc4[1] = 0x80 | (uint8_t)((ucp >> 12) & 0x3F);
278 esc4[2] = 0x80 | (uint8_t)((ucp >> 6) & 0x3F);
279 esc4[3] = 0x80 | (uint8_t)((ucp >> 0) & 0x3F);
280 return write_dst(&esc4[0], 4);
281 }
282
Nigel Tao2cf76db2020-02-27 22:42:01 +1100283 return "main: internal error: unexpected Unicode code point";
Nigel Tao3b486982020-02-27 15:05:59 +1100284}
285
286const char* //
Nigel Tao2cf76db2020-02-27 22:42:01 +1100287handle_token(wuffs_base__token t) {
288 do {
289 uint64_t vbc = t.value_base_category();
290 uint64_t vbd = t.value_base_detail();
291 uint64_t len = t.length();
Nigel Tao1b073492020-02-16 22:11:36 +1100292
293 // Handle ']' or '}'.
Nigel Tao9f7a2502020-02-23 09:42:02 +1100294 if ((vbc == WUFFS_BASE__TOKEN__VBC__STRUCTURE) &&
Nigel Tao2cf76db2020-02-27 22:42:01 +1100295 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__POP)) {
Nigel Tao1b073492020-02-16 22:11:36 +1100296 if (depth <= 0) {
297 return "main: internal error: inconsistent depth";
298 }
299 depth--;
300
301 // Write preceding whitespace.
302 if ((ctx != context::in_list_after_bracket) &&
303 (ctx != context::in_dict_after_brace)) {
304 TRY(write_dst("\n", 1));
305 for (size_t i = 0; i < depth; i++) {
306 TRY(write_dst(INDENT_STRING, indent));
307 }
308 }
309
Nigel Tao9f7a2502020-02-23 09:42:02 +1100310 TRY(write_dst(
311 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST) ? "]" : "}", 1));
312 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
313 ? context::in_list_after_value
314 : context::in_dict_after_key;
Nigel Tao1b073492020-02-16 22:11:36 +1100315 goto after_value;
316 }
317
Nigel Taod1c928a2020-02-28 12:43:53 +1100318 // Write preceding whitespace and punctuation, if it wasn't ']', '}' or a
319 // continuation of a multi-token chain.
320 if (t.link_prev()) {
321 // No-op.
322 } else if (ctx == context::in_dict_after_key) {
323 TRY(write_dst(": ", 2));
324 } else if (ctx != context::none) {
325 if ((ctx != context::in_list_after_bracket) &&
326 (ctx != context::in_dict_after_brace)) {
327 TRY(write_dst(",", 1));
328 }
329 TRY(write_dst("\n", 1));
330 for (size_t i = 0; i < depth; i++) {
331 TRY(write_dst(INDENT_STRING, indent));
Nigel Tao1b073492020-02-16 22:11:36 +1100332 }
333 }
334
335 // Handle the token itself: either a container ('[' or '{') or a simple
Nigel Tao85fba7f2020-02-29 16:28:06 +1100336 // value: string (a chain of raw or escaped parts), literal or number.
Nigel Tao1b073492020-02-16 22:11:36 +1100337 switch (vbc) {
Nigel Tao85fba7f2020-02-29 16:28:06 +1100338 case WUFFS_BASE__TOKEN__VBC__STRUCTURE:
339 TRY(write_dst(
340 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST) ? "[" : "{", 1));
341 depth++;
342 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
343 ? context::in_list_after_bracket
344 : context::in_dict_after_brace;
345 return nullptr;
346
Nigel Tao2cf76db2020-02-27 22:42:01 +1100347 case WUFFS_BASE__TOKEN__VBC__STRING:
Nigel Taod1c928a2020-02-28 12:43:53 +1100348 if (!t.link_prev()) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100349 TRY(write_dst("\"", 1));
350 }
Nigel Taocb37a562020-02-28 09:56:24 +1100351
352 if (vbd & WUFFS_BASE__TOKEN__VBD__STRING__CONVERT_0_DST_1_SRC_DROP) {
353 // No-op.
354 } else if (vbd &
355 WUFFS_BASE__TOKEN__VBD__STRING__CONVERT_1_DST_1_SRC_COPY) {
356 TRY(write_dst(src.data.ptr + curr_token_end_src_index - len, len));
357 } else {
358 return "main: internal error: unexpected string-token conversion";
359 }
360
Nigel Taod1c928a2020-02-28 12:43:53 +1100361 if (t.link_next()) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100362 return nullptr;
363 }
364 TRY(write_dst("\"", 1));
365 goto after_value;
366
367 case WUFFS_BASE__TOKEN__VBC__UNICODE_CODE_POINT:
368 return handle_unicode_code_point(vbd);
369
Nigel Tao85fba7f2020-02-29 16:28:06 +1100370 case WUFFS_BASE__TOKEN__VBC__LITERAL:
Nigel Tao2cf76db2020-02-27 22:42:01 +1100371 case WUFFS_BASE__TOKEN__VBC__NUMBER:
372 TRY(write_dst(src.data.ptr + curr_token_end_src_index - len, len));
373 goto after_value;
Nigel Tao1b073492020-02-16 22:11:36 +1100374 }
375
376 // Return an error if we didn't match the (vbc, vbd) pair.
Nigel Tao2cf76db2020-02-27 22:42:01 +1100377 return "main: internal error: unexpected token";
378 } while (0);
Nigel Tao1b073492020-02-16 22:11:36 +1100379
Nigel Tao2cf76db2020-02-27 22:42:01 +1100380 // Book-keeping after completing a value (whether a container value or a
381 // simple value). Empty parent containers are no longer empty. If the parent
382 // container is a "{...}" object, toggle between keys and values.
383after_value:
384 if (depth == 0) {
385 return eod;
386 }
387 switch (ctx) {
388 case context::in_list_after_bracket:
389 ctx = context::in_list_after_value;
390 break;
391 case context::in_dict_after_brace:
392 ctx = context::in_dict_after_key;
393 break;
394 case context::in_dict_after_key:
395 ctx = context::in_dict_after_value;
396 break;
397 case context::in_dict_after_value:
398 ctx = context::in_dict_after_key;
399 break;
400 }
401 return nullptr;
402}
403
404const char* //
405main1(int argc, char** argv) {
406 TRY(initialize_globals(argc, argv));
407
408 while (true) {
409 wuffs_base__status status = dec.decode_tokens(&tok, &src);
410
411 while (tok.meta.ri < tok.meta.wi) {
412 wuffs_base__token t = tok.data.ptr[tok.meta.ri++];
413 uint64_t n = t.length();
414 if ((src.meta.ri - curr_token_end_src_index) < n) {
415 return "main: internal error: inconsistent src indexes";
416 }
417 curr_token_end_src_index += n;
418
419 if (t.value() == 0) {
420 continue;
421 }
422
423 const char* z = handle_token(t);
424 if (z == nullptr) {
425 continue;
426 } else if (z == eod) {
427 break;
428 }
429 return z;
Nigel Tao1b073492020-02-16 22:11:36 +1100430 }
Nigel Tao2cf76db2020-02-27 22:42:01 +1100431
432 if (status.repr == nullptr) {
433 break;
434 } else if (status.repr == wuffs_base__suspension__short_read) {
435 if (curr_token_end_src_index != src.meta.ri) {
436 return "main: internal error: inconsistent src indexes";
437 }
438 TRY(read_src());
439 curr_token_end_src_index = src.meta.ri;
440 } else if (status.repr == wuffs_base__suspension__short_write) {
441 tok.compact();
442 } else {
443 return status.message();
Nigel Tao1b073492020-02-16 22:11:36 +1100444 }
445 }
Nigel Tao6b161af2020-02-24 11:01:48 +1100446
Nigel Tao6b161af2020-02-24 11:01:48 +1100447 // Consume an optional whitespace trailer. This isn't part of the JSON spec,
448 // but it works better with line oriented Unix tools (such as "echo 123 |
449 // jsonptr" where it's "echo", not "echo -n") or hand-edited JSON files which
450 // can accidentally contain trailing whitespace.
451 //
452 // A whitespace trailer is zero or more ' ' and then zero or one '\n'.
453 while (true) {
454 if (src.meta.ri < src.meta.wi) {
455 uint8_t c = src.data.ptr[src.meta.ri];
456 if (c == ' ') {
457 src.meta.ri++;
458 continue;
459 } else if (c == '\n') {
460 src.meta.ri++;
461 break;
462 }
463 // The "exhausted the input" check below will fail.
464 break;
465 } else if (src.meta.closed) {
466 break;
467 }
468 TRY(read_src());
469 }
470
471 // Check that we've exhausted the input.
472 if ((src.meta.ri < src.meta.wi) || !src.meta.closed) {
473 return "main: valid JSON followed by further (unexpected) data";
474 }
475
476 // Check that we've used all of the decoded tokens, other than trailing
477 // filler tokens. For example, a bare `"foo"` string is valid JSON, but even
478 // without a trailing '\n', the Wuffs JSON parser emits a filler token for
479 // the final '\"'.
480 for (; tok.meta.ri < tok.meta.wi; tok.meta.ri++) {
481 if (tok.data.ptr[tok.meta.ri].value_base_category() !=
482 WUFFS_BASE__TOKEN__VBC__FILLER) {
483 return "main: internal error: decoded OK but unprocessed tokens remain";
484 }
485 }
486
487 return nullptr;
Nigel Tao1b073492020-02-16 22:11:36 +1100488}
489
Nigel Tao2914bae2020-02-26 09:40:30 +1100490int //
491compute_exit_code(const char* status_msg) {
Nigel Tao9cc2c252020-02-23 17:05:49 +1100492 if (!status_msg) {
493 return 0;
494 }
495 size_t n = strnlen(status_msg, 2047);
496 if (n >= 2047) {
497 status_msg = "main: internal error: error message is too long";
498 n = strnlen(status_msg, 2047);
499 }
500 fprintf(stderr, "%s\n", status_msg);
501 // Return an exit code of 1 for regular (forseen) errors, e.g. badly
502 // formatted or unsupported input.
503 //
504 // Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
505 // run-time checks found that an internal invariant did not hold.
506 //
507 // Automated testing, including badly formatted inputs, can therefore
508 // discriminate between expected failure (exit code 1) and unexpected failure
509 // (other non-zero exit codes). Specifically, exit code 2 for internal
510 // invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
511 // linux) for a segmentation fault (e.g. null pointer dereference).
512 return strstr(status_msg, "internal error:") ? 2 : 1;
513}
514
Nigel Tao2914bae2020-02-26 09:40:30 +1100515int //
516main(int argc, char** argv) {
Nigel Tao1b073492020-02-16 22:11:36 +1100517 const char* z0 = main1(argc, argv);
Nigel Tao2cf76db2020-02-27 22:42:01 +1100518 const char* z1 = write_dst("\n", 1);
519 const char* z2 = flush_dst();
520 int exit_code = compute_exit_code(z0 ? z0 : (z1 ? z1 : z2));
Nigel Tao9cc2c252020-02-23 17:05:49 +1100521 return exit_code;
Nigel Tao1b073492020-02-16 22:11:36 +1100522}