blob: c7fe7802981bc8774a3ac37857db8bcb96a73697 [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
Nigel Taoc5b3a9e2020-02-24 11:54:35 +110020As of 2020-02-24, this program passes all 318 "test_parsing" cases from the
21JSON test suite (https://github.com/nst/JSONTestSuite), an appendix to the
22"Parsing JSON is a Minefield" article (http://seriot.ch/parsing_json.php) that
23was first published on 2016-10-26 and updated on 2018-03-30.
24
Nigel Tao1b073492020-02-16 22:11:36 +110025This example program differs from most other example Wuffs programs in that it
26is written in C++, not C.
27
28$CXX jsonptr.cc && ./a.out < ../../test/data/github-tags.json; rm -f a.out
29
30for a C++ compiler $CXX, such as clang++ or g++.
Nigel Tao569a2942020-02-23 23:13:51 +110031
32After modifying this program, run "build-example.sh example/jsonptr/" and then
33"script/run-json-test-suite.sh" to catch correctness regressions.
Nigel Tao1b073492020-02-16 22:11:36 +110034*/
35
36#include <inttypes.h>
37#include <stdio.h>
Nigel Tao9cc2c252020-02-23 17:05:49 +110038#include <string.h>
Nigel Tao1b073492020-02-16 22:11:36 +110039
40// Wuffs ships as a "single file C library" or "header file library" as per
41// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
42//
43// To use that single file as a "foo.c"-like implementation, instead of a
44// "foo.h"-like header, #define WUFFS_IMPLEMENTATION before #include'ing or
45// compiling it.
46#define WUFFS_IMPLEMENTATION
47
48// Defining the WUFFS_CONFIG__MODULE* macros are optional, but it lets users of
49// release/c/etc.c whitelist which parts of Wuffs to build. That file contains
50// the entire Wuffs standard library, implementing a variety of codecs and file
51// formats. Without this macro definition, an optimizing compiler or linker may
52// very well discard Wuffs code for unused codecs, but listing the Wuffs
53// modules we use makes that process explicit. Preprocessing means that such
54// code simply isn't compiled.
55#define WUFFS_CONFIG__MODULES
56#define WUFFS_CONFIG__MODULE__BASE
57#define WUFFS_CONFIG__MODULE__JSON
58
59// If building this program in an environment that doesn't easily accommodate
60// relative includes, you can use the script/inline-c-relative-includes.go
61// program to generate a stand-alone C++ file.
62#include "../../release/c/wuffs-unsupported-snapshot.c"
63
Nigel Tao2cf76db2020-02-27 22:42:01 +110064#define TRY(error_msg) \
65 do { \
66 const char* z = error_msg; \
67 if (z) { \
68 return z; \
69 } \
70 } while (false)
71
72static const char* eod = "main: end of data";
73
74// ----
75
76#define MAX_INDENT 8
Nigel Tao107f0ef2020-03-01 21:35:02 +110077#define INDENT_SPACES_STRING " "
78#define INDENT_TABS_STRING "\t\t\t\t\t\t\t\t"
79
Nigel Tao1b073492020-02-16 22:11:36 +110080#ifndef DST_BUFFER_SIZE
81#define DST_BUFFER_SIZE (32 * 1024)
82#endif
83#ifndef SRC_BUFFER_SIZE
84#define SRC_BUFFER_SIZE (32 * 1024)
85#endif
86#ifndef TOKEN_BUFFER_SIZE
87#define TOKEN_BUFFER_SIZE (4 * 1024)
88#endif
89
Nigel Tao2cf76db2020-02-27 22:42:01 +110090uint8_t dst_array[DST_BUFFER_SIZE];
91uint8_t src_array[SRC_BUFFER_SIZE];
92wuffs_base__token tok_array[TOKEN_BUFFER_SIZE];
Nigel Tao1b073492020-02-16 22:11:36 +110093
94wuffs_base__io_buffer dst;
95wuffs_base__io_buffer src;
96wuffs_base__token_buffer tok;
97
Nigel Tao2cf76db2020-02-27 22:42:01 +110098// curr_token_end_src_index is the src.data.ptr index of the end of the current
99// token. An invariant is that (curr_token_end_src_index <= src.meta.ri).
100size_t curr_token_end_src_index;
101
Nigel Tao2cf76db2020-02-27 22:42:01 +1100102uint64_t depth;
103
104enum class context {
105 none,
106 in_list_after_bracket,
107 in_list_after_value,
108 in_dict_after_brace,
109 in_dict_after_key,
110 in_dict_after_value,
111} ctx;
112
Nigel Tao1b073492020-02-16 22:11:36 +1100113wuffs_json__decoder dec;
Nigel Tao1b073492020-02-16 22:11:36 +1100114
Nigel Tao68920952020-03-03 11:25:18 +1100115struct {
116 int remaining_argc;
117 char** remaining_argv;
118
119 bool compact;
120 size_t indent;
121 bool tabs;
122} flags = {0};
123
124const char* //
125parse_flags(int argc, char** argv) {
126 bool explicit_indent = false;
127
128 int c = (argc > 0) ? 1 : 0; // Skip argv[0], the program name.
129 for (; c < argc; c++) {
130 char* arg = argv[c];
131 if (*arg++ != '-') {
132 break;
133 }
134
135 // A double-dash "--foo" is equivalent to a single-dash "-foo". As special
136 // cases, a bare "-" is not a flag (some programs may interpret it as
137 // stdin) and a bare "--" means to stop parsing flags.
138 if (*arg == '\x00') {
139 break;
140 } else if (*arg == '-') {
141 arg++;
142 if (*arg == '\x00') {
143 c++;
144 break;
145 }
146 }
147
148 if (!strcmp(arg, "c") || !strcmp(arg, "compact")) {
149 flags.compact = true;
150 continue;
151 }
152 if (!strncmp(arg, "i=", 2) || !strncmp(arg, "indent=", 7)) {
153 while (*arg++ != '=') {
154 }
155 if (('0' <= arg[0]) && (arg[0] <= '8') && (arg[1] == '\x00')) {
156 flags.indent = arg[0] - '0';
157 explicit_indent = true;
158 continue;
159 }
160 }
161 if (!strcmp(arg, "t") || !strcmp(arg, "tabs")) {
162 flags.tabs = true;
163 continue;
164 }
165
166 return "main: unrecognized flag argument";
167 }
168
169 flags.remaining_argc = argc - c;
170 flags.remaining_argv = argv + c;
171 if (!explicit_indent) {
172 flags.indent = flags.tabs ? 1 : 4;
173 }
174 return NULL;
175}
176
Nigel Tao2cf76db2020-02-27 22:42:01 +1100177const char* //
178initialize_globals(int argc, char** argv) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100179 dst = wuffs_base__make_io_buffer(
180 wuffs_base__make_slice_u8(dst_array, DST_BUFFER_SIZE),
181 wuffs_base__empty_io_buffer_meta());
Nigel Tao1b073492020-02-16 22:11:36 +1100182
Nigel Tao2cf76db2020-02-27 22:42:01 +1100183 src = wuffs_base__make_io_buffer(
184 wuffs_base__make_slice_u8(src_array, SRC_BUFFER_SIZE),
185 wuffs_base__empty_io_buffer_meta());
186
187 tok = wuffs_base__make_token_buffer(
188 wuffs_base__make_slice_token(tok_array, TOKEN_BUFFER_SIZE),
189 wuffs_base__empty_token_buffer_meta());
190
191 curr_token_end_src_index = 0;
192
Nigel Tao2cf76db2020-02-27 22:42:01 +1100193 depth = 0;
194
195 ctx = context::none;
196
Nigel Tao68920952020-03-03 11:25:18 +1100197 TRY(parse_flags(argc, argv));
198 if (flags.remaining_argc > 0) {
199 return "main: bad argument: use \"program < input\", not \"program input\"";
Nigel Tao107f0ef2020-03-01 21:35:02 +1100200 }
201
Nigel Tao2cf76db2020-02-27 22:42:01 +1100202 return dec.initialize(sizeof__wuffs_json__decoder(), WUFFS_VERSION, 0)
203 .message();
204}
Nigel Tao1b073492020-02-16 22:11:36 +1100205
206// ----
207
Nigel Tao2914bae2020-02-26 09:40:30 +1100208const char* //
209read_src() {
Nigel Taoa8406922020-02-19 12:22:00 +1100210 if (src.meta.closed) {
Nigel Tao9cc2c252020-02-23 17:05:49 +1100211 return "main: internal error: read requested on a closed source";
Nigel Taoa8406922020-02-19 12:22:00 +1100212 }
Nigel Tao1b073492020-02-16 22:11:36 +1100213 src.compact();
214 if (src.meta.wi >= src.data.len) {
215 return "main: src buffer is full";
216 }
217 size_t n = fread(src.data.ptr + src.meta.wi, sizeof(uint8_t),
218 src.data.len - src.meta.wi, stdin);
219 src.meta.wi += n;
Nigel Tao67306562020-02-19 14:04:49 +1100220 src.meta.closed = feof(stdin);
221 if ((n == 0) && !src.meta.closed) {
Nigel Taoa8406922020-02-19 12:22:00 +1100222 return "main: read error";
Nigel Tao1b073492020-02-16 22:11:36 +1100223 }
224 return nullptr;
225}
226
Nigel Tao2914bae2020-02-26 09:40:30 +1100227const char* //
228flush_dst() {
Nigel Tao1b073492020-02-16 22:11:36 +1100229 size_t n = dst.meta.wi - dst.meta.ri;
230 if (n > 0) {
231 size_t i = fwrite(dst.data.ptr + dst.meta.ri, sizeof(uint8_t), n, stdout);
232 dst.meta.ri += i;
233 if (i != n) {
234 return "main: write error";
235 }
236 dst.compact();
237 }
238 return nullptr;
239}
240
Nigel Tao2914bae2020-02-26 09:40:30 +1100241const char* //
242write_dst(const void* s, size_t n) {
Nigel Tao1b073492020-02-16 22:11:36 +1100243 const uint8_t* p = static_cast<const uint8_t*>(s);
244 while (n > 0) {
245 size_t i = dst.writer_available();
246 if (i == 0) {
247 const char* z = flush_dst();
248 if (z) {
249 return z;
250 }
251 i = dst.writer_available();
252 if (i == 0) {
253 return "main: dst buffer is full";
254 }
255 }
256
257 if (i > n) {
258 i = n;
259 }
260 memcpy(dst.data.ptr + dst.meta.wi, p, i);
261 dst.meta.wi += i;
262 p += i;
263 n -= i;
264 }
265 return nullptr;
266}
267
268// ----
269
Nigel Tao2914bae2020-02-26 09:40:30 +1100270uint8_t //
271hex_digit(uint8_t nibble) {
Nigel Taob5461bd2020-02-21 14:13:37 +1100272 nibble &= 0x0F;
273 if (nibble <= 9) {
274 return '0' + nibble;
275 }
276 return ('A' - 10) + nibble;
277}
278
Nigel Tao2914bae2020-02-26 09:40:30 +1100279const char* //
Nigel Tao3b486982020-02-27 15:05:59 +1100280handle_unicode_code_point(uint32_t ucp) {
281 if (ucp < 0x0020) {
282 switch (ucp) {
283 case '\b':
284 return write_dst("\\b", 2);
285 case '\f':
286 return write_dst("\\f", 2);
287 case '\n':
288 return write_dst("\\n", 2);
289 case '\r':
290 return write_dst("\\r", 2);
291 case '\t':
292 return write_dst("\\t", 2);
293 default: {
294 // Other bytes less than 0x0020 are valid UTF-8 but not valid in a
295 // JSON string. They need to remain escaped.
296 uint8_t esc6[6];
297 esc6[0] = '\\';
298 esc6[1] = 'u';
299 esc6[2] = '0';
300 esc6[3] = '0';
301 esc6[4] = hex_digit(ucp >> 4);
302 esc6[5] = hex_digit(ucp >> 0);
303 return write_dst(&esc6[0], 6);
304 }
305 }
306
307 } else if (ucp <= 0x007F) {
308 switch (ucp) {
309 case '\"':
310 return write_dst("\\\"", 2);
311 case '\\':
312 return write_dst("\\\\", 2);
313 default: {
314 // The UTF-8 encoding takes 1 byte.
315 uint8_t esc0 = (uint8_t)(ucp);
316 return write_dst(&esc0, 1);
317 }
318 }
319
320 } else if (ucp <= 0x07FF) {
321 // The UTF-8 encoding takes 2 bytes.
322 uint8_t esc2[2];
323 esc2[0] = 0xC0 | (uint8_t)((ucp >> 6));
324 esc2[1] = 0x80 | (uint8_t)((ucp >> 0) & 0x3F);
325 return write_dst(&esc2[0], 2);
326
327 } else if (ucp <= 0xFFFF) {
328 if ((0xD800 <= ucp) && (ucp <= 0xDFFF)) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100329 return "main: internal error: unexpected Unicode surrogate";
Nigel Tao3b486982020-02-27 15:05:59 +1100330 }
331 // The UTF-8 encoding takes 3 bytes.
332 uint8_t esc3[3];
333 esc3[0] = 0xE0 | (uint8_t)((ucp >> 12));
334 esc3[1] = 0x80 | (uint8_t)((ucp >> 6) & 0x3F);
335 esc3[2] = 0x80 | (uint8_t)((ucp >> 0) & 0x3F);
336 return write_dst(&esc3[0], 3);
337
338 } else if (ucp <= 0x10FFFF) {
339 // The UTF-8 encoding takes 4 bytes.
340 uint8_t esc4[4];
341 esc4[0] = 0xF0 | (uint8_t)((ucp >> 18));
342 esc4[1] = 0x80 | (uint8_t)((ucp >> 12) & 0x3F);
343 esc4[2] = 0x80 | (uint8_t)((ucp >> 6) & 0x3F);
344 esc4[3] = 0x80 | (uint8_t)((ucp >> 0) & 0x3F);
345 return write_dst(&esc4[0], 4);
346 }
347
Nigel Tao2cf76db2020-02-27 22:42:01 +1100348 return "main: internal error: unexpected Unicode code point";
Nigel Tao3b486982020-02-27 15:05:59 +1100349}
350
351const char* //
Nigel Tao2cf76db2020-02-27 22:42:01 +1100352handle_token(wuffs_base__token t) {
353 do {
354 uint64_t vbc = t.value_base_category();
355 uint64_t vbd = t.value_base_detail();
356 uint64_t len = t.length();
Nigel Tao1b073492020-02-16 22:11:36 +1100357
358 // Handle ']' or '}'.
Nigel Tao9f7a2502020-02-23 09:42:02 +1100359 if ((vbc == WUFFS_BASE__TOKEN__VBC__STRUCTURE) &&
Nigel Tao2cf76db2020-02-27 22:42:01 +1100360 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__POP)) {
Nigel Tao1b073492020-02-16 22:11:36 +1100361 if (depth <= 0) {
362 return "main: internal error: inconsistent depth";
363 }
364 depth--;
365
366 // Write preceding whitespace.
367 if ((ctx != context::in_list_after_bracket) &&
Nigel Tao68920952020-03-03 11:25:18 +1100368 (ctx != context::in_dict_after_brace) && !flags.compact) {
Nigel Tao1b073492020-02-16 22:11:36 +1100369 TRY(write_dst("\n", 1));
370 for (size_t i = 0; i < depth; i++) {
Nigel Tao68920952020-03-03 11:25:18 +1100371 TRY(write_dst(flags.tabs ? INDENT_TABS_STRING : INDENT_SPACES_STRING,
372 flags.indent));
Nigel Tao1b073492020-02-16 22:11:36 +1100373 }
374 }
375
Nigel Tao9f7a2502020-02-23 09:42:02 +1100376 TRY(write_dst(
377 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__FROM_LIST) ? "]" : "}", 1));
378 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
379 ? context::in_list_after_value
380 : context::in_dict_after_key;
Nigel Tao1b073492020-02-16 22:11:36 +1100381 goto after_value;
382 }
383
Nigel Taod1c928a2020-02-28 12:43:53 +1100384 // Write preceding whitespace and punctuation, if it wasn't ']', '}' or a
385 // continuation of a multi-token chain.
386 if (t.link_prev()) {
387 // No-op.
388 } else if (ctx == context::in_dict_after_key) {
Nigel Tao68920952020-03-03 11:25:18 +1100389 TRY(write_dst(": ", flags.compact ? 1 : 2));
Nigel Taod1c928a2020-02-28 12:43:53 +1100390 } else if (ctx != context::none) {
391 if ((ctx != context::in_list_after_bracket) &&
392 (ctx != context::in_dict_after_brace)) {
393 TRY(write_dst(",", 1));
394 }
Nigel Tao68920952020-03-03 11:25:18 +1100395 if (!flags.compact) {
Nigel Tao107f0ef2020-03-01 21:35:02 +1100396 TRY(write_dst("\n", 1));
397 for (size_t i = 0; i < depth; i++) {
Nigel Tao68920952020-03-03 11:25:18 +1100398 TRY(write_dst(flags.tabs ? INDENT_TABS_STRING : INDENT_SPACES_STRING,
399 flags.indent));
Nigel Tao107f0ef2020-03-01 21:35:02 +1100400 }
Nigel Tao1b073492020-02-16 22:11:36 +1100401 }
402 }
403
404 // Handle the token itself: either a container ('[' or '{') or a simple
Nigel Tao85fba7f2020-02-29 16:28:06 +1100405 // value: string (a chain of raw or escaped parts), literal or number.
Nigel Tao1b073492020-02-16 22:11:36 +1100406 switch (vbc) {
Nigel Tao85fba7f2020-02-29 16:28:06 +1100407 case WUFFS_BASE__TOKEN__VBC__STRUCTURE:
408 TRY(write_dst(
409 (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST) ? "[" : "{", 1));
410 depth++;
411 ctx = (vbd & WUFFS_BASE__TOKEN__VBD__STRUCTURE__TO_LIST)
412 ? context::in_list_after_bracket
413 : context::in_dict_after_brace;
414 return nullptr;
415
Nigel Tao2cf76db2020-02-27 22:42:01 +1100416 case WUFFS_BASE__TOKEN__VBC__STRING:
Nigel Taod1c928a2020-02-28 12:43:53 +1100417 if (!t.link_prev()) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100418 TRY(write_dst("\"", 1));
419 }
Nigel Taocb37a562020-02-28 09:56:24 +1100420
421 if (vbd & WUFFS_BASE__TOKEN__VBD__STRING__CONVERT_0_DST_1_SRC_DROP) {
422 // No-op.
423 } else if (vbd &
424 WUFFS_BASE__TOKEN__VBD__STRING__CONVERT_1_DST_1_SRC_COPY) {
425 TRY(write_dst(src.data.ptr + curr_token_end_src_index - len, len));
426 } else {
427 return "main: internal error: unexpected string-token conversion";
428 }
429
Nigel Taod1c928a2020-02-28 12:43:53 +1100430 if (t.link_next()) {
Nigel Tao2cf76db2020-02-27 22:42:01 +1100431 return nullptr;
432 }
433 TRY(write_dst("\"", 1));
434 goto after_value;
435
436 case WUFFS_BASE__TOKEN__VBC__UNICODE_CODE_POINT:
437 return handle_unicode_code_point(vbd);
438
Nigel Tao85fba7f2020-02-29 16:28:06 +1100439 case WUFFS_BASE__TOKEN__VBC__LITERAL:
Nigel Tao2cf76db2020-02-27 22:42:01 +1100440 case WUFFS_BASE__TOKEN__VBC__NUMBER:
441 TRY(write_dst(src.data.ptr + curr_token_end_src_index - len, len));
442 goto after_value;
Nigel Tao1b073492020-02-16 22:11:36 +1100443 }
444
445 // Return an error if we didn't match the (vbc, vbd) pair.
Nigel Tao2cf76db2020-02-27 22:42:01 +1100446 return "main: internal error: unexpected token";
447 } while (0);
Nigel Tao1b073492020-02-16 22:11:36 +1100448
Nigel Tao2cf76db2020-02-27 22:42:01 +1100449 // Book-keeping after completing a value (whether a container value or a
450 // simple value). Empty parent containers are no longer empty. If the parent
451 // container is a "{...}" object, toggle between keys and values.
452after_value:
453 if (depth == 0) {
454 return eod;
455 }
456 switch (ctx) {
457 case context::in_list_after_bracket:
458 ctx = context::in_list_after_value;
459 break;
460 case context::in_dict_after_brace:
461 ctx = context::in_dict_after_key;
462 break;
463 case context::in_dict_after_key:
464 ctx = context::in_dict_after_value;
465 break;
466 case context::in_dict_after_value:
467 ctx = context::in_dict_after_key;
468 break;
469 }
470 return nullptr;
471}
472
473const char* //
474main1(int argc, char** argv) {
475 TRY(initialize_globals(argc, argv));
476
477 while (true) {
478 wuffs_base__status status = dec.decode_tokens(&tok, &src);
479
480 while (tok.meta.ri < tok.meta.wi) {
481 wuffs_base__token t = tok.data.ptr[tok.meta.ri++];
482 uint64_t n = t.length();
483 if ((src.meta.ri - curr_token_end_src_index) < n) {
484 return "main: internal error: inconsistent src indexes";
485 }
486 curr_token_end_src_index += n;
487
488 if (t.value() == 0) {
489 continue;
490 }
491
492 const char* z = handle_token(t);
493 if (z == nullptr) {
494 continue;
495 } else if (z == eod) {
496 break;
497 }
498 return z;
Nigel Tao1b073492020-02-16 22:11:36 +1100499 }
Nigel Tao2cf76db2020-02-27 22:42:01 +1100500
501 if (status.repr == nullptr) {
502 break;
503 } else if (status.repr == wuffs_base__suspension__short_read) {
504 if (curr_token_end_src_index != src.meta.ri) {
505 return "main: internal error: inconsistent src indexes";
506 }
507 TRY(read_src());
508 curr_token_end_src_index = src.meta.ri;
509 } else if (status.repr == wuffs_base__suspension__short_write) {
510 tok.compact();
511 } else {
512 return status.message();
Nigel Tao1b073492020-02-16 22:11:36 +1100513 }
514 }
Nigel Tao6b161af2020-02-24 11:01:48 +1100515
Nigel Tao6b161af2020-02-24 11:01:48 +1100516 // Consume an optional whitespace trailer. This isn't part of the JSON spec,
517 // but it works better with line oriented Unix tools (such as "echo 123 |
518 // jsonptr" where it's "echo", not "echo -n") or hand-edited JSON files which
519 // can accidentally contain trailing whitespace.
520 //
521 // A whitespace trailer is zero or more ' ' and then zero or one '\n'.
522 while (true) {
523 if (src.meta.ri < src.meta.wi) {
524 uint8_t c = src.data.ptr[src.meta.ri];
525 if (c == ' ') {
526 src.meta.ri++;
527 continue;
528 } else if (c == '\n') {
529 src.meta.ri++;
530 break;
531 }
532 // The "exhausted the input" check below will fail.
533 break;
534 } else if (src.meta.closed) {
535 break;
536 }
537 TRY(read_src());
538 }
539
540 // Check that we've exhausted the input.
541 if ((src.meta.ri < src.meta.wi) || !src.meta.closed) {
542 return "main: valid JSON followed by further (unexpected) data";
543 }
544
545 // Check that we've used all of the decoded tokens, other than trailing
546 // filler tokens. For example, a bare `"foo"` string is valid JSON, but even
547 // without a trailing '\n', the Wuffs JSON parser emits a filler token for
548 // the final '\"'.
549 for (; tok.meta.ri < tok.meta.wi; tok.meta.ri++) {
550 if (tok.data.ptr[tok.meta.ri].value_base_category() !=
551 WUFFS_BASE__TOKEN__VBC__FILLER) {
552 return "main: internal error: decoded OK but unprocessed tokens remain";
553 }
554 }
555
556 return nullptr;
Nigel Tao1b073492020-02-16 22:11:36 +1100557}
558
Nigel Tao2914bae2020-02-26 09:40:30 +1100559int //
560compute_exit_code(const char* status_msg) {
Nigel Tao9cc2c252020-02-23 17:05:49 +1100561 if (!status_msg) {
562 return 0;
563 }
564 size_t n = strnlen(status_msg, 2047);
565 if (n >= 2047) {
566 status_msg = "main: internal error: error message is too long";
567 n = strnlen(status_msg, 2047);
568 }
569 fprintf(stderr, "%s\n", status_msg);
570 // Return an exit code of 1 for regular (forseen) errors, e.g. badly
571 // formatted or unsupported input.
572 //
573 // Return an exit code of 2 for internal (exceptional) errors, e.g. defensive
574 // run-time checks found that an internal invariant did not hold.
575 //
576 // Automated testing, including badly formatted inputs, can therefore
577 // discriminate between expected failure (exit code 1) and unexpected failure
578 // (other non-zero exit codes). Specifically, exit code 2 for internal
579 // invariant violation, exit code 139 (which is 128 + SIGSEGV on x86_64
580 // linux) for a segmentation fault (e.g. null pointer dereference).
581 return strstr(status_msg, "internal error:") ? 2 : 1;
582}
583
Nigel Tao2914bae2020-02-26 09:40:30 +1100584int //
585main(int argc, char** argv) {
Nigel Tao1b073492020-02-16 22:11:36 +1100586 const char* z0 = main1(argc, argv);
Nigel Tao2cf76db2020-02-27 22:42:01 +1100587 const char* z1 = write_dst("\n", 1);
588 const char* z2 = flush_dst();
589 int exit_code = compute_exit_code(z0 ? z0 : (z1 ? z1 : z2));
Nigel Tao9cc2c252020-02-23 17:05:49 +1100590 return exit_code;
Nigel Tao1b073492020-02-16 22:11:36 +1100591}