From d6c252d3bea9c4a56093e5749d2c1d8cabdf7c5c Mon Sep 17 00:00:00 2001 From: John Doneth Date: Sun, 4 Oct 2020 17:37:02 -0400 Subject: [PATCH] Fix zero argument panic in JSON.parse() (#785) * Fix 0 arity panic in JSON.parse() * Requested changes * Throw syntax error instead of a string error * Add a test to assert JSON.parse() throws a syntax error --- boa/src/builtins/json/mod.rs | 15 ++++++++------- boa/src/builtins/json/tests.rs | 7 +++++++ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/boa/src/builtins/json/mod.rs b/boa/src/builtins/json/mod.rs index dc44292045..6bcf0e6b53 100644 --- a/boa/src/builtins/json/mod.rs +++ b/boa/src/builtins/json/mod.rs @@ -61,12 +61,13 @@ impl Json { /// [spec]: https://tc39.es/ecma262/#sec-json.parse /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse pub(crate) fn parse(_: &Value, args: &[Value], ctx: &mut Context) -> Result { - match serde_json::from_str::( - &args - .get(0) - .expect("cannot get argument for JSON.parse") - .to_string(ctx)?, - ) { + let arg = args + .get(0) + .cloned() + .unwrap_or_else(Value::undefined) + .to_string(ctx)?; + + match serde_json::from_str::(&arg) { Ok(json) => { let j = Value::from_json(json, ctx); match args.get(1) { @@ -78,7 +79,7 @@ impl Json { _ => Ok(j), } } - Err(err) => Err(Value::from(err.to_string())), + Err(err) => ctx.throw_syntax_error(err.to_string()), } } diff --git a/boa/src/builtins/json/tests.rs b/boa/src/builtins/json/tests.rs index 14ec37ced6..12b4fa0be3 100644 --- a/boa/src/builtins/json/tests.rs +++ b/boa/src/builtins/json/tests.rs @@ -315,3 +315,10 @@ fn json_fields_should_be_enumerable() { assert_eq!(actual_object, expected); assert_eq!(actual_array_index, expected); } + +#[test] +fn json_parse_with_no_args_throws_syntax_error() { + let mut engine = Context::new(); + let result = forward(&mut engine, "JSON.parse();"); + assert!(result.contains("SyntaxError")); +}