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