quickjs-pure 0.17.29

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! `Function.prototype` and the `Function` constructor.
//!
//! `Function.prototype` is itself callable and returns `undefined`, which is what
//! makes `Object.getPrototypeOf(f)(…)` harmless. `new Function(args, body)` needs to
//! compile source at run time, so it goes back through the parser and compiler.

use crate::builtins::{arg, define_method};
use crate::interp::{Interp, JsResult, Signal};
use crate::object::{JsObject, Property};
use crate::value::Value;
use js_gc::Gc;

/// Install `Function` and its prototype methods.
pub fn install(interp: &mut Interp<'_>, function_proto: &Gc<JsObject>) {
    // `%Function.prototype%` is itself a function, so it has the two own data properties
    // every function gets. They are load-bearing rather than decorative: `delete f.length`
    // succeeds (the property is configurable) and then the read falls through to these,
    // which is why `eval.length` is `0` after a successful delete instead of `undefined`.
    // Their attributes are the function ones — not writable, not enumerable, configurable.
    function_proto.define("length", Property::name_or_length(Value::Int(0)));
    function_proto.define("name", Property::name_or_length(interp.string("")));
    define_method(function_proto, "call", 1, call, interp);
    define_method(function_proto, "apply", 2, apply, interp);
    define_method(function_proto, "bind", 1, bind, interp);
    define_method(function_proto, "toString", 0, to_string, interp);
    // §20.2.3.6: `Function.prototype[Symbol.hasInstance]` is the one place
    // `OrdinaryHasInstance` is exposed as a function, so a subclass can reach the default
    // behaviour (`super[Symbol.hasInstance](x)`) while still being able to override it.
    //
    // It was missing outright, which cost 10 test262 cases and made
    // `Function.prototype[Symbol.hasInstance]` a `TypeError: undefined is not a function`.
    // `instanceof` itself worked, because `instance_of_operator` falls back to the walk —
    // so the gap only showed up in the tests that name the method.
    let has_instance = interp.new_native("[Symbol.hasInstance]", 1, symbol_has_instance);
    let key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::HasInstance);
    // §20.2.3.6: all three attributes are **false** — the only method on
    // `Function.prototype` that is not writable, and not configurable either. Checked
    // against the reference rather than derived: the reflex for a method is "writable and
    // configurable", and `prop-desc.js` contradicts it.
    function_proto.define_key(
        &key,
        Property {
            value: Some(Value::Object(has_instance)),
            ..Property::default()
        },
    );
    // `%ThrowTypeError%`: the single frozen accessor pair behind `caller`, `arguments` and
    // every other "this property may not be accessed" hole in the language. The spec makes
    // it one shared object with an identity requirement, so it is created once here and
    // reused for both properties — `Object.getOwnPropertyDescriptor(Function.prototype,
    // "caller").get === Object.getOwnPropertyDescriptor(Function.prototype,
    // "arguments").get` holds in the reference.
    //
    // Why it lives on `Function.prototype` rather than on bound functions: a bound
    // function inherits it, and `BoundFunction_restricted-properties` asserts that
    // `bound.hasOwnProperty("caller")` is **false** while `"caller" in bound` is true. An
    // own pair on each bound function (the first thing I wrote) passes the four throwing
    // assertions and fails that one. Ordinary functions do not reach this pair at all —
    // their own `[[Get]]` answers `undefined` for these names — so `function f(){}; f.caller`
    // stays `undefined` while `f.bind(null).caller` throws.
    // §10.2.4: one `%ThrowTypeError%` per realm, with `length`/`name`/`prototype` all
    // frozen and no extensibility. `Object.isFrozen` is the observable half — a plain
    // `new_native` leaves `length` and `name` *configurable* and the object extensible,
    // and `ThrowTypeError/{length,name,frozen,extensible}.js` check exactly that.
    //
    // Stored on the realm because a strict `arguments` object's `callee` accessor is the
    // documented way to reach it, and it has to be the *same* object.
    let thrower = interp.new_native("", 0, throw_type_error);
    for name in ["length", "name"] {
        let value = thrower
            .own_property(name)
            .and_then(|property| property.value)
            .unwrap_or(Value::Undefined);
        thrower.define(name, Property::frozen(value));
    }
    thrower.set_extensible(false);
    interp.realm.throw_type_error = Some(thrower.clone());
    for name in ["caller", "arguments"] {
        function_proto.define(
            name,
            Property {
                getter: Some(Value::Object(thrower.clone())),
                setter: Some(Value::Object(thrower.clone())),
                enumerable: false,
                configurable: true,
                ..Property::default()
            },
        );
    }
    // Where the function was written. The reference exposes these as accessors on
    // `Function.prototype` reading the function's own bytecode debug info, which is why
    // `eval("\n  function f(){}; f").lineNumber` is `2` — the declaration's line, not
    // the eval call's. Test scripts use them to check that positions are reported
    // rather than approximated.
    //
    // The three getters are separate functions rather than one function told which
    // field to read: a native getter runs without a frame of its own, so it cannot
    // recognise itself the way a constructor reads its `_class`.
    for (name, getter) in [
        ("fileName", file_name as crate::object::NativeFn),
        ("lineNumber", line_number),
        ("columnNumber", column_number),
    ] {
        let getter = interp.new_native(name, 0, getter);
        // Not enumerable: these are the reference's own extension on
        // `Function.prototype`, and an enumerable one is inherited by *every* function,
        // so `for (k in Boolean)` listed `fileName`/`lineNumber`/`columnNumber`. That is
        // observable enough to break `for…in` over a function.
        function_proto.define(
            name,
            Property::accessor_with(Some(Value::Object(getter)), None, false),
        );
    }

    let constructor = interp.new_native_constructor("Function", 1, constructor);
    constructor.define(
        "prototype",
        Property::with_attributes(Value::Object(function_proto.clone()), false, false),
    );
    function_proto.define(
        "constructor",
        Property::with_attributes(Value::Object(constructor.clone()), true, false),
    );
    let global = interp.realm.global.clone();
    global.define(
        "Function",
        Property::with_attributes(Value::Object(constructor.clone()), true, false),
    );
}

