blob: ce24ed9fd9c7be361ade9c44da01a42158e12663 [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
20This example program differs from most other example Wuffs programs in that it
21is written in C++, not C.
22
23$CXX jsonptr.cc && ./a.out < ../../test/data/github-tags.json; rm -f a.out
24
25for a C++ compiler $CXX, such as clang++ or g++.
26*/
27
28#include <inttypes.h>
29#include <stdio.h>
Nigel Tao9cc2c252020-02-23 17:05:49 +110030#include <string.h>
Nigel Tao1b073492020-02-16 22:11:36 +110031
32// Wuffs ships as a "single file C library" or "header file library" as per
33// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
34//
35// To use that single file as a "foo.c"-like implementation, instead of a
36// "foo.h"-like header, #define WUFFS_IMPLEMENTATION before #include'ing or
37// compiling it.
38#define WUFFS_IMPLEMENTATION
39
40// Defining the WUFFS_CONFIG__MODULE* macros are optional, but it lets users of
41// release/c/etc.c whitelist which parts of Wuffs to build. That file contains
42// the entire Wuffs standard library, implementing a variety of codecs and file
43// formats. Without this macro definition, an optimizing compiler or linker may
44// very well discard Wuffs code for unused codecs, but listing the Wuffs
45// modules we use makes that process explicit. Preprocessing means that such
46// code simply isn't compiled.
47#define WUFFS_CONFIG__MODULES
48#define WUFFS_CONFIG__MODULE__BASE
49#define WUFFS_CONFIG__MODULE__JSON
50
51// If building this program in an environment that doesn't easily accommodate
52// relative includes, you can use the script/inline-c-relative-includes.go
53// program to generate a stand-alone C++ file.
54#include "../../release/c/wuffs-unsupported-snapshot.c"
55
56#ifndef DST_BUFFER_SIZE
57#define DST_BUFFER_SIZE (32 * 1024)
58#endif
59#ifndef SRC_BUFFER_SIZE
60#define SRC_BUFFER_SIZE (32 * 1024)
61#endif
62#ifndef TOKEN_BUFFER_SIZE
63#define TOKEN_BUFFER_SIZE (4 * 1024)
64#endif
65
66uint8_t dst_buffer[DST_BUFFER_SIZE];
67uint8_t src_buffer[SRC_BUFFER_SIZE];
68wuffs_base__token tok_buffer[TOKEN_BUFFER_SIZE];
69
70wuffs_base__io_buffer dst;
71wuffs_base__io_buffer src;
72wuffs_base__token_buffer tok;
73
74wuffs_json__decoder dec;
75wuffs_base__status dec_status;
76
77// dec_current_token_end_src_index is the src.data.ptr index of the end of the
78// current token. An invariant is that (dec_current_token_end_src_index <=
79// src.meta.ri).
80size_t dec_current_token_end_src_index;
81
82#define MAX_INDENT 8
83#define INDENT_STRING " "
84size_t indent;
85
86#define TRY(error_msg) \
87 do { \
88 const char* z = error_msg; \
89 if (z) { \
90 return z; \
91 } \
92 } while (false)
93
94// ----
95
96const char* read_src() {
Nigel Taoa8406922020-02-19 12:22:00 +110097 if (src.meta.closed) {
Nigel Tao9cc2c252020-02-23 17:05:49 +110098 return "main: internal error: read requested on a closed source";
Nigel Taoa8406922020-02-19 12:22:00 +110099 }
Nigel Tao1b073492020-02-16 22:11:36 +1100100 src.compact();
101 if (src.meta.wi >= src.data.len) {
102 return "main: src buffer is full";
103 }
104 size_t n = fread(src.data.ptr + src.meta.wi, sizeof(uint8_t),
105 src.data.len - src.meta.wi, stdin);
106 src.meta.wi += n;
Nigel Tao67306562020-02-19 14:04:49 +1100107 src.meta.closed = feof(stdin);
108 if ((n == 0) && !src.meta.closed) {
Nigel Taoa8406922020-02-19 12:22:00 +1100109 return "main: read error";
Nigel Tao1b073492020-02-16 22:11:36 +1100110 }
111 return nullptr;
112}
113
114const char* flush_dst() {
115 size_t n = dst.meta.wi - dst.meta.ri;
116 if (n > 0) {
117 size_t i = fwrite(dst.data.ptr + dst.meta.ri, sizeof(uint8_t), n, stdout);
118 dst.meta.ri += i;
119 if (i != n) {
120 return "main: write error";
121 }
122 dst.compact();
123 }
124 return nullptr;
125}
126
127const char* write_dst(const void* s, size_t n) {
128 const uint8_t* p = static_cast<const uint8_t*>(s);
129 while (n > 0) {
130 size_t i = dst.writer_available();
131 if (i == 0) {
132 const char* z = flush_dst();
133 if (z) {
134 return z;
135 }
136 i = dst.writer_available();
137 if (i == 0) {
138 return "main: dst buffer is full";
139 }
140 }
141
142 if (i > n) {
143 i = n;
144 }
145 memcpy(dst.data.ptr + dst.meta.wi, p, i);
146 dst.meta.wi += i;
147 p += i;
148 n -= i;
149 }
150 return nullptr;
151}
152
153// ----
154
155enum class context {
156 none,
157 in_list_after_bracket,
158 in_list_after_value,
159 in_dict_after_brace,
160 in_dict_after_key,
161 in_dict_after_value,
162};
163
164// parsed_token is a result type, combining a wuffs_base_token and an error.
165// For the parsed_token returned by make_parsed_token, it also contains the src
166// data bytes for the token. This slice is just a view into the src_buffer
167// array, and its contents may change on the next call to parse_next_token.
168//
169// An invariant is that (token.length() == data.len).
170typedef struct {
171 const char* error_msg;
172 wuffs_base__token token;
173 wuffs_base__slice_u8 data;
174} parsed_token;
175
176parsed_token make_pt_error(const char* error_msg) {
177 parsed_token p;
178 p.error_msg = error_msg;
179 p.token = wuffs_base__make_token(0);
180 p.data = wuffs_base__make_slice_u8(nullptr, 0);
181 return p;
182}
183
184parsed_token make_pt_token(uint64_t token_repr,
185 uint8_t* data_ptr,
186 size_t data_len) {
187 parsed_token p;
188 p.error_msg = nullptr;
189 p.token = wuffs_base__make_token(token_repr);
190 p.data = wuffs_base__make_slice_u8(data_ptr, data_len);
191 return p;
192}
193
194parsed_token parse_next_token() {
195 while (true) {
196 // Return a previously produced token, if one exists.
197 //
198 // We do this before checking dec_status. This is analogous to Go's
199 // io.Reader's documented idiom, when processing io.Reader.Read's returned
200 // (n int, err error), to "process the n > 0 bytes returned before
201 // considering the error err. Doing so correctly handles I/O errors that
202 // happen after reading some bytes".
203 if (tok.meta.ri < tok.meta.wi) {
204 wuffs_base__token t = tok.data.ptr[tok.meta.ri++];
205
206 uint64_t n = t.length();
207 if ((src.meta.ri - dec_current_token_end_src_index) < n) {
208 return make_pt_error("main: internal error: inconsistent src indexes");
209 }
210 dec_current_token_end_src_index += n;
211
212 // Filter out any filler tokens (e.g. whitespace).
213 if (t.value_base_category() == 0) {
214 continue;
215 }
216
217 return make_pt_token(
218 t.repr, src.data.ptr + dec_current_token_end_src_index - n, n);
219 }
220
221 // Now consider dec_status.
222 if (dec_status.repr == nullptr) {
223 return make_pt_error("main: internal error: parser stopped");
224
225 } else if (dec_status.repr == wuffs_base__suspension__short_read) {
226 if (dec_current_token_end_src_index != src.meta.ri) {
227 return make_pt_error("main: internal error: inconsistent src indexes");
228 }
229 const char* z = read_src();
230 if (z) {
231 return make_pt_error(z);
232 }
233 dec_current_token_end_src_index = src.meta.ri;
234
235 } else if (dec_status.repr == wuffs_base__suspension__short_write) {
236 tok.compact();
237
238 } else {
239 return make_pt_error(dec_status.message());
240 }
241
242 // Retry a "short read" or "short write" suspension.
243 dec_status = dec.decode_tokens(&tok, &src);
244 }
245}
246
247// ----
248
Nigel Taob5461bd2020-02-21 14:13:37 +1100249uint8_t hex_digit(uint8_t nibble) {
250 nibble &= 0x0F;
251 if (nibble <= 9) {
252 return '0' + nibble;
253 }
254 return ('A' - 10) + nibble;
255}
256
Nigel Tao1b073492020-02-16 22:11:36 +1100257const char* handle_string(parsed_token pt) {
Nigel Tao0711f232020-02-17 13:17:06 +1100258 TRY(write_dst("\"", 1));
Nigel Tao1b073492020-02-16 22:11:36 +1100259 while (true) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100260 uint64_t vbc = pt.token.value_base_category();
261 uint64_t vbd = pt.token.value_base_detail();
262
Nigel Tao9f7a2502020-02-23 09:42:02 +1100263 if (vbc == WUFFS_BASE__TOKEN__VBC__STRING) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100264 TRY(write_dst(pt.data.ptr, pt.data.len));
Nigel Tao9f7a2502020-02-23 09:42:02 +1100265 if ((vbd & WUFFS_BASE__TOKEN__VBD__STRING__INCOMPLETE) == 0) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100266 break;
267 }
268
Nigel Tao9f7a2502020-02-23 09:42:02 +1100269 } else if (vbc != WUFFS_BASE__TOKEN__VBC__UNICODE_CODE_POINT) {
270 return "main: unexpected token";
271
Nigel Taob5461bd2020-02-21 14:13:37 +1100272 } else if (vbd < 0x0020) {
273 switch (vbd) {
274 case '\b':
275 TRY(write_dst("\\b", 2));
276 break;
277 case '\f':
278 TRY(write_dst("\\f", 2));
279 break;
280 case '\n':
281 TRY(write_dst("\\n", 2));
282 break;
283 case '\r':
284 TRY(write_dst("\\r", 2));
285 break;
286 case '\t':
287 TRY(write_dst("\\t", 2));
288 break;
289 default: {
290 // Other bytes less than 0x0020 are valid UTF-8 but not valid in a
291 // JSON string. They need to remain escaped.
292 uint8_t esc6[6];
293 esc6[0] = '\\';
294 esc6[1] = 'u';
295 esc6[2] = '0';
296 esc6[3] = '0';
297 esc6[4] = hex_digit(vbd >> 4);
298 esc6[5] = hex_digit(vbd >> 0);
299 TRY(write_dst(&esc6[0], 6));
300 break;
301 }
302 }
303
304 } else if (vbd <= 0x007F) {
305 switch (vbd) {
306 case '\"':
307 TRY(write_dst("\\\"", 2));
308 break;
309 case '\\':
310 TRY(write_dst("\\\\", 2));
311 break;
312 default: {
313 // The UTF-8 encoding takes 1 byte.
314 uint8_t esc0 = (uint8_t)(vbd);
315 TRY(write_dst(&esc0, 1));
316 break;
317 }
318 }
319
320 } else if (vbd <= 0x07FF) {
321 // The UTF-8 encoding takes 2 bytes.
322 uint8_t esc2[6];
323 esc2[0] = 0xC0 | (uint8_t)((vbd >> 6));
324 esc2[1] = 0x80 | (uint8_t)((vbd >> 0) & 0x3F);
325 TRY(write_dst(&esc2[0], 2));
326
327 } else if (vbd <= 0xFFFF) {
328 // The UTF-8 encoding takes 3 bytes.
329 uint8_t esc3[6];
330 esc3[0] = 0xE0 | (uint8_t)((vbd >> 12));
331 esc3[1] = 0x80 | (uint8_t)((vbd >> 6) & 0x3F);
332 esc3[2] = 0x80 | (uint8_t)((vbd >> 0) & 0x3F);
333 TRY(write_dst(&esc3[0], 3));
334
335 } else {
336 return "main: unexpected Unicode code point";
Nigel Tao1b073492020-02-16 22:11:36 +1100337 }
Nigel Taob5461bd2020-02-21 14:13:37 +1100338
Nigel Tao1b073492020-02-16 22:11:36 +1100339 pt = parse_next_token();
340 if (pt.error_msg) {
341 return pt.error_msg;
342 }
343 }
344 TRY(write_dst("\"", 1));
345 return nullptr;
346}
347
348const char* main2() {
349 dec_status = dec.initialize(sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0);
350 if (!dec_status.is_ok()) {
351 return dec_status.message();
352 }
353 dec_status = dec.decode_tokens(&tok, &src);
354 dec_current_token_end_src_index = 0;
355
356 uint64_t depth = 0;
357 context ctx = context::none;
358
359continue_loop:
360 while (true) {
361 parsed_token pt = parse_next_token();
362 if (pt.error_msg) {
363 return pt.error_msg;
364 }
365 uint64_t vbc = pt.token.value_base_category();
366 uint64_t vbd = pt.token.value_base_detail();
367
368 // Handle ']' or '}'.
Nigel Tao9f7a2502020-02-23 09:42:02 +1100369 if ((vbc == WUFFS_BASE__TOKEN__VBC__STRUCTURE) &&
370 ((vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__POP) != 0)) {
Nigel Tao1b073492020-02-16 22:11:36 +1100371 if (depth <= 0) {
372 return "main: internal error: inconsistent depth";
373 }
374 depth--;
375
376 // Write preceding whitespace.
377 if ((ctx != context::in_list_after_bracket) &&
378 (ctx != context::in_dict_after_brace)) {
379 TRY(write_dst("\n", 1));
380 for (size_t i = 0; i < depth; i++) {
381 TRY(write_dst(INDENT_STRING, indent));
382 }
383 }
384
Nigel Tao9f7a2502020-02-23 09:42:02 +1100385 TRY(write_dst(
386 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST) ? "]" : "}", 1));
387 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
388 ? context::in_list_after_value
389 : context::in_dict_after_key;
Nigel Tao1b073492020-02-16 22:11:36 +1100390 goto after_value;
391 }
392
393 // Write preceding whitespace and punctuation, if it wasn't ']' or '}'.
394 if (ctx == context::in_dict_after_key) {
395 TRY(write_dst(": ", 2));
396 } else if (ctx != context::none) {
397 if ((ctx != context::in_list_after_bracket) &&
398 (ctx != context::in_dict_after_brace)) {
399 TRY(write_dst(",", 1));
400 }
401 TRY(write_dst("\n", 1));
402 for (size_t i = 0; i < depth; i++) {
403 TRY(write_dst(INDENT_STRING, indent));
404 }
405 }
406
407 // Handle the token itself: either a container ('[' or '{') or a simple
408 // value (number, string or literal).
409 switch (vbc) {
Nigel Tao9f7a2502020-02-23 09:42:02 +1100410 case WUFFS_BASE__TOKEN__VBC__STRUCTURE:
411 TRY(write_dst(
412 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST) ? "[" : "{", 1));
Nigel Tao1b073492020-02-16 22:11:36 +1100413 depth++;
Nigel Tao9f7a2502020-02-23 09:42:02 +1100414 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
415 ? context::in_list_after_bracket
416 : context::in_dict_after_brace;
Nigel Tao1b073492020-02-16 22:11:36 +1100417 goto continue_loop;
418
Nigel Tao9f7a2502020-02-23 09:42:02 +1100419 case WUFFS_BASE__TOKEN__VBC__NUMBER:
Nigel Tao8850d382020-02-19 12:25:00 +1100420 TRY(write_dst(pt.data.ptr, pt.data.len));
421 goto after_value;
422
Nigel Tao9f7a2502020-02-23 09:42:02 +1100423 case WUFFS_BASE__TOKEN__VBC__STRING:
Nigel Tao1b073492020-02-16 22:11:36 +1100424 TRY(handle_string(pt));
425 goto after_value;
426 }
427
428 // Return an error if we didn't match the (vbc, vbd) pair.
429 return "main: unexpected token";
430
431 // Book-keeping after completing a value (whether a container value or a
432 // simple value). Empty parent containers are no longer empty. If the
433 // parent container is a "{...}" object, toggle between keys and values.
434 after_value:
435 if (depth <= 0) {
436 return nullptr;
437 }
438 switch (ctx) {
439 case context::in_list_after_bracket:
440 ctx = context::in_list_after_value;
441 break;
442 case context::in_dict_after_brace:
443 ctx = context::in_dict_after_key;
444 break;
445 case context::in_dict_after_key:
446 ctx = context::in_dict_after_value;
447 break;
448 case context::in_dict_after_value:
449 ctx = context::in_dict_after_key;
450 break;
451 }
452 }
453}
454
455const char* main1(int argc, char** argv) {
456 dst = wuffs_base__make_io_buffer(
457 wuffs_base__make_slice_u8(dst_buffer, DST_BUFFER_SIZE),
458 wuffs_base__empty_io_buffer_meta());
459
460 src = wuffs_base__make_io_buffer(
461 wuffs_base__make_slice_u8(src_buffer, SRC_BUFFER_SIZE),
462 wuffs_base__empty_io_buffer_meta());
463
464 tok = wuffs_base__make_token_buffer(
465 wuffs_base__make_slice_token(tok_buffer, TOKEN_BUFFER_SIZE),
466 wuffs_base__empty_token_buffer_meta());
467
468 indent = 4;
469
470 TRY(main2());
471 TRY(write_dst("\n", 1));
472 return nullptr;
473}
474
Nigel Tao9cc2c252020-02-23 17:05:49 +1100475int compute_exit_code(const char* status_msg) {
476 if (!status_msg) {
477 return 0;
478 }
479 size_t n = strnlen(status_msg, 2047);
480 if (n >= 2047) {
481 status_msg = "main: internal error: error message is too long";
482 n = strnlen(status_msg, 2047);
483 }
484 fprintf(stderr, "%s\n", status_msg);
485 // Return an exit code of 1 for regular (forseen) errors, e.g. badly
486 // formatted or unsupported input.
487 //
488 // Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
489 // run-time checks found that an internal invariant did not hold.
490 //
491 // Automated testing, including badly formatted inputs, can therefore
492 // discriminate between expected failure (exit code 1) and unexpected failure
493 // (other non-zero exit codes). Specifically, exit code 2 for internal
494 // invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
495 // linux) for a segmentation fault (e.g. null pointer dereference).
496 return strstr(status_msg, "internal error:") ? 2 : 1;
497}
498
Nigel Tao1b073492020-02-16 22:11:36 +1100499int main(int argc, char** argv) {
500 const char* z0 = main1(argc, argv);
501 const char* z1 = flush_dst();
Nigel Tao9cc2c252020-02-23 17:05:49 +1100502 int exit_code = compute_exit_code(z0 ? z0 : z1);
503 return exit_code;
Nigel Tao1b073492020-02-16 22:11:36 +1100504}