Skip to main content

quickjs/builtins/
mod.rs

1//! The standard library: the globals a script reaches without an import.
2//!
3//! The set installed here is the one milestone M4 targets — `Object`, `Function`,
4//! `Array`, `String`, `Number`, `Boolean`, `Math`, `JSON` and the error classes —
5//! which is what a script needs before it can do anything useful at all.
6//!
7//! Two conventions run through every module:
8//!
9//! * A method is a native function stored on a prototype, and it receives `this`
10//!   exactly as a script method would. Nothing is special-cased by call site.
11//! * Argument checks throw the same error *class* the reference does, because the
12//!   test suite asserts on `instanceof` and on `e.name`.
13
14pub(crate) mod array;
15mod async_from_sync;
16mod base64;
17pub mod bigint;
18pub(crate) mod date;
19pub mod disposable;
20mod error;
21mod from_async;
22mod function;
23mod generator;
24mod global;
25pub mod iterator;
26pub mod json;
27pub mod map;
28mod math;
29mod number;
30pub(crate) mod object;
31
32/// Re-exported for `Interp`'s `[[DefineOwnProperty]]`, which runs the same
33/// `ValidateAndApplyPropertyDescriptor` comparison on a merged descriptor.
34pub(crate) use object::same_accessor_half;
35pub mod promise;
36pub mod proxy;
37mod reflect;
38pub mod regexp;
39mod string;
40mod substitution;
41pub mod symbol;
42pub mod typedarray;
43pub mod weak;
44
45use crate::interp::{Interp, JsResult};
46use crate::object::{JsObject, NativeFn, Property};
47use crate::value::Value;
48use js_gc::Gc;
49
50/// Install the standard library on `interp`'s realm.
51pub fn install(interp: &mut Interp<'_>) {
52    let object_proto = interp.realm.object_proto.clone();
53    // §20.1.2: `%Object.prototype%` is created with `[[SetPrototypeOf]]` set to
54    // `SetImmutablePrototype`, so its prototype can never change. `Object.setPrototypeOf`
55    // and `Reflect.setPrototypeOf` must answer `false` (and the former throw a `TypeError`)
56    // for it — `Object/prototype/setPrototypeOf-with-non-circular-values` pins that, and
57    // `setPrototypeOf-with-non-circular-values-__proto__` the same through `__proto__`.
58    interp.internal_set(&object_proto, "_immutable_proto", Value::Bool(true));
59    let function_proto = interp.realm.function_proto.clone();
60    let array_proto = interp.realm.array_proto.clone();
61
62    // Prototypes for the primitives have to exist before anything is installed on
63    // them, and before the constructors name them.
64    let string_proto = interp.new_object(Some(object_proto.clone()));
65    let number_proto = interp.new_object(Some(object_proto.clone()));
66    let boolean_proto = interp.new_object(Some(object_proto.clone()));
67    // Each of the three is a wrapper of its own type, carrying the empty value:
68    // `Boolean.prototype.valueOf()` is `false`, `Number.prototype.valueOf()` is `0` and
69    // `String.prototype.valueOf()` is `""`. Without the slot they were plain objects, so
70    // all three threw "not a boolean/number/string" from a method called on its own
71    // prototype — which §20.3.3, §21.1.3 and §22.1.3 make legal.
72    interp.init_primitive_wrapper(&boolean_proto, Value::Bool(false));
73    interp.init_primitive_wrapper(&number_proto, Value::Int(0));
74    interp.init_primitive_wrapper(&string_proto, interp.string(""));
75    interp.realm.string_proto = Some(string_proto.clone());
76    interp.realm.number_proto = Some(number_proto.clone());
77    interp.realm.boolean_proto = Some(boolean_proto.clone());
78
79    // `%GeneratorPrototype%` has no constructor of its own, so it is created here and
80    // kept on the realm for `new_generator` to use as the prototype of every generator.
81    let generator_proto = interp.new_object(Some(object_proto.clone()));
82    interp.realm.generator_proto = generator_proto.clone();
83
84    error::install(interp);
85    // `Symbol` installs first among the rest because the well-known symbols are property
86    // keys the other builtins store their methods under — `Array.prototype[Symbol.iterator]`
87    // is defined during `array::install` below.
88    symbol::install(interp);
89    // `Iterator` right after `Symbol` and before everything that makes an iterable:
90    // the array, string, map/set, typed-array and generator protos all inherit from
91    // `%IteratorPrototype%`, and they can only do that once it exists.
92    iterator::install(interp, &object_proto);
93    object::install(interp, &object_proto);
94    function::install(interp, &function_proto);
95    array::install(interp, &array_proto);
96    string::install(interp, &string_proto);
97    number::install(interp, &number_proto);
98    bigint::install(interp, &object_proto);
99    map::install(interp, &object_proto);
100    math::install(interp);
101    json::install(interp);
102    reflect::install(interp);
103    // `Promise` before `Proxy`: a proxy handler is a plain object, but the reverse is not
104    // true — nothing here reads the other's prototype.
105    promise::install(interp, &object_proto);
106    proxy::install(interp);
107    date::install(interp);
108    // `RegExp` after `String` (its methods dispatch to `Symbol.replace` and friends) and
109    // after `Symbol`, whose well-known keys it defines its methods under.
110    let regexp = regexp::install(interp, &object_proto);
111    let global = interp.realm.global.clone();
112    global.define(
113        "RegExp",
114        crate::object::Property::with_attributes(Value::Object(regexp), true, false),
115    );
116    // The stacks need `Symbol.dispose` (installed by `symbol`) and the error prototypes,
117    // and nothing else depends on them.
118    disposable::install(interp, &object_proto);
119    // The typed arrays need `Array.prototype`-style helpers (`join`) and `Symbol.toStringTag`,
120    // both of which are installed by now.
121    typedarray::install(interp, &object_proto);
122    generator::install(interp, &generator_proto);
123    global::install(interp, &boolean_proto);
124    // The weak-reference family needs the collection prototypes (it installs beside them),
125    // `Symbol.toStringTag`, and the error prototypes; nothing depends on it.
126    weak::install(interp, &object_proto);
127    // `Array.fromAsync` last: it is written in JavaScript and compiled here, so its
128    // source reaches for `Array`, `Promise`, `Reflect`, `Object`, `TypeError` and the
129    // well-known symbols by name. Every one of those has to exist by now.
130    from_async::install(interp);
131    async_from_sync::install(interp);
132}
133
134// ---------------------------------------------------------------------------
135// Helpers shared by the modules
136// ---------------------------------------------------------------------------
137
138/// A native function object, ready to be stored as a value.
139pub fn method(
140    interp: &Interp<'_>,
141    name: &str,
142    length: u32,
143    func: NativeFn,
144) -> crate::interp::JsResult<Value> {
145    Ok(Value::Object(interp.new_native(name, length, func)))
146}
147
148/// Define `name` on `target` as a non-enumerable method, the way every built-in
149/// method is defined.
150///
151/// Non-enumerable matters: `for (k in [])` must not list a hundred method names,
152/// and `JSON.stringify` must not serialise them.
153pub fn define_method(
154    target: &JsObject,
155    name: &str,
156    length: u32,
157    func: NativeFn,
158    interp: &Interp<'_>,
159) {
160    let function = interp.new_native(name, length, func);
161    target.define(
162        name,
163        Property::with_attributes(Value::Object(function), true, false),
164    );
165}
166
167/// `ToString(value)` as WTF-8, without the `RequireObjectCoercible` guard.
168///
169/// Distinct from [`builtins::this_object`]-based conversion in two ways that matter:
170///
171/// * an object goes through `ToPrimitive(String)`, so its `toString`/`valueOf` runs. Using
172///   `Value::to_js_string` — the engine's *total* conversion — skips that, which is why
173///   `parseInt({valueOf(){return 1}, toString(){return 0}})` answered `NaN` instead of `0`;
174/// * the answer keeps `Wtf8`, so an unpaired surrogate survives to be rejected by whoever
175///   needs to reject it. A `String` would have turned it into U+FFFD first.
176pub fn to_string_wtf8(interp: &mut Interp<'_>, value: &Value) -> JsResult<crate::value::Wtf8> {
177    let primitive = if matches!(value, Value::Object(_)) {
178        interp.to_primitive(value.clone(), crate::interp::Hint::String)?
179    } else {
180        value.clone()
181    };
182    match &primitive {
183        Value::String(text) => Ok(text.wtf8().clone()),
184        Value::Symbol(_) => Err(interp.type_error("cannot convert a Symbol to a string")),
185        other => Ok(crate::value::Wtf8::new(other.to_js_string())),
186    }
187}
188
189/// Argument `index`, or `undefined` when it was not passed.
190pub fn arg(args: &[Value], index: usize) -> Value {
191    args.get(index).cloned().unwrap_or(Value::Undefined)
192}
193
194/// Argument `index` as a number, with the `undefined`-is-`NaN` rule of `ToNumber`.
195pub fn arg_number(args: &[Value], index: usize) -> f64 {
196    arg(args, index).to_number()
197}
198
199/// Argument `index` as an integer, or `None` when it is `undefined` — the shape
200/// optional numeric arguments need.
201pub fn arg_int_or(args: &[Value], index: usize, fallback: i64) -> i64 {
202    match args.get(index) {
203        None | Some(Value::Undefined) => fallback,
204        Some(value) => value.to_number() as i64,
205    }
206}
207
208/// [`arg_int_or`] through `ToIntegerOrInfinity`, so an object argument is converted
209/// properly.
210///
211/// `arg_int_or` uses `Value::to_number`, which is a plain field read for an object — it
212/// answers `NaN` instead of running `valueOf`. That is fine for code that already has a
213/// number and wrong for everything the spec says `ToIntegerOrInfinity` about:
214/// `"ABBABABAB".indexOf("AB", {valueOf: () => true})` was `-1` because the object never
215/// became `1`. This version goes through the interpreter, so `valueOf` and `toString` run.
216pub fn arg_integer_or(
217    interp: &mut Interp<'_>,
218    args: &[Value],
219    index: usize,
220    fallback: f64,
221) -> JsResult<f64> {
222    match args.get(index) {
223        None | Some(Value::Undefined) => Ok(fallback),
224        Some(value) => {
225            let number = interp.to_js_number(value)?;
226            Ok(if number.is_nan() { 0.0 } else { number.trunc() })
227        }
228    }
229}
230
231/// Whether argument `index` was actually passed.
232pub fn has_arg(args: &[Value], index: usize) -> bool {
233    args.len() > index
234}
235
236/// Give `object` a `Symbol.toStringTag` data property answering `tag`.
237///
238/// A *data* property, not an accessor: `{value, writable: false, enumerable: false,
239/// configurable: true}`, which is what §17 requires of every `@@toStringTag` and what
240/// `verifyProperty` reads off the descriptor. An accessor reports `writable: undefined`
241/// and fails.
242///
243/// Namespaced objects (`Math`, `JSON`, `Reflect`, `Intl`, `Atomics`) all need one:
244/// without it `Object.prototype.toString.call(Math)` answers `[object Object]` instead of
245/// `[object Math]`, and a run of `Array.prototype` tests — `map`/`filter`/`forEach`/
246/// `some`/`every`/`reduce`/`reduceRight` applied to `Math` and `JSON` — check exactly
247/// that tag from inside the callback.
248pub fn install_tag(object: &Gc<JsObject>, tag: &str, interp: &Interp<'_>) {
249    object.define_key(
250        &interp
251            .realm
252            .well_known_key(crate::interp::WellKnown::ToStringTag),
253        Property {
254            value: Some(interp.string(tag)),
255            writable: false,
256            enumerable: false,
257            configurable: true,
258            ..Property::default()
259        },
260    );
261}
262
263/// Give `constructor` the `[Symbol.species]` accessor every derived-result constructor has.
264///
265/// It answers `this`, so `class A extends Array {}` inherits "the constructor I was called
266/// on" instead of a frozen `Array`. An accessor rather than a data property is also what
267/// `Object.getOwnPropertyDescriptor(Array, Symbol.species).get` finds, and the `length`,
268/// `name` and `symbol-species-name` cases of `Array/Symbol.species` read exactly those.
269pub fn install_species_accessor(constructor: &Gc<JsObject>, interp: &Interp<'_>) {
270    let getter = interp.new_native("get [Symbol.species]", 0, species_getter);
271    constructor.define_key(
272        &interp
273            .realm
274            .well_known_key(crate::interp::WellKnown::Species),
275        Property {
276            getter: Some(Value::Object(getter)),
277            enumerable: false,
278            configurable: true,
279            ..Property::default()
280        },
281    );
282}
283
284/// The shared `[Symbol.species]` getter: identity.
285///
286/// `Array`, `Map`, `Set`, `Promise`, `RegExp`, `ArrayBuffer` and `%TypedArray%` all define
287/// the same accessor, which answers the receiver.
288fn species_getter(
289    _interp: &mut Interp<'_>,
290    this: Value,
291    _args: &[Value],
292) -> crate::interp::JsResult<Value> {
293    Ok(this)
294}
295
296/// The `this` of a method call, as an object.
297///
298/// A primitive receiver is boxed: `"abc".indexOf(…)` reaches a method on
299/// `String.prototype` with a string `this`, and the method behaves as if it had an object.
300///
301/// This used to be a second, incomplete `ToObject`: it boxed by defining `_value` and
302/// nothing else, so a boxed string had no `length` and no index properties, and
303/// `Array.prototype.map.call("ab", …)` read nothing at all. Boxing now goes through the
304/// interpreter's one implementation, which builds the String exotic object properly.
305pub fn this_object(interp: &mut Interp<'_>, this: &Value) -> crate::interp::JsResult<Gc<JsObject>> {
306    interp.object_from(this)
307}
308
309/// The text a string method operates on, whether `this` is a primitive or a box.
310pub fn this_string(interp: &Interp<'_>, this: &Value) -> Option<String> {
311    match this {
312        Value::String(text) => Some(text.to_string_lossy().into_owned()),
313        Value::Object(object) => interp
314            .internal_get(object, "_value")
315            .map(|value| value.to_js_string()),
316        _ => {
317            let _ = interp;
318            None
319        }
320    }
321}