quickjs-pure 0.16.9

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
//! `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> {
    let body = match args.last() {
        Some(value) => value.to_js_string(),
        None => String::new(),
    };
    let params: Vec<String> = args
        .iter()
        .take(args.len().saturating_sub(1))
        .map(|value| value.to_js_string())
        .collect();
    let params = params.join(",");
    let source = format!("(function({params}) {{{body}}})");
    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 {
        object.define(
            "name",
            Property::with_attributes(interp.string("anonymous"), false, false),
        );
    }
    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(&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(this: &Value) -> Option<String> {
    this.as_object().and_then(|object| {
        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,
    })
}