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