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