@@ -45,6 +45,18 @@ namespace json {
4545
4646using IString = wasm::IString;
4747
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+
4860// Main value type
4961struct Value {
5062 struct Ref : public std ::shared_ptr<Value> {
@@ -277,7 +289,7 @@ struct Value {
277289 do {
278290 close = strchr (close + 1 , ' "' );
279291 } while (*(close - 1 ) == ' \\ ' );
280- assert ( close);
292+ THROW_IF (! close, " malformed JSON string " );
281293 *close = 0 ; // end this string, and reuse it straight from the input
282294 char * raw = curr + 1 ;
283295 if (stringEncoding == ASCII) {
@@ -301,24 +313,24 @@ struct Value {
301313 if (*curr == ' ]' ) {
302314 break ;
303315 }
304- assert (*curr == ' ,' );
316+ THROW_IF (*curr != ' ,' , " malformed JSON array " );
305317 curr++;
306318 skip ();
307319 }
308320 curr++;
309321 } else if (*curr == ' n' ) {
310322 // Null
311- assert (strncmp (curr, " null" , 4 ) == 0 );
323+ THROW_IF (strncmp (curr, " null" , 4 ) != 0 , " unexpected JSON literal " );
312324 setNull ();
313325 curr += 4 ;
314326 } else if (*curr == ' t' ) {
315327 // Bool true
316- assert (strncmp (curr, " true" , 4 ) == 0 );
328+ THROW_IF (strncmp (curr, " true" , 4 ) != 0 , " unexpected JSON literal " );
317329 setBool (true );
318330 curr += 4 ;
319331 } else if (*curr == ' f' ) {
320332 // Bool false
321- assert (strncmp (curr, " false" , 5 ) == 0 );
333+ THROW_IF (strncmp (curr, " false" , 5 ) != 0 , " unexpected JSON literal " );
322334 setBool (false );
323335 curr += 5 ;
324336 } else if (*curr == ' {' ) {
@@ -327,15 +339,15 @@ struct Value {
327339 skip ();
328340 setObject ();
329341 while (*curr != ' }' ) {
330- assert (*curr == ' "' );
342+ THROW_IF (*curr != ' "' , " malformed key in JSON object " );
331343 curr++;
332344 char * close = strchr (curr, ' "' );
333- assert ( close);
345+ THROW_IF (! close, " malformed key in JSON object " );
334346 *close = 0 ; // end this string, and reuse it straight from the input
335347 IString key (curr);
336348 curr = close + 1 ;
337349 skip ();
338- assert (*curr == ' :' );
350+ THROW_IF (*curr != ' :' , " missing ':', in JSON object " );
339351 curr++;
340352 skip ();
341353 Ref value = Ref (new Value ());
@@ -345,7 +357,7 @@ struct Value {
345357 if (*curr == ' }' ) {
346358 break ;
347359 }
348- assert (*curr == ' ,' );
360+ THROW_IF (*curr != ' ,' , " malformed value in JSON object " );
349361 curr++;
350362 skip ();
351363 }
0 commit comments