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;
15mod error;
16mod function;
17mod global;
18mod json;
19mod math;
20mod number;
21mod object;
22mod reflect;
23mod string;
24
25use crate::interp::Interp;
26use crate::object::{JsObject, NativeFn, Property};
27use crate::value::Value;
28use js_gc::Gc;
29
30/// Install the standard library on `interp`'s realm.
31pub fn install(interp: &mut Interp<'_>) {
32    let object_proto = interp.realm.object_proto.clone();
33    let function_proto = interp.realm.function_proto.clone();
34    let array_proto = interp.realm.array_proto.clone();
35
36    // Prototypes for the primitives have to exist before anything is installed on
37    // them, and before the constructors name them.
38    let string_proto = interp.new_object(Some(object_proto.clone()));
39    let number_proto = interp.new_object(Some(object_proto.clone()));
40    let boolean_proto = interp.new_object(Some(object_proto.clone()));
41    interp.realm.string_proto = Some(string_proto.clone());
42    interp.realm.number_proto = Some(number_proto.clone());
43    interp.realm.boolean_proto = Some(boolean_proto.clone());
44
45    error::install(interp);
46    object::install(interp, &object_proto);
47    function::install(interp, &function_proto);
48    array::install(interp, &array_proto);
49    string::install(interp, &string_proto);
50    number::install(interp, &number_proto);
51    math::install(interp);
52    json::install(interp);
53    reflect::install(interp);
54    global::install(interp, &boolean_proto);
55}
56
57// ---------------------------------------------------------------------------
58// Helpers shared by the modules
59// ---------------------------------------------------------------------------
60
61/// A native function object, ready to be stored as a value.
62pub fn method(
63    interp: &Interp<'_>,
64    name: &str,
65    length: u32,
66    func: NativeFn,
67) -> crate::interp::JsResult<Value> {
68    Ok(Value::Object(interp.new_native(name, length, func)))
69}
70
71/// Define `name` on `target` as a non-enumerable method, the way every built-in
72/// method is defined.
73///
74/// Non-enumerable matters: `for (k in [])` must not list a hundred method names,
75/// and `JSON.stringify` must not serialise them.
76pub fn define_method(
77    target: &JsObject,
78    name: &str,
79    length: u32,
80    func: NativeFn,
81    interp: &Interp<'_>,
82) {
83    let function = interp.new_native(name, length, func);
84    target.define(
85        name,
86        Property::with_attributes(Value::Object(function), true, false),
87    );
88}
89
90/// Argument `index`, or `undefined` when it was not passed.
91pub fn arg(args: &[Value], index: usize) -> Value {
92    args.get(index).cloned().unwrap_or(Value::Undefined)
93}
94
95/// Argument `index` as a number, with the `undefined`-is-`NaN` rule of `ToNumber`.
96pub fn arg_number(args: &[Value], index: usize) -> f64 {
97    arg(args, index).to_number()
98}
99
100/// Argument `index` as an integer, or `None` when it is `undefined` — the shape
101/// optional numeric arguments need.
102pub fn arg_int_or(args: &[Value], index: usize, fallback: i64) -> i64 {
103    match args.get(index) {
104        None | Some(Value::Undefined) => fallback,
105        Some(value) => value.to_number() as i64,
106    }
107}
108
109/// Whether argument `index` was actually passed.
110pub fn has_arg(args: &[Value], index: usize) -> bool {
111    args.len() > index
112}
113
114/// The `this` of a method call, as an object.
115///
116/// A primitive receiver is boxed on demand: `"abc".indexOf(…)` reaches a method on
117/// `String.prototype` with a string `this`, and the method has to behave as if it
118/// had an object. The box is only for property access, so the text is read through
119/// [`this_string`] instead.
120pub fn this_object(interp: &mut Interp<'_>, this: &Value) -> crate::interp::JsResult<Gc<JsObject>> {
121    match this {
122        Value::Object(object) => Ok(object.clone()),
123        Value::Undefined | Value::Null => {
124            Err(interp.type_error("cannot convert undefined or null to object"))
125        }
126        Value::String(_) => {
127            let proto = interp.realm.string_proto.clone();
128            let boxed = interp.new_object(proto);
129            boxed.define(
130                "_value",
131                Property::with_attributes(this.clone(), false, false),
132            );
133            Ok(boxed)
134        }
135        Value::Int(_) | Value::Float(_) => {
136            let proto = interp.realm.number_proto.clone();
137            let boxed = interp.new_object(proto);
138            boxed.define(
139                "_value",
140                Property::with_attributes(this.clone(), false, false),
141            );
142            Ok(boxed)
143        }
144        Value::Bool(_) => {
145            let proto = interp.realm.boolean_proto.clone();
146            let boxed = interp.new_object(proto);
147            boxed.define(
148                "_value",
149                Property::with_attributes(this.clone(), false, false),
150            );
151            Ok(boxed)
152        }
153        _ => Err(interp.type_error("cannot convert value to object")),
154    }
155}
156
157/// The text a string method operates on, whether `this` is a primitive or a box.
158pub fn this_string(interp: &Interp<'_>, this: &Value) -> Option<String> {
159    match this {
160        Value::String(text) => Some(text.as_str().to_string()),
161        Value::Object(object) => object
162            .own_property("_value")
163            .and_then(|property| property.value)
164            .map(|value| value.to_js_string()),
165        _ => {
166            let _ = interp;
167            None
168        }
169    }
170}