Skip to content

Commit cd094bf

Browse files
authored
feat: Function.prototype.toString returns a program function's source text (#103)
1 parent 99de27f commit cd094bf

19 files changed

Lines changed: 312 additions & 16 deletions

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
## Unreleased
44

5+
- `Function.prototype.toString` returns a program function's source text as written: an arrow or `function` as is, a
6+
method or accessor from its name, a class as its whole `class … {}`. Built-in, bound and host functions return
7+
`function name() { [native code] }`. A host can now keep a function a program hands it as text. `String(fn)` is
8+
unchanged.
59
- `ArrayBuffer`: the constructor, `byteLength`, `slice`, `ArrayBuffer.isView`, and the `resizable`, `maxByteLength`
610
and `detached` accessors. `Uint8Array` and `Buffer` sit on real `ArrayBuffer`s: `.buffer` works,
711
`new Uint8Array(arrayBuffer, offset, length)`, `subarray` and `Buffer.from(arrayBuffer, offset, length)` view its

‎interpreter-support.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,10 @@ Math.floor)` is `"3"`). A detached method loses its receiver, as in JS: `values.
181181
`Array.prototype.push.call(arr, 1)`, `Math.max.apply(null, values)`, `fn.bind(obj, first)`. `apply` accepts an
182182
array, an array-like object (its `length` clamped and capped like `Array.from`), or `null`/`undefined`. A
183183
bound function is named `bound f`, has its remaining `length`, and is not constructible.
184+
- [x] `Function.prototype.toString` gives a program function's source text as written: an arrow or `function` as is,
185+
a method or accessor from its name (`get g() {}`, `async *gen() {}`, without a class element's `static`), and
186+
a class its whole `class … {}`. The text survives a suspend and resume. Built-in, bound and host functions give
187+
`function name() { [native code] }`. Conversions don't call it: `String(fn)` stays `"[object Function]"`.
184188
- [x] `JSON.parse` revivers and `JSON.stringify` function replacers see the holder object as `this`. A reviver's third
185189
argument is `{ source }` for a primitive it has not changed (`JSON.parse("1.0", (k, v, c) => c.source)` is
186190
`"1.0"`) and `{}` otherwise.
@@ -261,7 +265,7 @@ Math.floor)` is `"3"`). A detached method loses its receiver, as in JS: `values.
261265
assigning a read-only one (`Math.PI`, `fn.name`) throws a `TypeError`, as in strict mode. `delete` of a
262266
non-reference (`delete 0`, `delete f()`) evaluates the operand and is `true`; `delete x` on a variable throws.
263267
- [x] Coercion helpers and template interpolation accept functions and namespaces: `String(fn)` and `${fn}` give
264-
`"[object Function]"` rather than the source text, `isNaN(fn)` is `true`.
268+
`"[object Function]"` rather than the source text (`fn.toString()` gives the text), `isNaN(fn)` is `true`.
265269
- [x] `==` and `!=` follow IsLooselyEqual: objects (including functions and host references) compare by identity, a
266270
nullish operand never coerces the other side, and a data object facing a primitive converts through its own
267271
`valueOf`/`toString` (default hint) (`fn == null` is `false`, `fn == fn` is `true`, `[1] == 1` and `[1, 2] == "1,2"` are `true`).

