blob: f791ba265b1dacee774355b892d63ec0fbd57023 [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 Taoa8406922020-02-19 12:22:00 +1100106 if (n > 0) {
107 // No-op.
108 } else if (feof(stdin)) {
109 src.meta.closed = true;
110 } else {
111 return "main: read error";
Nigel Tao1b073492020-02-16 22:11:36 +1100112 }
113 return nullptr;
114}
115
116const char* flush_dst() {
117 size_t n = dst.meta.wi - dst.meta.ri;
118 if (n > 0) {
119 size_t i = fwrite(dst.data.ptr + dst.meta.ri, sizeof(uint8_t), n, stdout);
120 dst.meta.ri += i;
121 if (i != n) {
122 return "main: write error";
123 }
124 dst.compact();
125 }
126 return nullptr;
127}
128
129const char* write_dst(const void* s, size_t n) {
130 const uint8_t* p = static_cast<const uint8_t*>(s);
131 while (n > 0) {
132 size_t i = dst.writer_available();
133 if (i == 0) {
134 const char* z = flush_dst();
135 if (z) {
136 return z;
137 }
138 i = dst.writer_available();
139 if (i == 0) {
140 return "main: dst buffer is full";
141 }
142 }
143
144 if (i > n) {
145 i = n;
146 }
147 memcpy(dst.data.ptr + dst.meta.wi, p, i);
148 dst.meta.wi += i;
149 p += i;
150 n -= i;
151 }
152 return nullptr;
153}
154
155// ----
156
157enum class context {
158 none,
159 in_list_after_bracket,
160 in_list_after_value,
161 in_dict_after_brace,
162 in_dict_after_key,
163 in_dict_after_value,
164};
165
166// parsed_token is a result type, combining a wuffs_base_token and an error.
167// For the parsed_token returned by make_parsed_token, it also contains the src
168// data bytes for the token. This slice is just a view into the src_buffer
169// array, and its contents may change on the next call to parse_next_token.
170//
171// An invariant is that (token.length() == data.len).
172typedef struct {
173 const char* error_msg;
174 wuffs_base__token token;
175 wuffs_base__slice_u8 data;
176} parsed_token;
177
178parsed_token make_pt_error(const char* error_msg) {
179 parsed_token p;
180 p.error_msg = error_msg;
181 p.token = wuffs_base__make_token(0);
182 p.data = wuffs_base__make_slice_u8(nullptr, 0);
183 return p;
184}
185
186parsed_token make_pt_token(uint64_t token_repr,
187 uint8_t* data_ptr,
188 size_t data_len) {
189 parsed_token p;
190 p.error_msg = nullptr;
191 p.token = wuffs_base__make_token(token_repr);
192 p.data = wuffs_base__make_slice_u8(data_ptr, data_len);
193 return p;
194}
195
196parsed_token parse_next_token() {
197 while (true) {
198 // Return a previously produced token, if one exists.
199 //
200 // We do this before checking dec_status. This is analogous to Go's
201 // io.Reader's documented idiom, when processing io.Reader.Read's returned
202 // (n int, err error), to "process the n > 0 bytes returned before
203 // considering the error err. Doing so correctly handles I/O errors that
204 // happen after reading some bytes".
205 if (tok.meta.ri < tok.meta.wi) {
206 wuffs_base__token t = tok.data.ptr[tok.meta.ri++];
207
208 uint64_t n = t.length();
209 if ((src.meta.ri - dec_current_token_end_src_index) < n) {
210 return make_pt_error("main: internal error: inconsistent src indexes");
211 }
212 dec_current_token_end_src_index += n;
213
214 // Filter out any filler tokens (e.g. whitespace).
215 if (t.value_base_category() == 0) {
216 continue;
217 }
218
219 return make_pt_token(
220 t.repr, src.data.ptr + dec_current_token_end_src_index - n, n);
221 }
222
223 // Now consider dec_status.
224 if (dec_status.repr == nullptr) {
225 return make_pt_error("main: internal error: parser stopped");
226
227 } else if (dec_status.repr == wuffs_base__suspension__short_read) {
228 if (dec_current_token_end_src_index != src.meta.ri) {
229 return make_pt_error("main: internal error: inconsistent src indexes");
230 }
231 const char* z = read_src();
232 if (z) {
233 return make_pt_error(z);
234 }
235 dec_current_token_end_src_index = src.meta.ri;
236
237 } else if (dec_status.repr == wuffs_base__suspension__short_write) {
238 tok.compact();
239
240 } else {
241 return make_pt_error(dec_status.message());
242 }
243
244 // Retry a "short read" or "short write" suspension.
245 dec_status = dec.decode_tokens(&tok, &src);
246 }
247}
248
249// ----
250
251const char* handle_string(parsed_token pt) {
Nigel Tao0711f232020-02-17 13:17:06 +1100252 TRY(write_dst("\"", 1));
Nigel Tao1b073492020-02-16 22:11:36 +1100253 while (true) {
Nigel Tao1b073492020-02-16 22:11:36 +1100254 TRY(write_dst(pt.data.ptr, pt.data.len));
255 if ((pt.token.value_base_detail() & 1) == 0) {
256 break;
257 }
258 pt = parse_next_token();
259 if (pt.error_msg) {
260 return pt.error_msg;
261 }
262 }
263 TRY(write_dst("\"", 1));
264 return nullptr;
265}
266
267const char* main2() {
268 dec_status = dec.initialize(sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0);
269 if (!dec_status.is_ok()) {
270 return dec_status.message();
271 }
272 dec_status = dec.decode_tokens(&tok, &src);
273 dec_current_token_end_src_index = 0;
274
275 uint64_t depth = 0;
276 context ctx = context::none;
277
278continue_loop:
279 while (true) {
280 parsed_token pt = parse_next_token();
281 if (pt.error_msg) {
282 return pt.error_msg;
283 }
284 uint64_t vbc = pt.token.value_base_category();
285 uint64_t vbd = pt.token.value_base_detail();
286
287 // Handle ']' or '}'.
288 if ((vbc == 1) && ((vbd & 0x2) != 0)) {
289 if (depth <= 0) {
290 return "main: internal error: inconsistent depth";
291 }
292 depth--;
293
294 // Write preceding whitespace.
295 if ((ctx != context::in_list_after_bracket) &&
296 (ctx != context::in_dict_after_brace)) {
297 TRY(write_dst("\n", 1));
298 for (size_t i = 0; i < depth; i++) {
299 TRY(write_dst(INDENT_STRING, indent));
300 }
301 }
302
303 TRY(write_dst((vbd & 0x10) ? "]" : "}", 1));
304 ctx = (vbd & 0x1000) ? context::in_list_after_value
305 : context::in_dict_after_key;
306 goto after_value;
307 }
308
309 // Write preceding whitespace and punctuation, if it wasn't ']' or '}'.
310 if (ctx == context::in_dict_after_key) {
311 TRY(write_dst(": ", 2));
312 } else if (ctx != context::none) {
313 if ((ctx != context::in_list_after_bracket) &&
314 (ctx != context::in_dict_after_brace)) {
315 TRY(write_dst(",", 1));
316 }
317 TRY(write_dst("\n", 1));
318 for (size_t i = 0; i < depth; i++) {
319 TRY(write_dst(INDENT_STRING, indent));
320 }
321 }
322
323 // Handle the token itself: either a container ('[' or '{') or a simple
324 // value (number, string or literal).
325 switch (vbc) {
326 case 1:
327 TRY(write_dst((vbd & 0x10) ? "[" : "{", 1));
328 depth++;
329 ctx = (vbd & 0x10) ? context::in_list_after_bracket
330 : context::in_dict_after_brace;
331 goto continue_loop;
332
Nigel Tao8850d382020-02-19 12:25:00 +1100333 case 2:
334 TRY(write_dst(pt.data.ptr, pt.data.len));
335 goto after_value;
336
Nigel Tao1b073492020-02-16 22:11:36 +1100337 case 3:
338 TRY(handle_string(pt));
339 goto after_value;
340 }
341
342 // Return an error if we didn't match the (vbc, vbd) pair.
343 return "main: unexpected token";
344
345 // Book-keeping after completing a value (whether a container value or a
346 // simple value). Empty parent containers are no longer empty. If the
347 // parent container is a "{...}" object, toggle between keys and values.
348 after_value:
349 if (depth <= 0) {
350 return nullptr;
351 }
352 switch (ctx) {
353 case context::in_list_after_bracket:
354 ctx = context::in_list_after_value;
355 break;
356 case context::in_dict_after_brace:
357 ctx = context::in_dict_after_key;
358 break;
359 case context::in_dict_after_key:
360 ctx = context::in_dict_after_value;
361 break;
362 case context::in_dict_after_value:
363 ctx = context::in_dict_after_key;
364 break;
365 }
366 }
367}
368
369const char* main1(int argc, char** argv) {
370 dst = wuffs_base__make_io_buffer(
371 wuffs_base__make_slice_u8(dst_buffer, DST_BUFFER_SIZE),
372 wuffs_base__empty_io_buffer_meta());
373
374 src = wuffs_base__make_io_buffer(
375 wuffs_base__make_slice_u8(src_buffer, SRC_BUFFER_SIZE),
376 wuffs_base__empty_io_buffer_meta());
377
378 tok = wuffs_base__make_token_buffer(
379 wuffs_base__make_slice_token(tok_buffer, TOKEN_BUFFER_SIZE),
380 wuffs_base__empty_token_buffer_meta());
381
382 indent = 4;
383
384 TRY(main2());
385 TRY(write_dst("\n", 1));
386 return nullptr;
387}
388
389int main(int argc, char** argv) {
390 const char* z0 = main1(argc, argv);
391 const char* z1 = flush_dst();
392 const char* z = z0 ? z0 : z1;
393 if (z) {
394 fprintf(stderr, "%s\n", z);
395 return 1;
396 }
397 return 0;
398}