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