Browse Source

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
pull/795/head
John Doneth 4 years ago committed by GitHub
parent
commit
d6c252d3be
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 15
      boa/src/builtins/json/mod.rs
  2. 7
      boa/src/builtins/json/tests.rs

15
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<Value> {
match serde_json::from_str::<JSONValue>(
&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::<JSONValue>(&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()),
}
}

7
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"));
}

Loading…
Cancel
Save