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/// Argument `index`, or `undefined` when it was not passed.
160pub fn arg(args: &[Value], index: usize) -> Value {
161 args.get(index).cloned().unwrap_or(Value::Undefined)
162}
163
164/// Argument `index` as a number, with the `undefined`-is-`NaN` rule of `ToNumber`.
165pub fn arg_number(args: &[Value], index: usize) -> f64 {
166 arg(args, index).to_number()
167}
168
169/// Argument `index` as an integer, or `None` when it is `undefined` — the shape
170/// optional numeric arguments need.
171pub fn arg_int_or(args: &[Value], index: usize, fallback: i64) -> i64 {
172 match args.get(index) {
173 None | Some(Value::Undefined) => fallback,
174 Some(value) => value.to_number() as i64,
175 }
176}
177
178/// [`arg_int_or`] through `ToIntegerOrInfinity`, so an object argument is converted
179/// properly.
180///
181/// `arg_int_or` uses `Value::to_number`, which is a plain field read for an object — it
182/// answers `NaN` instead of running `valueOf`. That is fine for code that already has a
183/// number and wrong for everything the spec says `ToIntegerOrInfinity` about:
184/// `"ABBABABAB".indexOf("AB", {valueOf: () => true})` was `-1` because the object never
185/// became `1`. This version goes through the interpreter, so `valueOf` and `toString` run.
186pub fn arg_integer_or(
187 interp: &mut Interp<'_>,
188 args: &[Value],
189 index: usize,
190 fallback: f64,
191) -> JsResult<f64> {
192 match args.get(index) {
193 None | Some(Value::Undefined) => Ok(fallback),
194 Some(value) => {
195 let number = interp.to_js_number(value)?;
196 Ok(if number.is_nan() { 0.0 } else { number.trunc() })
197 }
198 }
199}
200
201/// Whether argument `index` was actually passed.
202pub fn has_arg(args: &[Value], index: usize) -> bool {
203 args.len() > index
204}
205
206/// Give `object` a `Symbol.toStringTag` data property answering `tag`.
207///
208/// A *data* property, not an accessor: `{value, writable: false, enumerable: false,
209/// configurable: true}`, which is what §17 requires of every `@@toStringTag` and what
210/// `verifyProperty` reads off the descriptor. An accessor reports `writable: undefined`
211/// and fails.
212///
213/// Namespaced objects (`Math`, `JSON`, `Reflect`, `Intl`, `Atomics`) all need one:
214/// without it `Object.prototype.toString.call(Math)` answers `[object Object]` instead of
215/// `[object Math]`, and a run of `Array.prototype` tests — `map`/`filter`/`forEach`/
216/// `some`/`every`/`reduce`/`reduceRight` applied to `Math` and `JSON` — check exactly
217/// that tag from inside the callback.
218pub fn install_tag(object: &Gc<JsObject>, tag: &str, interp: &Interp<'_>) {
219 object.define_key(
220 &interp
221 .realm
222 .well_known_key(crate::interp::WellKnown::ToStringTag),
223 Property {
224 value: Some(interp.string(tag)),
225 writable: false,
226 enumerable: false,
227 configurable: true,
228 ..Property::default()
229 },
230 );
231}
232
233/// Give `constructor` the `[Symbol.species]` accessor every derived-result constructor has.
234///
235/// It answers `this`, so `class A extends Array {}` inherits "the constructor I was called
236/// on" instead of a frozen `Array`. An accessor rather than a data property is also what
237/// `Object.getOwnPropertyDescriptor(Array, Symbol.species).get` finds, and the `length`,
238/// `name` and `symbol-species-name` cases of `Array/Symbol.species` read exactly those.
239pub fn install_species_accessor(constructor: &Gc<JsObject>, interp: &Interp<'_>) {
240 let getter = interp.new_native("get [Symbol.species]", 0, species_getter);
241 constructor.define_key(
242 &interp
243 .realm
244 .well_known_key(crate::interp::WellKnown::Species),
245 Property {
246 getter: Some(Value::Object(getter)),
247 enumerable: false,
248 configurable: true,
249 ..Property::default()
250 },
251 );
252}
253
254/// The shared `[Symbol.species]` getter: identity.
255///
256/// `Array`, `Map`, `Set`, `Promise`, `RegExp`, `ArrayBuffer` and `%TypedArray%` all define
257/// the same accessor, which answers the receiver.
258fn species_getter(
259 _interp: &mut Interp<'_>,
260 this: Value,
261 _args: &[Value],
262) -> crate::interp::JsResult<Value> {
263 Ok(this)
264}
265
266/// The `this` of a method call, as an object.
267///
268/// A primitive receiver is boxed: `"abc".indexOf(…)` reaches a method on
269/// `String.prototype` with a string `this`, and the method behaves as if it had an object.
270///
271/// This used to be a second, incomplete `ToObject`: it boxed by defining `_value` and
272/// nothing else, so a boxed string had no `length` and no index properties, and
273/// `Array.prototype.map.call("ab", …)` read nothing at all. Boxing now goes through the
274/// interpreter's one implementation, which builds the String exotic object properly.
275pub fn this_object(interp: &mut Interp<'_>, this: &Value) -> crate::interp::JsResult<Gc<JsObject>> {
276 interp.object_from(this)
277}
278
279/// The text a string method operates on, whether `this` is a primitive or a box.
280pub fn this_string(interp: &Interp<'_>, this: &Value) -> Option<String> {
281 match this {
282 Value::String(text) => Some(text.to_string_lossy().into_owned()),
283 Value::Object(object) => interp
284 .internal_get(object, "_value")
285 .map(|value| value.to_js_string()),
286 _ => {
287 let _ = interp;
288 None
289 }
290 }
291}