blob: 39100489cc8b0d1e50c11d274bd944928c345082 [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() {
96 src.compact();
97 if (src.meta.wi >= src.data.len) {
98 return "main: src buffer is full";
99 }
100 size_t n = fread(src.data.ptr + src.meta.wi, sizeof(uint8_t),
101 src.data.len - src.meta.wi, stdin);
102 src.meta.wi += n;
103 if (n == 0) {
104 if (feof(stdin)) {
105 return "main: read error: unexpected EOF";
106 } else {
107 return "main: read error";
108 }
109 }
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
248const char* handle_string(parsed_token pt) {
Nigel Tao0711f232020-02-17 13:17:06 +1100249 TRY(write_dst("\"", 1));
Nigel Tao1b073492020-02-16 22:11:36 +1100250 while (true) {
Nigel Tao1b073492020-02-16 22:11:36 +1100251 TRY(write_dst(pt.data.ptr, pt.data.len));
252 if ((pt.token.value_base_detail() & 1) == 0) {
253 break;
254 }
255 pt = parse_next_token();
256 if (pt.error_msg) {
257 return pt.error_msg;
258 }
259 }
260 TRY(write_dst("\"", 1));
261 return nullptr;
262}
263
264const char* main2() {
265 dec_status = dec.initialize(sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0);
266 if (!dec_status.is_ok()) {
267 return dec_status.message();
268 }
269 dec_status = dec.decode_tokens(&tok, &src);
270 dec_current_token_end_src_index = 0;
271
272 uint64_t depth = 0;
273 context ctx = context::none;
274
275continue_loop:
276 while (true) {
277 parsed_token pt = parse_next_token();
278 if (pt.error_msg) {
279 return pt.error_msg;
280 }
281 uint64_t vbc = pt.token.value_base_category();
282 uint64_t vbd = pt.token.value_base_detail();
283
284 // Handle ']' or '}'.
285 if ((vbc == 1) && ((vbd & 0x2) != 0)) {
286 if (depth <= 0) {
287 return "main: internal error: inconsistent depth";
288 }
289 depth--;
290
291 // Write preceding whitespace.
292 if ((ctx != context::in_list_after_bracket) &&
293 (ctx != context::in_dict_after_brace)) {
294 TRY(write_dst("\n", 1));
295 for (size_t i = 0; i < depth; i++) {
296 TRY(write_dst(INDENT_STRING, indent));
297 }
298 }
299
300 TRY(write_dst((vbd & 0x10) ? "]" : "}", 1));
301 ctx = (vbd & 0x1000) ? context::in_list_after_value
302 : context::in_dict_after_key;
303 goto after_value;
304 }
305
306 // Write preceding whitespace and punctuation, if it wasn't ']' or '}'.
307 if (ctx == context::in_dict_after_key) {
308 TRY(write_dst(": ", 2));
309 } else if (ctx != context::none) {
310 if ((ctx != context::in_list_after_bracket) &&
311 (ctx != context::in_dict_after_brace)) {
312 TRY(write_dst(",", 1));
313 }
314 TRY(write_dst("\n", 1));
315 for (size_t i = 0; i < depth; i++) {
316 TRY(write_dst(INDENT_STRING, indent));
317 }
318 }
319
320 // Handle the token itself: either a container ('[' or '{') or a simple
321 // value (number, string or literal).
322 switch (vbc) {
323 case 1:
324 TRY(write_dst((vbd & 0x10) ? "[" : "{", 1));
325 depth++;
326 ctx = (vbd & 0x10) ? context::in_list_after_bracket
327 : context::in_dict_after_brace;
328 goto continue_loop;
329
330 case 3:
331 TRY(handle_string(pt));
332 goto after_value;
333 }
334
335 // Return an error if we didn't match the (vbc, vbd) pair.
336 return "main: unexpected token";
337
338 // Book-keeping after completing a value (whether a container value or a
339 // simple value). Empty parent containers are no longer empty. If the
340 // parent container is a "{...}" object, toggle between keys and values.
341 after_value:
342 if (depth <= 0) {
343 return nullptr;
344 }
345 switch (ctx) {
346 case context::in_list_after_bracket:
347 ctx = context::in_list_after_value;
348 break;
349 case context::in_dict_after_brace:
350 ctx = context::in_dict_after_key;
351 break;
352 case context::in_dict_after_key:
353 ctx = context::in_dict_after_value;
354 break;
355 case context::in_dict_after_value:
356 ctx = context::in_dict_after_key;
357 break;
358 }
359 }
360}
361
362const char* main1(int argc, char** argv) {
363 dst = wuffs_base__make_io_buffer(
364 wuffs_base__make_slice_u8(dst_buffer, DST_BUFFER_SIZE),
365 wuffs_base__empty_io_buffer_meta());
366
367 src = wuffs_base__make_io_buffer(
368 wuffs_base__make_slice_u8(src_buffer, SRC_BUFFER_SIZE),
369 wuffs_base__empty_io_buffer_meta());
370
371 tok = wuffs_base__make_token_buffer(
372 wuffs_base__make_slice_token(tok_buffer, TOKEN_BUFFER_SIZE),
373 wuffs_base__empty_token_buffer_meta());
374
375 indent = 4;
376
377 TRY(main2());
378 TRY(write_dst("\n", 1));
379 return nullptr;
380}
381
382int main(int argc, char** argv) {
383 const char* z0 = main1(argc, argv);
384 const char* z1 = flush_dst();
385 const char* z = z0 ? z0 : z1;
386 if (z) {
387 fprintf(stderr, "%s\n", z);
388 return 1;
389 }
390 return 0;
391}