blob: a6ee35538b9c8ab805f199b3ce8cb5e5c99aa75f [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
Nigel Tao9f7a2502020-02-23 09:42:02 +1100262 if (vbc == WUFFS_BASE__TOKEN__VBC__STRING) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100263 TRY(write_dst(pt.data.ptr, pt.data.len));
Nigel Tao9f7a2502020-02-23 09:42:02 +1100264 if ((vbd & WUFFS_BASE__TOKEN__VBD__STRING__INCOMPLETE) == 0) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100265 break;
266 }
267
Nigel Tao9f7a2502020-02-23 09:42:02 +1100268 } else if (vbc != WUFFS_BASE__TOKEN__VBC__UNICODE_CODE_POINT) {
269 return "main: unexpected token";
270
Nigel Taob5461bd2020-02-21 14:13:37 +1100271 } else if (vbd < 0x0020) {
272 switch (vbd) {
273 case '\b':
274 TRY(write_dst("\\b", 2));
275 break;
276 case '\f':
277 TRY(write_dst("\\f", 2));
278 break;
279 case '\n':
280 TRY(write_dst("\\n", 2));
281 break;
282 case '\r':
283 TRY(write_dst("\\r", 2));
284 break;
285 case '\t':
286 TRY(write_dst("\\t", 2));
287 break;
288 default: {
289 // Other bytes less than 0x0020 are valid UTF-8 but not valid in a
290 // JSON string. They need to remain escaped.
291 uint8_t esc6[6];
292 esc6[0] = '\\';
293 esc6[1] = 'u';
294 esc6[2] = '0';
295 esc6[3] = '0';
296 esc6[4] = hex_digit(vbd >> 4);
297 esc6[5] = hex_digit(vbd >> 0);
298 TRY(write_dst(&esc6[0], 6));
299 break;
300 }
301 }
302
303 } else if (vbd <= 0x007F) {
304 switch (vbd) {
305 case '\"':
306 TRY(write_dst("\\\"", 2));
307 break;
308 case '\\':
309 TRY(write_dst("\\\\", 2));
310 break;
311 default: {
312 // The UTF-8 encoding takes 1 byte.
313 uint8_t esc0 = (uint8_t)(vbd);
314 TRY(write_dst(&esc0, 1));
315 break;
316 }
317 }
318
319 } else if (vbd <= 0x07FF) {
320 // The UTF-8 encoding takes 2 bytes.
321 uint8_t esc2[6];
322 esc2[0] = 0xC0 | (uint8_t)((vbd >> 6));
323 esc2[1] = 0x80 | (uint8_t)((vbd >> 0) & 0x3F);
324 TRY(write_dst(&esc2[0], 2));
325
326 } else if (vbd <= 0xFFFF) {
327 // The UTF-8 encoding takes 3 bytes.
328 uint8_t esc3[6];
329 esc3[0] = 0xE0 | (uint8_t)((vbd >> 12));
330 esc3[1] = 0x80 | (uint8_t)((vbd >> 6) & 0x3F);
331 esc3[2] = 0x80 | (uint8_t)((vbd >> 0) & 0x3F);
332 TRY(write_dst(&esc3[0], 3));
333
334 } else {
335 return "main: unexpected Unicode code point";
Nigel Tao1b073492020-02-16 22:11:36 +1100336 }
Nigel Taob5461bd2020-02-21 14:13:37 +1100337
Nigel Tao1b073492020-02-16 22:11:36 +1100338 pt = parse_next_token();
339 if (pt.error_msg) {
340 return pt.error_msg;
341 }
342 }
343 TRY(write_dst("\"", 1));
344 return nullptr;
345}
346
347const char* main2() {
348 dec_status = dec.initialize(sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0);
349 if (!dec_status.is_ok()) {
350 return dec_status.message();
351 }
352 dec_status = dec.decode_tokens(&tok, &src);
353 dec_current_token_end_src_index = 0;
354
355 uint64_t depth = 0;
356 context ctx = context::none;
357
358continue_loop:
359 while (true) {
360 parsed_token pt = parse_next_token();
361 if (pt.error_msg) {
362 return pt.error_msg;
363 }
364 uint64_t vbc = pt.token.value_base_category();
365 uint64_t vbd = pt.token.value_base_detail();
366
367 // Handle ']' or '}'.
Nigel Tao9f7a2502020-02-23 09:42:02 +1100368 if ((vbc == WUFFS_BASE__TOKEN__VBC__STRUCTURE) &&
369 ((vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__POP) != 0)) {
Nigel Tao1b073492020-02-16 22:11:36 +1100370 if (depth <= 0) {
371 return "main: internal error: inconsistent depth";
372 }
373 depth--;
374
375 // Write preceding whitespace.
376 if ((ctx != context::in_list_after_bracket) &&
377 (ctx != context::in_dict_after_brace)) {
378 TRY(write_dst("\n", 1));
379 for (size_t i = 0; i < depth; i++) {
380 TRY(write_dst(INDENT_STRING, indent));
381 }
382 }
383
Nigel Tao9f7a2502020-02-23 09:42:02 +1100384 TRY(write_dst(
385 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST) ? "]" : "}", 1));
386 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
387 ? context::in_list_after_value
388 : context::in_dict_after_key;
Nigel Tao1b073492020-02-16 22:11:36 +1100389 goto after_value;
390 }
391
392 // Write preceding whitespace and punctuation, if it wasn't ']' or '}'.
393 if (ctx == context::in_dict_after_key) {
394 TRY(write_dst(": ", 2));
395 } else if (ctx != context::none) {
396 if ((ctx != context::in_list_after_bracket) &&
397 (ctx != context::in_dict_after_brace)) {
398 TRY(write_dst(",", 1));
399 }
400 TRY(write_dst("\n", 1));
401 for (size_t i = 0; i < depth; i++) {
402 TRY(write_dst(INDENT_STRING, indent));
403 }
404 }
405
406 // Handle the token itself: either a container ('[' or '{') or a simple
407 // value (number, string or literal).
408 switch (vbc) {
Nigel Tao9f7a2502020-02-23 09:42:02 +1100409 case WUFFS_BASE__TOKEN__VBC__STRUCTURE:
410 TRY(write_dst(
411 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST) ? "[" : "{", 1));
Nigel Tao1b073492020-02-16 22:11:36 +1100412 depth++;
Nigel Tao9f7a2502020-02-23 09:42:02 +1100413 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
414 ? context::in_list_after_bracket
415 : context::in_dict_after_brace;
Nigel Tao1b073492020-02-16 22:11:36 +1100416 goto continue_loop;
417
Nigel Tao9f7a2502020-02-23 09:42:02 +1100418 case WUFFS_BASE__TOKEN__VBC__NUMBER:
Nigel Tao8850d382020-02-19 12:25:00 +1100419 TRY(write_dst(pt.data.ptr, pt.data.len));
420 goto after_value;
421
Nigel Tao9f7a2502020-02-23 09:42:02 +1100422 case WUFFS_BASE__TOKEN__VBC__STRING:
Nigel Tao1b073492020-02-16 22:11:36 +1100423 TRY(handle_string(pt));
424 goto after_value;
425 }
426
427 // Return an error if we didn't match the (vbc, vbd) pair.
428 return "main: unexpected token";
429
430 // Book-keeping after completing a value (whether a container value or a
431 // simple value). Empty parent containers are no longer empty. If the
432 // parent container is a "{...}" object, toggle between keys and values.
433 after_value:
434 if (depth <= 0) {
435 return nullptr;
436 }
437 switch (ctx) {
438 case context::in_list_after_bracket:
439 ctx = context::in_list_after_value;
440 break;
441 case context::in_dict_after_brace:
442 ctx = context::in_dict_after_key;
443 break;
444 case context::in_dict_after_key:
445 ctx = context::in_dict_after_value;
446 break;
447 case context::in_dict_after_value:
448 ctx = context::in_dict_after_key;
449 break;
450 }
451 }
452}
453
454const char* main1(int argc, char** argv) {
455 dst = wuffs_base__make_io_buffer(
456 wuffs_base__make_slice_u8(dst_buffer, DST_BUFFER_SIZE),
457 wuffs_base__empty_io_buffer_meta());
458
459 src = wuffs_base__make_io_buffer(
460 wuffs_base__make_slice_u8(src_buffer, SRC_BUFFER_SIZE),
461 wuffs_base__empty_io_buffer_meta());
462
463 tok = wuffs_base__make_token_buffer(
464 wuffs_base__make_slice_token(tok_buffer, TOKEN_BUFFER_SIZE),
465 wuffs_base__empty_token_buffer_meta());
466
467 indent = 4;
468
469 TRY(main2());
470 TRY(write_dst("\n", 1));
471 return nullptr;
472}
473
474int main(int argc, char** argv) {
475 const char* z0 = main1(argc, argv);
476 const char* z1 = flush_dst();
477 const char* z = z0 ? z0 : z1;
478 if (z) {
479 fprintf(stderr, "%s\n", z);
480 return 1;
481 }
482 return 0;
483}