@@ -45,6 +45,18 @@ namespace json {
45
45
46
46
using IString = wasm::IString;
47
47
48
+ struct JsonParseException {
49
+ std::string errorText;
50
+
51
+ JsonParseException (std::string errorText) : errorText(errorText) {}
52
+ void dump (std::ostream& o) const { o << " JSON parse error: " << errorText; }
53
+ };
54
+
55
+ #define THROW_IF (expr, message ) \
56
+ if (expr) { \
57
+ throw JsonParseException (message); \
58
+ }
59
+
48
60
// Main value type
49
61
struct Value {
50
62
struct Ref : public std ::shared_ptr<Value> {
@@ -277,7 +289,7 @@ struct Value {
277
289
do {
278
290
close = strchr (close + 1 , ' "' );
279
291
} while (*(close - 1 ) == ' \\ ' );
280
- assert ( close);
292
+ THROW_IF (! close, " malformed JSON string " );
281
293
*close = 0 ; // end this string, and reuse it straight from the input
282
294
char * raw = curr + 1 ;
283
295
if (stringEncoding == ASCII) {
@@ -301,24 +313,24 @@ struct Value {
301
313
if (*curr == ' ]' ) {
302
314
break ;
303
315
}
304
- assert (*curr == ' ,' );
316
+ THROW_IF (*curr != ' ,' , " malformed JSON array " );
305
317
curr++;
306
318
skip ();
307
319
}
308
320
curr++;
309
321
} else if (*curr == ' n' ) {
310
322
// Null
311
- assert (strncmp (curr, " null" , 4 ) == 0 );
323
+ THROW_IF (strncmp (curr, " null" , 4 ) != 0 , " unexpected JSON literal " );
312
324
setNull ();
313
325
curr += 4 ;
314
326
} else if (*curr == ' t' ) {
315
327
// Bool true
316
- assert (strncmp (curr, " true" , 4 ) == 0 );
328
+ THROW_IF (strncmp (curr, " true" , 4 ) != 0 , " unexpected JSON literal " );
317
329
setBool (true );
318
330
curr += 4 ;
319
331
} else if (*curr == ' f' ) {
320
332
// Bool false
321
- assert (strncmp (curr, " false" , 5 ) == 0 );
333
+ THROW_IF (strncmp (curr, " false" , 5 ) != 0 , " unexpected JSON literal " );
322
334
setBool (false );
323
335
curr += 5 ;
324
336
} else if (*curr == ' {' ) {
@@ -327,15 +339,15 @@ struct Value {
327
339
skip ();
328
340
setObject ();
329
341
while (*curr != ' }' ) {
330
- assert (*curr == ' "' );
342
+ THROW_IF (*curr != ' "' , " malformed key in JSON object " );
331
343
curr++;
332
344
char * close = strchr (curr, ' "' );
333
- assert ( close);
345
+ THROW_IF (! close, " malformed key in JSON object " );
334
346
*close = 0 ; // end this string, and reuse it straight from the input
335
347
IString key (curr);
336
348
curr = close + 1 ;
337
349
skip ();
338
- assert (*curr == ' :' );
350
+ THROW_IF (*curr != ' :' , " missing ':', in JSON object " );
339
351
curr++;
340
352
skip ();
341
353
Ref value = Ref (new Value ());
@@ -345,7 +357,7 @@ struct Value {
345
357
if (*curr == ' }' ) {
346
358
break ;
347
359
}
348
- assert (*curr == ' ,' );
360
+ THROW_IF (*curr != ' ,' , " malformed value in JSON object " );
349
361
curr++;
350
362
skip ();
351
363
}
0 commit comments