diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 3cb7dc96af..fa0c2e35cc 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -326,8 +326,45 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { assert_eq!(modern["log"], json!([2]), "{modern}"); let legacy = s.execute("script.run", &path(&write("third.jsx", "#targetengine kept\nvc.log(k2);\nconst c = 1;"))); assert!(legacy.unwrap_err().to_string().contains("SyntaxError")); - let legacy = s.execute("script.run", &path(&write("fourth.jsx", "#targetengine kept\nvc.log(k2 + kept);"))).unwrap(); - assert_eq!(legacy["log"], json!([3]), "{legacy}"); + let fourth = "#targetengine kept\nvc.log(k2 + kept);\ntry { eval('let x = 1'); } catch (e) { vc.log(e.name); }"; + let legacy = s.execute("script.run", &path(&write("fourth.jsx", fourth))).unwrap(); + assert_eq!(legacy["log"], json!([3, "SyntaxError"]), "{legacy}"); + // `for`-`of` and destructuring, in a new engine and in one a `.jsx` script made. + let loops = "var s = 0;\nfor (const [a, { b = 1 }] of [[1, {}], [2, { b: 3 }]]) s += a + b;\nvar { p, q: [r] } = { p: 4, q: [5] };\nvc.log(s);\nvc.log(p + r);\nvc.log(typeof Symbol);"; + let r = s.execute("script.run", &path(&write("loops.js", loops))).unwrap(); + assert_eq!(r["log"], json!([7, 9, "function"]), "{r}"); + let kept = s + .execute("script.run", &path(&write("fifth.js", "#targetengine kept\nfor (const [i, ...j] of [[kept, 'x', 'y']]) vc.log(i + j.join(''));"))) + .unwrap(); + assert_eq!(kept["log"], json!(["1xy"]), "{kept}"); + let e = s.execute("script.run", &path(&write("pattern.jsx", "var [a] = [1];"))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_js_script_reads_object_literal_extensions_and_function_names_and_a_jsx_script_does_not() { + let dir = fresh_folder("es2015-objects"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let modern = "var k = 'b';\nvar a = 1;\nvar o = { a, [k + 1]: 2, m() { return 3; }, f: () => 4 };\n\ + vc.log(o.a + o.b1 + o.m() + o.f());\nvc.log(o.m.name + ',' + o.f.name + ',' + o.f.bind().name + ',' + Math.max.name);\n"; + let r = s.execute("script.run", &path(&write("objects.js", modern))).unwrap(); + assert_eq!(r["log"], json!([10, "m,f,bound f,max"]), "{r}"); + for (name, text) in [("short.jsx", "var a = 1; var o = { a };"), ("computed.jsx", "var o = { ['b']: 1 };"), ("method.jsx", "var o = { m() {} };")] + { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + let legacy = s.execute("script.run", &path(&write("names.jsx", "var f = function () {};\nvc.log(f.hasOwnProperty('name'));"))).unwrap(); + assert_eq!(legacy["log"], json!([false]), "{legacy}"); + // Script text given without a file keeps the ExtendScript language. + assert!(run(&mut s, "var a = 1; var o = { a };").unwrap_err().to_string().contains("SyntaxError")); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index 92cf258da2..e255258f34 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -82,15 +82,19 @@ pub enum PropertyKey { Ident(String), String(Vec), Number(f64), + /// `[expression]` with [`crate::Options::es2015`]: the key is the expression's value. + Computed(ExprId), } impl PropertyKey { - /// The key as the string a property is stored under (a number through ToString). + /// The key as the string a property is stored under (a number through ToString); empty for + /// a computed key, whose string is known only at run time. pub fn to_utf16(&self) -> Vec { match self { PropertyKey::Ident(name) => name.encode_utf16().collect(), PropertyKey::String(s) => s.clone(), PropertyKey::Number(n) => crate::number::to_string(*n).encode_utf16().collect(), + PropertyKey::Computed(_) => Vec::new(), } } } @@ -100,6 +104,8 @@ pub enum PropertyValue { Init(ExprId), Get(FunctionId), Set(FunctionId), + /// A method (`m() {…}`, ECMA-262 2015 section 14.3). + Method(FunctionId), } #[derive(Clone, Debug, PartialEq)] @@ -109,6 +115,18 @@ pub struct Property { pub span: Span, } +impl Property { + /// The property is `__proto__: value`, which sets the new object's prototype (ECMA-262 2015 + /// section B.3.1): a data property with a name written out, not computed and not shorthand + /// (`{__proto__}`, whose value starts where the property does). + pub fn is_proto_setter(&self, ast: &Ast) -> bool { + let PropertyValue::Init(value) = self.value else { return false }; + ast.expr_span(value).start != self.span.start + && matches!(self.key, PropertyKey::Ident(_) | PropertyKey::String(_)) + && self.key.to_utf16().into_iter().eq("__proto__".encode_utf16()) + } +} + #[derive(Clone, Debug, PartialEq)] pub enum Expr { This, @@ -277,20 +295,33 @@ pub enum XmlNamePart { Computed(ExprId), } +/// What a declaration, a parameter or a catch clause binds: a name, or with +/// [`crate::Options::es2015`] a destructuring pattern (ECMA-262 11th edition, section 13.3.3). +/// +/// A pattern is an [`Expr::Array`] or an [`Expr::Object`] whose targets are [`Expr::Ident`] +/// names or nested patterns; an [`Expr::Assign`] with no operator gives a target its default +/// value, and an [`Expr::Spread`] as the last element of an array pattern is its rest element. +#[derive(Clone, Debug, PartialEq)] +pub enum Binding { + Name(Name), + Pattern(ExprId), +} + #[derive(Clone, Debug, PartialEq)] pub struct VarDecl { - pub name: Name, + pub target: Binding, pub init: Option, } -/// What a `for (… in …)` statement assigns each property name to. +/// What a `for (… in …)` or `for (… of …)` statement assigns each property name or value to. #[derive(Clone, Debug, PartialEq)] pub enum ForInTarget { /// `for (var x in o)`, with the declaration's initializer if it has one. Var(VarDecl), + /// An assignment target, or with [`crate::Options::es2015`] an assignment pattern. Expr(ExprId), /// `for (let x in o)` or `for (const x in o)`: a new binding for each name. - Lexical(LexKind, Name), + Lexical(LexKind, Binding), } #[derive(Clone, Debug, PartialEq)] @@ -312,7 +343,7 @@ pub struct SwitchCase { #[derive(Clone, Debug, PartialEq)] pub struct CatchClause { - pub param: Name, + pub param: Binding, pub body: Vec, } @@ -351,6 +382,12 @@ pub enum Stmt { body: StmtId, each: bool, }, + /// `for (… of …)` with [`crate::Options::es2015`] (ECMA-262 11th edition, section 13.7.5). + ForOf { + target: ForInTarget, + iterable: ExprId, + body: StmtId, + }, /// `default xml namespace = expression;`. DefaultXmlNamespace(ExprId), Continue(Option), @@ -385,6 +422,8 @@ pub enum FunctionKind { Setter, /// An arrow function; one with an expression body has a body of one `return` statement. Arrow, + /// A method in an object literal. + Method, } #[derive(Clone, Debug, PartialEq)] @@ -392,11 +431,11 @@ pub struct Function { pub kind: FunctionKind, pub name: Option, /// The parameters before a rest parameter. - pub params: Vec, + pub params: Vec, /// Each parameter's default value, in the order of `params` (empty when none has one). pub defaults: Vec>, - /// The rest parameter (`...name`). - pub rest: Option, + /// The rest parameter (`...name` or `...[pattern]`). + pub rest: Option, pub body: Vec, /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. @@ -405,9 +444,9 @@ pub struct Function { } impl Function { - /// The parameters are plain names: no default value and no rest parameter. + /// The parameters are plain names: no pattern, no default value and no rest parameter. pub fn simple_params(&self) -> bool { - self.rest.is_none() && self.defaults.iter().all(Option::is_none) + self.rest.is_none() && self.defaults.iter().all(Option::is_none) && self.params.iter().all(|p| matches!(p, Binding::Name(_))) } } @@ -440,6 +479,34 @@ impl Ast { self.functions.get(id.0 as usize) } + /// The names a binding binds, in source order. + pub fn bound_names(&self, binding: &Binding) -> Vec { + match binding { + Binding::Name(n) => vec![n.clone()], + Binding::Pattern(p) => self.pattern_names(*p), + } + } + + /// The names a destructuring pattern binds, in source order, walked without recursion. + pub fn pattern_names(&self, pattern: ExprId) -> Vec { + let mut out = Vec::new(); + let mut work = vec![pattern]; + while let Some(id) = work.pop() { + match self.expr(id) { + Some(Expr::Ident(n)) => out.push(Name { name: n.clone(), span: self.expr_span(id) }), + Some(Expr::Array(elements)) => work.extend(elements.iter().rev().flatten().copied()), + Some(Expr::Object(props)) => work.extend(props.iter().rev().filter_map(|p| match p.value { + PropertyValue::Init(e) => Some(e), + _ => None, + })), + Some(Expr::Assign { target, .. }) => work.push(*target), + Some(Expr::Spread(arg)) => work.push(*arg), + _ => {} + } + } + out + } + /// The expression with any parentheses around it removed. pub fn unparenthesized(&self, mut id: ExprId) -> ExprId { while let Some(Expr::Paren(inner)) = self.expr(id) { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index f2c02bdf4c..49eeebf9f4 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,7 +3,8 @@ //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex //! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with //! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. +//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and +//! the iterators of arrays, strings and `arguments` objects (in `iterator`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can @@ -12,16 +13,19 @@ mod array; pub(crate) mod extensions; mod global; +pub(crate) mod iterator; mod json; mod math; mod object; +mod symbol; use std::rc::Rc; use crate::bytecode::{CodeKind, Source}; use crate::compiler::{CompileFail, compile_constructed_function}; use crate::heap::{ - BOUND_ARG_BYTES, Class, Func, HIDDEN, Key, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key, string_bytes, + BOUND_ARG_BYTES, CONFIGURABLE, Class, Func, HIDDEN, Key, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key, + string_bytes, }; use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult}; use crate::value::{Str, Value, index_key, number_to_str, to_uint32}; @@ -32,9 +36,30 @@ fn alloc(interp: &mut Interp, class: Class, proto: Option) -> ObjId { /// A built-in function object. pub(crate) fn native(interp: &mut Interp, name: &'static str, f: NativeFn, length: u32, kind: NativeKind, constructor: bool) -> JsResult { + native_with_prefix(interp, "", name, f, length, kind, constructor) +} + +/// The function of a built-in accessor `name`: `prefix` is `get ` for its getter and `set ` for +/// its setter. +pub(crate) fn accessor_native(interp: &mut Interp, prefix: &'static str, name: &'static str, f: NativeFn, length: u32) -> JsResult { + native_with_prefix(interp, prefix, name, f, length, NativeKind::Plain, false) +} + +fn native_with_prefix( + interp: &mut Interp, + prefix: &'static str, + name: &'static str, + f: NativeFn, + length: u32, + kind: NativeKind, + constructor: bool, +) -> JsResult { let proto = interp.intrinsics.function_proto; - let o = alloc(interp, Class::Function(Func::Native { f, kind, constructor, name }), Some(proto)); + let o = alloc(interp, Class::Function(Func::Native { f, kind, constructor, name, prefix }), Some(proto)); interp.define(o, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + if interp.builtin_names { + es2015_native(interp, o, Some(&format!("{prefix}{name}")))?; + } Ok(o) } @@ -44,9 +69,97 @@ pub(crate) fn pausable_method(interp: &mut Interp, on: ObjId, name: &'static str let proto = interp.intrinsics.function_proto; let m = alloc(interp, Class::Function(Func::Pausable { f, name }), Some(proto)); interp.define(m, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + if interp.builtin_names { + es2015_native(interp, m, Some(name))?; + } interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN }) } +/// Gives the built-in functions the `name` and `length` of ECMA-262 2015 section 17: each one's +/// `length` becomes configurable, and it gets a `name` that is not writable, not enumerable and +/// configurable: the name it is installed under, with `get ` or `set ` before it for an accessor's +/// function, and `""` for `Function.prototype`. A realm does this once, at the start of its first +/// run with [`crate::Options::es2015`], under the limits set for that run; [`native`] and +/// [`pausable_method`] do it for the functions made after that. The bytes of the new properties +/// are checked against the heap limit first: when they do not fit, nothing changes and the error +/// is returned, and the next run with the option tries again. +pub(crate) fn es2015_names(interp: &mut Interp) -> JsResult<()> { + if interp.builtin_names { + return Ok(()); + } + // Functions no script can reach any more are collected first, so the plan names only the + // ones that stay. + interp.collect_garbage(); + let plan = es2015_name_plan(interp); + let bytes = plan + .iter() + .filter_map(|(_, name)| name.as_ref()) + .map(|name| PROP_BYTES + string_bytes("name".len()) + string_bytes(name.len())) + .sum::(); + interp.reserve_heap(bytes)?; + let thrower = interp.intrinsics.throw_type_error; + for (id, name) in plan { + // A function the reservation's collection freed needs no name. + if interp.heap.object(id).is_none() { + continue; + } + if id == thrower { + // %ThrowTypeError% keeps its fixed `length`, and its `name` is fixed too (ECMA-262 + // 2020 section 9.2.9.1). + if name.is_some() { + interp.define(id, key("name"), Prop::Data { value: Value::str(""), flags: 0 })?; + } + } else { + es2015_native(interp, id, name.as_deref())?; + } + } + interp.builtin_names = true; + Ok(()) +} + +/// The built-in functions, each with the `name` [`es2015_names`] gives it, or `None` when it has +/// one already (a script may have defined it). +fn es2015_name_plan(interp: &Interp) -> Vec<(ObjId, Option)> { + let thrower = interp.intrinsics.throw_type_error; + let mut plan = Vec::new(); + for id in interp.heap.object_ids() { + let Some(o) = interp.heap.object(id) else { continue }; + // A function a script made non-extensible (frozen, sealed or locked) keeps its properties + // as they are. + if !o.extensible && id != thrower { + continue; + } + let name = match &o.class { + _ if id == thrower => String::new(), + Class::Function(Func::Native { name, prefix, .. }) => format!("{prefix}{name}"), + Class::Function(Func::Pausable { name, .. }) => (*name).to_string(), + _ => continue, + }; + plan.push((id, (!o.props.contains(&key("name"))).then_some(name))); + } + plan +} + +/// Makes built-in function `f`'s `length` configurable and gives it the `name` `name`, when there +/// is one, unless it has a `name` already. A function that is not extensible keeps its properties +/// as they are. The new property's bytes are checked against the heap limit first, with `f` held +/// as a root. +fn es2015_native(interp: &mut Interp, f: ObjId, name: Option<&str>) -> JsResult<()> { + if !interp.object_mut(f)?.extensible { + return Ok(()); + } + if let Some(Prop::Data { flags, .. }) = interp.object_mut(f)?.props.get_mut(&key("length")) { + *flags |= CONFIGURABLE; + } + let Some(name) = name.filter(|_| !interp.heap.object(f).is_some_and(|o| o.props.contains(&key("name")))) else { return Ok(()) }; + interp.rooted(&[Value::Object(f)], |i| i.reserve_heap(PROP_BYTES + string_bytes("name".len()) + string_bytes(name.len())))?; + let o = interp.object_mut(f)?; + // `name` comes right after `length`, as the built-ins list them. + o.props.insert_after(&key("length"), key("name"), Prop::Data { value: Value::str(name), flags: CONFIGURABLE }); + interp.heap.bytes = interp.heap.bytes.saturating_add(PROP_BYTES + string_bytes("name".len()) + string_bytes(name.len())); + Ok(()) +} + pub(crate) fn method(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn, length: u32) -> JsResult<()> { let m = native(interp, name, f, length, NativeKind::Plain, false)?; interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN }) @@ -83,7 +196,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { interp.intrinsics.object_proto = object_proto; let function_proto = alloc( interp, - Class::Function(Func::Native { f: function_proto_call, kind: NativeKind::Plain, constructor: false, name: "" }), + Class::Function(Func::Native { f: function_proto_call, kind: NativeKind::Plain, constructor: false, name: "", prefix: "" }), Some(object_proto), ); interp.intrinsics.function_proto = function_proto; @@ -142,6 +255,10 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { crate::number_builtins::install(interp)?; crate::regexp_builtins::install(interp)?; crate::date_builtins::install(interp)?; + if interp.options.es2015 { + symbol::install(interp, object)?; + iterator::install(interp)?; + } if interp.options.e4x { crate::xml_builtins::install(interp)?; } @@ -370,7 +487,9 @@ fn object_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResu interp.to_object(&v).map(Value::Object) } -/// `Object.prototype.toString` (section 15.2.4.2). +/// `Object.prototype.toString` (section 15.2.4.2). In a run with [`crate::Options::es2015`], a +/// string `@@toStringTag` takes the place of the class name (ECMA-262 11th edition, section +/// 19.1.3.6). fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { // With `$.localize` on, a localization object gives its text for the current locale. if interp.localization.enabled() @@ -384,6 +503,13 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J Value::Null => "Null", _ => { let o = interp.to_object(&this)?; + // The tag's getter can run script that collects, and the object of a primitive is + // reachable from nowhere else. + let tag = interp.rooted(&[Value::Object(o)], |i| i.string_tag_of(o))?; + if let Some(tag) = tag { + let roots = [Value::String(tag.clone())]; + return interp.rooted(&roots, |i| i.wrap_str("[object ", Some(&tag), "]")); + } interp.heap.object(o).map_or("Object", |o| o.class.name()) } }; @@ -431,9 +557,9 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js } fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let k = interp.to_key(&arg(args, 0))?; + let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some())) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some())) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -450,9 +576,9 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> } fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let k = interp.to_key(&arg(args, 0))?; + let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()))) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()))) } // ---- Function ---- @@ -538,15 +664,21 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J let bound_this = arg(args, 0); let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into(); // A host function's `length` is an ordinary property a script can set, so it is converted - // to an integer first, as later editions specify. - let target_length = match interp.get_from(target, &key("length"), &this)? { + // to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is + // read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run. + let has_length = !interp.options.es2015 || interp.get_own_property(target, &key("length"))?.is_some(); + let length_value = if has_length { interp.get_from(target, &key("length"), &this)? } else { Value::Undefined }; + let target_length = match length_value { Value::Number(n) if n.is_nan() => 0.0, Value::Number(n) => n.trunc(), _ => 0.0, }; // Adding 0 turns a negative zero into 0. let length = (target_length - bound_args.len() as f64).max(0.0) + 0.0; - interp.reserve_heap(OBJECT_BYTES + 4 * PROP_BYTES + BOUND_ARG_BYTES * bound_args.len())?; + if interp.options.es2015 { + return bind_es2015(interp, target, bound_this, bound_args, length); + } + interp.reserve_heap(OBJECT_BYTES + prop_bytes(&["length", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len())?; let proto = interp.intrinsics.function_proto; let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() }); let f = interp.heap.alloc_object(Object::new(class, Some(proto))); @@ -559,6 +691,44 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J Ok(Value::Object(f)) } +/// The bytes [`Interp::define`] counts for new properties with these names. +fn prop_bytes(names: &[&str]) -> usize { + names.iter().map(|n| PROP_BYTES + string_bytes(n.len())).sum() +} + +/// The rest of `Function.prototype.bind` with [`crate::Options::es2015`] (ECMA-262 2020 section +/// 19.2.3.2): the bound function's `length` is configurable, its `name` is `bound ` and the +/// target's `name` when that is a string (read after `length`, so a getter for it runs). It keeps +/// the `caller` and `arguments` that throw, as without the option. +fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { + let target_name = match interp.get_from(target, &key("name"), &Value::Object(target))? { + Value::String(s) => s, + _ => Str::from(""), + }; + let name_len = "bound ".len().saturating_add(target_name.len()); + // A rope name is flattened first, with the copy's bytes reserved and its units charged as fuel. + let target_units = crate::string_builtins::flat_charged(interp, &target_name)?; + interp.rooted(&[Value::String(target_name.clone())], |i| { + i.reserve_heap( + OBJECT_BYTES + prop_bytes(&["length", "name", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len), + ) + })?; + crate::string_builtins::charge_units(interp, name_len)?; + let mut units: Vec = "bound ".encode_utf16().collect(); + units.extend_from_slice(&target_units); + let proto = interp.intrinsics.function_proto; + let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() }); + let f = interp.heap.alloc_object(Object::new(class, Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len)); + interp.define(f, key("length"), Prop::Data { value: Value::Number(length), flags: CONFIGURABLE })?; + interp.define(f, key("name"), Prop::Data { value: Value::String(Str::from_units(units)), flags: CONFIGURABLE })?; + let thrower = Some(interp.intrinsics.throw_type_error); + for name in ["caller", "arguments"] { + interp.define(f, key(name), Prop::Accessor { get: thrower, set: thrower, flags: 0 })?; + } + Ok(Value::Object(f)) +} + /// The global `eval` called indirectly (section 15.1.2.1.1): global code in the global /// environment. fn eval(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 3c58fc64a1..62d2e75210 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -235,6 +235,7 @@ impl Source { } Value::String(s) => self.quoted(interp, &s.flat()), Value::Object(id) => self.object(interp, *id), + Value::Symbol(_) => Err(interp.type_error("toSource: a Symbol cannot be written as source")), } } @@ -280,13 +281,18 @@ impl Source { // only, so an array with other properties, an object with another prototype and a property // that is not enumerable are refused. let enumerable = o.props.iter().all(|(_, p)| p.enumerable()); + let has_symbols = o.syms.as_ref().is_some_and(|m| m.len() > 0); let shape = match &o.class { Class::Array { length, .. } - if o.proto == Some(array_proto) && enumerable && o.props.iter().all(|(k, _)| array_index(k).is_some_and(|i| i < *length)) => + if o.proto == Some(array_proto) + && enumerable + && !has_symbols + && o.props.iter().all(|(k, _)| array_index(k).is_some_and(|i| i < *length)) => { Some(Err(*length)) } Class::Array { .. } => return Err(interp.type_error(NOT_PLAIN_ARRAY)), + Class::Ordinary if has_symbols => return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source")), Class::Ordinary if o.proto == Some(object_proto) && enumerable => { Some(Ok(o.props.iter().map(|(k, p)| (k.clone(), p.clone())).collect::>())) } diff --git a/crates/js/src/builtins/iterator.rs b/crates/js/src/builtins/iterator.rs new file mode 100644 index 0000000000..b40f979fc0 --- /dev/null +++ b/crates/js/src/builtins/iterator.rs @@ -0,0 +1,230 @@ +//! The iterators of arrays, strings and `arguments` objects (ECMA-262 11th edition, +//! ): `%IteratorPrototype%` (section 25.1.2), +//! `%ArrayIteratorPrototype%` with `Array.prototype.values`, `keys`, `entries` and `@@iterator` +//! (sections 22.1.3 and 22.1.5), `%StringIteratorPrototype%` with `String.prototype[@@iterator]` +//! (sections 21.1.3.29 and 21.1.5), which steps by code point, and the `@@iterator` of every +//! `arguments` object (section 9.4.4). Installed in a realm with [`crate::Options::es2015`] only. +//! +//! An iterator's `next` takes a unit of fuel for each step. An Array Iterator reads its object's +//! `length` at every step, so elements added while it runs are visited, and it lets go of the +//! object once it is done. + +use super::{create_at, data, native, new_array, new_string}; +use crate::heap::{CONFIGURABLE, Class, HIDDEN, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key, string_bytes}; +use crate::interp::{Interp, JsResult}; +use crate::value::{Str, Value, number_to_str}; + +/// What an Array Iterator gives at each step (section 22.1.5.1). +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum ArrayKind { + Keys, + Values, + Entries, +} + +/// An iterator's state. The object or string is `None` once the iterator is done. +#[derive(Clone)] +pub(crate) enum IterState { + /// [[IteratedObject]], [[ArrayIteratorNextIndex]] and [[ArrayIterationKind]]. + Array { target: Option, next: f64, kind: ArrayKind }, + /// [[IteratedString]], flat, and [[StringIteratorNextIndex]] in code units. + String { text: Option, pos: usize }, +} + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + let Some(wk) = interp.symbols.well_known.as_ref() else { return Ok(()) }; + let (iterator, to_string_tag) = (wk.iterator.clone(), wk.to_string_tag.clone()); + let Some(mut objects) = interp.symbols.objects else { return Ok(()) }; + + let object_proto = interp.intrinsics.object_proto; + let iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + super::symbol::sym_method(interp, iterator_proto, iterator.clone(), "[Symbol.iterator]", return_this, 0, HIDDEN)?; + + let array_iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + super::method(interp, array_iterator_proto, "next", array_iterator_next, 0)?; + interp.define_sym(array_iterator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Array Iterator"), flags: CONFIGURABLE })?; + + let string_iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + super::method(interp, string_iterator_proto, "next", string_iterator_next, 0)?; + interp.define_sym(string_iterator_proto, to_string_tag, Prop::Data { value: Value::str("String Iterator"), flags: CONFIGURABLE })?; + + let array_proto = interp.intrinsics.array_proto; + let values = native(interp, "values", array_values, 0, crate::heap::NativeKind::Plain, false)?; + data(interp, array_proto, "values", Value::Object(values), HIDDEN)?; + interp.define_sym(array_proto, iterator.clone(), Prop::Data { value: Value::Object(values), flags: HIDDEN })?; + super::method(interp, array_proto, "keys", array_keys, 0)?; + super::method(interp, array_proto, "entries", array_entries, 0)?; + + let string_proto = interp.intrinsics.string_proto; + super::symbol::sym_method(interp, string_proto, iterator, "[Symbol.iterator]", string_iterator, 0, HIDDEN)?; + + objects.array_iterator_proto = array_iterator_proto; + objects.string_iterator_proto = string_iterator_proto; + objects.array_values = values; + interp.symbols.objects = Some(objects); + Ok(()) +} + +/// Gives a new `arguments` object its `@@iterator`, `%ArrayProto_values%` (section 9.4.4.6, +/// step 20, and section 9.4.4.7, step 7), in a realm that has it. +pub(crate) fn define_arguments_iterator(interp: &mut Interp, a: ObjId) -> JsResult<()> { + let (Some(objects), Some(sym)) = (interp.symbols.objects, interp.well_known(|w| &w.iterator)) else { return Ok(()) }; + interp.define_sym(a, sym, Prop::Data { value: Value::Object(objects.array_values), flags: HIDDEN }) +} + +/// `%IteratorPrototype%[@@iterator]()` (section 25.1.2.1): the iterator itself. +fn return_this(_: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(this) +} + +/// The bytes of an iterator result: the object and its `value` and `done` properties with their +/// keys, as [`Interp::define`] counts them. +fn iter_result_bytes() -> usize { + OBJECT_BYTES + 2 * PROP_BYTES + string_bytes("value".len()) + string_bytes("done".len()) +} + +/// CreateIterResultObject (section 7.4.7): `{ value, done }`. +fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { + interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(iter_result_bytes()))?; + let proto = interp.intrinsics.object_proto; + let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + interp.define(o, key("value"), Prop::Data { value, flags: OPEN })?; + interp.define(o, key("done"), Prop::Data { value: Value::Bool(done), flags: OPEN })?; + Ok(Value::Object(o)) +} + +/// A new iterator object with `state`, its target kept reachable while it is made. +fn new_iterator(interp: &mut Interp, proto: ObjId, state: IterState, root: Value) -> JsResult { + interp.rooted(&[root], |i| i.reserve_heap(OBJECT_BYTES))?; + Ok(Value::Object(interp.heap.alloc_object(Object::new(Class::Iterator(Box::new(state)), Some(proto))))) +} + +/// CreateArrayIterator (section 22.1.5.1) for `ToObject(this)`. +fn create_array_iterator(interp: &mut Interp, this: &Value, kind: ArrayKind) -> JsResult { + let o = interp.to_object(this)?; + let Some(proto) = interp.symbols.objects.map(|o| o.array_iterator_proto) else { return Ok(Value::Undefined) }; + new_iterator(interp, proto, IterState::Array { target: Some(o), next: 0.0, kind }, Value::Object(o)) +} + +/// `Array.prototype.values()` (section 22.1.3.32), which is also `Array.prototype[@@iterator]`. +fn array_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + create_array_iterator(interp, &this, ArrayKind::Values) +} + +/// `Array.prototype.keys()` (section 22.1.3.16). +fn array_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + create_array_iterator(interp, &this, ArrayKind::Keys) +} + +/// `Array.prototype.entries()` (section 22.1.3.4). +fn array_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + create_array_iterator(interp, &this, ArrayKind::Entries) +} + +/// `String.prototype[@@iterator]()` (section 21.1.3.29). +fn string_iterator(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + if this.is_nullish() { + return Err(interp.type_error("String.prototype[Symbol.iterator] was called on null or undefined")); + } + let s = interp.to_str(&this)?; + let flat = Str::from_rc(crate::string_builtins::flat_charged(interp, &s)?); + let Some(proto) = interp.symbols.objects.map(|o| o.string_iterator_proto) else { return Ok(Value::Undefined) }; + let root = Value::String(flat.clone()); + new_iterator(interp, proto, IterState::String { text: Some(flat), pos: 0 }, root) +} + +/// The state of the iterator `this`, or a `TypeError` naming `what` when `this` is not one. +fn state_of<'a>(interp: &'a mut Interp, this: &Value, string: bool, what: &str) -> JsResult<&'a mut IterState> { + let ok = match this { + Value::Object(o) => match interp.heap.object(*o).map(|x| &x.class) { + Some(Class::Iterator(s)) => matches!(**s, IterState::String { .. }) == string, + _ => false, + }, + _ => false, + }; + if !ok { + return Err(interp.type_error(&format!("{what}.next was called on a value that is not an {what}"))); + } + match this.as_object().and_then(|o| interp.heap.object_mut(o)).map(|x| &mut x.class) { + Some(Class::Iterator(s)) => Ok(s), + _ => Err(crate::interp::Abrupt::Internal("iterator state went missing".into())), + } +} + +/// ToLength (section 7.1.20). +fn to_length(interp: &mut Interp, v: &Value) -> JsResult { + let n = interp.to_number(v)?; + if n.is_nan() || n <= 0.0 { + return Ok(0.0); + } + Ok(n.trunc().min(9_007_199_254_740_991.0)) +} + +/// `%ArrayIteratorPrototype%.next()` (section 22.1.5.2.1). +fn array_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let IterState::Array { target, next, kind } = *state_of(interp, &this, false, "Array Iterator")? else { + return Err(crate::interp::Abrupt::Internal("not an Array Iterator".into())); + }; + interp.use_fuel()?; + let Some(a) = target else { return iter_result(interp, Value::Undefined, true) }; + // Reading `length` and the element can run script that collects, and that script can finish + // the iterator, which then no longer holds the object. + let roots = [this.clone(), Value::Object(a)]; + interp.rooted(&roots, |interp| array_step(interp, &this, a, next, kind)) +} + +/// One step of an Array Iterator over `a` at index `next`, with `this` and `a` kept reachable. +fn array_step(interp: &mut Interp, this: &Value, a: ObjId, next: f64, kind: ArrayKind) -> JsResult { + let len = interp.get_from(a, &key("length"), &Value::Object(a))?; + let len = to_length(interp, &len)?; + if next >= len { + if let IterState::Array { target, .. } = state_of(interp, this, false, "Array Iterator")? { + *target = None; + } + return iter_result(interp, Value::Undefined, true); + } + if let IterState::Array { next: n, .. } = state_of(interp, this, false, "Array Iterator")? { + *n = next + 1.0; + } + let index = Value::Number(next); + let value = match kind { + ArrayKind::Keys => index, + ArrayKind::Values | ArrayKind::Entries => { + let k = number_to_str(next).flat(); + let v = interp.get_from(a, &k, &Value::Object(a))?; + if kind == ArrayKind::Values { + v + } else { + let pair = interp.rooted(std::slice::from_ref(&v), |i| new_array(i, 0))?; + interp.rooted(&[Value::Object(pair), v.clone()], |i| { + create_at(i, pair, 0.0, index)?; + create_at(i, pair, 1.0, v.clone()) + })?; + Value::Object(pair) + } + } + }; + iter_result(interp, value, false) +} + +/// `%StringIteratorPrototype%.next()` (section 21.1.5.2.1): the next code point, a surrogate +/// pair kept together and a lone surrogate given alone. +fn string_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + interp.use_fuel()?; + let state = state_of(interp, &this, true, "String Iterator")?; + let IterState::String { text, pos } = state else { return Err(crate::interp::Abrupt::Internal("not a String Iterator".into())) }; + let Some(s) = text.as_ref() else { return iter_result(interp, Value::Undefined, true) }; + let units = s.flat(); + let Some(&first) = units.get(*pos) else { + *text = None; + return iter_result(interp, Value::Undefined, true); + }; + let pair = (0xD800..0xDC00).contains(&first) && units.get(*pos + 1).is_some_and(|u| (0xDC00..0xE000).contains(u)); + let width = if pair { 2 } else { 1 }; + let piece = units.get(*pos..*pos + width).map(<[u16]>::to_vec).unwrap_or_default(); + *pos += width; + interp.rooted(std::slice::from_ref(&this), |interp| { + let v = new_string(interp, piece)?; + iter_result(interp, v, false) + }) +} diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 364ec99696..e01a47b085 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -556,7 +556,7 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K } } Ok(match v { - Value::Undefined => Item::Skip, + Value::Undefined | Value::Symbol(_) => Item::Skip, Value::Object(_) if interp.is_callable(&v) => Item::Skip, Value::Object(o) => Item::Container(o), other => Item::Primitive(other), @@ -565,39 +565,19 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K /// ToNumber of a Number object, or ToString of a String object (of either when `as_string` is /// set), as section 15.12.3 applies them in Str step 4, step 4.b.ii and step 5. Returns `None` -/// for any other value. When the method that [[DefaultValue]] (section 8.12.8) calls first is not -/// found on the object or on its prototype chain before the object's standard prototype, the -/// result is the object's [[PrimitiveValue]] (sections 8.6.2 and 9.9), the value that -/// `Number.prototype.valueOf` (15.7.4.4), `Number.prototype.toString` (15.7.4.2) and -/// `String.prototype.toString` (15.5.4.2) return. Otherwise ToPrimitive calls the method found. +/// for any other value. The conversion is ToPrimitive (section 9.1) with the Number or String +/// hint, so `valueOf` and `toString` are looked up along the object's whole prototype chain, and +/// in a realm with [`crate::Options::es2015`] an `@@toPrimitive` method on the object is called +/// first (ECMA-262 11th edition, section 7.1.1). fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult> { let Value::Object(o) = v else { return Ok(None) }; - let (primitive, proto, string) = match interp.heap.object(*o).map(|x| &x.class) { - Some(Class::Number(n)) => (Value::Number(*n), interp.intrinsics.number_proto, as_string), - Some(Class::String(s)) => (Value::String(s.clone()), interp.intrinsics.string_proto, true), + let string = match interp.heap.object(*o).map(|x| &x.class) { + Some(Class::Number(_)) => as_string, + Some(Class::String(_)) => true, _ => return Ok(None), }; - let (hint, name) = if string { (Hint::String, "toString") } else { (Hint::Number, "valueOf") }; - let p = if reaches_prototype(interp, *o, proto, name)? { primitive } else { interp.to_primitive(v, hint)? }; - Ok(Some(if string { Value::String(interp.primitive_to_str(&p)) } else { Value::Number(interp.to_number(&p)?) })) -} - -/// Whether looking up `name` from `o` reaches the object `proto` on the prototype chain before -/// any object on the way, `proto` included, has its own property `name`. -fn reaches_prototype(interp: &mut Interp, o: ObjId, proto: ObjId, name: &str) -> JsResult { - let k = key(name); - let mut cur = Some(o); - while let Some(id) = cur { - interp.use_fuel()?; - if interp.get_own_property(id, &k)?.is_some() { - return Ok(false); - } - if id == proto { - return Ok(true); - } - cur = interp.heap.object(id).and_then(|x| x.proto); - } - Ok(false) + let p = interp.to_primitive(v, if string { Hint::String } else { Hint::Number })?; + Ok(Some(if string { Value::String(interp.to_str(&p)?) } else { Value::Number(interp.to_number(&p)?) })) } /// Quote (section 15.12.3): the string in double quotes with the characters JSON escapes. @@ -637,7 +617,7 @@ fn write_primitive(interp: &mut Interp, out: &mut Builder, v: &Value) -> JsResul let units = flat_charged(i, s)?; write_quoted(i, out, &units) }), - Value::Undefined | Value::Object(_) => Ok(()), + Value::Undefined | Value::Object(_) | Value::Symbol(_) => Ok(()), } } diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index af41bb7782..42947c7d7a 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -7,6 +7,7 @@ use super::{ELEMENT_BYTES, arg, create_at, method, new_array}; use crate::heap::{CONFIGURABLE, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, WRITABLE, key}; use crate::interp::{Desc, Interp, JsResult}; +use crate::symbol::PropKey; use crate::value::{Str, Value}; pub(super) fn install(interp: &mut Interp, object: ObjId) -> JsResult<()> { @@ -119,6 +120,14 @@ fn names_array(interp: &mut Interp, names: Vec) -> JsResult { }) } +/// The object's own property keys: its names, then its Symbols (ECMA-262 11th edition, section +/// 9.1.11). +fn own_prop_keys(interp: &mut Interp, o: ObjId) -> JsResult> { + let mut keys: Vec = interp.own_keys(o)?.into_iter().map(PropKey::Str).collect(); + keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym)); + Ok(keys) +} + /// `Object.getPrototypeOf` (section 15.2.3.2). fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; @@ -129,8 +138,8 @@ fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { - let k = interp.to_key(&arg(args, 1))?; - match interp.get_own_property(o, &k)? { + let k = interp.to_prop_key(&arg(args, 1))?; + match interp.get_own_pk(o, &k)? { Some(p) => from_prop(interp, &p), None => Ok(Value::Undefined), } @@ -166,10 +175,10 @@ fn create(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let o = require_object(interp, &arg(args, 0), "defineProperty")?; - interp.with_key(&arg(args, 1), |interp, k| { + interp.with_prop_key(&arg(args, 1), |interp, k| { let desc = to_desc(interp, &arg(args, 2))?; let roots = desc_values(&desc); - interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true)) + interp.rooted(&roots, |interp| interp.define_own_pk(o, k, &desc, true)) })?; Ok(Value::Object(o)) } @@ -189,12 +198,20 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { interp.temp_roots.push(Value::Object(p)); let r = (|| { let mut descs = Vec::new(); - for k in interp.own_keys(p)? { + let keys = own_prop_keys(interp, p)?; + // A getter can delete a Symbol-keyed property already read, so the Symbols stay rooted + // until they are defined on `o`. + for k in &keys { + if let PropKey::Sym(s) = k { + interp.temp_roots.push(Value::Symbol(s.clone())); + } + } + for k in keys { interp.use_fuel()?; - if !interp.get_own_property(p, &k)?.is_some_and(|prop| prop.enumerable()) { + if !interp.get_own_pk(p, &k)?.is_some_and(|prop| prop.enumerable()) { continue; } - let v = interp.get_from(p, &k, &Value::Object(p))?; + let v = interp.get_value_pk(&Value::Object(p), &k)?; interp.temp_roots.push(v.clone()); let desc = to_desc(interp, &v)?; interp.temp_roots.extend(desc_values(&desc)); @@ -202,7 +219,7 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { } for (k, desc) in descs { interp.use_fuel()?; - interp.define_own_property(o, k, &desc, true)?; + interp.define_own_pk(o, k, &desc, true)?; } Ok(()) })(); @@ -214,9 +231,9 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { /// then makes the object non-extensible (sections 15.2.3.8 and 15.2.3.9). fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { let Value::Object(o) = v else { return Ok(v) }; - for k in interp.own_keys(o)? { + for k in own_prop_keys(interp, o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_property(o, &k)? else { continue }; + let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; let mut desc = match &prop { Prop::Data { value, flags } => Desc::data(value.clone(), *flags), Prop::Accessor { get, set, flags } => Desc { @@ -231,7 +248,7 @@ fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { if freeze && desc.is_data() { desc.writable = Some(false); } - interp.define_own_property(o, k, &desc, true)?; + interp.define_own_pk(o, k, &desc, true)?; } if let Some(obj) = interp.heap.object_mut(o) { obj.extensible = false; @@ -263,9 +280,9 @@ fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let Value::Object(o) = v else { return Ok(Value::Bool(true)) }; let o = *o; - for k in interp.own_keys(o)? { + for k in own_prop_keys(interp, o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_property(o, &k)? else { continue }; + let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) { return Ok(Value::Bool(false)); } diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs new file mode 100644 index 0000000000..b671f51e42 --- /dev/null +++ b/crates/js/src/builtins/symbol.rs @@ -0,0 +1,183 @@ +//! `Symbol` (ECMA-262 11th edition, section 19.4, ): +//! the constructor with `Symbol.for`, `Symbol.keyFor` and the well-known Symbols, the methods of +//! `Symbol.prototype`, `Object.getOwnPropertySymbols` (section 19.1.2.10), +//! `Function.prototype[@@hasInstance]` (section 19.2.3.6) and `Date.prototype[@@toPrimitive]` +//! (section 20.4.4.45). Installed in a realm with [`crate::Options::es2015`] only. + +use super::{arg, constructor, create_at, data, method, native, new_array}; +use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES, string_bytes}; +use crate::interp::{Hint, Interp, JsResult}; +use crate::symbol::{Es2015Objects, REGISTRY_ENTRY_BYTES, Sym, WellKnown}; +use crate::value::{Str, Value}; + +pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { + let well_known = WellKnown::new(); + let names = [ + ("iterator", well_known.iterator.clone()), + ("asyncIterator", well_known.async_iterator.clone()), + ("hasInstance", well_known.has_instance.clone()), + ("toPrimitive", well_known.to_primitive.clone()), + ("toStringTag", well_known.to_string_tag.clone()), + ]; + let (to_string_tag, to_primitive, has_instance) = + (well_known.to_string_tag.clone(), well_known.to_primitive.clone(), well_known.has_instance.clone()); + interp.symbols.well_known = Some(well_known); + + let object_proto = interp.intrinsics.object_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let ctor = native(interp, "Symbol", symbol_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Symbol", ctor, proto)?; + method(interp, ctor, "for", symbol_for, 1)?; + method(interp, ctor, "keyFor", key_for, 1)?; + for (name, sym) in names { + data(interp, ctor, name, Value::Symbol(sym), 0)?; + } + method(interp, proto, "toString", to_string, 0)?; + method(interp, proto, "valueOf", value_of, 0)?; + let getter = native(interp, "get description", description, 0, NativeKind::Plain, false)?; + interp.define(proto, crate::heap::key("description"), Prop::Accessor { get: Some(getter), set: None, flags: CONFIGURABLE })?; + interp.define_sym(proto, to_string_tag, Prop::Data { value: Value::str("Symbol"), flags: CONFIGURABLE })?; + sym_method(interp, proto, to_primitive.clone(), "[Symbol.toPrimitive]", symbol_to_primitive, 1, CONFIGURABLE)?; + let date_proto = interp.intrinsics.date_proto; + sym_method(interp, date_proto, to_primitive, "[Symbol.toPrimitive]", date_to_primitive, 1, CONFIGURABLE)?; + + method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?; + let function_proto = interp.intrinsics.function_proto; + let has_instance = sym_method(interp, function_proto, has_instance, "[Symbol.hasInstance]", function_has_instance, 1, 0)?; + // The iterator prototypes and `%ArrayProto_values%` are set when the iterators are installed. + interp.symbols.objects = Some(Es2015Objects { + symbol_proto: proto, + array_iterator_proto: proto, + string_iterator_proto: proto, + array_values: has_instance, + has_instance, + }); + Ok(()) +} + +/// Defines a built-in function as the property `sym` of `on`, with the attribute `flags`. +pub(super) fn sym_method(interp: &mut Interp, on: ObjId, sym: Sym, name: &'static str, f: NativeFn, length: u32, flags: u8) -> JsResult { + let m = native(interp, name, f, length, NativeKind::Plain, false)?; + interp.define_sym(on, sym, Prop::Data { value: Value::Object(m), flags })?; + Ok(m) +} + +/// A new Symbol, its bytes checked against the heap limit and charged to the heap. +fn new_symbol(interp: &mut Interp, description: Option, registered: bool, extra: usize) -> JsResult { + let bytes = SYMBOL_BYTES.saturating_add(extra); + let roots: Vec = description.iter().cloned().map(Value::String).collect(); + interp.rooted(&roots, |i| i.reserve_heap(bytes))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + Ok(Sym::new(description, registered)) +} + +/// `Symbol([description])` (section 19.4.1.1). `new Symbol()` throws a `TypeError`. +fn symbol_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { + if construct { + return Err(interp.type_error("the value is not a constructor")); + } + let description = match arg(args, 0) { + Value::Undefined => None, + d => Some(interp.to_str(&d)?), + }; + new_symbol(interp, description, false, 0).map(Value::Symbol) +} + +/// `Symbol.for(key)` (section 19.4.2.2): the registry's Symbol for the key, made the first time. +fn symbol_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let key = interp.to_str(&arg(args, 0))?; + let units = crate::string_builtins::flat_charged(interp, &key)?; + if let Some(v) = interp.symbols.registry.get(&*units) { + return Ok(v.clone()); + } + let extra = REGISTRY_ENTRY_BYTES.saturating_add(string_bytes(units.len())); + let sym = new_symbol(interp, Some(Str::from_rc(units.clone())), true, extra)?; + interp.symbols.registry.insert(units, Value::Symbol(sym.clone())); + Ok(Value::Symbol(sym)) +} + +/// `Symbol.keyFor(sym)` (section 19.4.2.6). +fn key_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let Value::Symbol(sym) = arg(args, 0) else { return Err(interp.type_error("Symbol.keyFor was given a value that is not a Symbol")) }; + Ok(match sym.description() { + Some(d) if sym.registered() => Value::String(d.clone()), + _ => Value::Undefined, + }) +} + +/// thisSymbolValue (section 19.4.3): a Symbol, or the Symbol of a Symbol object. +fn this_symbol(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + let sym = match this { + Value::Symbol(s) => Some(s.clone()), + Value::Object(o) => match interp.heap.object(*o).map(|x| &x.class) { + Some(Class::Symbol(s)) => Some(s.clone()), + _ => None, + }, + _ => None, + }; + sym.ok_or_else(|| interp.type_error(&format!("Symbol.prototype.{name} was called on a value that is not a Symbol"))) +} + +/// `Symbol.prototype.toString` (section 19.4.3.3): `Symbol(description)`. +fn to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let sym = this_symbol(interp, &this, "toString")?; + interp.descriptive_string(&sym) +} + +/// `Symbol.prototype.valueOf` (section 19.4.3.4). +fn value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + this_symbol(interp, &this, "valueOf").map(Value::Symbol) +} + +/// The getter of `Symbol.prototype.description` (section 19.4.3.2). +fn description(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let sym = this_symbol(interp, &this, "description")?; + Ok(sym.description().map_or(Value::Undefined, |d| Value::String(d.clone()))) +} + +/// `Symbol.prototype[@@toPrimitive](hint)` (section 19.4.3.5). +fn symbol_to_primitive(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + this_symbol(interp, &this, "[Symbol.toPrimitive]").map(Value::Symbol) +} + +/// `Date.prototype[@@toPrimitive](hint)` (section 20.4.4.45): OrdinaryToPrimitive of any object, +/// `toString` first for the hints `"string"` and `"default"` and `valueOf` first for `"number"`. +/// Any other hint, or a `this` that is not an object, throws a `TypeError`. +fn date_to_primitive(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let Value::Object(o) = this else { + return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was called on a value that is not an object")); + }; + // The longest hint has 7 units, so a longer string is refused before it is flattened. + let name = match arg(args, 0) { + Value::String(s) if s.len() <= 7 => String::from_utf16_lossy(&s.flat()), + _ => String::new(), + }; + let hint = match name.as_str() { + "string" | "default" => Hint::String, + "number" => Hint::Number, + _ => return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was given a hint that is not \"string\", \"number\" or \"default\"")), + }; + interp.ordinary_to_primitive(o, &this, hint) +} + +/// `Object.getOwnPropertySymbols(o)` (section 19.1.2.10): the object's own Symbol keys in the +/// order they were added. +fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = interp.to_object(&arg(args, 0))?; + interp.rooted(&[Value::Object(o)], |interp| { + let syms = interp.own_symbols(o)?; + let a = new_array(interp, 0)?; + interp.rooted(&[Value::Object(a)], |interp| { + for (i, s) in syms.into_iter().enumerate() { + interp.use_fuel()?; + create_at(interp, a, i as f64, Value::Symbol(s))?; + } + Ok(Value::Object(a)) + }) + }) +} + +/// `Function.prototype[@@hasInstance](v)` (section 19.2.3.6): OrdinaryHasInstance. +fn function_has_instance(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + interp.ordinary_has_instance(&arg(args, 0), &this).map(Value::Bool) +} diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index 0a70e80433..c009dddc9a 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -684,6 +684,10 @@ fn json_stringify_unwraps_number_string_and_boolean_objects() { assert_eq!(string("Object.prototype.valueOf = function () { return 9; }; JSON.stringify(Object(3))"), "3"); assert_eq!(string("Object.getPrototypeOf(Object(1)).valueOf = function () { return 4; }; JSON.stringify(Object(3))"), "4"); assert_eq!(string("Object.getPrototypeOf(Object('')).toString = function () { return 'q'; }; JSON.stringify(Object('abc'))"), "\"q\""); + // Once the own prototype's method is deleted, the lookup goes on to Object.prototype. + let over = "Object.prototype.toString = function () { return '7'; };"; + assert_eq!(string(&format!("{over} delete String.prototype.toString; JSON.stringify(Object('abc'))")), "\"7\""); + assert_eq!(string(&format!("{over} delete Number.prototype.valueOf; delete Number.prototype.toString; JSON.stringify(Object(3))")), "7"); } #[test] diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index c805ad48e0..2671959b17 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -136,6 +136,15 @@ pub(crate) enum Op { /// `object function` → `object`. InitGetter(u32), InitSetter(u32), + /// `object value` → `object`: `__proto__: value` sets the object's prototype to the value + /// when it is an object or `null` (ECMA-262 2015 section B.3.1). + InitProto, + /// `function` → `function`: gives the new function the `name` `names[i]` (ECMA-262 2015 + /// section 9.2.11). + SetFunctionName(u32), + /// `name function` → `name function`: gives the new function the computed `name` on the + /// stack, after the prefix. + SetFunctionNameKey(NamePrefix), /// Pushes a new function made from `functions[i]` and the current environment. Closure(u32), /// Pushes a new regular expression object for `regexps[i]`. @@ -214,6 +223,29 @@ pub(crate) enum Op { ToStr, /// Pushes the template object of `templates[i]`, the same object for each evaluation. TemplateObject(u32), + /// `value` → its Iterator Record (GetIterator, ECMA-262 11th edition section 7.4.1). + GetIterator, + /// `record` → `record value`, or jumps with `record` when the iterator is done. + IterStep(u32), + /// `record x₁…xₙ` → `record x₁…xₙ value`: the next value, `undefined` once it is done. + IterValue(u32), + /// `record` → `record`: steps the iterator without reading the result's `value`, for a hole + /// in an array pattern. + IterSkip, + /// `record x₁…xₙ` → `record x₁…xₙ array`: the values left, in an array. + IterRest(u32), + /// `record` → nothing: closes the iterator unless it is done (IteratorClose). + IterClose, + /// `record exception` → throws the exception after closing the iterator unless it is done. + IterCloseThrow, + /// `value` → `value`: a `TypeError` when it is `undefined` or `null`. + RequireObjectCoercible, + /// `object key x₁…xₙ` → `object key x₁…xₙ object[key]`: an object pattern's property. + PatternGet(u32), + /// `object key value` → `object`: a property with a computed name. + InitIndex, + /// `object key function` → `object`: a getter (`true`) or a setter with a computed name. + InitAccessorIndex(bool), } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -305,9 +337,53 @@ pub(crate) struct Code { pub(crate) arrow: bool, /// The code reads `this` or calls `eval`, itself or in an arrow function inside it. pub(crate) uses_this: bool, - /// The function has default or rest parameters: its parameters start uninitialized, its - /// code initializes them and then enters its body with [`Op::BodyEnv`]. + /// The function has default, rest or destructured parameters: its parameters start + /// uninitialized, its code initializes them and then enters its body with [`Op::BodyEnv`]. pub(crate) param_init: bool, + /// The names the destructured parameters bind, which start uninitialized beside the + /// parameters. A destructured parameter's own entry in `params` is a name no script can + /// write. + pub(crate) pattern_names: Vec, + /// The code was read with [`crate::Options::es2015`]: its function's `length` can be + /// redefined, as ECMA-262 2015 section 19.2.4.1 has it. + pub(crate) es2015: bool, + /// The `name` its function objects get when they are made (ECMA-262 2015 sections 14.1.19 + /// and 14.1.20): a declaration's or a named function expression's name, with + /// [`crate::Options::es2015`]. + pub(crate) own_name: Option, + /// The code is a method's, a getter's or a setter's, read with [`crate::Options::es2015`]: + /// its functions have no `prototype` and cannot be constructed (section 14.3.8). + pub(crate) method: bool, +} + +/// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum NamePrefix { + None, + Get, + Set, +} + +impl NamePrefix { + /// The prefix's code units, with the space that follows it. + pub(crate) fn units(self) -> &'static [u16] { + const GET: &[u16] = &[0x67, 0x65, 0x74, 0x20]; + const SET: &[u16] = &[0x73, 0x65, 0x74, 0x20]; + match self { + NamePrefix::None => &[], + NamePrefix::Get => GET, + NamePrefix::Set => SET, + } + } + + /// The prefix with the space that follows it, as text. + pub(crate) fn text(self) -> &'static str { + match self { + NamePrefix::None => "", + NamePrefix::Get => "get ", + NamePrefix::Set => "set ", + } + } } impl Code { @@ -361,7 +437,9 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::Neg | Op::Plus | Op::BitNot | Op::Not | Op::Typeof | Op::ToNumber | Op::ArrayHole | Op::ForInStart | Op::CheckObject => e(1, 1), Op::GetMemberThis(_) => e(1, 2), Op::SetMember(_) | Op::GetIndex | Op::DeleteIndex | Op::IncIndex { .. } | Op::Binary(_) => e(2, 1), - Op::ArrayPush | Op::InitProp(_) | Op::InitGetter(_) | Op::InitSetter(_) => e(2, 1), + Op::ArrayPush | Op::InitProp(_) | Op::InitGetter(_) | Op::InitSetter(_) | Op::InitProto => e(2, 1), + Op::SetFunctionName(_) => e(1, 1), + Op::SetFunctionNameKey(_) => e(2, 2), Op::GetIndexThis => e(2, 2), Op::SetIndex => e(3, 1), Op::Call(n) | Op::CallEval(n) => e(n.checked_add(2).ok_or("operand too large")?, 1), @@ -391,7 +469,13 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::LoadParam(_) | Op::TemplateObject(_) => e(0, 1), Op::ArraySpread | Op::NewSpread => e(2, 1), Op::CallSpread(_) => e(3, 1), - Op::ToStr => e(1, 1), + Op::ToStr | Op::GetIterator | Op::IterSkip | Op::RequireObjectCoercible => e(1, 1), + Op::IterStep(t) => Effect { pops: 1, next: Some(2), jumps: vec![(t, 1)] }, + Op::IterValue(n) | Op::IterRest(n) => e(n.checked_add(1).ok_or("operand too large")?, n.checked_add(2).ok_or("operand too large")?), + Op::PatternGet(n) => e(n.checked_add(2).ok_or("operand too large")?, n.checked_add(3).ok_or("operand too large")?), + Op::IterClose => e(1, 0), + Op::IterCloseThrow => end(2), + Op::InitIndex | Op::InitAccessorIndex(_) => e(3, 1), }) } @@ -418,6 +502,7 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> { | Op::InitProp(i) | Op::InitGetter(i) | Op::InitSetter(i) + | Op::SetFunctionName(i) | Op::PushCatch(i) | Op::InitVar(i) | Op::LoadParam(i) diff --git a/crates/js/src/chars.rs b/crates/js/src/chars.rs index 61b9a7f318..60df43513c 100644 --- a/crates/js/src/chars.rs +++ b/crates/js/src/chars.rs @@ -123,7 +123,7 @@ pub fn hex_value(c: u32) -> Option { } } -/// The value of the digit values `digits` in `radix` (8 or 16), rounded once to the nearest number +/// The value of the digit values `digits` in `radix` (2, 8 or 16), rounded once to the nearest number /// with ties to even (sections 7.8.3 and 9.3.1), or `None` when there are no digits. Digits are /// kept exactly in a `u128` while they fit; past that, each later digit counts only for its /// position and for whether any of the dropped bits is set. diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index cbe5493cdc..26cd0a71cd 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -13,17 +13,20 @@ //! chains and labels are compiled with loops; every other kind of nesting is counted, and code //! nested deeper than [`MAX_DEPTH`] gives a `SyntaxError` instead of exhausting the stack. +mod pattern; + use std::collections::{HashMap, HashSet}; use std::rc::Rc; use crate::ast::{ - AssignOp, Ast, BinaryOp, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, PropertyValue, Stmt, StmtId, - TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, + AssignOp, Ast, BinaryOp, Binding, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, Property, PropertyKey, + PropertyValue, Stmt, StmtId, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, }; -use crate::bytecode::{BlockScope, Code, CodeKind, Handler, Op, Source, Template, fallthrough_effect, verify}; +use crate::bytecode::{BlockScope, Code, CodeKind, Handler, NamePrefix, Op, Source, Template, fallthrough_effect, verify}; use crate::error::{SyntaxError, TOO_DEEP}; use crate::heap::Key; use crate::value::Str; +use pattern::Mode; /// How deeply the compiler may recurse: past the parser's default nesting limit, and shallow /// enough for a 1 MiB stack. @@ -61,6 +64,10 @@ enum Ctx { Jump { labels: Vec, is_loop: bool, plain_break: bool, brk: Label, cont: Option