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