/// `new Function(p1, p2, …, body)`.
///
/// The source is compiled at run time, which is what `eval` does too — the only
/// difference is the scope the result closes over. Parameters here are local to the
/// new function and the body sees only globals, which is why the compiled script is a
/// plain top-level function.
fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // `ToString` per argument, and it is **observable**: `Function({toString(){...}},
    // "a2", body)` has to run that `toString`, and `Value::to_js_string` is the total
    // version that answers `"[object Object]"` without it — which then failed to parse as
    // a parameter list (`S15.3.4.4_A6_T3`, `…_T4` and the two `apply` twins).
    // §20.2.1.1 steps 3–5: **every parameter** is `ToString`-ed first, in order, and only
    // then the body. The order is observable: `new Function({toString(){throw 1}}, body)`
    // reports the parameter's `1`, not the body's value
    // (`S15.3.2.1_A3_T1` and `…_T3`).
    let params: Vec<String> = args
        .iter()
        .take(args.len().saturating_sub(1))
        .map(|value| interp.to_js_string(value))
        .collect::<JsResult<Vec<String>>>()?;
    let body = match args.last() {
        Some(value) => interp.to_js_string(value)?,
        None => String::new(),
    };
    let params = params.join(",");
    // The newline before `)` is not cosmetic: §20.2.1.1 wraps the parameter text in
    // `function anonymous(…\n) {…}` precisely because a parameter string may end in a
    // `//` comment, which would otherwise swallow the closing paren
    // (`Function.js` passes exactly that).
    let source = format!("(function({params}\n) {{\n{body}\n}})");
    let program = js_parse::parse_script(&source)
        .map_err(|error| Signal::Throw(interp.make_error("SyntaxError", &error.message.clone())))?;
    let compiled = js_compile::compile_script(&program)
        .map_err(|error| Signal::Throw(interp.make_error("SyntaxError", &error.message)))?;
    // The script's own last expression is the function literal, so running it yields
    // the closure. That reuses the whole compile-and-run path instead of duplicating
    // the constant-pool plumbing here.
    let function = interp.run_function_source(compiled)?;
    // The reference names a dynamically created function `anonymous`; without this the
    // compiled expression has no name and `f.name` reads `undefined`.
    if let Value::Object(object) = &function {
        // `{ writable: false, enumerable: false, configurable: true }` — the shape every
        // function's `name` has, so `verifyConfigurable(Function(), 'name')` passes
        // (`instance-name`). `with_attributes(value, false, false)` ties `configurable` to
        // `writable` and made it non-configurable.
        object.define("name", Property::name_or_length(interp.string("anonymous")));
        // §20.2.1.1 step 27: the text `toString` must report is **synthesised**, not the
        // source we compiled. The parameters and body are joined with a newline before `)`
        // and around the body, which is what `Function.js` compares against verbatim —
        // comments included, because they are part of the strings the caller passed.
        let text = dynamic_source_text("function", &params, &body);
        interp.internal_set(object, "_source_text", interp.string(text));
    }
    Ok(function)
}

