Skip to main content

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
14mod array;
15pub mod bigint;
16pub(crate) mod date;
17pub mod disposable;
18mod error;
19mod function;
20mod generator;
21mod global;
22mod json;
23pub mod map;
24mod math;
25mod number;
26mod object;
27pub mod promise;
28pub mod proxy;
29mod reflect;
30pub mod regexp;
31mod string;
32mod symbol;
33pub mod typedarray;
34
35use crate::interp::Interp;
36use crate::object::{JsObject, NativeFn, Property};
37use crate::value::Value;
38use js_gc::Gc;
39
40/// Install the standard library on `interp`'s realm.
41pub fn install(interp: &mut Interp<'_>) {
42    let object_proto = interp.realm.object_proto.clone();
43    let function_proto = interp.realm.function_proto.clone();
44    let array_proto = interp.realm.array_proto.clone();
45
46    // Prototypes for the primitives have to exist before anything is installed on
47    // them, and before the constructors name them.
48    let string_proto = interp.new_object(Some(object_proto.clone()));
49    let number_proto = interp.new_object(Some(object_proto.clone()));
50    let boolean_proto = interp.new_object(Some(object_proto.clone()));
51    interp.realm.string_proto = Some(string_proto.clone());
52    interp.realm.number_proto = Some(number_proto.clone());
53    interp.realm.boolean_proto = Some(boolean_proto.clone());
54
55    // `%GeneratorPrototype%` has no constructor of its own, so it is created here and
56    // kept on the realm for `new_generator` to use as the prototype of every generator.
57    let generator_proto = interp.new_object(Some(object_proto.clone()));
58    interp.realm.generator_proto = generator_proto.clone();
59
60    error::install(interp);
61    // `Symbol` installs first among the rest because the well-known symbols are property
62    // keys the other builtins store their methods under — `Array.prototype[Symbol.iterator]`
63    // is defined during `array::install` below.
64    symbol::install(interp);
65    object::install(interp, &object_proto);
66    function::install(interp, &function_proto);
67    array::install(interp, &array_proto);
68    string::install(interp, &string_proto);
69    number::install(interp, &number_proto);
70    bigint::install(interp, &object_proto);
71    map::install(interp, &object_proto);
72    math::install(interp);
73    json::install(interp);
74    reflect::install(interp);
75    // `Promise` before `Proxy`: a proxy handler is a plain object, but the reverse is not
76    // true — nothing here reads the other's prototype.
77    promise::install(interp, &object_proto);
78    proxy::install(interp);
79    date::install(interp);
80    // `RegExp` after `String` (its methods dispatch to `Symbol.replace` and friends) and
81    // after `Symbol`, whose well-known keys it defines its methods under.
82    let regexp = regexp::install(interp, &object_proto);
83    let global = interp.realm.global.clone();
84    global.define(
85        "RegExp",
86        crate::object::Property::with_attributes(Value::Object(regexp), true, false),
87    );
88    // The stacks need `Symbol.dispose` (installed by `symbol`) and the error prototypes,
89    // and nothing else depends on them.
90    disposable::install(interp, &object_proto);
91    // The typed arrays need `Array.prototype`-style helpers (`join`) and `Symbol.toStringTag`,
92    // both of which are installed by now.
93    typedarray::install(interp, &object_proto);
94    generator::install(interp, &generator_proto);
95    global::install(interp, &boolean_proto);
96}
97
98// ---------------------------------------------------------------------------
99// Helpers shared by the modules
100// ---------------------------------------------------------------------------
101
102/// A native function object, ready to be stored as a value.
103pub fn method(
104    interp: &Interp<'_>,
105    name: &str,
106    length: u32,
107    func: NativeFn,
108) -> crate::interp::JsResult<Value> {
109    Ok(Value::Object(interp.new_native(name, length, func)))
110}
111
112/// Define `name` on `target` as a non-enumerable method, the way every built-in
113/// method is defined.
114///
115/// Non-enumerable matters: `for (k in [])` must not list a hundred method names,
116/// and `JSON.stringify` must not serialise them.
117pub fn define_method(
118    target: &JsObject,
119    name: &str,
120    length: u32,
121    func: NativeFn,
122    interp: &Interp<'_>,
123) {
124    let function = interp.new_native(name, length, func);
125    target.define(
126        name,
127        Property::with_attributes(Value::Object(function), true, false),
128    );
129}
130
131/// Argument `index`, or `undefined` when it was not passed.
132pub fn arg(args: &[Value], index: usize) -> Value {
133    args.get(index).cloned().unwrap_or(Value::Undefined)
134}
135
136/// Argument `index` as a number, with the `undefined`-is-`NaN` rule of `ToNumber`.
137pub fn arg_number(args: &[Value], index: usize) -> f64 {
138    arg(args, index).to_number()
139}
140
141/// Argument `index` as an integer, or `None` when it is `undefined` — the shape
142/// optional numeric arguments need.
143pub fn arg_int_or(args: &[Value], index: usize, fallback: i64) -> i64 {
144    match args.get(index) {
145        None | Some(Value::Undefined) => fallback,
146        Some(value) => value.to_number() as i64,
147    }
148}
149
150/// Whether argument `index` was actually passed.
151pub fn has_arg(args: &[Value], index: usize) -> bool {
152    args.len() > index
153}
154
155/// The `this` of a method call, as an object.
156///
157/// A primitive receiver is boxed on demand: `"abc".indexOf(…)` reaches a method on
158/// `String.prototype` with a string `this`, and the method has to behave as if it
159/// had an object. The box is only for property access, so the text is read through
160/// [`this_string`] instead.
161pub fn this_object(interp: &mut Interp<'_>, this: &Value) -> crate::interp::JsResult<Gc<JsObject>> {
162    match this {
163        Value::Object(object) => Ok(object.clone()),
164        Value::Undefined | Value::Null => {
165            Err(interp.type_error("cannot convert undefined or null to object"))
166        }
167        Value::String(_) => {
168            let proto = interp.realm.string_proto.clone();
169            let boxed = interp.new_object(proto);
170            boxed.define(
171                "_value",
172                Property::with_attributes(this.clone(), false, false),
173            );
174            Ok(boxed)
175        }
176        Value::Int(_) | Value::Float(_) => {
177            let proto = interp.realm.number_proto.clone();
178            let boxed = interp.new_object(proto);
179            boxed.define(
180                "_value",
181                Property::with_attributes(this.clone(), false, false),
182            );
183            Ok(boxed)
184        }
185        Value::Bool(_) => {
186            let proto = interp.realm.boolean_proto.clone();
187            let boxed = interp.new_object(proto);
188            boxed.define(
189                "_value",
190                Property::with_attributes(this.clone(), false, false),
191            );
192            Ok(boxed)
193        }
194        // A symbol boxes like any other primitive, which is what makes `Object(sym)` a
195        // `Symbol` object whose `valueOf` hands the symbol back.
196        Value::Symbol(_) => {
197            let proto = interp.realm.symbol_proto.clone();
198            let boxed = interp.new_object(proto);
199            boxed.define(
200                "_value",
201                Property::with_attributes(this.clone(), false, false),
202            );
203            Ok(boxed)
204        }
205        _ => Err(interp.type_error("cannot convert value to object")),
206    }
207}
208
209/// The text a string method operates on, whether `this` is a primitive or a box.
210pub fn this_string(interp: &Interp<'_>, this: &Value) -> Option<String> {
211    match this {
212        Value::String(text) => Some(text.to_string_lossy().into_owned()),
213        Value::Object(object) => object
214            .own_property("_value")
215            .and_then(|property| property.value)
216            .map(|value| value.to_js_string()),
217        _ => {
218            let _ = interp;
219            None
220        }
221    }
222}