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