blob: 1a370ba2ee6ec95ae96cf9f436ad116c4f8c5c25 [file] [log] [blame]
Nigel Tao193527b2020-02-26 21:55:01 +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// print-json-token-debug-format.c parses JSON from stdin and prints the
18// resulting token stream, eliding any non-essential (e.g. whitespace) tokens.
19//
Nigel Taod1c928a2020-02-28 12:43:53 +110020// The output format is only for debugging or regression testing, and certainly
21// not for long term storage. It isn't guaranteed to be stable between versions
22// of this program and of the Wuffs standard library.
Nigel Tao193527b2020-02-26 21:55:01 +110023//
Nigel Taod1c928a2020-02-28 12:43:53 +110024// It prints 16 bytes (128 bits) per token, containing big-endian numbers:
25//
26// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
27// | POS | LEN | LP| LN| MAJOR | MINOR |
28// | | | | | |VBC| VBD |
29// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
30//
31// - POS (4 bytes) is the position: the sum of all previous tokens' lengths,
32// including elided tokens.
33// - LEN (2 bytes) is the length.
34// - LP (1 bytes) is the link_prev bit.
35// - LN (1 bytes) is the link_next bit
36// - MAJOR (4 bytes) is the value_major.
37//
38// The final 4 bytes are either value_minor (when the value_major is non-zero)
39// or 1 + 3 bytes for value_base_category and value_base_detail (otherwise).
40//
Nigel Tao193527b2020-02-26 21:55:01 +110041// Together with the hexadecimal WUFFS_BASE__TOKEN__ETC constants defined in
42// token-public.h, this format is somewhat human-readable when piped through a
Nigel Taod1c928a2020-02-28 12:43:53 +110043// hex-dump program (such as /usr/bin/hd), printing one token per line.
Nigel Tao6b29f322020-02-29 17:05:24 +110044// Alternatively, pass the -h (--human-readable) flag to this program.
45//
46// Pass -a (--all-tokens) to print all tokens, including whitespace.
Nigel Tao193527b2020-02-26 21:55:01 +110047//
48// If the input or output is larger than the program's buffers (64 MiB and
49// 131072 tokens by default), there may be multiple valid tokenizations of any
50// given input. For example, if a source string "abcde" straddles an I/O
Nigel Taod1c928a2020-02-28 12:43:53 +110051// boundary, it may be tokenized as single (no-link) 5-length string or as a
52// 3-length link_next'ed string followed by a 2-length link_prev'ed string.
Nigel Tao193527b2020-02-26 21:55:01 +110053//
Nigel Taod1c928a2020-02-28 12:43:53 +110054// A Wuffs token stream, in general, can support inputs more than 0xFFFF_FFFF
Nigel Tao193527b2020-02-26 21:55:01 +110055// bytes long, but this program can not, as it tracks the tokens' cumulative
56// position as a uint32.
57
58#include <inttypes.h>
59#include <stdio.h>
60#include <string.h>
61#include <unistd.h>
62
63// Wuffs ships as a "single file C library" or "header file library" as per
64// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
65//
66// To use that single file as a "foo.c"-like implementation, instead of a
67// "foo.h"-like header, #define WUFFS_IMPLEMENTATION before #include'ing or
68// compiling it.
69#define WUFFS_IMPLEMENTATION
70
71// Defining the WUFFS_CONFIG__MODULE* macros are optional, but it lets users of
72// release/c/etc.c whitelist which parts of Wuffs to build. That file contains
73// the entire Wuffs standard library, implementing a variety of codecs and file
74// formats. Without this macro definition, an optimizing compiler or linker may
75// very well discard Wuffs code for unused codecs, but listing the Wuffs
76// modules we use makes that process explicit. Preprocessing means that such
77// code simply isn't compiled.
78#define WUFFS_CONFIG__MODULES
79#define WUFFS_CONFIG__MODULE__BASE
80#define WUFFS_CONFIG__MODULE__JSON
81
82// If building this program in an environment that doesn't easily accommodate
83// relative includes, you can use the script/inline-c-relative-includes.go
84// program to generate a stand-alone C++ file.
85#include "../release/c/wuffs-unsupported-snapshot.c"
86
Nigel Taof3146c22020-03-26 08:47:42 +110087// Wuffs allows either statically or dynamically allocated work buffers. This
88// program exercises static allocation.
89#define WORK_BUFFER_ARRAY_SIZE \
90 WUFFS_JSON__DECODER_WORKBUF_LEN_MAX_INCL_WORST_CASE
91#if WORK_BUFFER_ARRAY_SIZE > 0
92uint8_t work_buffer_array[WORK_BUFFER_ARRAY_SIZE];
93#else
94// Not all C/C++ compilers support 0-length arrays.
95uint8_t work_buffer_array[1];
96#endif
97
Nigel Taofdac24a2020-03-06 21:53:08 +110098#ifndef SRC_BUFFER_ARRAY_SIZE
99#define SRC_BUFFER_ARRAY_SIZE (64 * 1024 * 1024)
Nigel Tao193527b2020-02-26 21:55:01 +1100100#endif
Nigel Taofdac24a2020-03-06 21:53:08 +1100101#ifndef TOKEN_BUFFER_ARRAY_SIZE
102#define TOKEN_BUFFER_ARRAY_SIZE (128 * 1024)
Nigel Tao193527b2020-02-26 21:55:01 +1100103#endif
104
Nigel Taofdac24a2020-03-06 21:53:08 +1100105uint8_t src_buffer_array[SRC_BUFFER_ARRAY_SIZE];
106wuffs_base__token tok_buffer_array[TOKEN_BUFFER_ARRAY_SIZE];
Nigel Tao193527b2020-02-26 21:55:01 +1100107
108wuffs_base__io_buffer src;
109wuffs_base__token_buffer tok;
110
111wuffs_json__decoder dec;
112wuffs_base__status dec_status;
113
Nigel Tao193527b2020-02-26 21:55:01 +1100114#define TRY(error_msg) \
115 do { \
116 const char* z = error_msg; \
117 if (z) { \
118 return z; \
119 } \
120 } while (false)
121
Nigel Tao68920952020-03-03 11:25:18 +1100122// ignore_return_value suppresses errors from -Wall -Werror.
123static void //
124ignore_return_value(int ignored) {}
125
Nigel Tao193527b2020-02-26 21:55:01 +1100126const char* //
127read_src() {
128 if (src.meta.closed) {
129 return "main: internal error: read requested on a closed source";
130 }
131 wuffs_base__io_buffer__compact(&src);
132 if (src.meta.wi >= src.data.len) {
133 return "main: src buffer is full";
134 }
135 size_t n = fread(src.data.ptr + src.meta.wi, sizeof(uint8_t),
136 src.data.len - src.meta.wi, stdin);
137 src.meta.wi += n;
138 src.meta.closed = feof(stdin);
139 if ((n == 0) && !src.meta.closed) {
140 return "main: read error";
141 }
142 return NULL;
143}
144
145// ----
146
Nigel Tao68920952020-03-03 11:25:18 +1100147struct {
148 int remaining_argc;
149 char** remaining_argv;
150
151 bool all_tokens;
152 bool human_readable;
Nigel Tao5d5a17c2020-03-24 16:38:43 +1100153 bool quirks;
Nigel Tao68920952020-03-03 11:25:18 +1100154} flags = {0};
155
156const char* //
157parse_flags(int argc, char** argv) {
158 int c = (argc > 0) ? 1 : 0; // Skip argv[0], the program name.
159 for (; c < argc; c++) {
160 char* arg = argv[c];
161 if (*arg++ != '-') {
162 break;
163 }
164
165 // A double-dash "--foo" is equivalent to a single-dash "-foo". As special
166 // cases, a bare "-" is not a flag (some programs may interpret it as
167 // stdin) and a bare "--" means to stop parsing flags.
168 if (*arg == '\x00') {
169 break;
170 } else if (*arg == '-') {
171 arg++;
172 if (*arg == '\x00') {
173 c++;
174 break;
175 }
176 }
177
178 if (!strcmp(arg, "a") || !strcmp(arg, "all-tokens")) {
179 flags.all_tokens = true;
180 continue;
181 }
182 if (!strcmp(arg, "h") || !strcmp(arg, "human-readable")) {
183 flags.human_readable = true;
184 continue;
185 }
Nigel Tao5d5a17c2020-03-24 16:38:43 +1100186 if (!strcmp(arg, "q") || !strcmp(arg, "quirks")) {
187 flags.quirks = true;
188 continue;
189 }
Nigel Tao68920952020-03-03 11:25:18 +1100190
191 return "main: unrecognized flag argument";
192 }
193
194 flags.remaining_argc = argc - c;
195 flags.remaining_argv = argv + c;
196 return NULL;
197}
198
Nigel Tao67f00c12020-02-29 12:48:59 +1100199const char* vbc_names[8] = {
200 "0:Filler..........", //
Nigel Tao85fba7f2020-02-29 16:28:06 +1100201 "1:Structure.......", //
202 "2:String..........", //
203 "3:UnicodeCodePoint", //
204 "4:Literal.........", //
205 "5:Number..........", //
Nigel Tao67f00c12020-02-29 12:48:59 +1100206 "6:Reserved........", //
207 "7:Reserved........", //
208};
209
210const int base38_decode[38] = {
211 ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '?', //
212 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', //
213 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', //
214};
215
Nigel Tao193527b2020-02-26 21:55:01 +1100216const char* //
217main1(int argc, char** argv) {
Nigel Tao68920952020-03-03 11:25:18 +1100218 TRY(parse_flags(argc, argv));
219 if (flags.remaining_argc > 0) {
220 return "main: bad argument: use \"program < input\", not \"program input\"";
Nigel Tao67f00c12020-02-29 12:48:59 +1100221 }
222
Nigel Tao193527b2020-02-26 21:55:01 +1100223 src = wuffs_base__make_io_buffer(
Nigel Taofdac24a2020-03-06 21:53:08 +1100224 wuffs_base__make_slice_u8(src_buffer_array, SRC_BUFFER_ARRAY_SIZE),
Nigel Tao193527b2020-02-26 21:55:01 +1100225 wuffs_base__empty_io_buffer_meta());
226
227 tok = wuffs_base__make_token_buffer(
Nigel Taofdac24a2020-03-06 21:53:08 +1100228 wuffs_base__make_slice_token(tok_buffer_array, TOKEN_BUFFER_ARRAY_SIZE),
Nigel Tao193527b2020-02-26 21:55:01 +1100229 wuffs_base__empty_token_buffer_meta());
230
231 wuffs_base__status init_status = wuffs_json__decoder__initialize(
232 &dec, sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0);
233 if (!wuffs_base__status__is_ok(&init_status)) {
234 return wuffs_base__status__message(&init_status);
235 }
236
Nigel Tao5d5a17c2020-03-24 16:38:43 +1100237 if (flags.quirks) {
238 uint32_t quirks[] = {
239 WUFFS_JSON__QUIRK_ALLOW_BACKSLASH_A,
240 WUFFS_JSON__QUIRK_ALLOW_BACKSLASH_CAPITAL_U,
241 WUFFS_JSON__QUIRK_ALLOW_BACKSLASH_E,
242 WUFFS_JSON__QUIRK_ALLOW_BACKSLASH_QUESTION_MARK,
243 WUFFS_JSON__QUIRK_ALLOW_BACKSLASH_SINGLE_QUOTE,
244 WUFFS_JSON__QUIRK_ALLOW_BACKSLASH_V,
245 WUFFS_JSON__QUIRK_ALLOW_BACKSLASH_X,
246 WUFFS_JSON__QUIRK_ALLOW_BACKSLASH_ZERO,
247 WUFFS_JSON__QUIRK_ALLOW_COMMENT_BLOCK,
248 WUFFS_JSON__QUIRK_ALLOW_COMMENT_LINE,
249 WUFFS_JSON__QUIRK_ALLOW_EXTRA_COMMA,
250 WUFFS_JSON__QUIRK_ALLOW_INF_NAN_NUMBERS,
251 WUFFS_JSON__QUIRK_ALLOW_LEADING_ASCII_RECORD_SEPARATOR,
252 WUFFS_JSON__QUIRK_ALLOW_LEADING_UNICODE_BYTE_ORDER_MARK,
253 WUFFS_JSON__QUIRK_ALLOW_TRAILING_NEW_LINE,
Nigel Tao3bfed6d2020-03-24 17:44:47 +1100254 WUFFS_JSON__QUIRK_REPLACE_INVALID_UNICODE,
Nigel Tao5d5a17c2020-03-24 16:38:43 +1100255 0,
256 };
257 uint32_t i;
258 for (i = 0; quirks[i]; i++) {
259 wuffs_json__decoder__set_quirk_enabled(&dec, quirks[i], true);
260 }
261 }
262
Nigel Tao193527b2020-02-26 21:55:01 +1100263 uint64_t pos = 0;
264 while (true) {
Nigel Taof3146c22020-03-26 08:47:42 +1100265 wuffs_base__status status = wuffs_json__decoder__decode_tokens(
266 &dec, &tok, &src,
267 wuffs_base__make_slice_u8(work_buffer_array, WORK_BUFFER_ARRAY_SIZE));
Nigel Tao193527b2020-02-26 21:55:01 +1100268
269 while (tok.meta.ri < tok.meta.wi) {
270 wuffs_base__token* t = &tok.data.ptr[tok.meta.ri++];
Nigel Taod1c928a2020-02-28 12:43:53 +1100271 uint16_t len = wuffs_base__token__length(t);
Nigel Tao193527b2020-02-26 21:55:01 +1100272
Nigel Tao68920952020-03-03 11:25:18 +1100273 if (flags.all_tokens || (wuffs_base__token__value(t) != 0)) {
Nigel Taod1c928a2020-02-28 12:43:53 +1100274 uint8_t lp = wuffs_base__token__link_prev(t) ? 1 : 0;
275 uint8_t ln = wuffs_base__token__link_next(t) ? 1 : 0;
276 uint32_t vmajor = wuffs_base__token__value_major(t);
Nigel Tao67f00c12020-02-29 12:48:59 +1100277 uint32_t vminor = wuffs_base__token__value_minor(t);
278 uint8_t vbc = wuffs_base__token__value_base_category(t);
279 uint32_t vbd = wuffs_base__token__value_base_detail(t);
Nigel Tao193527b2020-02-26 21:55:01 +1100280
Nigel Tao68920952020-03-03 11:25:18 +1100281 if (flags.human_readable) {
Nigel Tao67f00c12020-02-29 12:48:59 +1100282 printf("pos=0x%08" PRIX32 " len=0x%04" PRIX16 " link=0b%d%d ",
283 (uint32_t)(pos), len, (int)(lp), (int)(ln));
284
285 if (vmajor) {
286 uint32_t m = vmajor;
287 uint32_t m0 = m / (38 * 38 * 38);
288 m -= m0 * (38 * 38 * 38);
289 uint32_t m1 = m / (38 * 38);
290 m -= m1 * (38 * 38);
291 uint32_t m2 = m / (38);
292 m -= m2 * (38);
293 uint32_t m3 = m;
294
295 printf("vmajor=0x%06" PRIX32 ":%c%c%c%c vminor=0x%06" PRIX32 "\n",
296 vmajor, base38_decode[m0], base38_decode[m1],
297 base38_decode[m2], base38_decode[m3], vminor);
298 } else {
Nigel Tao68920952020-03-03 11:25:18 +1100299 printf("vbc=%s. vbd=0x%06" PRIX32 "\n", vbc_names[vbc & 7], vbd);
Nigel Tao67f00c12020-02-29 12:48:59 +1100300 }
301
Nigel Taod1c928a2020-02-28 12:43:53 +1100302 } else {
Nigel Tao67f00c12020-02-29 12:48:59 +1100303 uint8_t buf[16];
304 wuffs_base__store_u32be__no_bounds_check(&buf[0x0], (uint32_t)(pos));
305 wuffs_base__store_u16be__no_bounds_check(&buf[0x4], len);
306 wuffs_base__store_u8__no_bounds_check(&buf[0x0006], lp);
307 wuffs_base__store_u8__no_bounds_check(&buf[0x0007], ln);
308 wuffs_base__store_u32be__no_bounds_check(&buf[0x8], vmajor);
309 if (vmajor) {
310 wuffs_base__store_u32be__no_bounds_check(&buf[0xC], vminor);
311 } else {
312 wuffs_base__store_u8__no_bounds_check(&buf[0x000C], vbc);
313 wuffs_base__store_u24be__no_bounds_check(&buf[0xD], vbd);
314 }
315 const int stdout_fd = 1;
Nigel Tao68920952020-03-03 11:25:18 +1100316 ignore_return_value(write(stdout_fd, &buf[0], 16));
Nigel Taod1c928a2020-02-28 12:43:53 +1100317 }
Nigel Tao193527b2020-02-26 21:55:01 +1100318 }
319
320 pos += len;
321 if (pos > 0xFFFFFFFF) {
322 return "main: input is too long";
323 }
324 }
325
326 if (status.repr == NULL) {
327 return NULL;
328 } else if (status.repr == wuffs_base__suspension__short_read) {
329 TRY(read_src());
330 } else if (status.repr == wuffs_base__suspension__short_write) {
331 wuffs_base__token_buffer__compact(&tok);
332 } else {
333 return wuffs_base__status__message(&status);
334 }
335 }
336}
337
338// ----
339
340int //
341compute_exit_code(const char* status_msg) {
342 if (!status_msg) {
343 return 0;
344 }
345 size_t n = strnlen(status_msg, 2047);
346 if (n >= 2047) {
347 status_msg = "main: internal error: error message is too long";
348 n = strnlen(status_msg, 2047);
349 }
350 fprintf(stderr, "%s\n", status_msg);
351 // Return an exit code of 1 for regular (forseen) errors, e.g. badly
352 // formatted or unsupported input.
353 //
354 // Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
355 // run-time checks found that an internal invariant did not hold.
356 //
357 // Automated testing, including badly formatted inputs, can therefore
358 // discriminate between expected failure (exit code 1) and unexpected failure
359 // (other non-zero exit codes). Specifically, exit code 2 for internal
360 // invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
361 // linux) for a segmentation fault (e.g. null pointer dereference).
362 return strstr(status_msg, "internal error:") ? 2 : 1;
363}
364
365int //
366main(int argc, char** argv) {
367 const char* z = main1(argc, argv);
368 int exit_code = compute_exit_code(z);
369 return exit_code;
370}