fn call(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let new_this = arg(args, 0);
    let rest: Vec<Value> = args.iter().skip(1).cloned().collect();
    interp.call_value(this, new_this, rest)
}

fn apply(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let new_this = arg(args, 0);
    let rest = match arg(args, 1) {
        Value::Undefined | Value::Null => Vec::new(),
        Value::Object(object) => {
            let length = interp
                .get_property(&object, "length")?
                .map(|value| value.to_number().max(0.0) as usize)
                .unwrap_or(0);
            let mut out = Vec::with_capacity(length);
            for index in 0..length {
                out.push(
                    interp
                        .get_property(&object, &index.to_string())?
                        .unwrap_or(Value::Undefined),
                );
            }
            out
        }
        _ => return Err(interp.type_error("apply arguments must be an array-like")),
    };
    interp.call_value(this, new_this, rest)
}

/// `Function.prototype.bind`.
///
/// The result is a callable that carries its target, `this` and leading arguments.
/// Those are stored in a dedicated [`Callable`] variant because a native trampoline
/// cannot capture them, and putting them on the object as properties would make them
/// visible to a script.
fn bind(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // §20.2.3.2 step 2: `IsCallable(Target)` or `TypeError`. There was no check here at
    // all, so `Function.prototype.bind.call({})` answered a bound function and 17 cases in
    // `Function/prototype/bind` failed on `Expected a TypeError`. The natural mistake is to
    // assume the receiver must be a function because the method lives on
    // `Function.prototype` — but the method is reachable through `.call`, and the spec asks.
    //
    // `is_callable` rather than a prototype test: a proxy over a function is callable, and a
    // revoked one still is (`is_callable` is the same predicate `@@hasInstance` uses).
    if !matches!(&this, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("not a function"));
    }
    let bound_this = arg(args, 0);
    let leading: Vec<Value> = args.iter().skip(1).cloned().collect();
    let bound = interp.new_bound(this.clone(), bound_this, leading.clone());
    // `bind` shortens `length` by the number of bound arguments and renames the
    // function, both observable on the result.
    //
    // Three details, each with cases behind it:
    //
    // * **Own** `length`, not `Get`. §20.2.3.2 reads `Get(Target, "length")`, but the
    //   reference answers 0 for a function whose `length` is only inherited
    //   (`Object.setPrototypeOf(bar, {length: 42}); delete bar.length;
    //   Function.prototype.bind.call(bar, null, 1).length === 0`) — so what it actually
    //   reads is the own property. I briefly "fixed" this to `Get` and broke
    //   `instance-length-default-value`; the own read is the conforming one here.
    // * The subtraction happens **before** the integer truncation, not after. A `length` of
    //   `3.66` bound with one argument is `2`, not `3`.
    // * `+∞` survives: NaN maps to 0 and infinities stay, which is why a `Symbol` `length`
    //   answers `0` rather than throwing, and why an infinite `length` answers `Infinity`
    //   instead of `i32::MAX`.
    let length = this
        .as_object()
        .and_then(|object| object.own_property("length"))
        .and_then(|property| property.value)
        .unwrap_or(Value::Undefined)
        .to_number();
    let remaining = (length - leading.len() as f64).max(0.0);
    let remaining = if remaining.is_nan() {
        0.0
    } else {
        remaining.trunc()
    };
    bound.define("length", Property::name_or_length(Value::Float(remaining)));
    // `SetFunctionName(F, "bound " + name)`. Unlike `length` above, this one **is** a
    // `Get`: `instance-name-error` installs a throwing getter for `name` and expects the
    // exception to escape `bind`, which only happens if the read goes through `[[Get]]`.
    // (The asymmetry is real, not an oversight — the reference reads own `length` but
    // `Get`s `name`.) When the target has no string `name`, the prefix is still applied, so
    // the result is `"bound "` with a trailing space rather than `""`.
    let name = interp.get_property(this.as_object().expect("callable"), "name")?;
    let name = match name {
        Some(Value::String(text)) => text.to_string_lossy().to_string(),
        _ => String::new(),
    };
    let text = format!("bound {name}");
    bound.define("name", Property::name_or_length(interp.string(text)));
    Ok(Value::Object(bound))
}

/// `%ThrowTypeError%`: unconditionally throws, for every restricted property.
fn throw_type_error(interp: &mut Interp<'_>, _this: Value, _args: &[Value]) -> JsResult<Value> {
    Err(interp.type_error("'caller', 'callee', and 'arguments' properties may not be accessed"))
}