‎rust/conformance/cases/boundary-method-receivers.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@
185185
"TypeError",
186186
"Set.isSubsetOf received a Set-like object with an invalid size."
187187
],
188-
"[object Function]",
188+
"() => 1",
189189
1,
190190
null,
191191
[
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const arrow = async (input) => { return input.x + 1 }
2+
function declared(a, b = 2) {
3+
return a + b // é
4+
}
5+
const expression = function named() {}
6+
const o = { m(x) { return "ü" + x }, get g() { return 1 }, set g(v) {}, async *gen() {}, ["com" + "puted"]() {} }
7+
const accessors = Object.getOwnPropertyDescriptor(o, "g")
8+
class Base {}
9+
class A extends Base {
10+
constructor() { super() }
11+
foo() { return 1 }
12+
static bar() {}
13+
static async *baz() {}
14+
get size() { return 0 }
15+
}
16+
class Empty {}
17+
let error
18+
try { Function.prototype.toString.call({}) } catch (e) { error = e.constructor.name }
19+
return [
20+
arrow.toString(), declared.toString(), expression.toString(), (x => x * 2).toString(),
21+
o.m.toString(), accessors.get.toString(), accessors.set.toString(), o.gen.toString(), o.computed.toString(),
22+
A.toString(), new A().foo.toString(), A.bar.toString(), A.baz.toString(), Empty.toString(),
23+
Object.getOwnPropertyDescriptor(A.prototype, "size").get.toString(),
24+
Math.max.toString(), [].map.toString(), declared.bind(null, 1).toString(), Array.fromAsync.toString(),
25+
String(arrow), Function.prototype.toString.call(arrow), error,
26+
]
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
{
2+
"bindings": {},
3+
"ok": true,
4+
"value": [
5+
"async (input) => { return input.x + 1 }",
6+
"function declared(a, b = 2) {\n return a + b // é\n}",
7+
"function named() {}",
8+
"x => x * 2",
9+
"m(x) { return \"ü\" + x }",
10+
"get g() { return 1 }",
11+
"set g(v) {}",
12+
"async *gen() {}",
13+
"[\"com\" + \"puted\"]() {}",
14+
"class A extends Base {\n constructor() { super() }\n foo() { return 1 }\n static bar() {}\n static async *baz() {}\n get size() { return 0 }\n}",
15+
"foo() { return 1 }",
16+
"bar() {}",
17+
"async *baz() {}",
18+
"class Empty {}",
19+
"get size() { return 0 }",
20+
"function max() { [native code] }",
21+
"function map() { [native code] }",
22+
"function bound declared() { [native code] }",
23+
"function fromAsync() { [native code] }",
24+
"[object Function]",
25+
"async (input) => { return input.x + 1 }",
26+
"TypeError"
27+
],
28+
"logs": [],
29+
"metadata": null
30+
}

‎rust/conformance/cases/std-array-to-locale-args.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
"2",
77
"2",
88
"2",
9-
"[object Function]",
9+
"(...a) => 1",
1010
"1/1/1970, 12:00:00 AM,1/1/1970, 12:00:00 AM",
1111
",,2",
1212
"n,n",

‎rust/conformance/cases/std-builtin-key-order.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"Buffer.prototype.__proto__": "constructor,BYTES_PER_ELEMENT,length,byteLength,byteOffset,at,slice,subarray,set,fill,reverse,sort,toSorted,toReversed,with,copyWithin,indexOf,lastIndexOf,includes,join,toString,toBase64,toHex,setFromBase64,setFromHex,keys,values,entries,map,filter,forEach,some,every,find,findIndex,findLast,findLastIndex,reduce,reduceRight",
88
"Buffer.prototype.__proto__.__proto__": "constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toString,toLocaleString,valueOf",
99
"Buffer.__proto__": "length,name,prototype,from,of,fromBase64,fromHex,BYTES_PER_ELEMENT",
10-
"Buffer.__proto__.__proto__": "length,name,call,apply,bind,caller,arguments,constructor",
10+
"Buffer.__proto__.__proto__": "length,name,toString,call,apply,bind,caller,arguments,constructor",
1111
"TextEncoder": "length,name,prototype",
1212
"TextEncoder.prototype": "encoding,encode,encodeInto,constructor",
1313
"TextDecoder": "length,name,prototype",

‎rust/conformance/cases/std-object-prototype-receivers.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@
206206
],
207207
[
208208
"toLocaleString",
209-
"[object Function]"
209+
"() => 1"
210210
],
211211
[
212212
"toLocaleString",

‎rust/crates/psychoscript/src/builtins/object.rs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ pub fn setup(vm: &mut Vm) {
5858
vm.methods(
5959
fp,
6060
&[
61+
("toString", 0, function_to_string),
6162
("call", 1, function_call),
6263
("apply", 2, function_apply),
6364
("bind", 1, function_bind),
@@ -1040,6 +1041,29 @@ fn function_receiver(vm: &mut Vm, this: &Value, method: &str) -> Result<(), Valu
10401041
)))
10411042
}
10421043

1044+
// A program function's source text as written; a built-in, host or bound function has none, so it gets the spec's
1045+
// NativeFunction form. Conversions such as `String(fn)` don't use it.
1046+
fn function_to_string(vm: &mut Vm, this: Value, _: &[Value], _: Id) -> Res {
1047+
function_receiver(vm, &this, "toString")?;
1048+
let Some(id) = this.as_obj() else {
1049+
return Err(vm.type_error("Function.prototype.toString called on incompatible receiver."));
1050+
};
1051+
let span = match &vm.heap[id as usize].kind {
1052+
Kind::Closure(c) => c.proto.text,
1053+
_ => None,
1054+
};
1055+
if let Some(text) = span.and_then(|[start, end]| vm.code.get(start as usize..end as usize)) {
1056+
let text = text.to_owned();
1057+
return Ok(vm.string_val(text));
1058+
}
1059+
let nk = vm.names.name;
1060+
let name = match vm.get_obj(id, nk) {
1061+
Value::Str(s) => vm.text(s).to_owned(),
1062+
_ => String::new(),
1063+
};
1064+
Ok(vm.string_val(format!("function {name}() {{ [native code] }}")))
1065+
}
1066+
10431067
fn function_call(vm: &mut Vm, this: Value, args: &[Value], callee: Id) -> Res {
10441068
function_receiver(vm, &this, "call")?;
10451069
let rest = if args.is_empty() { &[][..] } else { &args[1..] };

‎rust/crates/psychoscript/src/bytecode.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,9 @@ pub struct FuncProto {
317317
/// The source offsets of the object and the key of each member instruction whose errors may point at them
318318
/// instead of at the member, by the instruction's index, ascending.
319319
pub sites: Vec<(u32, [u32; 2])>,
320+
/// Where the function's source text starts and ends in the program, as `Function.prototype.toString` returns
321+
/// it; `None` for built-in or compiler-made code.
322+
pub text: Option<[u32; 2]>,
320323
}
321324

322325
impl FuncProto {

0 commit comments

Comments
 (0)