mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
js: collect template cache entries with unreachable code
This commit is contained in:
5 files changed
+32
-12
No files matched your search
@@ -483,6 +483,18 @@ fn tagged_templates_get_one_frozen_strings_object_for_each_site() {
|
||||
truth("function tag(s) { return s.raw.join('|'); } tag`a\r\nb${0}\\\r\nc` === 'a\\nb|\\\\\\nc'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreachable_closures_release_their_template_objects_in_one_collection() {
|
||||
let mut realm = es();
|
||||
assert_eq!(
|
||||
realm.run("function tag(value) { return value; } var site = function () { return tag`gone`; }; site(); site = null; 0"),
|
||||
Ok(JsValue::Number(0.0)),
|
||||
);
|
||||
assert_eq!(realm.interp().template_objects.len(), 1);
|
||||
realm.collect_garbage();
|
||||
assert_eq!(realm.interp().template_objects.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_objects_go_once_their_code_cannot_run() {
|
||||
// Each eval makes code with two template sites; once it has run, nothing can run that code.
|
||||
|
||||
+13
-3
@@ -536,7 +536,7 @@ impl Heap {
|
||||
|
||||
/// Marks everything reachable from `roots` and frees the rest. Afterwards [`Heap::bytes`] is
|
||||
/// the estimated size of what is left, strings reachable from it included.
|
||||
pub(crate) fn collect(&mut self, roots: &Roots<'_>) {
|
||||
pub(crate) fn collect(&mut self, roots: &Roots<'_>) -> HashSet<usize> {
|
||||
let mut marks = vec![false; self.cells.len()];
|
||||
let mut work: Vec<u32> = Vec::new();
|
||||
let mut strings = StringSizes::default();
|
||||
@@ -549,7 +549,13 @@ impl Heap {
|
||||
for code in &roots.codes {
|
||||
mark_code(code, &mut strings);
|
||||
}
|
||||
while let Some(i) = work.pop() {
|
||||
let mut reached_codes = 0;
|
||||
loop {
|
||||
while let Some(&code) = strings.codes.get(reached_codes) {
|
||||
reached_codes += 1;
|
||||
work.extend(roots.template_objects.get(&code).into_iter().flatten().map(|id| id.0));
|
||||
}
|
||||
let Some(i) = work.pop() else { break };
|
||||
let Some(mark) = marks.get_mut(i as usize) else { continue };
|
||||
if *mark {
|
||||
continue;
|
||||
@@ -569,6 +575,7 @@ impl Heap {
|
||||
}
|
||||
self.bytes = live + strings.bytes;
|
||||
self.collections += 1;
|
||||
strings.codes.into_iter().collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -579,6 +586,7 @@ pub(crate) struct Roots<'a> {
|
||||
pub(crate) objects: Vec<ObjId>,
|
||||
pub(crate) envs: Vec<EnvId>,
|
||||
pub(crate) codes: Vec<&'a Code>,
|
||||
pub(crate) template_objects: HashMap<usize, Vec<ObjId>>,
|
||||
}
|
||||
|
||||
/// Sums the sizes of the strings and property names reached, counting each node and each
|
||||
@@ -586,6 +594,7 @@ pub(crate) struct Roots<'a> {
|
||||
#[derive(Default)]
|
||||
struct StringSizes {
|
||||
seen: HashSet<usize>,
|
||||
codes: Vec<usize>,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
@@ -661,6 +670,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
|
||||
if !strings.seen.insert(code as *const Code as usize) {
|
||||
continue;
|
||||
}
|
||||
strings.codes.push(code as *const Code as usize);
|
||||
if strings.seen.insert(Rc::as_ptr(&code.source) as usize) {
|
||||
strings.bytes += code.source.lines.heap_bytes();
|
||||
// The text can share its buffer with the string eval was given.
|
||||
@@ -845,7 +855,7 @@ mod tests {
|
||||
object.props.insert(name.clone(), Prop::Data { value: Value::String(Str::from_rc(name.clone())), flags: 0 });
|
||||
object.props.insert(key("other"), Prop::Data { value: Value::Undefined, flags: 0 });
|
||||
let id = heap.alloc_object(object);
|
||||
heap.collect(&Roots { objects: vec![id], ..Roots::default() });
|
||||
let _ = heap.collect(&Roots { objects: vec![id], ..Roots::default() });
|
||||
assert_eq!(heap.bytes, OBJECT_BYTES + 2 * PROP_BYTES + string_bytes(1000) + string_bytes(5));
|
||||
}
|
||||
|
||||
|
||||
@@ -911,16 +911,12 @@ impl Interp {
|
||||
roots.envs.push(self.global_env);
|
||||
roots.envs.push(self.global_lex);
|
||||
roots.envs.extend(self.temp_envs.iter().copied());
|
||||
// A template object stays while its code can still run: while the code has an owner other
|
||||
// than the entries of its own sites.
|
||||
let mut sites: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
|
||||
for &(code, _) in self.template_objects.keys() {
|
||||
*sites.entry(code).or_default() += 1;
|
||||
for (&(code, _), &(_, object)) in &self.template_objects {
|
||||
roots.template_objects.entry(code).or_default().push(object);
|
||||
}
|
||||
self.template_objects.retain(|(site, _), (code, _)| Rc::strong_count(code) > sites.get(site).copied().unwrap_or(0));
|
||||
roots.objects.extend(self.template_objects.values().map(|&(_, id)| id));
|
||||
self.promises.add_roots(&mut roots);
|
||||
self.heap.collect(&roots);
|
||||
let live_codes = self.heap.collect(&roots);
|
||||
self.template_objects.retain(|(code, _), _| live_codes.contains(code));
|
||||
crate::host_classes::forget_collected(&mut self.host_objects, &self.heap, &self.host_classes);
|
||||
// The collection counts the live total again, so bytes already released are not in it.
|
||||
self.held.released.set(0);
|
||||
|
||||
+2
-1
@@ -2736,7 +2736,8 @@ https://ecma-international.org/publications-and-standards/standards/ecma-357/):
|
||||
(https://extendscript.docsforadobe.dev/integrating-xml/the-xml-object/). A script run from a `.js` file also has
|
||||
`Promise` (described below); a `.jsx` file and a script given as `source` do not, except that a named engine
|
||||
(`#targetengine`) has `Promise` from the first `.js` run that names it and keeps it for every later run, as it keeps
|
||||
its globals. The script reaches the app through the global object `vc`, and writes to the Script Console and runs
|
||||
its globals. The collector retains tagged-template cache entries only while the site's code is reachable.
|
||||
The script reaches the app through the global object `vc`, and writes to the Script Console and runs
|
||||
other files through `$`:
|
||||
|
||||
- `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can
|
||||
|
||||
@@ -1112,6 +1112,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`).
|
||||
- `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread uses the iterator protocol (see the `for`-`of` line below). Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
The collector retains tagged-template cache entries only while the site's code is reachable.
|
||||
- `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`.
|
||||
- `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
|
||||
Reference in new issue
Block a user