/// `Function.prototype[Symbol.hasInstance](V)` — `OrdinaryHasInstance(this, V)`.
///
/// **A non-callable `this` answers `false`, it does not throw.** My first version returned a
/// `TypeError` on the reasoning that this is "the method" and step 2 must refuse; the
/// reference answers `Function.prototype[Symbol.hasInstance].call({})` with `false`, and
/// `this-val-not-callable.js` asserts exactly that. Worth the note because the tempting
/// reading (§10.3.1 having an `IsCallable` branch) is only about `instanceof` itself, which
/// never reaches here with a non-callable.
fn symbol_has_instance(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    if !matches!(&this, Value::Object(object) if object.is_callable()) {
        return Ok(Value::Bool(false));
    }
    let answer = interp.ordinary_instance_of(&arg(args, 0), &this)?;
    Ok(Value::Bool(answer))
}

fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    // §20.2.3.5 step 1-2: a non-callable receiver is a `TypeError`, not a string. Read
    // off the object, not by re-deriving callability from `this` being a function object:
    // a proxy over a function is callable too, and a *revoked* one still is.
    if !matches!(&this, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("Function.prototype.toString called on a non-callable"));
    }
    let name = this
        .as_object()
        .and_then(|object| object.own_property("name"))
        .and_then(|property| property.value)
        .map(|value| value.to_js_string())
        .unwrap_or_default();
    // §20.2.3.5: a function compiled from script answers with its *original* text. Only
    // a native, bound or host function has no source behind it, and those are exactly
    // the ones the spec lets answer the `[native code]` form.
    if let Some(text) = source_text(interp, &this) {
        return Ok(interp.string(text));
    }
    Ok(interp.string(format!("function {name}() {{\n    [native code]\n}}")))
}

/// The original source text of a script function, if it was compiled from source.
fn source_text(interp: &Interp<'_>, this: &Value) -> Option<String> {
    this.as_object().and_then(|object| {
        // A dynamically created function carries its synthesised text in an **internal
        // slot** — not a property, so `Object.getOwnPropertyNames` cannot see it — and
        // that text is what `toString` must answer, not the slice we compiled.
        if let Some(Value::String(text)) = interp.internal_get(object, "_source_text") {
            return text.wtf8().as_str().map(str::to_string);
        }
        object.with(|data| match &data.kind {
            crate::object::ObjectKind::Function(crate::object::Callable::Bytecode {
                code, ..
            }) => {
                // A builtin written in JavaScript (`Array.fromAsync`, the async
                // iterator helpers) is still a *builtin*: §20.2.3.5 gives those the
                // `[native code]` form whatever language the algorithm happens to be
                // written in, and `built-in-function-object.js` checks every intrinsic.
                if code.code.filename.as_deref() == Some("<builtin>") {
                    None
                } else {
                    code.code.source.clone()
                }
            }
            _ => None,
        })
    })
}

/// The declaration position of a function object: file, line and column.
///
/// `None` for a native function or a bound function, which have no source behind them;
/// the reference answers `undefined` for those rather than guessing.
fn declaration_position(this: &Value) -> Option<(Option<String>, u32, u32)> {
    this.as_object().and_then(|object| {
        object.with(|data| match &data.kind {
            crate::object::ObjectKind::Function(crate::object::Callable::Bytecode {
                code, ..
            }) => Some((code.code.filename.clone(), code.code.line, code.code.column)),
            _ => None,
        })
    })
}

/// `Function.prototype.fileName`.
fn file_name(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    Ok(match declaration_position(&this) {
        Some((Some(name), _, _)) => interp.string(name),
        _ => Value::Undefined,
    })
}

/// `Function.prototype.lineNumber`.
fn line_number(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    Ok(match declaration_position(&this) {
        Some((_, line, _)) => Value::Int(line as i32),
        None => Value::Undefined,
    })
}

/// `Function.prototype.columnNumber`.
fn column_number(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    Ok(match declaration_position(&this) {
        Some((_, _, column)) => Value::Int(column as i32),
        None => Value::Undefined,
    })
}

/// The text `Function.prototype.toString` reports for a dynamically created function.
///
/// §20.2.1.1's `CreateDynamicFunction` builds it by concatenation, so the shape is fixed:
/// `prefix + " anonymous(" + parameters + "\n) {\n" + body + "\n}"`. Comments and odd
/// whitespace inside the caller's strings survive because this is a plain join rather
/// than a re-print of the parsed form (`Function.js` and the three async/generator
/// siblings compare it verbatim).
pub(crate) fn dynamic_source_text(prefix: &str, params: &str, body: &str) -> String {
    format!("{prefix} anonymous({params}\n) {{\n{body}\n}}")
}