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