From 9ab0a490ac83c9bb8c6a899e27ac47172e07c379 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:00:59 -0800 Subject: [PATCH 01/50] JavaScript: Proxy and Reflect in ECMAScript 2015 realms A realm made with Options::es2015 has Proxy, with Proxy.revocable, and Reflect with its thirteen functions (ECMA-262 11th edition, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, in, delete, for-in, the Object functions, instanceof, calls and new, and when the proxy is a prototype or a with object. Array.isArray, concat and JSON.stringify treat a proxy of an array as an array. - Each trap result is checked against the target's invariants, and a violation or an operation on a revoked proxy throws a TypeError. - Traps take fuel and count against the limit on nested calls. - A proxy given to a host function throws a TypeError naming the argument, without running its traps. - Reflect.construct gives a built-in's result the prototype of newTarget, and Object with a different newTarget makes a new object. - for-in skips a name deleted or made non-enumerable during the loop, and does not ask a has trap. - Descriptor values a trap returns stay rooted while they are read. script.run gives a .js file both globals; a .jsx file and a source string have neither. cargo xtask test262 runs the suite's Proxy and Reflect tests whose features are present. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/tests/script_run.rs | 25 ++ crates/js/src/builtins.rs | 46 +- crates/js/src/builtins/array.rs | 40 +- crates/js/src/builtins/json.rs | 11 +- crates/js/src/builtins/object.rs | 102 +++-- crates/js/src/builtins/reflect.rs | 212 +++++++++ crates/js/src/file_classes.rs | 5 +- crates/js/src/heap.rs | 25 +- crates/js/src/host.rs | 3 + crates/js/src/interp.rs | 455 +++++++++++++++++--- crates/js/src/lib.rs | 9 +- crates/js/src/proxy.rs | 593 ++++++++++++++++++++++++++ crates/js/src/proxy_tests.rs | 439 +++++++++++++++++++ crates/js/tests/test262.rs | 93 ++++ docs/mcp.md | 7 +- docs/target-app-parity.md | 1 + 16 files changed, 1925 insertions(+), 141 deletions(-) create mode 100644 crates/js/src/builtins/reflect.rs create mode 100644 crates/js/src/proxy.rs create mode 100644 crates/js/src/proxy_tests.rs diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 7b0e4bc2f8..10eca3a3f4 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -331,6 +331,31 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_has_proxy_and_reflect_and_a_jsx_script_does_not() { + let dir = fresh_folder("proxy"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + json!({"path": p.to_string_lossy()}) + }; + let mut s = two_docs(); + let names = "vc.log(typeof Proxy + ' ' + typeof Reflect);"; + let modern = s.execute("script.run", &write("names.js", names)).unwrap(); + assert_eq!(modern["log"], json!(["function object"]), "{modern}"); + let legacy = s.execute("script.run", &write("names.jsx", names)).unwrap(); + assert_eq!(legacy["log"], json!(["undefined undefined"]), "{legacy}"); + assert_eq!(run(&mut s, names).unwrap()["log"], json!(["undefined undefined"])); + // A proxy given to the app is refused by name, and its traps do not run. + let given = "var ran = false;\nvar p = new Proxy({}, { ownKeys: function () { ran = true; return []; } });\n\ + try { vc.run('document.list', p); } catch (e) { vc.log(e.name + ': ' + e.message); }\nvc.log(ran);"; + let r = s.execute("script.run", &write("given.js", given)).unwrap(); + let log = r["log"].as_array().unwrap(); + assert!(log[0].as_str().is_some_and(|m| m.starts_with("TypeError") && m.contains("is a proxy")), "{r}"); + assert_eq!(log[1], json!(false), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A new empty folder for test `name`. fn fresh_folder(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index f2c02bdf4c..1513b59919 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,7 +3,8 @@ //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex //! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with //! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. +//! their own modules. A realm with [`crate::Options::es2015`] also has `Proxy` and `Reflect` (in +//! `reflect`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can @@ -14,7 +15,8 @@ pub(crate) mod extensions; mod global; mod json; mod math; -mod object; +pub(crate) mod object; +mod reflect; use std::rc::Rc; @@ -112,6 +114,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { data(interp, global, "eval", Value::Object(eval), HIDDEN)?; let object = native(interp, "Object", object_ctor, 1, NativeKind::Plain, true)?; + interp.intrinsics.object_ctor = object; constructor(interp, "Object", object, object_proto)?; method(interp, object_proto, "toString", object_to_string, 0)?; method(interp, object_proto, "toLocaleString", object_to_locale_string, 0)?; @@ -145,6 +148,9 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.e4x { crate::xml_builtins::install(interp)?; } + if interp.options.es2015 { + reflect::install(interp)?; + } Ok(()) } @@ -382,6 +388,15 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J let class = match &this { Value::Undefined => "Undefined", Value::Null => "Null", + // A proxy reads as an array when its target is one, and a revoked proxy is a + // `TypeError` (ECMA-262 2020 section 19.1.3.6). + Value::Object(o) if interp.is_proxy(*o) => { + if interp.is_array(&this)? { + "Array" + } else { + interp.heap.object(*o).map_or("Object", |o| o.class.name()) + } + } _ => { let o = interp.to_object(&this)?; interp.heap.object(o).map_or("Object", |o| o.class.name()) @@ -436,17 +451,33 @@ fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some())) } +/// `Object.prototype.isPrototypeOf` (section 15.2.4.6). The chain is read with +/// [[GetPrototypeOf]], so a proxy on it answers with its trap; the object being read and `this` +/// stay rooted. fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let Value::Object(mut v) = arg(args, 0) else { return Ok(Value::Bool(false)) }; let o = interp.to_object(&this)?; - while let Some(p) = interp.heap.object(v).and_then(|v| v.proto) { + let slot = interp.temp_roots.len(); + interp.temp_roots.extend([Value::Object(o), Value::Object(v)]); + let r = loop { + let p = match interp.get_prototype_of(v) { + Ok(Some(p)) => p, + Ok(None) => break Ok(Value::Bool(false)), + Err(e) => break Err(e), + }; if p == o { - return Ok(Value::Bool(true)); + break Ok(Value::Bool(true)); } v = p; - interp.use_fuel()?; - } - Ok(Value::Bool(false)) + if let Some(root) = interp.temp_roots.get_mut(slot + 1) { + *root = Value::Object(v); + } + if let Err(e) = interp.use_fuel() { + break Err(e); + } + }; + interp.temp_roots.truncate(slot); + r } fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -526,6 +557,7 @@ fn function_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Some(Func::Native { name, .. } | Func::Pausable { name, .. }) => format!("function {name}() {{ [native code] }}"), Some(Func::Host { name, .. } | Func::Data { name, .. } | Func::Eval { name, .. }) => format!("function {name}() {{ [native code] }}"), Some(Func::Bound { .. }) => "function () { [native code] }".to_string(), + None if interp.is_callable(&this) => "function () { [native code] }".to_string(), None => return Err(interp.type_error("Function.prototype.toString was called on a value that is not a function")), }; Ok(Value::str(&text)) diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index bfb4de5eac..655a3e81c8 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -97,26 +97,32 @@ fn numeric_index(k: &[u16]) -> Option { } /// The objects of the prototype chain from `obj`, with how many properties (and String object -/// indices) each holds. -fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> { +/// indices) each holds, or `None` when a proxy is on the chain: its traps decide which indices it +/// has, so every index is visited. +fn chain(interp: &Interp, obj: ObjId) -> Option> { let mut out = Vec::new(); let mut cur = Some(obj); while let Some(id) = cur { + if interp.is_proxy(id) { + return None; + } let Some(o) = interp.heap.object(id) else { break }; let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; out.push((id, o.props.len().saturating_add(string_len))); cur = o.proto; } - out + Some(out) } impl Indices { fn new(interp: &mut Interp, obj: ObjId, lo: u64, hi: u64, ascending: bool, maps: Vec) -> JsResult { let mut it = Indices { obj, lo, hi, ascending, maps, sparse: None }; - if hi.saturating_sub(lo) > DENSE_SPAN { - let present: usize = chain(interp, obj).iter().map(|(_, n)| *n).fold(0, usize::saturating_add); + if hi.saturating_sub(lo) > DENSE_SPAN + && let Some(links) = chain(interp, obj) + { + let present: usize = links.iter().map(|(_, n)| *n).fold(0, usize::saturating_add); if hi - lo > (present as u64).saturating_mul(8) { - it.sparse = Some(it.gather(interp)?); + it.sparse = it.gather(interp)?; } } Ok(it) @@ -130,12 +136,13 @@ impl Indices { Self::new(interp, obj, lo, hi, false, vec![Map::Shift(0)]) } - /// Lists the indices left to visit from the properties of the object and its prototypes. - /// Each property takes a unit of fuel. - fn gather(&self, interp: &mut Interp) -> JsResult { + /// Lists the indices left to visit from the properties of the object and its prototypes, or + /// gives `None` when a proxy is on the chain. Each property takes a unit of fuel. + fn gather(&self, interp: &mut Interp) -> JsResult> { let epoch = interp.heap.index_epoch; let mut list: Vec = Vec::new(); - for (id, n) in chain(interp, self.obj) { + let Some(links) = chain(interp, self.obj) else { return Ok(None) }; + for (id, n) in links { for _ in 0..n { interp.use_fuel()?; } @@ -164,7 +171,7 @@ impl Indices { list.sort_unstable_by(|a, b| b.cmp(a)); } list.dedup(); - Ok(Sparse { list, pos: 0, epoch }) + Ok(Some(Sparse { list, pos: 0, epoch })) } /// The next index to visit; it takes a unit of fuel. @@ -173,7 +180,7 @@ impl Indices { return Ok(None); } if self.sparse.as_ref().is_some_and(|s| s.epoch != interp.heap.index_epoch) { - self.sparse = Some(self.gather(interp)?); + self.sparse = self.gather(interp)?; } let k = match &mut self.sparse { None if self.ascending => self.lo, @@ -244,10 +251,10 @@ fn array_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResul }) } -/// `Array.isArray` (section 15.4.3.2). +/// `Array.isArray` (section 15.4.3.2). A proxy whose target is an array is one, and a revoked +/// proxy is a `TypeError` (ECMA-262 2020 section 7.2.2). fn is_array(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - let a = arg(args, 0).as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Array { .. })); - Ok(Value::Bool(a)) + interp.is_array(&arg(args, 0)).map(Value::Bool) } // ---- conversions ---- @@ -355,7 +362,8 @@ fn concat(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult let mut n = 0u64; for e in std::iter::once(Value::Object(o)).chain(args.iter().cloned()) { interp.use_fuel()?; - let spread = e.as_object().filter(|&id| interp.heap.object(id).is_some_and(|x| matches!(x.class, Class::Array { .. }))); + // A proxy whose target is an array is spread too (ECMA-262 2020 section 22.1.3.1.1). + let spread = if interp.is_array(&e)? { e.as_object() } else { None }; let Some(e) = spread else { create_at(interp, a, n as f64, e)?; n += 1; diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 364ec99696..9089595ac7 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -336,7 +336,7 @@ fn enter(interp: &mut Interp, holder: ObjId, name: Key) -> JsResult { interp.temp_roots.push(val.clone()); let mut keys = Vec::new(); if let Value::Object(o) = val { - if interp.heap.object(o).is_some_and(|x| matches!(x.class, Class::Array { .. })) { + if interp.is_array(&val)? { let len = length_of(interp, o)?; interp.reserve_heap((len as usize).saturating_mul(crate::heap::PROP_BYTES))?; for i in 0..len { @@ -464,7 +464,7 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult let mut cur = Some(o); while let Some(id) = cur { interp.use_fuel()?; + // Past a proxy the answer is its traps'; the caller then converts the value the long way. + if interp.is_proxy(id) { + return Ok(false); + } if interp.get_own_property(id, &k)?.is_some() { return Ok(false); } @@ -648,7 +652,8 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J if w.open.contains(&o) { return Err(interp.type_error("JSON.stringify cannot write a structure that contains itself")); } - let array = interp.heap.object(o).is_some_and(|x| matches!(x.class, Class::Array { .. })); + // A proxy whose target is an array is written as one (ECMA-262 2020 section 24.5.2.1). + let array = interp.is_array(&Value::Object(o))?; let keys = if array { let len = length_of(interp, o)?; // Every element is written as at least `null` and a comma, so a length that cannot fit diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index af41bb7782..69ba8fea1f 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -7,6 +7,7 @@ use super::{ELEMENT_BYTES, arg, create_at, method, new_array}; use crate::heap::{CONFIGURABLE, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, WRITABLE, key}; use crate::interp::{Desc, Interp, JsResult}; +use crate::proxy::desc_values; use crate::value::{Str, Value}; pub(super) fn install(interp: &mut Interp, object: ObjId) -> JsResult<()> { @@ -32,16 +33,8 @@ fn require_object(interp: &mut Interp, v: &Value, function: &str) -> JsResult Vec { - let mut out: Vec = desc.value.iter().cloned().collect(); - out.extend(desc.get.flatten().map(Value::Object)); - out.extend(desc.set.flatten().map(Value::Object)); - out -} - /// ToPropertyDescriptor (section 8.10.5). -pub(super) fn to_desc(interp: &mut Interp, v: &Value) -> JsResult { +pub(crate) fn to_desc(interp: &mut Interp, v: &Value) -> JsResult { let Value::Object(o) = v else { return Err(interp.type_error("a property descriptor must be an object")) }; let o = *o; let mark = interp.temp_roots.len(); @@ -87,8 +80,41 @@ fn read_desc(interp: &mut Interp, o: ObjId) -> JsResult { Ok(desc) } -/// FromPropertyDescriptor (section 8.10.4). -fn from_prop(interp: &mut Interp, prop: &Prop) -> JsResult { +/// FromPropertyDescriptor (ECMA-262 2020 section 6.2.5.4) of a descriptor that may leave fields +/// out: an object with the fields `desc` has, in the order `value`, `writable`, `get`, `set`, +/// `enumerable`, `configurable`. +pub(crate) fn from_desc(interp: &mut Interp, desc: &Desc) -> JsResult { + let roots = desc_values(desc); + interp.rooted(&roots, |interp| interp.reserve_heap(OBJECT_BYTES + 6 * ELEMENT_BYTES))?; + let o = interp.new_object(); + let fields = [ + ("value", desc.value.clone()), + ("writable", desc.writable.map(Value::Bool)), + ("get", desc.get.map(|g| g.map_or(Value::Undefined, Value::Object))), + ("set", desc.set.map(|s| s.map_or(Value::Undefined, Value::Object))), + ("enumerable", desc.enumerable.map(Value::Bool)), + ("configurable", desc.configurable.map(Value::Bool)), + ]; + for (name, v) in fields { + if let Some(v) = v { + interp.define(o, key(name), Prop::Data { value: v, flags: OPEN })?; + } + } + Ok(Value::Object(o)) +} + +/// FromPropertyDescriptor (section 8.10.4). The property's values stay rooted while the +/// descriptor object is made, since a proxy's trap can give values no other object holds. +pub(crate) fn from_prop(interp: &mut Interp, prop: &Prop) -> JsResult { + let roots: Vec = match prop { + Prop::Data { value, .. } => vec![value.clone()], + Prop::Accessor { get, set, .. } => get.iter().chain(set).map(|f| Value::Object(*f)).collect(), + }; + interp.rooted(&roots, |interp| descriptor_object(interp, prop)) +} + +/// The descriptor object of `prop`, whose values the caller keeps rooted. +fn descriptor_object(interp: &mut Interp, prop: &Prop) -> JsResult { interp.reserve_heap(OBJECT_BYTES + 4 * ELEMENT_BYTES)?; let o = interp.new_object(); let flags = prop.flags(); @@ -108,7 +134,7 @@ fn from_prop(interp: &mut Interp, prop: &Prop) -> JsResult { } /// An array of the names, kept reachable while it is filled. -fn names_array(interp: &mut Interp, names: Vec) -> JsResult { +pub(crate) fn names_array(interp: &mut Interp, names: Vec) -> JsResult { let a = new_array(interp, 0)?; interp.rooted(&[Value::Object(a)], |interp| { for (i, k) in names.into_iter().enumerate() { @@ -122,7 +148,7 @@ fn names_array(interp: &mut Interp, names: Vec) -> JsResult { /// `Object.getPrototypeOf` (section 15.2.3.2). fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; - Ok(interp.heap.object(o).and_then(|o| o.proto).map_or(Value::Null, Value::Object)) + Ok(interp.rooted(&[Value::Object(o)], |interp| interp.get_prototype_of(o))?.map_or(Value::Null, Value::Object)) } /// `Object.getOwnPropertyDescriptor` (section 15.2.3.3). @@ -210,32 +236,28 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { r } -/// Makes every own property non-configurable, and with `freeze` every data property read-only, -/// then makes the object non-extensible (sections 15.2.3.8 and 15.2.3.9). +/// SetIntegrityLevel (ECMA-262 2020 section 7.3.14): makes the object non-extensible, then every +/// own property non-configurable, and with `freeze` every data property read-only (sections +/// 15.2.3.8 and 15.2.3.9). A proxy that does not become non-extensible is a `TypeError`. fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { let Value::Object(o) = v else { return Ok(v) }; + if !interp.prevent_extensions(o)? { + let what = if freeze { "frozen" } else { "sealed" }; + return Err(interp.type_error(&format!("the object cannot be {what}: it did not stop being extensible"))); + } for k in interp.own_keys(o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_property(o, &k)? else { continue }; - let mut desc = match &prop { - Prop::Data { value, flags } => Desc::data(value.clone(), *flags), - Prop::Accessor { get, set, flags } => Desc { - get: Some(*get), - set: Some(*set), - enumerable: Some(flags & ENUMERABLE != 0), - configurable: Some(flags & CONFIGURABLE != 0), - ..Desc::default() - }, + let desc = if freeze { + let Some(prop) = interp.get_own_property(o, &k)? else { continue }; + match prop { + Prop::Data { .. } => Desc { configurable: Some(false), writable: Some(false), ..Desc::default() }, + Prop::Accessor { .. } => Desc { configurable: Some(false), ..Desc::default() }, + } + } else { + Desc { configurable: Some(false), ..Desc::default() } }; - desc.configurable = Some(false); - if freeze && desc.is_data() { - desc.writable = Some(false); - } interp.define_own_property(o, k, &desc, true)?; } - if let Some(obj) = interp.heap.object_mut(o) { - obj.extensible = false; - } Ok(Value::Object(o)) } @@ -251,18 +273,22 @@ fn freeze(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let v = arg(args, 0); if let Value::Object(o) = v - && let Some(obj) = interp.heap.object_mut(o) + && !interp.prevent_extensions(o)? { - obj.extensible = false; + return Err(interp.type_error("Object.preventExtensions: the proxy did not stop being extensible")); } Ok(v) } -/// Whether no own property is configurable (and with `frozen`, no data property is writable) -/// and the object is not extensible (sections 15.2.3.11 and 15.2.3.12). +/// TestIntegrityLevel (ECMA-262 2020 section 7.3.15): whether the object is not extensible and no +/// own property is configurable (and with `frozen`, no data property is writable) (sections +/// 15.2.3.11 and 15.2.3.12). fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let Value::Object(o) = v else { return Ok(Value::Bool(true)) }; let o = *o; + if interp.is_extensible(o)? { + return Ok(Value::Bool(false)); + } for k in interp.own_keys(o)? { interp.use_fuel()?; let Some(prop) = interp.get_own_property(o, &k)? else { continue }; @@ -270,7 +296,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { return Ok(Value::Bool(false)); } } - Ok(Value::Bool(!interp.heap.object(o).is_some_and(|o| o.extensible))) + Ok(Value::Bool(true)) } fn is_sealed(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { @@ -284,7 +310,7 @@ fn is_frozen(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult /// `Object.isExtensible` (section 15.2.3.13). fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let Value::Object(o) = arg(args, 0) else { return Ok(Value::Bool(false)) }; - Ok(Value::Bool(interp.heap.object(o).is_some_and(|o| o.extensible))) + interp.is_extensible(o).map(Value::Bool) } /// `Object.keys` (section 15.2.3.14). diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs new file mode 100644 index 0000000000..bd2352132f --- /dev/null +++ b/crates/js/src/builtins/reflect.rs @@ -0,0 +1,212 @@ +//! `Proxy` and `Reflect` (ECMA-262 2020 sections 26.2 and 26.1, +//! ), installed in a realm with +//! [`crate::Options::es2015`]. The proxy objects themselves are in `crate::proxy`. + +use std::rc::Rc; + +use super::object::{from_prop, names_array, to_desc}; +use super::{arg, data, method, native}; +use crate::heap::{Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key}; +use crate::interp::{Desc, Interp, JsResult}; +use crate::proxy::desc_values; +use crate::value::Value; + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + let global = interp.global; + let proxy = native(interp, "Proxy", proxy_ctor, 2, NativeKind::Plain, true)?; + method(interp, proxy, "revocable", revocable, 2)?; + data(interp, global, "Proxy", Value::Object(proxy), HIDDEN)?; + + let object_proto = interp.intrinsics.object_proto; + let reflect = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + data(interp, global, "Reflect", Value::Object(reflect), HIDDEN)?; + method(interp, reflect, "apply", apply, 3)?; + method(interp, reflect, "construct", construct, 2)?; + method(interp, reflect, "defineProperty", define_property, 3)?; + method(interp, reflect, "deleteProperty", delete_property, 2)?; + method(interp, reflect, "get", get, 2)?; + method(interp, reflect, "getOwnPropertyDescriptor", get_own_property_descriptor, 2)?; + method(interp, reflect, "getPrototypeOf", get_prototype_of, 1)?; + method(interp, reflect, "has", has, 2)?; + method(interp, reflect, "isExtensible", is_extensible, 1)?; + method(interp, reflect, "ownKeys", own_keys, 1)?; + method(interp, reflect, "preventExtensions", prevent_extensions, 1)?; + method(interp, reflect, "set", set, 3)?; + method(interp, reflect, "setPrototypeOf", set_prototype_of, 2) +} + +// ---- Proxy ---- + +/// `new Proxy(target, handler)` (section 26.2.1.1). Calling it without `new` is a `TypeError`. +fn proxy_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + if !constructing { + return Err(interp.type_error("Proxy must be called with new")); + } + interp.proxy_create(&arg(args, 0), &arg(args, 1)).map(Value::Object) +} + +/// `Proxy.revocable(target, handler)` (section 26.2.2.1): an object whose `proxy` is a new proxy +/// and whose `revoke` function revokes it. The function holds the proxy as the `this` of a bound +/// call to [`revoke`], and calling it again does nothing. +fn revocable(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let p = interp.proxy_create(&arg(args, 0), &arg(args, 1))?; + interp.rooted(&[Value::Object(p)], |interp| { + interp.reserve_heap(3 * OBJECT_BYTES)?; + let inner = native(interp, "", revoke, 0, NativeKind::Plain, false)?; + let proto = interp.intrinsics.function_proto; + let class = Class::Function(Func::Bound { target: inner, this: Value::Object(p), args: Rc::from(Vec::new()) }); + let f = interp.heap.alloc_object(Object::new(class, Some(proto))); + interp.define(f, key("length"), Prop::Data { value: Value::Number(0.0), flags: 0 })?; + let result = interp.new_object(); + interp.define(result, key("proxy"), Prop::Data { value: Value::Object(p), flags: OPEN })?; + interp.define(result, key("revoke"), Prop::Data { value: Value::Object(f), flags: OPEN })?; + Ok(Value::Object(result)) + }) +} + +/// A revocation function's call (section 26.2.2.1.1): `this` is the proxy it revokes. +fn revoke(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + if let Value::Object(p) = this { + interp.proxy_revoke(p); + } + Ok(Value::Undefined) +} + +// ---- Reflect ---- + +/// The `target` argument of a `Reflect` function, which must be an object. +fn target(interp: &mut Interp, args: &[Value], function: &str) -> JsResult { + match arg(args, 0) { + Value::Object(o) => Ok(o), + _ => Err(interp.type_error(&format!("Reflect.{function}: the target is not an object"))), + } +} + +/// CreateListFromArrayLike (section 7.3.17) of an argument list, which must be an object. +fn argument_list(interp: &mut Interp, list: &Value, function: &str) -> JsResult> { + if !matches!(list, Value::Object(_)) { + return Err(interp.type_error(&format!("Reflect.{function}: the argument list is not an object"))); + } + interp.list_from_array_like(list) +} + +/// `Reflect.apply(target, thisArgument, argumentsList)` (section 26.1.1). +fn apply(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let f = arg(args, 0); + if !interp.is_callable(&f) { + return Err(interp.type_error("Reflect.apply: the target is not a function")); + } + let list = argument_list(interp, &arg(args, 2), "apply")?; + let mark = interp.temp_roots.len(); + interp.temp_roots.extend(list.iter().cloned()); + let r = interp.call(&f, &arg(args, 1), &list); + interp.temp_roots.truncate(mark); + r +} + +/// `Reflect.construct(target, argumentsList[, newTarget])` (section 26.1.2). Without +/// `newTarget` the target is constructed with its own prototype. A constructor written in +/// JavaScript gives its new object the `prototype` of `newTarget`; a built-in constructor makes +/// its object as it does for `new`. +fn construct(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let f = arg(args, 0); + if !interp.is_constructor(&f) { + return Err(interp.type_error("Reflect.construct: the target is not a constructor")); + } + let new_target = if args.len() > 2 { arg(args, 2) } else { f.clone() }; + if !interp.is_constructor(&new_target) { + return Err(interp.type_error("Reflect.construct: newTarget is not a constructor")); + } + let list = argument_list(interp, &arg(args, 1), "construct")?; + let mark = interp.temp_roots.len(); + interp.temp_roots.extend(list.iter().cloned()); + let r = interp.construct(&f, &list, &new_target); + interp.temp_roots.truncate(mark); + r +} + +/// `Reflect.defineProperty(target, propertyKey, attributes)` (section 26.1.3): whether the +/// property was defined. +fn define_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = target(interp, args, "defineProperty")?; + interp.with_key(&arg(args, 1), |interp, k| { + let desc: Desc = to_desc(interp, &arg(args, 2))?; + let roots = desc_values(&desc); + interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, false)).map(Value::Bool) + }) +} + +/// `Reflect.deleteProperty(target, propertyKey)` (section 26.1.4): whether the property is gone. +fn delete_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = target(interp, args, "deleteProperty")?; + interp.with_key(&arg(args, 1), |interp, k| interp.delete(o, &k, false)).map(Value::Bool) +} + +/// `Reflect.get(target, propertyKey[, receiver])` (section 26.1.5). +fn get(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = target(interp, args, "get")?; + let receiver = if args.len() > 2 { arg(args, 2) } else { Value::Object(o) }; + interp.with_key(&arg(args, 1), |interp, k| interp.get_from(o, &k, &receiver)) +} + +/// `Reflect.getOwnPropertyDescriptor(target, propertyKey)` (section 26.1.6). +fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = target(interp, args, "getOwnPropertyDescriptor")?; + interp.with_key(&arg(args, 1), |interp, k| match interp.get_own_property(o, &k)? { + Some(p) => from_prop(interp, &p), + None => Ok(Value::Undefined), + }) +} + +/// `Reflect.getPrototypeOf(target)` (section 26.1.7). +fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = target(interp, args, "getPrototypeOf")?; + Ok(interp.get_prototype_of(o)?.map_or(Value::Null, Value::Object)) +} + +/// `Reflect.has(target, propertyKey)` (section 26.1.8). +fn has(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = target(interp, args, "has")?; + interp.with_key(&arg(args, 1), |interp, k| interp.has_property(o, &k)).map(Value::Bool) +} + +/// `Reflect.isExtensible(target)` (section 26.1.9). +fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = target(interp, args, "isExtensible")?; + interp.is_extensible(o).map(Value::Bool) +} + +/// `Reflect.ownKeys(target)` (section 26.1.10): every own property name, enumerable or not. +fn own_keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = target(interp, args, "ownKeys")?; + let names = interp.own_keys(o)?; + names_array(interp, names) +} + +/// `Reflect.preventExtensions(target)` (section 26.1.11): whether the object is now not +/// extensible. +fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = target(interp, args, "preventExtensions")?; + interp.prevent_extensions(o).map(Value::Bool) +} + +/// `Reflect.set(target, propertyKey, V[, receiver])` (section 26.1.12): whether the value was +/// set. +fn set(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = target(interp, args, "set")?; + let receiver = if args.len() > 3 { arg(args, 3) } else { Value::Object(o) }; + let v = arg(args, 2); + interp.with_key(&arg(args, 1), |interp, k| interp.set_with_receiver(o, k, v, &receiver)).map(Value::Bool) +} + +/// `Reflect.setPrototypeOf(target, proto)` (section 26.1.13): whether the prototype was set. A +/// `proto` that is neither an object nor `null` is a `TypeError`. +fn set_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let o = target(interp, args, "setPrototypeOf")?; + let proto = match arg(args, 1) { + Value::Object(p) => Some(p), + Value::Null => None, + _ => return Err(interp.type_error("Reflect.setPrototypeOf: the prototype is neither an object nor null")), + }; + interp.set_prototype_of(o, proto).map(Value::Bool) +} diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 30de04cf12..a634c7fffd 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -84,9 +84,10 @@ fn field(i: &mut Interp, v: &Value, name: &str) -> JsResult { } } -/// The value of the own data property `name` of `o`, `undefined` when it has none. +/// The value of the own data property `name` of `o`, `undefined` when it has none. A proxy's +/// traps do not run: a proxy has no such property. fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { - Ok(match i.get_own_property(o, &key(name))? { + Ok(match i.ordinary_own_property(o, &key(name))? { Some(Prop::Data { value, .. }) => value, _ => Value::Undefined, }) diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 0750204403..9304c95921 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,19 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// A proxy (ECMA-262 2020 section 9.5), made by `Proxy` in a realm with + /// [`crate::Options::es2015`]. + Proxy(Box), +} + +/// A proxy's target and handler, `None` once it is revoked, and whether it can be called and +/// constructed, which its target decided when it was made. +#[derive(Clone, Copy, Debug)] +pub(crate) struct ProxyData { + pub(crate) target: Option, + pub(crate) handler: Option, + pub(crate) callable: bool, + pub(crate) constructor: bool, } /// What an XML value is. @@ -322,6 +335,8 @@ impl Class { Class::String(_) => "String", Class::RegExp(_) => "RegExp", Class::Date(_) => "Date", + Class::Proxy(p) if p.callable => "Function", + Class::Proxy(_) => "Object", } } } @@ -415,6 +430,8 @@ pub(crate) const XML_LIST_BYTES: usize = 96; pub(crate) const XML_REF_BYTES: usize = 8; /// The estimated bytes of a namespace an XML node holds. pub(crate) const XML_NS_BYTES: usize = 48; +/// The estimated bytes of a proxy's target, handler and flags. +pub(crate) const PROXY_BYTES: usize = 32; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; @@ -432,8 +449,8 @@ pub(crate) struct Heap { /// How many collections have run. pub(crate) collections: usize, /// Counts the properties whose names start with a digit (the array indices among them) added - /// to any object, so an operation that lists the indices an object has can tell whether a - /// script added one since. + /// to any object, and the prototypes changed, so an operation that lists the indices an object + /// and its prototypes have can tell whether a script added one since. pub(crate) index_epoch: u64, } @@ -708,6 +725,10 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::Proxy(p) => { + work.extend(p.target.iter().chain(&p.handler).map(|o| o.0)); + extra = PROXY_BYTES; + } _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4c18d0f76f..92e8fa86cb 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -263,6 +263,9 @@ impl Interp { } Shape::Plain(o.props.iter().filter(|(_, p)| p.enumerable()).map(|(k, p)| (k.clone(), p.clone())).collect()) } + // A host reads plain data without running script, so a proxy, whose traps are script, + // is refused, as is any other object that is not plain data. + Class::Proxy(_) => return Err(self.data_error(r, ErrorType::Type, "is a proxy, not plain data")), other => { let what = format!("is a {}, not plain data", other.name()); return Err(self.data_error(r, ErrorType::Type, &what)); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 1030101bab..23deea9a9c 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -101,6 +101,8 @@ pub(crate) struct Intrinsics { pub(crate) error_protos: [ObjId; 7], pub(crate) eval: ObjId, pub(crate) throw_type_error: ObjId, + /// The `Object` constructor, which makes a new object for a different `newTarget`. + pub(crate) object_ctor: ObjId, /// The `XML` constructor, which holds the XML settings. pub(crate) xml_ctor: ObjId, pub(crate) xml_proto: ObjId, @@ -124,6 +126,7 @@ impl Intrinsics { error_protos: [o; 7], eval: o, throw_type_error: o, + object_ctor: o, xml_ctor: o, xml_proto: o, xml_list_proto: o, @@ -157,6 +160,7 @@ impl Intrinsics { self.date_proto, self.eval, self.throw_type_error, + self.object_ctor, self.xml_ctor, self.xml_proto, self.xml_list_proto, @@ -386,7 +390,7 @@ const MIN_GC_BYTES: usize = 1 << 20; pub(crate) const MAX_APPLY_ARGS: usize = 1 << 16; /// The estimated bytes of a name's entries in the list and the set `for-in` builds. -const KEY_ENTRY_BYTES: usize = 32; +pub(crate) const KEY_ENTRY_BYTES: usize = 32; /// The most units of a computed property name an error about a property of `null` or `undefined` /// names; a longer name is left out of the message. @@ -1403,9 +1407,17 @@ impl Interp { self.heap.object_mut(id).ok_or_else(|| Abrupt::Internal("object out of range".into())) } - /// [[GetOwnProperty]] (section 8.12.1, with the special cases of arrays, strings and - /// arguments objects). - pub(crate) fn get_own_property(&self, id: ObjId, k: &[u16]) -> JsResult> { + /// [[GetOwnProperty]] (section 8.12.1), through a proxy's trap when `id` is a proxy. + pub(crate) fn get_own_property(&mut self, id: ObjId, k: &[u16]) -> JsResult> { + if self.is_proxy(id) { + return self.proxy_get_own_property(id, k); + } + self.ordinary_own_property(id, k) + } + + /// [[GetOwnProperty]] of an object that is not a proxy (section 8.12.1, with the special cases + /// of arrays, strings and arguments objects). A proxy has no own properties here. + pub(crate) fn ordinary_own_property(&self, id: ObjId, k: &[u16]) -> JsResult> { let o = self.object(id)?; match &o.class { Class::Array { length, length_writable } if is(k, "length") => { @@ -1461,13 +1473,17 @@ impl Interp { Ok(o.props.get(k).cloned()) } - /// [[GetProperty]]: the property found on the object or its prototype chain. - pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult> { + /// The property found on the object or its prototype chain, without running a proxy's traps: + /// the search stops at a proxy, which it reports. + pub(crate) fn lookup(&self, id: ObjId, k: &[u16]) -> JsResult { let mut cur = Some(id); let mut steps = 0usize; while let Some(o) = cur { - if let Some(p) = self.get_own_property(o, k)? { - return Ok(Some(p)); + if self.is_proxy(o) { + return Ok(Lookup::Proxy(o)); + } + if let Some(p) = self.ordinary_own_property(o, k)? { + return Ok(Lookup::Found(p)); } cur = self.object(o)?.proto; steps += 1; @@ -1475,19 +1491,61 @@ impl Interp { return internal("prototype chain too long"); } } - Ok(None) + Ok(Lookup::Missing) } - pub(crate) fn has_property(&self, id: ObjId, k: &[u16]) -> JsResult { - Ok(self.find_property(id, k)?.is_some()) + /// [[GetProperty]]: the property found on the object or its prototype chain, through the + /// `getOwnPropertyDescriptor` and `getPrototypeOf` traps of the proxies on it. + pub(crate) fn find_property(&mut self, id: ObjId, k: &[u16]) -> JsResult> { + let mark = self.temp_roots.len(); + let r = (|| { + let mut cur = id; + loop { + match self.lookup(cur, k)? { + Lookup::Found(p) => return Ok(Some(p)), + Lookup::Missing => return Ok(None), + Lookup::Proxy(p) => { + if let Some(prop) = self.get_own_property(p, k)? { + return Ok(Some(prop)); + } + let Some(next) = self.get_prototype_of(p)? else { return Ok(None) }; + self.use_fuel()?; + self.temp_roots.push(Value::Object(next)); + cur = next; + } + } + } + })(); + self.temp_roots.truncate(mark); + r } - /// [[Get]] starting at `start`, with `receiver` as `this` for a getter. + /// The property found on the object or its prototype chain, running no script: a proxy on the + /// chain ends the search. + pub(crate) fn find_ordinary_property(&self, id: ObjId, k: &[u16]) -> JsResult> { + Ok(match self.lookup(id, k)? { + Lookup::Found(p) => Some(p), + Lookup::Missing | Lookup::Proxy(_) => None, + }) + } + + /// [[HasProperty]], through the `has` trap of a proxy on the prototype chain. + pub(crate) fn has_property(&mut self, id: ObjId, k: &[u16]) -> JsResult { + match self.lookup(id, k)? { + Lookup::Found(_) => Ok(true), + Lookup::Missing => Ok(false), + Lookup::Proxy(p) => self.proxy_has(p, k), + } + } + + /// [[Get]] starting at `start`, with `receiver` as `this` for a getter, through the `get` trap + /// of a proxy on the prototype chain. pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { - match self.find_property(start, k)? { - None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), - Some(Prop::Data { value, .. }) => Ok(value), - Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), + match self.lookup(start, k)? { + Lookup::Missing | Lookup::Found(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), + Lookup::Found(Prop::Data { value, .. }) => Ok(value), + Lookup::Found(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), + Lookup::Proxy(p) => self.proxy_get(p, k, receiver), } } @@ -1552,6 +1610,13 @@ impl Interp { /// arguments object rules of section 10.6). Returns whether the property was defined; with /// `throw` a rejection throws a `TypeError` instead. pub(crate) fn define_own_property(&mut self, id: ObjId, k: Key, desc: &Desc, throw: bool) -> JsResult { + if self.is_proxy(id) { + let defined = self.proxy_define_own_property(id, &k, desc)?; + if !defined { + return self.reject_bool(throw, &k, "the proxy's defineProperty trap returned false"); + } + return Ok(true); + } match &self.object(id)?.class { Class::Array { length, length_writable } => { let (length, length_writable) = (*length, *length_writable); @@ -1715,8 +1780,11 @@ impl Interp { /// The names of an object's own properties (section 15.2.3.4): a String object's indices and /// `length` first, then the rest in the order they were added, which is the order `for-in` /// visits them, then an array's `length`. Each name takes a unit of fuel, and the heap for the - /// list is checked first. + /// list is checked first. A proxy's names come from its `ownKeys` trap. pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult> { + if self.is_proxy(id) { + return self.proxy_own_keys(id); + } let o = self.object(id)?; let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; let is_string = matches!(o.class, Class::String(_)); @@ -1758,9 +1826,16 @@ impl Interp { Ok(()) } - /// [[Put]] (section 8.12.5). + /// [[Put]] (section 8.12.5). On a proxy, or past a proxy on the prototype chain, it is the + /// proxy's [[Set]] with the object as the receiver (ECMA-262 2020 sections 9.1.9 and 9.5.9). pub(crate) fn put(&mut self, id: ObjId, k: Key, v: Value, throw: bool) -> JsResult<()> { - match self.get_own_property(id, &k)? { + if self.is_proxy(id) { + if !self.set_with_receiver(id, k.clone(), v, &Value::Object(id))? { + return self.reject(throw, &k, "the proxy did not set it"); + } + return Ok(()); + } + match self.ordinary_own_property(id, &k)? { Some(Prop::Data { flags, .. }) => { if flags & WRITABLE == 0 { return self.reject(throw, &k, "it is read-only"); @@ -1772,10 +1847,16 @@ impl Interp { None => {} } let proto = self.object(id)?.proto; - match proto.map(|p| self.find_property(p, &k)).transpose()?.flatten() { - Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), - Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), - Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"), + match proto.map(|p| self.lookup(p, &k)).transpose()? { + Some(Lookup::Found(Prop::Accessor { set: Some(s), .. })) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), + Some(Lookup::Found(Prop::Accessor { set: None, .. })) => return self.reject(throw, &k, "it has only a getter"), + Some(Lookup::Found(Prop::Data { flags, .. })) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"), + Some(Lookup::Proxy(p)) => { + if !self.set_with_receiver(p, k.clone(), v, &Value::Object(id))? { + return self.reject(throw, &k, "the proxy did not set it"); + } + return Ok(()); + } _ => {} } let o = self.object(id)?; @@ -1835,7 +1916,15 @@ impl Interp { /// [[Delete]] (section 8.12.7). pub(crate) fn delete(&mut self, id: ObjId, k: &[u16], throw: bool) -> JsResult { - match self.get_own_property(id, k)? { + if self.is_proxy(id) { + let deleted = self.proxy_delete(id, k)?; + if !deleted && throw { + let key = String::from_utf16_lossy(k); + return Err(self.type_error(&format!("cannot delete property '{key}': the proxy's deleteProperty trap returned false"))); + } + return Ok(deleted); + } + match self.ordinary_own_property(id, k)? { None => Ok(true), Some(p) if p.configurable() => { // A deleted global variable no longer stops a `let` or `const` of its name @@ -1880,8 +1969,17 @@ impl Interp { _ => { let proto = self.primitive_proto(base, &k)?; let own = matches!(base, Value::String(s) if is(&k, "length") || array_index(&k).is_some_and(|i| (i as usize) < s.len())); - if !own && let Some(Prop::Accessor { set: Some(s), .. }) = self.find_property(proto, &k)? { - return self.call(&Value::Object(s), base, &[v]).map(drop); + if !own { + match self.lookup(proto, &k)? { + Lookup::Found(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), base, &[v]).map(drop), + Lookup::Proxy(p) => { + if !self.set_with_receiver(p, k.clone(), v, base)? { + return self.reject(strict, &k, "the proxy did not set it"); + } + return Ok(()); + } + _ => {} + } } self.reject(strict, &k, "the value is a primitive") } @@ -2507,10 +2605,37 @@ impl Interp { if self.options.e4x && self.is_xml(&Value::Object(id)) { return self.xml_enumerate(id); } + let slot = self.temp_roots.len(); + self.temp_roots.push(Value::Undefined); + let r = self.enumerable_keys_from(id, slot); + self.temp_roots.truncate(slot); + r + } + + /// [`Self::enumerable_keys`] after the XML case. A proxy on the chain gives its names with its + /// `ownKeys` trap, whether each is enumerable with its `getOwnPropertyDescriptor` trap and the + /// next object with its `getPrototypeOf` trap, which `temp_roots[slot]` keeps reachable. + fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult> { let mut seen = std::collections::HashSet::new(); let mut out = Vec::new(); let mut cur = Some(id); while let Some(o) = cur { + if self.is_proxy(o) { + for k in self.own_keys(o)? { + self.use_fuel()?; + if !seen.insert(k.clone()) { + continue; + } + if self.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) { + out.push(k); + } + } + cur = self.get_prototype_of(o)?; + if let Some(root) = self.temp_roots.get_mut(slot) { + *root = cur.map_or(Value::Undefined, Value::Object); + } + continue; + } let obj = self.object(o)?; let string_len = if let Class::String(s) = &obj.class { Some(s.len()) } else { None }; let is_array = matches!(obj.class, Class::Array { .. }); @@ -2572,18 +2697,70 @@ impl Interp { let Some(k) = state.keys.get(state.pos).cloned() else { return self.jump_to(target) }; state.pos += 1; let object = state.object; - if let Some(o) = object - && self.scope_has(o, &k)? - { + let Some(o) = object else { continue }; + let visit = if self.options.e4x && self.is_xml(&Value::Object(o)) { self.scope_has(o, &k)? } else { self.for_in_still_has(o, &k)? }; + if visit { return self.push(Value::String(Str::from_rc(k))); } } } + /// Whether `for-in` over `o` still visits `k` (section 12.6.4; ECMA-262 2020 section + /// 13.7.5.15): an object on the chain before any proxy has the property, or a proxy's + /// `getOwnPropertyDescriptor` trap gives an enumerable one, or the objects after a proxy + /// without the property have it. A name deleted, or on a proxy made non-enumerable, after the + /// names were listed is skipped. A proxy's `has` trap is not asked. Each proxy on the chain + /// takes a unit of fuel. + fn for_in_still_has(&mut self, o: ObjId, k: &[u16]) -> JsResult { + let mark = self.temp_roots.len(); + let r = self.for_in_still_has_rooted(o, k); + self.temp_roots.truncate(mark); + r + } + + fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &[u16]) -> JsResult { + loop { + let p = match self.lookup(cur, k)? { + Lookup::Found(_) => return Ok(true), + Lookup::Missing => return Ok(false), + Lookup::Proxy(p) => p, + }; + self.use_fuel()?; + if let Some(prop) = self.get_own_property(p, k)? { + return Ok(prop.enumerable()); + } + let Some(next) = self.get_prototype_of(p)? else { return Ok(false) }; + self.temp_roots.push(Value::Object(next)); + cur = next; + } + } + // ---- calls ---- pub(crate) fn is_callable(&self, v: &Value) -> bool { - v.as_object().and_then(|o| self.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Function(_))) + v.as_object().and_then(|o| self.heap.object(o)).is_some_and(|o| match &o.class { + Class::Function(_) => true, + Class::Proxy(p) => p.callable, + _ => false, + }) + } + + /// IsConstructor (ECMA-262 2020 section 7.2.4): a function written in JavaScript other than + /// an arrow function, a built-in constructor, a bound function whose target is one, or a + /// proxy made with one. + pub(crate) fn is_constructor(&self, v: &Value) -> bool { + let mut cur = v.as_object(); + // A chain of bound functions is as long as the heap allows; the steps are bounded by it. + while let Some(o) = cur.and_then(|o| self.heap.object(o)) { + match &o.class { + Class::Function(Func::Closure { code, .. }) => return !code.arrow, + Class::Function(Func::Native { constructor, .. }) => return *constructor, + Class::Function(Func::Bound { target, .. }) => cur = Some(*target), + Class::Proxy(p) => return p.constructor, + _ => return false, + } + } + false } fn func_of(&self, v: &Value) -> Option { @@ -2597,7 +2774,19 @@ impl Interp { /// JavaScript comes back to be entered by the caller. fn prepare_call(&mut self, mut f: Value, mut this: Value, mut args: Vec) -> JsResult { loop { - let Some(func) = self.func_of(&f) else { return Err(self.type_error("the value is not a function")) }; + let Some(func) = self.func_of(&f) else { + if let Some(p) = f.as_object().filter(|&p| self.is_proxy(p)) { + // A proxy without an `apply` trap calls its target, which the loop takes next. + match self.proxy_call(p, &this, &args)? { + ProxyCall::Target(target) => { + f = Value::Object(target); + continue; + } + ProxyCall::Done(v) => return Ok(Prepared::Done(v)), + } + } + return Err(self.type_error("the value is not a function")); + }; match func { Func::Closure { code, env } => { let callee = f.as_object().ok_or_else(|| Abrupt::Internal("callee is not an object".into()))?; @@ -2675,7 +2864,7 @@ impl Interp { } /// The elements of an array-like `apply` argument (section 15.3.4.3). - fn list_from_array_like(&mut self, list: &Value) -> JsResult> { + pub(crate) fn list_from_array_like(&mut self, list: &Value) -> JsResult> { let Value::Object(o) = list else { if list.is_nullish() { return Ok(Vec::new()); @@ -2732,41 +2921,130 @@ impl Interp { let n = argc as usize; let start = self.stack.len().checked_sub(n + 1).filter(|&s| s >= self.base()).ok_or_else(|| Abrupt::Internal("new below the stack".into()))?; - let mut f = self.stack.get(start).cloned().unwrap_or(Value::Undefined); - let mut args: Vec = self.stack.get(start + 1..).map(<[Value]>::to_vec).unwrap_or_default(); - // A bound function constructs its target with its arguments first (section 15.3.4.5.2); - // the bound function on the stack keeps them reachable. - while let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) { - self.use_fuel()?; - let mut all = bound_args.to_vec(); - all.append(&mut args); - args = all; - f = Value::Object(target); - } - match self.func_of(&f) { - Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")), - Some(Func::Closure { code, env }) => { - let Some(callee) = f.as_object() else { return internal("callee is not an object") }; - let proto = match self.get_from(callee, &key("prototype"), &f)? { - Value::Object(p) => p, - _ => self.intrinsics.object_proto, - }; - let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); - self.stack.truncate(start); - self.enter_function(Entry { callee, code, env, this: Value::Object(obj), args }, Some(obj), false) - } - Some(Func::Native { f: native, constructor: true, .. }) => { - let held = self.held_bytes; - let r = native(self, Value::Undefined, &args, true); - self.held_bytes = held; - let v = r?; + let f = self.stack.get(start).cloned().unwrap_or(Value::Undefined); + let args: Vec = self.stack.get(start + 1..).map(<[Value]>::to_vec).unwrap_or_default(); + match self.prepare_construct(f.clone(), args, f)? { + Prepared::Done(v) => { self.stack.truncate(start); self.push(v) } - _ => Err(self.type_error("the value is not a constructor")), + Prepared::Closure(entry) => { + let obj = entry.this.as_object(); + self.stack.truncate(start); + self.enter_function(entry, obj, false) + } } } + /// [[Construct]] of `f` with `args`, `new_target` giving the new object's prototype: runs a + /// built-in constructor or a proxy's `construct` trap, or gives the frame a constructor written + /// in JavaScript enters with the new object as `this`. A bound function constructs its target + /// with its arguments first (section 15.3.4.5.2), and a proxy without a `construct` trap its + /// target (ECMA-262 2020 section 9.5.13). The values stay rooted while the steps run script. + fn prepare_construct(&mut self, f: Value, args: Vec, new_target: Value) -> JsResult { + let mark = self.temp_roots.len(); + self.temp_roots.push(f.clone()); + self.temp_roots.push(new_target.clone()); + self.temp_roots.extend(args.iter().cloned()); + let r = self.prepare_construct_rooted(f, args, new_target); + self.temp_roots.truncate(mark); + r + } + + fn prepare_construct_rooted(&mut self, mut f: Value, mut args: Vec, mut new_target: Value) -> JsResult { + loop { + if let Some(p) = f.as_object().filter(|&p| self.is_proxy(p)) { + match self.proxy_construct(p, &args, &new_target)? { + ProxyCall::Target(target) => { + f = Value::Object(target); + self.temp_roots.push(f.clone()); + continue; + } + ProxyCall::Done(v) => return Ok(Prepared::Done(v)), + } + } + match self.func_of(&f) { + // The bound function, reachable from the rooted `f`, keeps its target and + // arguments reachable. + Some(Func::Bound { target, args: bound_args, .. }) => { + self.use_fuel()?; + let mut all = bound_args.to_vec(); + all.append(&mut args); + args = all; + if same_value(&f, &new_target) { + new_target = Value::Object(target); + } + f = Value::Object(target); + } + Some(Func::Closure { code, .. }) if code.arrow => return Err(self.type_error("an arrow function is not a constructor")), + Some(Func::Closure { code, env }) => { + let Some(callee) = f.as_object() else { return internal("callee is not an object") }; + let proto = match self.get_value(&new_target, &key("prototype"))? { + Value::Object(p) => p, + _ => self.intrinsics.object_proto, + }; + let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + return Ok(Prepared::Closure(Entry { callee, code, env, this: Value::Object(obj), args })); + } + Some(Func::Native { f: native, constructor: true, .. }) => { + // With a different `newTarget` (`Reflect.construct`), the new object takes + // its `prototype` when that is an object (ECMA-262 2020 section 9.1.14). An + // argument given back and a proxy keep their own. `Object` makes a new object + // instead of converting its argument (section 19.1.1.1). + let proto = if same_value(&f, &new_target) { + None + } else { + match self.get_value(&new_target, &key("prototype"))? { + Value::Object(p) => { + self.temp_roots.push(Value::Object(p)); + Some(p) + } + _ => None, + } + }; + if !same_value(&f, &new_target) && f.as_object() == Some(self.intrinsics.object_ctor) { + let proto = proto.unwrap_or(self.intrinsics.object_proto); + self.reserve_heap(OBJECT_BYTES)?; + let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + return Ok(Prepared::Done(Value::Object(obj))); + } + let held = self.held_bytes; + let r = native(self, Value::Undefined, &args, true); + self.held_bytes = held; + let v = r?; + if let (Some(p), Value::Object(o)) = (proto, &v) + && !self.is_proxy(*o) + && !args.iter().any(|a| same_value(a, &v)) + && let Some(obj) = self.heap.object_mut(*o) + { + obj.proto = Some(p); + } + return Ok(Prepared::Done(v)); + } + _ => return Err(self.type_error("the value is not a constructor")), + } + } + } + + /// Construct (ECMA-262 2020 section 7.3.13) from Rust: runs a constructor written in + /// JavaScript to its end. + pub(crate) fn construct(&mut self, f: &Value, args: &[Value], new_target: &Value) -> JsResult { + if self.reentry >= self.limits.reentry { + return Err(Abrupt::Limit(LimitKind::Reentry)); + } + self.reentry += 1; + let r = match self.prepare_construct(f.clone(), args.to_vec(), new_target.clone()) { + Ok(Prepared::Done(v)) => Ok(v), + Ok(Prepared::Closure(entry)) => { + let obj = entry.this.as_object(); + self.enter_function(entry, obj, true).and_then(|()| self.execute()) + } + Err(e) => Err(e), + }; + self.reentry -= 1; + r + } + /// Pushes a frame for a call to a function written in JavaScript, its operands already off /// the stack. fn enter_function(&mut self, entry: Entry, construct: Option, boundary: bool) -> JsResult<()> { @@ -3699,17 +3977,34 @@ impl Interp { return Err(self.type_error("the function's prototype is not an object")); }; let mut steps = 0usize; - while let Some(p) = self.object(o)?.proto { + // A proxy's `getPrototypeOf` trap can give an object nothing else refers to, so the object + // being read stays rooted, as does the prototype compared with. + let slot = self.temp_roots.len(); + self.temp_roots.push(Value::Object(proto)); + self.temp_roots.push(Value::Object(o)); + // Past a proxy the chain can be a cycle, which the fuel each trap takes ends. + let mut proxied = false; + let r = loop { + proxied |= self.is_proxy(o); + let next = match self.get_prototype_of(o) { + Ok(next) => next, + Err(e) => break Err(e), + }; + let Some(p) = next else { break Ok(false) }; if p == proto { - return Ok(true); + break Ok(true); } o = p; - steps += 1; - if steps > 1_000_000 { - return internal("prototype chain too long"); + if let Some(root) = self.temp_roots.get_mut(slot + 1) { + *root = Value::Object(o); } - } - Ok(false) + steps += 1; + if steps > 1_000_000 && !proxied { + break internal("prototype chain too long"); + } + }; + self.temp_roots.truncate(slot); + r } // ---- host values ---- @@ -3749,7 +4044,7 @@ impl Interp { /// the text of a primitive. pub(crate) fn describe(&mut self, v: &Value) -> String { let Value::Object(o) = v else { return self.primitive_to_str(v).to_rust_string() }; - let data = |interp: &Self, k: &str| match interp.find_property(*o, &key(k)) { + let data = |interp: &Self, k: &str| match interp.find_ordinary_property(*o, &key(k)) { Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.to_rust_string()), _ => None, }; @@ -3768,6 +4063,24 @@ pub(crate) enum CompileError { Internal(String), } +/// What [`Interp::lookup`] found for a name on a prototype chain. +pub(crate) enum Lookup { + /// The property, on an object before any proxy. + Found(Prop), + /// A proxy, before the property was found: the rest of the search is the proxy's to answer. + Proxy(ObjId), + /// No object on the chain has the property. + Missing, +} + +/// What a proxy's [[Call]] or [[Construct]] did. +pub(crate) enum ProxyCall { + /// The proxy has no trap for it: the target is called or constructed instead. + Target(ObjId), + /// The trap ran and gave this value. + Done(Value), +} + /// A property descriptor (section 8.10): each field is `None` when it is absent. `get` and `set` /// are `Some(None)` when present as `undefined`. #[derive(Clone, Default, Debug)] @@ -3801,7 +4114,7 @@ impl Desc { } /// The attribute flags the descriptor gives, each absent one taken from `default`. - fn flags_or(&self, default: u8) -> u8 { + pub(crate) fn flags_or(&self, default: u8) -> u8 { let pick = |field: Option, bit: u8| match field { Some(true) => bit, Some(false) => 0, @@ -3821,7 +4134,7 @@ pub(crate) fn same_value(a: &Value, b: &Value) -> bool { /// Steps 5 to 12 of [[DefineOwnProperty]] (section 8.12.9) for an existing property: the /// property after `desc` is applied, or `None` when the change is not allowed. -fn merge_desc(current: &Prop, desc: &Desc) -> Option { +pub(crate) fn merge_desc(current: &Prop, desc: &Desc) -> Option { let flags = current.flags(); let configurable = flags & CONFIGURABLE != 0; if !configurable { diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index f1fa58730f..f2ae96e581 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -56,7 +56,9 @@ //! `new` (sections 12.2.5 and 12.3.6.1). Spread reads arrays by index, reading the length again //! before each element, strings and `String` objects by code point, and objects with a `length` by //! index; other values are a `TypeError`. Destructuring, `for … of`, classes, -//! generators and modules stay syntax errors. +//! generators and modules stay syntax errors. A realm made with the option also has `Proxy`, with +//! `Proxy.revocable`, and `Reflect`, as ECMAScript 2020 defines them (sections 26.1 and 26.2 and +//! 9.5, ), with string property names. #![forbid(unsafe_code)] pub mod ast; @@ -74,6 +76,7 @@ mod lexer; mod number; mod number_builtins; mod parser; +mod proxy; mod realm; mod regexp; mod regexp_builtins; @@ -115,6 +118,8 @@ pub struct Options { /// template literals (tagged ones included), default and rest parameters, and spread in array /// literals, calls and `new`. Off, they are syntax errors and the language is ES5.1's. Code a /// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts. + /// A realm made with it also has the globals `Proxy` and `Reflect`; turning it on later for a + /// realm made without it does not add them. pub es2015: bool, } @@ -227,6 +232,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod proxy_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs new file mode 100644 index 0000000000..15b2c3af01 --- /dev/null +++ b/crates/js/src/proxy.rs @@ -0,0 +1,593 @@ +//! Proxy objects (ECMA-262 2020 section 9.5, ) +//! and the internal methods every object answers through: [[GetPrototypeOf]], [[SetPrototypeOf]], +//! [[IsExtensible]], [[PreventExtensions]], [[Set]] with a receiver, and the proxy cases of +//! [[GetOwnProperty]], [[DefineOwnProperty]], [[HasProperty]], [[Get]], [[Delete]], +//! [[OwnPropertyKeys]], [[Call]] and [[Construct]], which [`Interp`]'s property methods send here. +//! +//! A trap is a script call: each proxy operation takes a unit of fuel and counts as a nested call +//! against [`crate::Limits::reentry`] while it runs, so a proxy whose target or handler is another +//! proxy, or a trap that uses its own proxy, ends at that limit rather than exhausting the native +//! stack. A trap's result is checked against the target as section 9.5 says, and a result that +//! breaks an invariant is a `TypeError`. The proxy, its target and handler, and every value a trap +//! gives stay rooted while the operation runs, so a trap that revokes the proxy or starts a +//! collection leaves them in place. + +use std::collections::HashSet; + +use crate::LimitKind; +use crate::builtins::object::{from_desc, to_desc}; +use crate::heap::{ + CONFIGURABLE, Class, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, PROXY_BYTES, Prop, ProxyData, WRITABLE, key, string_bytes, +}; +use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, Interp, JsResult, KEY_ENTRY_BYTES, Lookup, ProxyCall, merge_desc, same_value}; +use crate::value::{Str, Value, index_key}; + +/// The most names an `ownKeys` trap may give. +const MAX_OWN_KEYS: f64 = (1u64 << 24) as f64; + +impl Interp { + pub(crate) fn is_proxy(&self, id: ObjId) -> bool { + matches!(self.heap.object(id).map(|o| &o.class), Some(Class::Proxy(_))) + } + + fn proxy_data(&self, id: ObjId) -> Option { + match self.heap.object(id).map(|o| &o.class) { + Some(Class::Proxy(p)) => Some(**p), + _ => None, + } + } + + /// ProxyCreate (section 9.5.14): a proxy for `target` with `handler`. + pub(crate) fn proxy_create(&mut self, target: &Value, handler: &Value) -> JsResult { + let Value::Object(t) = target else { return Err(self.type_error("a proxy's target must be an object")) }; + let Value::Object(h) = handler else { return Err(self.type_error("a proxy's handler must be an object")) }; + let data = ProxyData { target: Some(*t), handler: Some(*h), callable: self.is_callable(target), constructor: self.is_constructor(target) }; + self.rooted(&[target.clone(), handler.clone()], |i| i.reserve_heap(OBJECT_BYTES + PROXY_BYTES))?; + self.heap.bytes = self.heap.bytes.saturating_add(PROXY_BYTES); + Ok(self.heap.alloc_object(Object::new(Class::Proxy(Box::new(data)), None))) + } + + /// Revokes the proxy `id`: every later operation on it is a `TypeError`. A value that is not a + /// proxy is left as it is. + pub(crate) fn proxy_revoke(&mut self, id: ObjId) { + if let Some(Object { class: Class::Proxy(p), .. }) = self.heap.object_mut(id) { + p.target = None; + p.handler = None; + } + } + + /// Runs `f` with the proxy's target and handler for the operation `what`: a revoked proxy is a + /// `TypeError`. The operation takes a unit of fuel and a nested call, and `p`, its target and + /// handler and `roots` stay rooted while it runs, with anything `f` adds to the roots. + fn proxy_op(&mut self, p: ObjId, what: &str, roots: &[Value], f: impl FnOnce(&mut Self, ObjId, ObjId) -> JsResult) -> JsResult { + if self.reentry >= self.limits.reentry { + return Err(Abrupt::Limit(LimitKind::Reentry)); + } + self.use_fuel()?; + let Some(ProxyData { target: Some(target), handler: Some(handler), .. }) = self.proxy_data(p) else { + return Err(self.type_error(&format!("cannot {what} a revoked proxy"))); + }; + let mark = self.temp_roots.len(); + self.temp_roots.extend([Value::Object(p), Value::Object(target), Value::Object(handler)]); + self.temp_roots.extend(roots.iter().cloned()); + self.reentry += 1; + let r = f(self, target, handler); + self.reentry -= 1; + self.temp_roots.truncate(mark); + r + } + + /// GetMethod (section 7.3.10) of the handler: the trap `name`, or `None` when it is + /// `undefined` or `null`. + fn proxy_trap(&mut self, handler: ObjId, name: &str) -> JsResult> { + let trap = self.get_from(handler, &key(name), &Value::Object(handler))?; + if trap.is_nullish() { + return Ok(None); + } + if !self.is_callable(&trap) { + return Err(self.type_error(&format!("the proxy handler's {name} is not a function"))); + } + self.temp_roots.push(trap.clone()); + Ok(Some(trap)) + } + + /// Calls the trap with the handler as `this`, keeping its result rooted. + fn call_trap(&mut self, trap: &Value, handler: ObjId, args: &[Value]) -> JsResult { + let v = self.call(trap, &Value::Object(handler), args)?; + self.temp_roots.push(v.clone()); + Ok(v) + } + + fn key_value(k: &[u16]) -> Value { + Value::String(Str::from_units(k.to_vec())) + } + + fn invariant(&mut self, trap: &str, why: &str) -> Abrupt { + self.type_error(&format!("the proxy's {trap} trap {why}")) + } + + // ---- [[GetPrototypeOf]], [[SetPrototypeOf]], [[IsExtensible]], [[PreventExtensions]] ---- + + /// [[GetPrototypeOf]] (sections 9.1.1 and 9.5.1). + pub(crate) fn get_prototype_of(&mut self, id: ObjId) -> JsResult> { + if !self.is_proxy(id) { + return Ok(self.object(id)?.proto); + } + self.proxy_op(id, "read the prototype of", &[], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "getPrototypeOf")? else { return i.get_prototype_of(target) }; + let proto = match i.call_trap(&trap, handler, &[Value::Object(target)])? { + Value::Object(p) => Some(p), + Value::Null => None, + _ => return Err(i.invariant("getPrototypeOf", "returned a value that is neither an object nor null")), + }; + if i.is_extensible(target)? { + return Ok(proto); + } + if i.get_prototype_of(target)? != proto { + return Err(i.invariant("getPrototypeOf", "returned a prototype other than its non-extensible target's")); + } + Ok(proto) + }) + } + + /// [[SetPrototypeOf]] (sections 9.1.2 and 9.5.2): whether the prototype was set. The + /// prototype of `Object.prototype` cannot change (section 9.4.7). + pub(crate) fn set_prototype_of(&mut self, id: ObjId, proto: Option) -> JsResult { + if self.is_proxy(id) { + let arg = proto.map_or(Value::Null, Value::Object); + return self.proxy_op(id, "set the prototype of", std::slice::from_ref(&arg), |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "setPrototypeOf")? else { return i.set_prototype_of(target, proto) }; + if !i.call_trap(&trap, handler, &[Value::Object(target), arg.clone()])?.truthy() { + return Ok(false); + } + if i.is_extensible(target)? { + return Ok(true); + } + if i.get_prototype_of(target)? != proto { + return Err(i.invariant("setPrototypeOf", "reported setting a prototype its non-extensible target does not have")); + } + Ok(true) + }); + } + let o = self.object(id)?; + if o.proto == proto { + return Ok(true); + } + if !o.extensible || id == self.intrinsics.object_proto { + return Ok(false); + } + // The new prototype's chain must not lead back to the object; a proxy on it ends the check. + let mut cur = proto; + while let Some(p) = cur { + if p == id { + return Ok(false); + } + if self.is_proxy(p) { + break; + } + self.use_fuel()?; + cur = self.object(p)?.proto; + } + self.object_mut(id)?.proto = proto; + // A new prototype can bring indices with it. + self.heap.index_epoch = self.heap.index_epoch.wrapping_add(1); + Ok(true) + } + + /// [[IsExtensible]] (sections 9.1.3 and 9.5.3). + pub(crate) fn is_extensible(&mut self, id: ObjId) -> JsResult { + if !self.is_proxy(id) { + return Ok(self.object(id)?.extensible); + } + self.proxy_op(id, "test the extensibility of", &[], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "isExtensible")? else { return i.is_extensible(target) }; + let answer = i.call_trap(&trap, handler, &[Value::Object(target)])?.truthy(); + if answer != i.is_extensible(target)? { + return Err(i.invariant("isExtensible", "gave an answer other than its target's")); + } + Ok(answer) + }) + } + + /// [[PreventExtensions]] (sections 9.1.4 and 9.5.4): whether the object is now not + /// extensible. + pub(crate) fn prevent_extensions(&mut self, id: ObjId) -> JsResult { + if !self.is_proxy(id) { + self.object_mut(id)?.extensible = false; + return Ok(true); + } + self.proxy_op(id, "prevent extensions of", &[], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "preventExtensions")? else { return i.prevent_extensions(target) }; + let done = i.call_trap(&trap, handler, &[Value::Object(target)])?.truthy(); + if done && i.is_extensible(target)? { + return Err(i.invariant("preventExtensions", "returned true while its target is extensible")); + } + Ok(done) + }) + } + + // ---- properties ---- + + /// [[GetOwnProperty]] of a proxy (section 9.5.5). + pub(crate) fn proxy_get_own_property(&mut self, p: ObjId, k: &[u16]) -> JsResult> { + self.proxy_op(p, "read a property of", &[], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "getOwnPropertyDescriptor")? else { return i.get_own_property(target, k) }; + let result = i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k)])?; + if !matches!(result, Value::Object(_) | Value::Undefined) { + return Err(i.invariant("getOwnPropertyDescriptor", "returned a value that is neither an object nor undefined")); + } + let target_prop = i.get_own_property(target, k)?; + if matches!(result, Value::Undefined) { + let Some(current) = target_prop else { return Ok(None) }; + if !current.configurable() { + return Err(i.invariant("getOwnPropertyDescriptor", "hid a non-configurable property of its target")); + } + if !i.is_extensible(target)? { + return Err(i.invariant("getOwnPropertyDescriptor", "hid a property of its non-extensible target")); + } + return Ok(None); + } + let extensible = i.is_extensible(target)?; + let desc = to_desc(i, &result)?; + i.temp_roots.extend(desc_values(&desc)); + let prop = complete(&desc); + let desc = prop_desc(&prop); + if !compatible(extensible, &desc, target_prop.as_ref()) { + return Err(i.invariant("getOwnPropertyDescriptor", "gave a descriptor its target's property does not allow")); + } + if !prop.configurable() { + match &target_prop { + Some(t) if !t.configurable() => {} + _ => { + return Err( + i.invariant("getOwnPropertyDescriptor", "reported a non-configurable property its target has as configurable or lacks") + ); + } + } + if desc.writable == Some(false) && matches!(target_prop, Some(Prop::Data { flags, .. }) if flags & WRITABLE != 0) { + return Err( + i.invariant("getOwnPropertyDescriptor", "reported a writable property of its target as non-configurable and read-only") + ); + } + } + Ok(Some(prop)) + }) + } + + /// [[DefineOwnProperty]] of a proxy (section 9.5.6): whether the trap defined the property. + pub(crate) fn proxy_define_own_property(&mut self, p: ObjId, k: &Key, desc: &Desc) -> JsResult { + let roots = desc_values(desc); + self.proxy_op(p, "define a property of", &roots, |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "defineProperty")? else { return i.define_own_property(target, k.clone(), desc, false) }; + let desc_obj = from_desc(i, desc)?; + i.temp_roots.push(desc_obj.clone()); + if !i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k), desc_obj])?.truthy() { + return Ok(false); + } + let target_prop = i.get_own_property(target, k)?; + let extensible = i.is_extensible(target)?; + let setting_config_false = desc.configurable == Some(false); + let Some(current) = target_prop else { + if !extensible { + return Err(i.invariant("defineProperty", "added a property to its non-extensible target")); + } + if setting_config_false { + return Err(i.invariant("defineProperty", "defined a non-configurable property its target lacks")); + } + return Ok(true); + }; + if !compatible(extensible, desc, Some(¤t)) { + return Err(i.invariant("defineProperty", "defined a property its target's property does not allow")); + } + if setting_config_false && current.configurable() { + return Err(i.invariant("defineProperty", "defined a property as non-configurable that is configurable on its target")); + } + if let Prop::Data { flags, .. } = current + && flags & CONFIGURABLE == 0 + && flags & WRITABLE != 0 + && desc.writable == Some(false) + { + return Err(i.invariant("defineProperty", "made a property read-only that is writable on its target")); + } + Ok(true) + }) + } + + /// [[HasProperty]] of a proxy (section 9.5.7). + pub(crate) fn proxy_has(&mut self, p: ObjId, k: &[u16]) -> JsResult { + self.proxy_op(p, "test a property of", &[], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "has")? else { return i.has_property(target, k) }; + let found = i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k)])?.truthy(); + if !found && let Some(current) = i.get_own_property(target, k)? { + if !current.configurable() { + return Err(i.invariant("has", "hid a non-configurable property of its target")); + } + if !i.is_extensible(target)? { + return Err(i.invariant("has", "hid a property of its non-extensible target")); + } + } + Ok(found) + }) + } + + /// [[Get]] of a proxy (section 9.5.8). + pub(crate) fn proxy_get(&mut self, p: ObjId, k: &[u16], receiver: &Value) -> JsResult { + self.proxy_op(p, "read a property of", std::slice::from_ref(receiver), |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "get")? else { return i.get_from(target, k, receiver) }; + let v = i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k), receiver.clone()])?; + match i.get_own_property(target, k)? { + Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(&v, &value) => { + Err(i.invariant("get", "gave a value other than its target's non-configurable, read-only property")) + } + Some(Prop::Accessor { get: None, flags, .. }) if flags & CONFIGURABLE == 0 && !matches!(v, Value::Undefined) => { + Err(i.invariant("get", "gave a value for a non-configurable property of its target that has no getter")) + } + _ => Ok(v), + } + }) + } + + /// [[Set]] of a proxy (section 9.5.9): whether the trap set the property. + fn proxy_set(&mut self, p: ObjId, k: &Key, v: &Value, receiver: &Value) -> JsResult { + self.proxy_op(p, "set a property of", &[v.clone(), receiver.clone()], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "set")? else { return i.set_with_receiver(target, k.clone(), v.clone(), receiver) }; + if !i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k), v.clone(), receiver.clone()])?.truthy() { + return Ok(false); + } + match i.get_own_property(target, k)? { + Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(v, &value) => { + Err(i.invariant("set", "set a value other than its target's non-configurable, read-only property")) + } + Some(Prop::Accessor { set: None, flags, .. }) if flags & CONFIGURABLE == 0 => { + Err(i.invariant("set", "set a non-configurable property of its target that has no setter")) + } + _ => Ok(true), + } + }) + } + + /// [[Delete]] of a proxy (section 9.5.10): whether the trap deleted the property. + pub(crate) fn proxy_delete(&mut self, p: ObjId, k: &[u16]) -> JsResult { + self.proxy_op(p, "delete a property of", &[], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "deleteProperty")? else { return i.delete(target, k, false) }; + if !i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k)])?.truthy() { + return Ok(false); + } + let Some(current) = i.get_own_property(target, k)? else { return Ok(true) }; + if !current.configurable() { + return Err(i.invariant("deleteProperty", "deleted a non-configurable property of its target")); + } + if !i.is_extensible(target)? { + return Err(i.invariant("deleteProperty", "deleted a property of its non-extensible target")); + } + Ok(true) + }) + } + + /// [[OwnPropertyKeys]] of a proxy (section 9.5.11). The trap must give an array-like object + /// of distinct strings, at most [`MAX_OWN_KEYS`] of them, that holds every non-configurable + /// name of the target, and of a non-extensible target exactly its names. Each name takes a + /// unit of fuel and counts against the heap limit while the list is built. + pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult> { + self.proxy_op(p, "list the properties of", &[], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.own_keys(target) }; + let result = i.call_trap(&trap, handler, &[Value::Object(target)])?; + let mut held = HeldBytes::new(i); + let keys = i.trap_key_list(&result, &mut held)?; + i.check_own_keys(target, &keys)?; + Ok(keys) + }) + } + + /// CreateListFromArrayLike (section 7.3.17) of an `ownKeys` trap's result, refusing a value + /// that is not a string and a name given twice. + fn trap_key_list(&mut self, result: &Value, held: &mut HeldBytes) -> JsResult> { + let Value::Object(list) = result else { return Err(self.invariant("ownKeys", "returned a value that is not an object")) }; + let length = self.get_from(*list, &key("length"), result)?; + let n = self.to_number(&length)?; + // ToLength (section 7.1.15). + let n = if n.is_nan() || n <= 0.0 { 0.0 } else { n.trunc() }; + if n > MAX_OWN_KEYS { + return Err(self.throw(ErrorType::Range, "the proxy's ownKeys trap returned too many names")); + } + let mut keys = Vec::new(); + let mut seen: HashSet = HashSet::new(); + for index in 0..n as u32 { + self.use_fuel()?; + let v = self.get_from(*list, &index_key(index), result)?; + let Value::String(s) = v else { return Err(self.invariant("ownKeys", "returned a name that is not a string")) }; + held.add(self, string_bytes(s.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; + let k = s.flat(); + if !seen.insert(k.clone()) { + let name = String::from_utf16_lossy(&k); + return Err(self.invariant("ownKeys", &format!("returned the name '{name}' twice"))); + } + keys.push(k); + } + Ok(keys) + } + + /// Steps 16 to 23 of section 9.5.11: the names `keys` the trap gave against the target's. + fn check_own_keys(&mut self, target: ObjId, keys: &[Key]) -> JsResult<()> { + let extensible = self.is_extensible(target)?; + let target_keys = self.own_keys(target)?; + let mut fixed = Vec::new(); + let mut configurable = Vec::new(); + for k in target_keys { + self.use_fuel()?; + if self.get_own_property(target, &k)?.is_some_and(|p| !p.configurable()) { + fixed.push(k); + } else { + configurable.push(k); + } + } + if extensible && fixed.is_empty() { + return Ok(()); + } + let mut unchecked: HashSet<&[u16]> = keys.iter().map(|k| &**k).collect(); + for k in &fixed { + if !unchecked.remove(&**k) { + let name = String::from_utf16_lossy(k); + return Err(self.invariant("ownKeys", &format!("left out the non-configurable property '{name}' of its target"))); + } + } + if extensible { + return Ok(()); + } + for k in &configurable { + if !unchecked.remove(&**k) { + let name = String::from_utf16_lossy(k); + return Err(self.invariant("ownKeys", &format!("left out the property '{name}' of its non-extensible target"))); + } + } + if !unchecked.is_empty() { + return Err(self.invariant("ownKeys", "gave a name its non-extensible target does not have")); + } + Ok(()) + } + + /// [[Set]] (section 9.1.9) of `k` on `o` with `receiver`: a proxy's `set` trap, a setter found + /// on the chain, or a data property defined on the receiver. Whether the value was set. + pub(crate) fn set_with_receiver(&mut self, o: ObjId, k: Key, v: Value, receiver: &Value) -> JsResult { + let mark = self.temp_roots.len(); + self.temp_roots.extend([Value::Object(o), v.clone(), receiver.clone()]); + let r = self.ordinary_set(o, k, v, receiver); + self.temp_roots.truncate(mark); + r + } + + fn ordinary_set(&mut self, o: ObjId, k: Key, v: Value, receiver: &Value) -> JsResult { + let own = match self.lookup(o, &k)? { + Lookup::Proxy(p) => return self.proxy_set(p, &k, &v, receiver), + Lookup::Found(prop) => prop, + Lookup::Missing => Prop::Data { value: Value::Undefined, flags: OPEN }, + }; + match own { + Prop::Accessor { set: Some(s), .. } => { + self.call(&Value::Object(s), receiver, &[v])?; + Ok(true) + } + Prop::Accessor { set: None, .. } => Ok(false), + Prop::Data { flags, .. } if flags & WRITABLE == 0 => Ok(false), + Prop::Data { .. } => { + let Value::Object(r) = receiver else { return Ok(false) }; + let r = *r; + match self.get_own_property(r, &k)? { + Some(Prop::Accessor { .. }) => Ok(false), + Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => Ok(false), + Some(Prop::Data { .. }) => self.define_own_property(r, k, &Desc { value: Some(v), ..Desc::default() }, false), + None => self.define_own_property(r, k, &Desc::data(v, OPEN), false), + } + } + } + } + + // ---- calls ---- + + /// [[Call]] of a proxy (section 9.5.12): the trap's result, or the target to call when the + /// handler has no `apply` trap. + pub(crate) fn proxy_call(&mut self, p: ObjId, this: &Value, args: &[Value]) -> JsResult { + if !self.proxy_data(p).is_some_and(|d| d.callable) { + return Err(self.type_error("the value is not a function")); + } + let mut roots = vec![this.clone()]; + roots.extend(args.iter().cloned()); + self.proxy_op(p, "call", &roots, |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "apply")? else { return Ok(ProxyCall::Target(target)) }; + let list = i.trap_array(args)?; + let v = i.call_trap(&trap, handler, &[Value::Object(target), this.clone(), list])?; + Ok(ProxyCall::Done(v)) + }) + } + + /// [[Construct]] of a proxy (section 9.5.13): the object the trap made, or the target to + /// construct when the handler has no `construct` trap. + pub(crate) fn proxy_construct(&mut self, p: ObjId, args: &[Value], new_target: &Value) -> JsResult { + if !self.proxy_data(p).is_some_and(|d| d.constructor) { + return Err(self.type_error("the value is not a constructor")); + } + let mut roots = vec![new_target.clone()]; + roots.extend(args.iter().cloned()); + self.proxy_op(p, "construct", &roots, |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "construct")? else { return Ok(ProxyCall::Target(target)) }; + let list = i.trap_array(args)?; + let v = i.call_trap(&trap, handler, &[Value::Object(target), list, new_target.clone()])?; + if !matches!(v, Value::Object(_)) { + return Err(i.invariant("construct", "returned a value that is not an object")); + } + Ok(ProxyCall::Done(v)) + }) + } + + /// CreateArrayFromList (section 7.3.16) of the arguments a trap is given, checked against the + /// heap limit and kept rooted. + fn trap_array(&mut self, args: &[Value]) -> JsResult { + self.reserve_heap(OBJECT_BYTES.saturating_add(args.len().saturating_mul(PROP_BYTES + string_bytes(10))))?; + let a = Value::Object(self.array_of(args)?); + self.temp_roots.push(a.clone()); + Ok(a) + } + + /// IsArray (section 7.2.2): an array, or a proxy whose target is one. A revoked proxy is a + /// `TypeError`. + pub(crate) fn is_array(&mut self, v: &Value) -> JsResult { + let mut cur = v.as_object(); + while let Some(o) = cur { + match self.heap.object(o).map(|x| &x.class) { + Some(Class::Array { .. }) => return Ok(true), + Some(Class::Proxy(p)) => { + let ProxyData { target, handler, .. } = **p; + if handler.is_none() { + return Err(self.type_error("cannot test whether a revoked proxy is an array")); + } + self.use_fuel()?; + cur = target; + } + _ => return Ok(false), + } + } + Ok(false) + } +} + +/// The values a descriptor holds, to keep them reachable while more script runs. +pub(crate) fn desc_values(desc: &Desc) -> Vec { + let mut out: Vec = desc.value.iter().cloned().collect(); + out.extend(desc.get.flatten().map(Value::Object)); + out.extend(desc.set.flatten().map(Value::Object)); + out +} + +/// CompletePropertyDescriptor (section 6.2.5.6): the property `desc` describes, each absent field +/// at its default. +fn complete(desc: &Desc) -> Prop { + let flags = desc.flags_or(0); + if desc.is_accessor() { + Prop::Accessor { get: desc.get.flatten(), set: desc.set.flatten(), flags: flags & (ENUMERABLE | CONFIGURABLE) } + } else { + Prop::Data { value: desc.value.clone().unwrap_or(Value::Undefined), flags } + } +} + +/// The descriptor with every field of `prop`. +fn prop_desc(prop: &Prop) -> Desc { + match prop { + Prop::Data { value, flags } => Desc::data(value.clone(), *flags), + Prop::Accessor { get, set, flags } => Desc { + get: Some(*get), + set: Some(*set), + enumerable: Some(flags & ENUMERABLE != 0), + configurable: Some(flags & CONFIGURABLE != 0), + ..Desc::default() + }, + } +} + +/// IsCompatiblePropertyDescriptor (section 9.1.6.2): whether a target with `current` (and, when +/// it has none, `extensible`) allows `desc`. +fn compatible(extensible: bool, desc: &Desc, current: Option<&Prop>) -> bool { + match current { + None => extensible, + Some(current) => merge_desc(current, desc).is_some(), + } +} diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs new file mode 100644 index 0000000000..a8f6f4a13b --- /dev/null +++ b/crates/js/src/proxy_tests.rs @@ -0,0 +1,439 @@ +//! `Proxy` and `Reflect` in a realm with `Options::es2015`. + +use std::cell::RefCell; +use std::rc::Rc; + +use crate::{Data, HostFunction, HostItem, JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es_options() -> Options { + Options { es2015: true, ..Options::default() } +} + +fn es() -> Realm { + Realm::with_options(es_options(), Limits::default()) +} + +/// `type_error(f)` is true when calling `f` throws a `TypeError`. +const PRELUDE: &str = "function type_error(f) { try { f(); } catch (e) { return e instanceof TypeError; } return false; }\n"; + +fn truth(src: &str) { + let script = format!("{PRELUDE}{src}"); + match es().run(&script) { + Ok(v) => assert_eq!(v, JsValue::Bool(true), "{src}"), + Err(e) => panic!("{src}\n{e:?}"), + } +} + +/// Each script, run after [`PRELUDE`], throws a `TypeError` from its last statement. +fn type_errors(scripts: &[&str]) { + for src in scripts { + let script = format!("{PRELUDE}{src}"); + match es().run(&script) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } + } +} + +fn limit(src: &str, limits: Limits) -> LimitKind { + match Realm::with_options(es_options(), limits).run(src) { + Err(RunError { kind: RunErrorKind::Limit(kind), .. }) => kind, + other => panic!("{src}: {other:?}"), + } +} + +// ---- the realm gate ---- + +#[test] +fn only_a_realm_made_with_es2015_has_proxy_and_reflect() { + let names = "typeof Proxy + ' ' + typeof Reflect"; + assert_eq!(es().run(names), Ok(JsValue::String("function object".into()))); + assert_eq!(Realm::new().run(names), Ok(JsValue::String("undefined undefined".into()))); + let e4x = Options { e4x: true, ..Options::default() }; + assert_eq!(Realm::with_options(e4x, Limits::default()).run(names), Ok(JsValue::String("undefined undefined".into()))); + let mut later = Realm::new(); + later.set_es2015(true); + assert_eq!(later.run(names), Ok(JsValue::String("undefined undefined".into()))); +} + +// ---- Proxy ---- + +#[test] +fn the_constructor_needs_new_and_two_objects() { + truth("Proxy.length === 2 && Proxy.revocable.length === 2 && Proxy.prototype === undefined"); + type_errors(&["Proxy({}, {})", "new Proxy(1, {})", "new Proxy({}, null)", "new Proxy({})"]); +} + +#[test] +fn traps_get_the_target_key_and_receiver_with_the_handler_as_this() { + truth( + "var target = { a: 1 }, seen = []; + var handler = { get: function (t, k, r) { seen.push(this === handler, t === target, k, r === p); return 42; } }; + var p = new Proxy(target, handler); + p.a === 42 && seen.join() === 'true,true,a,true'", + ); + truth( + "var log = []; + var p = new Proxy({}, { set: function (t, k, v, r) { log.push(k, v, r === p); t[k] = v * 2; return true; } }); + p.x = 3; + log.join() === 'x,3,true' && p.x === 6", + ); + truth( + "var p = new Proxy({}, { has: function (t, k) { return k === 'yes'; } }); + ('yes' in p) && !('no' in p)", + ); + truth( + "var p = new Proxy({ a: 1, b: 2 }, { deleteProperty: function (t, k) { delete t[k]; return k === 'a'; } }); + delete p.a && !Reflect.deleteProperty(p, 'b')", + ); +} + +#[test] +fn an_absent_trap_forwards_each_operation_to_the_target() { + truth( + "var target = { a: 1 }; + var p = new Proxy(target, {}); + p.b = 2; + Object.defineProperty(p, 'c', { value: 3, enumerable: false }); + var ok = p.a === 1 && target.b === 2 && ('c' in p) && Object.keys(p).join() === 'a,b'; + ok = ok && Reflect.ownKeys(p).join() === 'a,b,c' && delete p.a && !('a' in target); + ok = ok && Object.getPrototypeOf(p) === Object.prototype && Reflect.setPrototypeOf(p, null) && Object.getPrototypeOf(target) === null; + Object.preventExtensions(p); + ok && !Object.isExtensible(target) && Object.isFrozen(Object.freeze(p)) && Object.isFrozen(target)", + ); +} + +#[test] +fn callable_and_constructable_proxies() { + truth( + "function add(a, b) { return a + b; } + var p = new Proxy(add, {}); + var q = new Proxy(add, { apply: function (t, self, args) { return [self, args.length, t(args[0], args[1])]; } }); + var r = q.call('me', 2, 3); + typeof p === 'function' && p(1, 2) === 3 && r[0] === 'me' && r[1] === 2 && r[2] === 5 && p.apply(null, [4, 5]) === 9", + ); + truth( + "function Point(x) { this.x = x; } + var P = new Proxy(Point, {}); + var made = new P(7); + var C = new Proxy(Point, { construct: function (t, args, nt) { return { args: args.length, nt: nt === C }; } }); + var c = new C(1, 2); + made.x === 7 && made instanceof Point && c.args === 2 && c.nt", + ); + type_errors(&[ + "new Proxy({}, {})()", + "new (new Proxy(function () {}, { construct: function () { return 1; } }))()", + "new (new Proxy(Math.max, {}))()", + "var arrow = new Proxy(() => 1, {}); new arrow()", + ]); + truth("typeof new Proxy({}, {}) === 'object' && Object.prototype.toString.call(new Proxy(function () {}, {})) === '[object Function]'"); +} + +#[test] +fn a_revoked_proxy_refuses_every_operation() { + truth( + "var r = Proxy.revocable(function () {}, {}); + var p = r.proxy; + r.revoke(); + r.revoke(); + var ops = [ + function () { return p.x; }, function () { p.x = 1; }, function () { return 'x' in p; }, function () { delete p.x; }, + function () { Object.keys(p); }, function () { Object.getPrototypeOf(p); }, function () { Object.isExtensible(p); }, + function () { Object.preventExtensions(p); }, function () { Object.defineProperty(p, 'x', {}); }, + function () { Object.getOwnPropertyDescriptor(p, 'x'); }, function () { p(); }, function () { new p(); }, + function () { Array.isArray(p); }, function () { for (var k in p) {} }, function () { JSON.stringify(p); }, + function () { Object.prototype.toString.call(p); }, function () { ({}) instanceof p; }, + ]; + var all = true; + for (var i = 0; i < ops.length; i++) all = all && type_error(ops[i]); + all && typeof p === 'function' && r.revoke.length === 0 && r.revoke() === undefined", + ); + // A trap that revokes its own proxy still has its target for the checks that follow. + truth( + "var target = {}; + Object.defineProperty(target, 'k', { value: 5 }); + var r = Proxy.revocable(target, { get: function () { r.revoke(); return 5; } }); + r.proxy.k === 5 && type_error(function () { return r.proxy.k; })", + ); +} + +// ---- invariants ---- + +#[test] +fn a_trap_result_that_breaks_an_invariant_is_a_type_error() { + let fixed = "var t = {}; Object.defineProperty(t, 'k', { value: 1 });"; + let sealed = "var t = { k: 1 }; Object.preventExtensions(t);"; + type_errors(&[ + &format!("{fixed} new Proxy(t, {{ get: function () {{ return 2; }} }}).k"), + "var t = {}; Object.defineProperty(t, 'k', { set: function () {} }); new Proxy(t, { get: function () { return 1; } }).k", + &format!("{fixed} 'use strict'; new Proxy(t, {{ set: function () {{ return true; }} }}).k = 2"), + "var t = {}; Object.defineProperty(t, 'k', { get: function () {} }); Reflect.set(new Proxy(t, { set: function () { return true; } }), 'k', 1)", + &format!("{fixed} 'k' in new Proxy(t, {{ has: function () {{ return false; }} }})"), + &format!("{sealed} 'k' in new Proxy(t, {{ has: function () {{ return false; }} }})"), + &format!("{fixed} delete new Proxy(t, {{ deleteProperty: function () {{ return true; }} }}).k"), + &format!("{sealed} delete new Proxy(t, {{ deleteProperty: function () {{ return true; }} }}).k"), + "var t = {}; Object.preventExtensions(t); Object.defineProperty(new Proxy(t, { defineProperty: function () { return true; } }), 'n', { value: 1 })", + "Object.defineProperty(new Proxy({}, { defineProperty: function () { return true; } }), 'n', { value: 1, configurable: false })", + "var t = { k: 1 }; Object.defineProperty(new Proxy(t, { defineProperty: function () { return true; } }), 'k', { configurable: false })", + "var t = {}; Object.defineProperty(t, 'k', { value: 1, writable: true }); \ + Reflect.defineProperty(new Proxy(t, { defineProperty: function () { return true; } }), 'k', { writable: false })", + &format!("{fixed} Object.getOwnPropertyDescriptor(new Proxy(t, {{ getOwnPropertyDescriptor: function () {{ return undefined; }} }}), 'k')"), + &format!("{sealed} Object.getOwnPropertyDescriptor(new Proxy(t, {{ getOwnPropertyDescriptor: function () {{ return undefined; }} }}), 'k')"), + "Object.getOwnPropertyDescriptor(new Proxy({}, { getOwnPropertyDescriptor: function () { return { value: 1 }; } }), 'k')", + "Object.getOwnPropertyDescriptor(new Proxy({}, { getOwnPropertyDescriptor: function () { return 1; } }), 'k')", + "var t = {}; Object.defineProperty(t, 'k', { value: 1, writable: true }); \ + Object.getOwnPropertyDescriptor(new Proxy(t, { getOwnPropertyDescriptor: function () { return { value: 1, writable: false }; } }), 'k')", + "var t = {}; Object.preventExtensions(t); Object.getPrototypeOf(new Proxy(t, { getPrototypeOf: function () { return Array.prototype; } }))", + "Object.getPrototypeOf(new Proxy({}, { getPrototypeOf: function () { return 1; } }))", + "var t = {}; Object.preventExtensions(t); Reflect.setPrototypeOf(new Proxy(t, { setPrototypeOf: function () { return true; } }), Array.prototype)", + "Object.isExtensible(new Proxy({}, { isExtensible: function () { return false; } }))", + "Object.preventExtensions(new Proxy({}, { preventExtensions: function () { return true; } }))", + "Object.preventExtensions(new Proxy({}, { preventExtensions: function () { return false; } }))", + "new Proxy({}, { get: 1 }).k", + ]); +} + +#[test] +fn an_own_keys_result_is_checked_against_the_target() { + type_errors(&[ + "Object.keys(new Proxy({}, { ownKeys: function () { return ['a', 'a']; } }))", + "Object.keys(new Proxy({}, { ownKeys: function () { return ['a', 1]; } }))", + "Object.keys(new Proxy({}, { ownKeys: function () { return 'ab'; } }))", + "var t = {}; Object.defineProperty(t, 'k', { value: 1 }); Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return []; } }))", + "var t = { a: 1 }; Object.preventExtensions(t); Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return []; } }))", + "var t = { a: 1 }; Object.preventExtensions(t); Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return ['a', 'b']; } }))", + ]); + truth( + "var t = { a: 1 }; Object.preventExtensions(t); + var keys = Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return ['a']; } })); + var listed = Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return { length: 2, 0: 'x', 1: 'y' }; } })); + keys.join() === 'a' && listed.join() === 'x,y'", + ); + let mut realm = es(); + let e = realm.run("Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return { length: 1e9 }; } }))").unwrap_err(); + assert!(e.message.starts_with("RangeError"), "{e:?}"); +} + +// ---- limits ---- + +#[test] +fn traps_stay_within_the_run_limits() { + let fuel = Limits { fuel: 200_000, ..Limits::default() }; + assert_eq!(limit("new Proxy({}, { get: function () { while (true) {} } }).x", fuel.clone()), LimitKind::Fuel); + // A trap that reads its own proxy, a chain of proxies without traps and a handler that is a proxy + // of itself end at the nested-call limit rather than exhausting the native stack. + assert_eq!(limit("var p = new Proxy({}, { get: function (t, k, r) { return r[k]; } }); p.x", Limits::default()), LimitKind::Reentry); + assert_eq!(limit("var p = {}; for (var i = 0; i < 100000; i++) p = new Proxy(p, {}); p.x", Limits::default()), LimitKind::Reentry); + assert_eq!( + limit("var h = {}; var p = new Proxy({}, h); h.__proto__ = p; Reflect.setPrototypeOf(h, p); p.x", Limits::default()), + LimitKind::Reentry + ); + // A `getPrototypeOf` trap that gives the proxy back makes a chain without end, which the fuel ends. + let chain = "var p = new Proxy({}, { getPrototypeOf: function () { return p; } });"; + assert_eq!(limit(&format!("{chain} for (var k in p) {{}}"), fuel.clone()), LimitKind::Fuel); + assert_eq!(limit(&format!("{chain} ({{}}) instanceof function () {{}}; Object.prototype.isPrototypeOf.call({{}}, p)"), fuel), LimitKind::Fuel); +} + +// ---- Reflect ---- + +#[test] +fn reflect_is_a_plain_object_of_functions() { + truth( + "var names = Object.getOwnPropertyNames(Reflect).sort().join(); + names === 'apply,construct,defineProperty,deleteProperty,get,getOwnPropertyDescriptor,getPrototypeOf,has,isExtensible,ownKeys,preventExtensions,set,setPrototypeOf' + && Object.getPrototypeOf(Reflect) === Object.prototype && Reflect.apply.length === 3 && Reflect.construct.length === 2 + && Reflect.set.length === 3", + ); + type_errors(&["Reflect()", "new Reflect()", "Reflect.get(1, 'x')", "Reflect.ownKeys('abc')", "Reflect.apply(function () {}, null, 1)"]); +} + +#[test] +fn reflect_methods_answer_with_booleans_and_receivers() { + truth( + "var o = {}; Object.defineProperty(o, 'fixed', { value: 1 }); Object.preventExtensions(o); + !Reflect.defineProperty(o, 'n', { value: 1 }) && !Reflect.deleteProperty(o, 'fixed') && !Reflect.set(o, 'fixed', 2) + && !Reflect.set(o, 'n', 1) && Reflect.has(o, 'fixed') && !Reflect.isExtensible(o) && Reflect.preventExtensions(o)", + ); + truth( + "var base = { get who() { return this.name; }, set who(v) { this.got = v; } }; + var me = { name: 'me' }; + Reflect.get(base, 'who', me) === 'me' && Reflect.set(base, 'who', 5, me) && me.got === 5 && !('got' in base)", + ); + truth( + "var data = { v: 1 }, target = {}; + Reflect.set(data, 'v', 2, target) && data.v === 1 && target.v === 2 && Reflect.getOwnPropertyDescriptor(target, 'v').enumerable", + ); + truth( + "var a = {}, b = Object.create(a); + !Reflect.setPrototypeOf(a, b) && !Reflect.setPrototypeOf(Object.prototype, {}) && Reflect.setPrototypeOf(Object.prototype, null) + && Reflect.setPrototypeOf(b, null) && Reflect.getPrototypeOf(b) === null && type_error(function () { Reflect.setPrototypeOf(b, 1); })", + ); + truth( + "function F(x) { this.x = x; } F.prototype.kind = 'F'; + function G() {} G.prototype.kind = 'G'; + var f = Reflect.construct(F, [3]), g = Reflect.construct(F, [4], G); + f.x === 3 && f.kind === 'F' && g.x === 4 && g.kind === 'G' && Reflect.apply(Math.max, null, [1, 5, 2]) === 5 + && type_error(function () { Reflect.construct(F, [], Math.max); }) && type_error(function () { Reflect.construct(Math.max, []); })", + ); + truth( + "var d = Reflect.getOwnPropertyDescriptor({ a: 1 }, 'a'); + d.value === 1 && d.writable && Reflect.getOwnPropertyDescriptor({}, 'a') === undefined && Reflect.ownKeys([1]).join() === '0,length'", + ); +} + +#[test] +fn reflect_construct_gives_a_built_in_object_the_prototype_of_new_target() { + truth( + "function F() {} F.prototype.kind = 'F'; + var a = Reflect.construct(Array, [1, 2], F), e = Reflect.construct(Error, ['m'], F), d = Reflect.construct(Date, [0], F); + Object.getPrototypeOf(a) === F.prototype && a.length === 2 && Array.isArray(a) && a.kind === 'F' + && Object.getPrototypeOf(e) === F.prototype && e.message === 'm' && Object.getPrototypeOf(d) === F.prototype", + ); + // A `newTarget` whose `prototype` is not an object leaves the built-in's own. `Object` with a + // different `newTarget` makes a new object and leaves its argument alone. + truth( + "function G() {} G.prototype = 1; function F() {} var o = {}; + var made = Reflect.construct(Object, [o], F), plain = Reflect.construct(Object, [o], G); + Object.getPrototypeOf(Reflect.construct(Array, [], G)) === Array.prototype + && made !== o && Object.getPrototypeOf(made) === F.prototype && Object.getPrototypeOf(o) === Object.prototype + && plain !== o && Object.getPrototypeOf(plain) === Object.prototype && Reflect.construct(Object, [o]) === o", + ); +} + +/// Runs `src` with a collection at every heap reservation, and checks that it gives `true`. +fn truth_collecting(src: &str) { + let mut realm = es(); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let r = realm.run(&format!("{PRELUDE}{src}")); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert_eq!(r, Ok(JsValue::Bool(true)), "{src}"); + assert!(realm.interp().heap.collections > 0, "{src}"); +} + +#[test] +fn a_descriptor_a_trap_makes_stays_reachable_while_it_is_read() { + let trap = "var p = new Proxy({}, { getOwnPropertyDescriptor: function () { return { value: { v: 7 }, configurable: true }; } });"; + let accessor = "var q = new Proxy({}, { getOwnPropertyDescriptor: function () { + return { get: function () { return 8; }, configurable: true }; } });"; + truth_collecting(&format!( + "{trap} Object.getOwnPropertyDescriptor(p, 'x').value.v === 7 && Reflect.getOwnPropertyDescriptor(p, 'x').value.v === 7" + )); + truth_collecting(&format!("{accessor} Object.getOwnPropertyDescriptor(q, 'x').get() === 8")); +} + +// ---- proxies elsewhere in the language ---- + +#[test] +fn a_proxy_works_as_a_prototype_and_a_with_scope() { + truth( + "var p = new Proxy({}, { get: function (t, k, r) { return k === 'hi' ? 'from proxy' : undefined; }, + has: function (t, k) { return k === 'hi'; } }); + var o = Object.create(p); + o.own = 1; + var r; + with (p) { r = hi; } + o.hi === 'from proxy' && ('hi' in o) && r === 'from proxy' && p.isPrototypeOf === undefined", + ); + truth( + "var log = []; + var p = new Proxy({}, { set: function (t, k, v, r) { log.push(k, r === o); return true; } }); + var o = Object.create(p); + o.x = 1; + log.join() === 'x,true' && !o.hasOwnProperty('x')", + ); + truth("var o = {}; Object.prototype.isPrototypeOf.call(Object.prototype, new Proxy(o, {}))"); +} + +#[test] +fn arrays_json_for_in_and_keys_read_a_proxy_through_its_traps() { + truth( + "var p = new Proxy([1, 2], {}); + Array.isArray(p) && JSON.stringify(p) === '[1,2]' && JSON.stringify({ a: p }) === '{\"a\":[1,2]}' + && Object.prototype.toString.call(p) === '[object Array]' && [0].concat(p).length === 3", + ); + truth( + "var p = new Proxy({}, { + ownKeys: function () { return ['b', 'a', 'hidden']; }, + getOwnPropertyDescriptor: function (t, k) { return { value: k, enumerable: k !== 'hidden', configurable: true }; }, + get: function (t, k) { return k.toUpperCase(); } + }); + var seen = []; + for (var k in p) seen.push(k); + seen.join() === 'b,a' && Object.keys(p).join() === 'b,a' && JSON.stringify(p) === '{\"b\":\"B\",\"a\":\"A\"}'", + ); + // A proxy on the prototype chain lists its names, and its `has` trap does not hide them. + truth( + "var p = new Proxy({ x: 1 }, { has: function () { return false; } }); + var seen = []; + for (var k in Object.create(p)) seen.push(k); + seen.join() === 'x'", + ); + // A name deleted or made non-enumerable during the loop is not visited, a name from the + // proxy's prototype still is, and the `has` trap is not asked. + truth( + "var t = { a: 1, b: 2, c: 3 }, asked = false; + var p = new Proxy(t, { has: function () { asked = true; return true; } }); + Reflect.setPrototypeOf(t, { d: 4 }); + var seen = []; + for (var k in p) { seen.push(k); if (k === 'a') { delete t.b; Object.defineProperty(t, 'c', { enumerable: false }); } } + seen.join() === 'a,d' && !asked", + ); + // A proxy on an array's prototype chain answers for indices the array's own properties do not + // show, so a long array method visits every index rather than only the stored ones. + truth( + "var p = new Proxy({}, { has: function (t, k) { return k === '5000'; }, get: function (t, k) { return k === '5000' ? 'x' : undefined; } }); + var a = []; a.length = 20000; Reflect.setPrototypeOf(a, p); + Array.prototype.indexOf.call(a, 'x') === 5000", + ); + // A new prototype set during a long array method brings its indices with it. + truth( + "var proto = Object.create(Array.prototype); proto[19999] = 'z'; + var a = []; a.length = 20000; a[0] = 0; + var seen = []; + a.forEach(function (v, i) { seen.push(i); if (i === 0) Reflect.setPrototypeOf(a, proto); }); + seen.join() === '0,19999'", + ); +} + +#[test] +fn instanceof_and_typeof_read_a_proxy() { + truth( + "function F() {} + var f = new F(); + var PF = new Proxy(F, { get: function (t, k) { return k === 'prototype' ? Array.prototype : t[k]; } }); + var viaProto = new Proxy({}, { getPrototypeOf: function () { return F.prototype; } }); + [] instanceof PF && !(f instanceof PF) && viaProto instanceof F && typeof PF === 'function'", + ); +} + +// ---- host functions ---- + +#[test] +fn a_host_function_refuses_a_proxy_and_names_the_argument() { + let mut realm = es(); + let seen: Rc>> = Rc::default(); + let log = seen.clone(); + let f: HostFunction = Rc::new(move |mut args| { + let v = if args.is_empty() { Data::Undefined } else { args.remove(0) }; + log.borrow_mut().push(v.clone()); + Ok(v) + }); + realm.define_host_object("host", vec![("take".into(), HostItem::Function(f))]).unwrap(); + for (src, place) in + [("host.take(new Proxy({}, {}))", "argument[0] is a proxy"), ("host.take({ a: [new Proxy([], {})] })", "argument[0].a[0] is a proxy")] + { + match realm.run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => { + assert!(message.starts_with("TypeError") && message.contains(place), "{src}: {message}"); + } + other => panic!("{src}: {other:?}"), + } + } + assert!(seen.borrow().is_empty(), "the host function did not run"); + // The traps did not run either. + let mut realm = es(); + let f: HostFunction = Rc::new(|_| Ok(Data::Undefined)); + realm.define_host_object("host", vec![("take".into(), HostItem::Function(f))]).unwrap(); + let r = realm.run("var ran = false; try { host.take(new Proxy({}, { ownKeys: function () { ran = true; return []; } })); } catch (e) {} ran"); + assert_eq!(r, Ok(JsValue::Bool(false))); +} diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index d9713de57f..e133e9104f 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -32,6 +32,10 @@ //! arrow functions, templates, default and rest parameters) without and with that option, and //! prints both counts; its failures with the option go to `es2015-failures.txt`. //! +//! A sixth test runs the tests under `test/built-ins/Proxy` and `test/built-ins/Reflect` whose +//! feature tags are all in [`PROXY_REFLECT_FEATURES`], without and with `Options::es2015`, and +//! prints both counts; its failures with the option go to `proxy-reflect-failures.txt`. +//! //! Two more tests read the Annex B trees, where tests name any edition's section: one parses every //! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset //! (failures in `annexb-parse-failures.txt`), and one runs those tests and the tests under the @@ -788,6 +792,95 @@ fn run_es2015(dir: &Path) { assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display()); } +/// The feature tags of the `Proxy` and `Reflect` tests [`run_proxy_reflect`] runs: the two +/// objects and the forms [`Options::es2015`] reads. A test with any other tag (`Symbol`, `class` +/// and the like) is counted as skipped. +const PROXY_REFLECT_FEATURES: &[&str] = + &["Proxy", "Reflect", "Reflect.construct", "let", "const", "arrow-function", "template", "default-parameters", "rest-parameters"]; + +#[test] +fn proxy_and_reflect_run() { + let Some(dir) = suite_dir() else { + println!("test262 Proxy and Reflect: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_proxy_reflect(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests under `test/built-ins/Proxy` and `test/built-ins/Reflect` whose feature tags +/// are all in [`PROXY_REFLECT_FEATURES`], each in a new realm after the harness as [`run_tests`] +/// runs them, once without and once with [`Options::es2015`]. Module, asynchronous and negative +/// parse tests, and those that need another missing built-in, are counted as skipped. The counts +/// of both runs are printed, and the failures with the option go to `proxy-reflect-failures.txt`. +fn run_proxy_reflect(dir: &Path) { + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let missing = missing_builtins(&[TEXT_BUILTINS, "Proxy Reflect"]); + let modern = Options { es2015: true, ..Options::default() }; + let editions = [Options::default(), modern.clone()]; + let mut counts = [RunCounts::default(), RunCounts::default()]; + let (mut skipped, mut other_features) = (0usize, 0usize); + for folder in ["test/built-ins/Proxy", "test/built-ins/Reflect"] { + let root = or_fail(inside(dir, folder)); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + for path in or_fail(test_files(&root)) { + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if !meta.features.iter().all(|f| PROXY_REFLECT_FEATURES.contains(&f.as_str())) { + other_features += 1; + continue; + } + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + if has("module") + || has("async") + || meta.negative_phase.as_deref() == Some("parse") + || needs_missing_builtin_in(&[&source, &includes], &missing, &modern) + { + skipped += 1; + continue; + } + for (options, counts) in editions.iter().zip(counts.iter_mut()) { + counts.tests += 1; + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_one(&script, negative_type.as_deref(), options)) { + Ok(Ok(())) => counts.passed += 1, + Ok(Err(why)) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {why}\n")); + } + Err(_) => { + counts.failed += 1; + counts.panicked += 1; + counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n")); + } + } + } + } + } + } + let [before, after] = counts; + assert!(after.tests > 0, "no Proxy or Reflect tests under {}", dir.display()); + let report = dir.join("proxy-reflect-failures.txt"); + if let Err(e) = std::fs::write(&report, &after.failures) { + println!("could not write {}: {e}", report.display()); + } + println!( + "test262 Proxy and Reflect: without Options::es2015 {}; with it {}. Skipped {skipped} module, asynchronous, negative \ + parse or missing-built-in tests and {other_features} tests with other feature tags. Failures: {}", + before.summary(), + after.summary(), + report.display() + ); + assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display()); +} + #[test] fn annex_b_runs() { let Some(dir) = suite_dir() else { diff --git a/docs/mcp.md b/docs/mcp.md index ec6f2d7f76..a4a1c48430 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2624,7 +2624,12 @@ parameters, and spread in array literals, calls and `new`. Spread reads arrays b before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and -an engine that `#targetengine` keeps reads each run the way that run's script does. A +an engine that `#targetengine` keeps reads each run the way that run's script does. A `.js` script also has the +globals `Proxy`, with `Proxy.revocable`, and `Reflect` (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 +and 26.2), with string property names. A trap is a script call: it takes fuel and counts against the limit on nested calls, and +a trap result that breaks one of the proxy invariants, or any operation on a revoked proxy, throws a `TypeError`. A +proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps has +`Proxy` and `Reflect` when its first run was a `.js` script. A `.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. The script reaches the app through the global object `vc`, and writes to the Script Console and runs other files through `$`: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 98cb315cc1..079dff8c9b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1080,6 +1080,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 reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. 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. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 557 other runs pass with it (373 and 27 without it); the 24 failing runs expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file both globals; a `.jsx` file and a `source` string have neither. `cargo xtask test262` runs the suite's `Proxy` and `Reflect` tests whose features are present: 573 of 659 runs pass with the option (0 without it); the 86 failing runs expect function `name` properties and a configurable function `length`, `Object.setPrototypeOf`, and integer keys listed before other keys, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.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), 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: 6,798 of 6,866 runs pass (the 34 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,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 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`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. From 6538539cbe5237bdb9e84ada72433d5df9132218 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:29:34 -0800 Subject: [PATCH 02/50] Docs: Proxy and Reflect test262 counts include the tests that do not parse --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 09eac1ca0a..405984ca5c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1080,7 +1080,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 reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. 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. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file both globals; a `.jsx` file and a `source` string have neither. `cargo xtask test262` runs the suite's `Proxy` and `Reflect` tests whose features are present: 573 of 659 runs pass with the option (0 without it); the 86 failing runs expect function `name` properties and a configurable function `length`, `Object.setPrototypeOf`, and integer keys listed before other keys, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file both globals; a `.jsx` file and a `source` string have neither. `cargo xtask test262` runs the suite's `Proxy` and `Reflect` tests whose features are present: 573 of 663 runs pass with the option (0 without it). Of the 90 failing runs, 4 do not parse because the tests use method definitions, and 86 expect function `name` properties and a configurable function `length`, `Object.setPrototypeOf`, and integer keys listed before other keys, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.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), 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: 6,798 of 6,866 runs pass (the 34 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,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 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`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. From 831c19121c84c06eb8486bdd83b47e132db60748 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:11:30 -0800 Subject: [PATCH 03/50] JavaScript: a kept engine gets Proxy and Reflect at its first .js run A realm made without Options::es2015 adds Proxy and Reflect at its first run with the option, and keeps them when the option is turned off. A Proxy or Reflect global that an earlier run defined stays as it is. --- crates/engine/src/tests/script_run.rs | 6 ++++++ crates/js/src/builtins.rs | 9 ++++++++- crates/js/src/builtins/reflect.rs | 21 +++++++++++++++++---- crates/js/src/interp.rs | 4 ++++ crates/js/src/proxy_tests.rs | 15 +++++++++++++-- crates/js/src/realm.rs | 15 ++++++++++++++- docs/mcp.md | 4 ++-- 7 files changed, 64 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 10eca3a3f4..5dd1cf2aa9 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -353,6 +353,12 @@ fn a_js_script_has_proxy_and_reflect_and_a_jsx_script_does_not() { let log = r["log"].as_array().unwrap(); assert!(log[0].as_str().is_some_and(|m| m.starts_with("TypeError") && m.contains("is a proxy")), "{r}"); assert_eq!(log[1], json!(false), "{r}"); + // An engine that `#targetengine` keeps gets both at its first `.js` run, after a `.jsx` one. + let kept = format!("#targetengine proxykept\n{names}"); + let first = s.execute("script.run", &write("kept.jsx", &kept)).unwrap(); + assert_eq!(first["log"], json!(["undefined undefined"]), "{first}"); + let second = s.execute("script.run", &write("kept.js", &kept)).unwrap(); + assert_eq!(second["log"], json!(["function object"]), "{second}"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 1513b59919..9594bf9a44 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -80,6 +80,13 @@ pub(crate) fn install(interp: &mut Interp) { } } +/// Adds `Proxy` and `Reflect` to a realm that does not have them yet, for a run with +/// [`crate::Options::es2015`] in a realm made without it. A `Proxy` or `Reflect` global that an +/// earlier run defined stays as it is. +pub(crate) fn install_es2015(interp: &mut Interp) -> JsResult<()> { + if interp.es2015_installed { Ok(()) } else { reflect::install(interp, true) } +} + fn try_install(interp: &mut Interp) -> JsResult<()> { let object_proto = alloc(interp, Class::Ordinary, None); interp.intrinsics.object_proto = object_proto; @@ -149,7 +156,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { crate::xml_builtins::install(interp)?; } if interp.options.es2015 { - reflect::install(interp)?; + reflect::install(interp, false)?; } Ok(()) } diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index bd2352132f..d8d2a558d4 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -11,12 +11,25 @@ use crate::interp::{Desc, Interp, JsResult}; use crate::proxy::desc_values; use crate::value::Value; -pub(super) fn install(interp: &mut Interp) -> JsResult<()> { +/// Defines `Proxy` and `Reflect` on the global object. With `keep`, for a realm that gets them +/// after earlier runs, a global of the same name that a script defined stays as it is. +pub(super) fn install(interp: &mut Interp, keep: bool) -> JsResult<()> { let global = interp.global; - let proxy = native(interp, "Proxy", proxy_ctor, 2, NativeKind::Plain, true)?; - method(interp, proxy, "revocable", revocable, 2)?; - data(interp, global, "Proxy", Value::Object(proxy), HIDDEN)?; + if !(keep && interp.get_own_property(global, &key("Proxy"))?.is_some()) { + let proxy = native(interp, "Proxy", proxy_ctor, 2, NativeKind::Plain, true)?; + data(interp, global, "Proxy", Value::Object(proxy), HIDDEN)?; + method(interp, proxy, "revocable", revocable, 2)?; + } + if !(keep && interp.get_own_property(global, &key("Reflect"))?.is_some()) { + install_reflect(interp)?; + } + interp.es2015_installed = true; + Ok(()) +} +/// The `Reflect` object and its functions (section 26.1). +fn install_reflect(interp: &mut Interp) -> JsResult<()> { + let global = interp.global; let object_proto = interp.intrinsics.object_proto; let reflect = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); data(interp, global, "Reflect", Value::Object(reflect), HIDDEN)?; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index f3ff24645e..e22743bb86 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -243,6 +243,9 @@ pub(crate) struct Interp { global_vars: std::collections::HashSet, /// The [`Options::es2015`] a host set while a run was going, for the runs after it. pub(crate) next_es2015: Option, + /// Whether the realm has `Proxy` and `Reflect`. A run with [`Options::es2015`] in a realm + /// made without it adds them. + pub(crate) es2015_installed: bool, /// The template objects tagged templates have made, by code and template index, each with /// its code (ECMA-262 2015 section 12.2.9.3 keeps one object for each site). pub(crate) template_objects: std::collections::HashMap<(usize, u32), (Rc, ObjId)>, @@ -539,6 +542,7 @@ impl Interp { global_lex, global_vars: std::collections::HashSet::new(), next_es2015: None, + es2015_installed: false, template_objects: std::collections::HashMap::new(), intrinsics: Intrinsics::placeholder(), fuel: u64::MAX, diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index a8f6f4a13b..5d1b8146d7 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -45,15 +45,26 @@ fn limit(src: &str, limits: Limits) -> LimitKind { // ---- the realm gate ---- #[test] -fn only_a_realm_made_with_es2015_has_proxy_and_reflect() { +fn only_a_realm_that_ran_es2015_code_has_proxy_and_reflect() { let names = "typeof Proxy + ' ' + typeof Reflect"; assert_eq!(es().run(names), Ok(JsValue::String("function object".into()))); assert_eq!(Realm::new().run(names), Ok(JsValue::String("undefined undefined".into()))); let e4x = Options { e4x: true, ..Options::default() }; assert_eq!(Realm::with_options(e4x, Limits::default()).run(names), Ok(JsValue::String("undefined undefined".into()))); + // A realm made without the option gets both at its first run with it, once, and keeps them. let mut later = Realm::new(); - later.set_es2015(true); assert_eq!(later.run(names), Ok(JsValue::String("undefined undefined".into()))); + later.set_es2015(true); + assert_eq!(later.run(&format!("var first = Proxy, firstReflect = Reflect; {names}")), Ok(JsValue::String("function object".into()))); + later.set_es2015(false); + assert_eq!(later.run(names), Ok(JsValue::String("function object".into()))); + later.set_es2015(true); + assert_eq!(later.run("Proxy === first && Reflect === firstReflect"), Ok(JsValue::Bool(true))); + // A global of either name that an earlier run defined stays as that run left it. + let mut taken = Realm::new(); + assert_eq!(taken.run("var Proxy = 1; Object.defineProperty(this, 'Reflect', { value: 2 }); 0"), Ok(JsValue::Number(0.0))); + taken.set_es2015(true); + assert_eq!(taken.run("Proxy + Reflect"), Ok(JsValue::Number(3.0))); } // ---- Proxy ---- diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 728839949c..6edc064a23 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -218,7 +218,8 @@ impl Realm { /// Sets [`Options::es2015`] for the next runs, and for the code they evaluate. The `let` and /// `const` names earlier runs declared stay visible when it is turned off. A run begun with /// [`Realm::start`] that is still going keeps the language it started with for the code it - /// evaluates; the new one applies once it ends. + /// evaluates; the new one applies once it ends. A realm made without the option gets `Proxy` + /// and `Reflect` at its first run with it, and keeps them when it is turned off. pub fn set_es2015(&mut self, es2015: bool) { if self.is_running() || self.interp.waiting { self.interp.next_es2015 = Some(es2015); @@ -274,6 +275,18 @@ impl Realm { interp.finally_marks.clear(); interp.finally_sites.clear(); interp.error_mark = None; + // A realm made without `Options::es2015` gets `Proxy` and `Reflect` at its first run with it. + if interp.options.es2015 + && let Err(e) = crate::builtins::install_es2015(interp) + { + interp.temp_roots.clear(); + let (kind, message) = match e { + Abrupt::Limit(kind) => (RunErrorKind::Limit(kind), format!("limit reached: {kind:?}")), + Abrupt::Throw(v) => (RunErrorKind::Internal, format!("Proxy and Reflect could not be installed: {}", interp.describe(&v))), + Abrupt::Internal(m) => (RunErrorKind::Internal, format!("Proxy and Reflect could not be installed: {m}")), + }; + return Err(RunError { kind, message, line: 0, column: 0, authored: false }); + } let strict = interp.options.strict; interp.evaluated = next_tag(interp.evaluated); self.script_tag = interp.evaluated; diff --git a/docs/mcp.md b/docs/mcp.md index a4a1c48430..10bf9c68e6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2628,8 +2628,8 @@ an engine that `#targetengine` keeps reads each run the way that run's script do globals `Proxy`, with `Proxy.revocable`, and `Reflect` (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. A trap is a script call: it takes fuel and counts against the limit on nested calls, and a trap result that breaks one of the proxy invariants, or any operation on a revoked proxy, throws a `TypeError`. A -proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps has -`Proxy` and `Reflect` when its first run was a `.js` script. A +proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets +`Proxy` and `Reflect` at its first `.js` run and keeps them for later `.jsx` runs. A `.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. The script reaches the app through the global object `vc`, and writes to the Script Console and runs other files through `$`: From 1296c9d7e68229ef5630696ac69491b06621a8f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:26:46 -0800 Subject: [PATCH 04/50] JavaScript: Reflect.apply and Reflect.construct read an argument list length with ToLength A negative or NaN length gives no arguments, and a fractional length is truncated before the argument limit is checked. Function.prototype.apply keeps the ES5 ToUint32 rule. --- crates/js/src/builtins/reflect.rs | 2 +- crates/js/src/interp.rs | 19 +++++++++++++++---- crates/js/src/proxy_tests.rs | 13 +++++++++++++ 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index d8d2a558d4..450a9eb2f4 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -100,7 +100,7 @@ fn argument_list(interp: &mut Interp, list: &Value, function: &str) -> JsResult< if !matches!(list, Value::Object(_)) { return Err(interp.type_error(&format!("Reflect.{function}: the argument list is not an object"))); } - interp.list_from_array_like(list) + interp.list_from_array_like(list, true) } /// `Reflect.apply(target, thisArgument, argumentsList)` (section 26.1.1). diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index e22743bb86..7862dbe3c6 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2843,7 +2843,7 @@ impl Interp { let list = args.get(1).cloned().unwrap_or(Value::Undefined); f = this; this = args.first().cloned().unwrap_or(Value::Undefined); - args = self.list_from_array_like(&list)?; + args = self.list_from_array_like(&list, false)?; } Func::Bound { target, this: bound_this, args: bound_args } => { self.use_fuel()?; @@ -2901,8 +2901,10 @@ impl Interp { } } - /// The elements of an array-like `apply` argument (section 15.3.4.3). - pub(crate) fn list_from_array_like(&mut self, list: &Value) -> JsResult> { + /// The elements of an array-like `apply` argument (section 15.3.4.3). With `to_length`, the + /// length is read with ToLength (ECMA-262 2020 sections 7.1.20 and 7.3.17), so a negative + /// length gives no elements; otherwise it is read with ToUint32. + pub(crate) fn list_from_array_like(&mut self, list: &Value, to_length: bool) -> JsResult> { let Value::Object(o) = list else { if list.is_nullish() { return Ok(Vec::new()); @@ -2910,7 +2912,16 @@ impl Interp { return Err(self.type_error("the argument list is not an object")); }; let len = self.get_from(*o, &key("length"), list)?; - let n = to_uint32(self.to_number(&len)?) as usize; + let len = self.to_number(&len)?; + let n = if !to_length { + to_uint32(len) as usize + } else if len.is_nan() || len <= 0.0 { + 0 + } else if len.trunc() > MAX_APPLY_ARGS as f64 { + MAX_APPLY_ARGS + 1 + } else { + to_uint32(len) as usize + }; if n > MAX_APPLY_ARGS { return Err(self.throw(ErrorType::Range, "too many arguments")); } diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 5d1b8146d7..ec993f914c 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -258,6 +258,19 @@ fn reflect_is_a_plain_object_of_functions() { type_errors(&["Reflect()", "new Reflect()", "Reflect.get(1, 'x')", "Reflect.ownKeys('abc')", "Reflect.apply(function () {}, null, 1)"]); } +#[test] +fn reflect_reads_an_argument_list_length_with_to_length() { + truth( + "function count() { return arguments.length; } + function Made() { this.n = arguments.length; } + Reflect.apply(count, null, { length: -1 }) === 0 && Reflect.apply(count, null, { length: 2.5 }) === 2 + && Reflect.apply(count, null, { length: NaN }) === 0 && new Made().n === 0 + && Reflect.apply(count, null, { length: 65536.5 }) === 65536 + && Reflect.construct(Made, { length: -5 }).n === 0 + && (function () { try { Reflect.apply(count, null, { length: 4294967296 }); } catch (e) { return e instanceof RangeError; } return false; })()", + ); +} + #[test] fn reflect_methods_answer_with_booleans_and_receivers() { truth( From 7285bd87a18c8cc596536e933fcc02fbbd6bd320 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 15:47:52 -0800 Subject: [PATCH 05/50] JavaScript: for-in, spread, Reflect.construct and eval follow the proxy and kept-realm rules - for-in skips a name made non-enumerable during the loop on an ordinary object as it does on a proxy, and a name a proxy's ownKeys trap lists without a descriptor no longer hides the same name further up the chain. - Spread treats a proxy on an array's prototype chain as code that can run on an index read, so a long array is not refused before its elements are read. - Reflect.construct with Number, String, Date or Function converts the arguments before it reads newTarget's prototype (ECMA-262 2020 sections 20.1.1.1, 21.1.1.1, 20.4.2 and 19.2.1.1.1). - Eval code outside strict mode code is checked against the let and const names of earlier runs when Options::es2015 is off. - Options::es2015's doc and the target-app-parity line describe a kept realm that gets Proxy and Reflect at its first run with the option. --- crates/js/src/es2015_tests.rs | 16 +++++++ crates/js/src/interp.rs | 79 ++++++++++++++++++++++++----------- crates/js/src/lib.rs | 5 ++- crates/js/src/proxy_tests.rs | 74 ++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 5 files changed, 149 insertions(+), 27 deletions(-) diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 0173fb2d6c..53493ceb21 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -194,6 +194,22 @@ fn a_function_eval_declares_on_the_global_object_sees_global_lexical_bindings() assert_eq!(realm.run("function g() { eval('function inner() { return x; }'); return inner(); } g()"), Ok(JsValue::Number(7.0))); } +#[test] +fn eval_without_the_option_cannot_redeclare_an_earlier_runs_let() { + // An earlier run's `let` stays a `let` when the option is turned off: an eval `var` or + // function of the same name is a `SyntaxError`, and the binding keeps its value. + let mut realm = es(); + assert_eq!(realm.run("let x = 1; 0"), Ok(JsValue::Number(0.0))); + realm.set_es2015(false); + for src in ["eval('var x = 2')", "eval('function x() {}')", "(0, eval)('var x = 2')"] { + let r = realm.run(src); + assert!(matches!(&r, Err(RunError { message, .. }) if message.starts_with("SyntaxError")), "{src}: {r:?}"); + } + assert_eq!(realm.run("x === 1 && !this.hasOwnProperty('x')"), Ok(JsValue::Bool(true))); + // A name no `let` holds is still declared. + assert_eq!(realm.run("eval('var y = 3'); y"), Ok(JsValue::Number(3.0))); +} + #[test] fn a_global_var_makes_its_own_property_over_an_inherited_one() { // ECMA-262 2015 section 8.1.1.4.17 reads the global object's own property, so `var` makes a diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 7862dbe3c6..b41d3609e0 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2534,11 +2534,15 @@ impl Interp { } /// Whether reading the elements of `o` by index can run code: `o` or an object it inherits - /// from has an accessor property with an index name. Each object takes a unit of fuel. + /// from has an accessor property with an index name, or a proxy, whose traps answer the reads + /// that reach it, is on its prototype chain. Each object takes a unit of fuel. fn has_index_getter(&mut self, o: ObjId) -> JsResult { let mut cur = Some(o); while let Some(id) = cur { self.use_fuel()?; + if self.is_proxy(id) { + return Ok(true); + } let object = self.object(id)?; if object.props.iter().any(|(k, p)| matches!(p, Prop::Accessor { .. }) && array_index(k).is_some()) { return Ok(true); @@ -2652,7 +2656,8 @@ impl Interp { /// [`Self::enumerable_keys`] after the XML case. A proxy on the chain gives its names with its /// `ownKeys` trap, whether each is enumerable with its `getOwnPropertyDescriptor` trap and the - /// next object with its `getPrototypeOf` trap, which `temp_roots[slot]` keeps reachable. + /// next object with its `getPrototypeOf` trap, which `temp_roots[slot]` keeps reachable. A name + /// whose descriptor trap gives `undefined` does not hide the same name further up the chain. fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult> { let mut seen = std::collections::HashSet::new(); let mut out = Vec::new(); @@ -2661,10 +2666,12 @@ impl Interp { if self.is_proxy(o) { for k in self.own_keys(o)? { self.use_fuel()?; - if !seen.insert(k.clone()) { + if seen.contains(&k) { continue; } - if self.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) { + let Some(p) = self.get_own_property(o, &k)? else { continue }; + seen.insert(k.clone()); + if p.enumerable() { out.push(k); } } @@ -2744,11 +2751,11 @@ impl Interp { } /// Whether `for-in` over `o` still visits `k` (section 12.6.4; ECMA-262 2020 section - /// 13.7.5.15): an object on the chain before any proxy has the property, or a proxy's - /// `getOwnPropertyDescriptor` trap gives an enumerable one, or the objects after a proxy - /// without the property have it. A name deleted, or on a proxy made non-enumerable, after the - /// names were listed is skipped. A proxy's `has` trap is not asked. Each proxy on the chain - /// takes a unit of fuel. + /// 13.7.5.15): the property found first on the chain, on an ordinary object or through a + /// proxy's `getOwnPropertyDescriptor` trap, is enumerable. After a proxy without the property, + /// the objects that follow it are searched. A name deleted or made non-enumerable after the + /// names were listed is skipped, on an ordinary object as on a proxy. A proxy's `has` trap is + /// not asked. Each proxy on the chain takes a unit of fuel. fn for_in_still_has(&mut self, o: ObjId, k: &[u16]) -> JsResult { let mark = self.temp_roots.len(); let r = self.for_in_still_has_rooted(o, k); @@ -2759,7 +2766,7 @@ impl Interp { fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &[u16]) -> JsResult { loop { let p = match self.lookup(cur, k)? { - Lookup::Found(_) => return Ok(true), + Lookup::Found(prop) => return Ok(prop.enumerable()), Lookup::Missing => return Ok(false), Lookup::Proxy(p) => p, }; @@ -3039,19 +3046,24 @@ impl Interp { // With a different `newTarget` (`Reflect.construct`), the new object takes // its `prototype` when that is an object (ECMA-262 2020 section 9.1.14). An // argument given back and a proxy keep their own. `Object` makes a new object - // instead of converting its argument (section 19.1.1.1). - let proto = if same_value(&f, &new_target) { - None - } else { - match self.get_value(&new_target, &key("prototype"))? { - Value::Object(p) => { - self.temp_roots.push(Value::Object(p)); - Some(p) - } - _ => None, + // instead of converting its argument (section 19.1.1.1). `Number`, `String`, + // `Date` and `Function` convert their arguments before `prototype` is read + // (sections 20.1.1.1, 21.1.1.1, 20.4.2 and 19.2.1.1.1), so a conversion that + // throws reads nothing from `newTarget`. + let other_target = !same_value(&f, &new_target); + let converts_first = other_target && { + let i = &self.intrinsics; + let own = [i.number_proto, i.string_proto, i.date_proto, i.function_proto]; + match f.as_object().map(|c| self.ordinary_own_property(c, &key("prototype"))).transpose()?.flatten() { + Some(Prop::Data { value: Value::Object(p), .. }) => own.contains(&p), + _ => false, } }; - if !same_value(&f, &new_target) && f.as_object() == Some(self.intrinsics.object_ctor) { + let mut proto = None; + if other_target && !converts_first { + proto = self.prototype_of_new_target(&new_target)?; + } + if other_target && f.as_object() == Some(self.intrinsics.object_ctor) { let proto = proto.unwrap_or(self.intrinsics.object_proto); self.reserve_heap(OBJECT_BYTES)?; let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); @@ -3061,6 +3073,11 @@ impl Interp { let r = native(self, Value::Undefined, &args, true); self.held_bytes = held; let v = r?; + if converts_first { + // The new object stays reachable while `prototype` is read. + self.temp_roots.push(v.clone()); + proto = self.prototype_of_new_target(&new_target)?; + } if let (Some(p), Value::Object(o)) = (proto, &v) && !self.is_proxy(*o) && !args.iter().any(|a| same_value(a, &v)) @@ -3075,6 +3092,18 @@ impl Interp { } } + /// The `prototype` of `newTarget` when it is an object, kept reachable in `temp_roots` + /// (ECMA-262 2020 section 9.1.14). + fn prototype_of_new_target(&mut self, new_target: &Value) -> JsResult> { + Ok(match self.get_value(new_target, &key("prototype"))? { + Value::Object(p) => { + self.temp_roots.push(Value::Object(p)); + Some(p) + } + _ => None, + }) + } + /// Construct (ECMA-262 2020 section 7.3.13) from Rust: runs a constructor written in /// JavaScript to its end. pub(crate) fn construct(&mut self, f: &Value, args: &[Value], new_target: &Value) -> JsResult { @@ -3618,12 +3647,14 @@ impl Interp { /// /// Gives the environment the code runs in: `env`, or with [`Options::es2015`] eval code's own /// environment of its `let` and `const` names. A script's `let` and `const` names go in the - /// global scope ([`Self::declare_global_lexical`]). + /// global scope ([`Self::declare_global_lexical`]). Eval code outside strict mode code is + /// checked against the `let` and `const` names around it ([`Self::check_eval_vars`]) with the + /// option on or off, so it also meets the names that earlier runs of a kept realm declared. fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { let configurable = if is_eval { CONFIGURABLE } else { 0 }; - if is_eval && !code.strict && self.options.es2015 { + if is_eval && !code.strict { self.check_eval_vars(code, env, var_env)?; - if var_env == self.global_env { + if self.options.es2015 && var_env == self.global_env { self.check_global_functions(code)?; self.check_global_vars(code)?; } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index f2ae96e581..3a8740c4d6 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -118,8 +118,9 @@ pub struct Options { /// template literals (tagged ones included), default and rest parameters, and spread in array /// literals, calls and `new`. Off, they are syntax errors and the language is ES5.1's. Code a /// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts. - /// A realm made with it also has the globals `Proxy` and `Reflect`; turning it on later for a - /// realm made without it does not add them. + /// A realm made with it also has the globals `Proxy` and `Reflect`. A realm made without it + /// gets them at its first run with the option on, and keeps them when later runs turn it off. + /// A `Proxy` or `Reflect` global that an earlier run defined stays as it is. pub es2015: bool, } diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index ec993f914c..e84697eb69 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -324,6 +324,39 @@ fn reflect_construct_gives_a_built_in_object_the_prototype_of_new_target() { ); } +#[test] +fn reflect_construct_reads_new_target_prototype_after_number_and_string_convert() { + // `Number`, `String`, `Date` and `Function` convert their arguments before they read + // `newTarget.prototype`; `Array` and the error types read it first. + let made = "var log = []; + var nt = new Proxy(function () {}, { get: function (t, k) { log.push(k); return t[k]; } }); + var arg = { valueOf: function () { log.push('valueOf'); return 3; }, toString: function () { log.push('toString'); return 's'; } }; + var n = Reflect.construct(Number, [arg], nt), numberLog = log.join(); log = []; + var s = Reflect.construct(String, [arg], nt), stringLog = log.join(); log = []; + var d = Reflect.construct(Date, [arg], nt), dateLog = log.join(); log = []; + var e = Reflect.construct(Error, [arg], nt), errorLog = log.join(); log = []; + var proto = nt.prototype;"; + assert_eq!( + es().run(&format!("{made} [numberLog, stringLog, dateLog, errorLog].join(' | ')")), + Ok(JsValue::String("valueOf,prototype | toString,prototype | valueOf,prototype | prototype,toString".into())) + ); + truth(&format!( + "{made} Object.getPrototypeOf(n) === proto && Number.prototype.valueOf.call(n) === 3 + && Object.getPrototypeOf(s) === proto && String.prototype.toString.call(s) === 's' + && Object.getPrototypeOf(d) === proto && Date.prototype.getTime.call(d) === 3 && Object.getPrototypeOf(e) === proto" + )); + // A conversion that throws reads nothing from `newTarget`. + truth( + "var log = []; + var nt = new Proxy(function () {}, { get: function (t, k) { log.push(k); return t[k]; } }); + var bad = { valueOf: function () { throw 1; }, toString: function () { throw 1; } }; + var thrown = 0; + try { Reflect.construct(Number, [bad], nt); } catch (e) { thrown++; } + try { Reflect.construct(String, [bad], nt); } catch (e) { thrown++; } + thrown === 2 && log.length === 0", + ); +} + /// Runs `src` with a collection at every heap reservation, and checks that it gives `true`. fn truth_collecting(src: &str) { let mut realm = es(); @@ -419,6 +452,47 @@ fn arrays_json_for_in_and_keys_read_a_proxy_through_its_traps() { ); } +#[test] +fn for_in_reads_ordinary_and_proxy_names_by_the_same_rules() { + // A name made non-enumerable during the loop is skipped on an ordinary object, as on a proxy. + truth( + "var o = { a: 1, b: 2, c: 3 }, seen = []; + for (var k in o) { seen.push(k); if (k === 'a') Object.defineProperty(o, 'b', { enumerable: false }); } + var p = new Proxy({ a: 1, b: 2 }, {}), proxySeen = []; + for (var k in Object.create(p)) { proxySeen.push(k); if (k === 'a') Object.defineProperty(p, 'b', { enumerable: false }); } + seen.join() === 'a,c' && proxySeen.join() === 'a'", + ); + // A name the `ownKeys` trap lists without a descriptor does not hide an enumerable one further + // up the chain; a non-enumerable own property does. + truth( + "var p = new Proxy(Object.create({ x: 1, y: 2 }), { + ownKeys: function () { return ['x', 'y']; }, + getOwnPropertyDescriptor: function (t, k) { return k === 'y' ? { value: 0, enumerable: false, configurable: true } : undefined; } + }); + var seen = []; + for (var k in p) seen.push(k); + seen.join() === 'x'", + ); +} + +#[test] +fn spread_lets_a_proxy_on_the_prototype_chain_shrink_a_long_array() { + // A proxy's `get` trap answers for the indices the array does not hold, so the length is not + // refused before the elements are read. + truth( + "var a = []; a.length = 4294967295; + Reflect.setPrototypeOf(a, new Proxy({}, { get: function (t, k) { if (k === '0') a.length = 1; return 'v'; } })); + var r = [...a]; + r.length === 1 && r[0] === 'v'", + ); + // Without a proxy or a getter, the length is refused at once. + let src = "var a = []; a.length = 4294967295; [...a]"; + match es().run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("RangeError"), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + #[test] fn instanceof_and_typeof_read_a_proxy() { truth( diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 405984ca5c..34e09f8112 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1080,7 +1080,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 reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. 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. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file both globals; a `.jsx` file and a `source` string have neither. `cargo xtask test262` runs the suite's `Proxy` and `Reflect` tests whose features are present: 573 of 663 runs pass with the option (0 without it). Of the 90 failing runs, 4 do not parse because the tests use method definitions, and 86 expect function `name` properties and a configurable function `length`, `Object.setPrototypeOf`, and integer keys listed before other keys, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file both globals; a `.jsx` file and a `source` string have neither in a new engine or in an engine that has not run a `.js` file. An engine that `#targetengine` keeps gets both globals at its first `.js` run and keeps them for later `.jsx` runs, which still read ES5.1. `cargo xtask test262` runs the suite's `Proxy` and `Reflect` tests whose features are present: 573 of 663 runs pass with the option (0 without it). Of the 90 failing runs, 4 do not parse because the tests use method definitions, and 86 expect function `name` properties and a configurable function `length`, `Object.setPrototypeOf`, and integer keys listed before other keys, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.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), 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: 6,798 of 6,866 runs pass (the 34 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,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 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`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. From 6df45292e1cd2e5da8de9754497213ef580145a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:01:17 -0800 Subject: [PATCH 06/50] JavaScript: spread reads a proxy of an array as an array, and Proxy ignores newTarget - Spread treats a proxy whose target is an array as an array and reads its length again, through the traps, before each element after the first. A proxy that its length read revokes spreads as the array that length gives. - Reflect.construct(Proxy, args, newTarget) does not read newTarget.prototype (ECMA-262 2020 section 26.2.1.1). --- crates/js/src/interp.rs | 26 +++++++++++++++++++------- crates/js/src/proxy_tests.rs | 20 +++++++++++++++++++- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index b41d3609e0..e3065b709d 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2473,14 +2473,16 @@ impl Interp { } Value::Object(o) if self.has_property(*o, &key("length"))? => { let o = *o; + // Tested before any trap reads `length`, which may revoke the proxy. + let array = self.is_array(&Value::Object(o))?; let len = self.get_from(o, &key("length"), &v)?; // ToLength (ECMA-262 2015 section 7.1.15): a negative or NaN length reads nothing. let n = crate::string_builtins::to_integer(self.to_number(&len)?).max(0.0); // An array's iterator reads its length again before each element (ECMA-262 2015 // section 22.1.5.2.1), so a getter that shrinks or grows the array changes the count, - // and the room is checked as each element is read. Any other object, and an array + // and the room is checked as each element is read. A proxy of an array is read + // the same way, its `length` through its traps. Any other object, and an array // whose elements no getter reads, is checked against the length it has now. - let array = matches!(self.object(o)?.class, Class::Array { .. }); if n >= f64::from(room) && !(array && self.has_index_getter(o)?) { return Err(self.throw(ErrorType::Range, "array literal too long")); } @@ -2492,8 +2494,17 @@ impl Interp { let mut read = || -> JsResult<()> { let mut i = 0; loop { - let end = match &self.object(o)?.class { - Class::Array { length, .. } if array => *length, + let stored = match &self.object(o)?.class { + Class::Array { length, .. } => Some(*length), + _ => None, + }; + let end = match stored { + Some(length) if array => length, + None if array && i > 0 => { + let len = self.get_from(o, &key("length"), &v)?; + let len = crate::string_builtins::to_integer(self.to_number(&len)?).max(0.0); + if len >= f64::from(u32::MAX) { u32::MAX } else { len as u32 } + } _ => n, }; if i >= end { @@ -3042,15 +3053,16 @@ impl Interp { let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); return Ok(Prepared::Closure(Entry { callee, code, env, this: Value::Object(obj), args })); } - Some(Func::Native { f: native, constructor: true, .. }) => { + Some(Func::Native { f: native, constructor: true, name, .. }) => { // With a different `newTarget` (`Reflect.construct`), the new object takes // its `prototype` when that is an object (ECMA-262 2020 section 9.1.14). An // argument given back and a proxy keep their own. `Object` makes a new object // instead of converting its argument (section 19.1.1.1). `Number`, `String`, // `Date` and `Function` convert their arguments before `prototype` is read // (sections 20.1.1.1, 21.1.1.1, 20.4.2 and 19.2.1.1.1), so a conversion that - // throws reads nothing from `newTarget`. - let other_target = !same_value(&f, &new_target); + // throws reads nothing from `newTarget`. `Proxy` does not read it (section + // 26.2.1.1). + let other_target = !same_value(&f, &new_target) && name != "Proxy"; let converts_first = other_target && { let i = &self.intrinsics; let own = [i.number_proto, i.string_proto, i.date_proto, i.function_proto]; diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index e84697eb69..62fa93e2bd 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -355,6 +355,12 @@ fn reflect_construct_reads_new_target_prototype_after_number_and_string_convert( try { Reflect.construct(String, [bad], nt); } catch (e) { thrown++; } thrown === 2 && log.length === 0", ); + // `Proxy` does not read `newTarget.prototype`. + truth( + "var nt = new Proxy(function () {}, { get: function (t, k) { if (k === 'prototype') throw new Error('read'); return t[k]; } }); + var p = Reflect.construct(Proxy, [{ a: 1 }, {}], nt); + p.a === 1", + ); } /// Runs `src` with a collection at every heap reservation, and checks that it gives `true`. @@ -476,7 +482,7 @@ fn for_in_reads_ordinary_and_proxy_names_by_the_same_rules() { } #[test] -fn spread_lets_a_proxy_on_the_prototype_chain_shrink_a_long_array() { +fn spread_lets_a_proxy_shrink_the_array_it_reads() { // A proxy's `get` trap answers for the indices the array does not hold, so the length is not // refused before the elements are read. truth( @@ -485,6 +491,18 @@ fn spread_lets_a_proxy_on_the_prototype_chain_shrink_a_long_array() { var r = [...a]; r.length === 1 && r[0] === 'v'", ); + // A proxy of an array is spread as an array: its length is read again before each element. + truth( + "var t = [1, 2, 3]; + var p = new Proxy(t, { get: function (o, k) { if (k === '0') t.length = 1; return o[k]; } }); + var r = [...p]; + r.length === 1 && r[0] === 1", + ); + // A proxy that its `length` read revokes spreads as the empty array that length gives. + truth( + "var made = Proxy.revocable([], { get: function (t, k) { if (k === 'length') { made.revoke(); return 0; } return t[k]; } }); + [...made.proxy].length === 0", + ); // Without a proxy or a getter, the length is refused at once. let src = "var a = []; a.length = 4294967295; [...a]"; match es().run(src) { From 83b0a2f693a52782537c9e8c9653c070478b3108 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:07:13 -0800 Subject: [PATCH 07/50] JavaScript: spread reads an array's length without asking whether it has one Spread tests whether the value is an array, or a proxy of one, before any trap runs, and then reads its length without calling the proxy's has trap. --- crates/js/src/interp.rs | 7 ++++--- crates/js/src/proxy_tests.rs | 6 ++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index e3065b709d..ab55d891e5 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2455,6 +2455,9 @@ impl Interp { }; // The most elements the array has room for. let room = u32::MAX.saturating_sub(current); + // An array, or a proxy of one, is tested before any trap runs, since a trap may revoke + // the proxy. Its `length` is read without asking whether it has one. + let array = boxed.is_none() && self.is_array(&v)?; let items: Vec = match boxed.as_ref().unwrap_or(&v) { Value::String(s) => { let units = crate::string_builtins::flat_charged(self, s)?; @@ -2471,10 +2474,8 @@ impl Interp { } out } - Value::Object(o) if self.has_property(*o, &key("length"))? => { + Value::Object(o) if array || self.has_property(*o, &key("length"))? => { let o = *o; - // Tested before any trap reads `length`, which may revoke the proxy. - let array = self.is_array(&Value::Object(o))?; let len = self.get_from(o, &key("length"), &v)?; // ToLength (ECMA-262 2015 section 7.1.15): a negative or NaN length reads nothing. let n = crate::string_builtins::to_integer(self.to_number(&len)?).max(0.0); diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 62fa93e2bd..bc71623878 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -503,6 +503,12 @@ fn spread_lets_a_proxy_shrink_the_array_it_reads() { "var made = Proxy.revocable([], { get: function (t, k) { if (k === 'length') { made.revoke(); return 0; } return t[k]; } }); [...made.proxy].length === 0", ); + // A proxy of an array is not asked whether it has a `length`. + truth( + "var asked = false; + var p = new Proxy([1, 2], { has: function (t, k) { asked = true; return k in t; } }); + [...p].join() === '1,2' && !asked", + ); // Without a proxy or a getter, the length is refused at once. let src = "var a = []; a.length = 4294967295; [...a]"; match es().run(src) { From 0a66163dec904a54001e0889397953fd5373fd47 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:05:58 -0800 Subject: [PATCH 08/50] Docs: an earlier run's Proxy or Reflect global stays at the first .js run The target-app-parity line for Proxy and Reflect now says that a Proxy or Reflect global an earlier run in a kept engine defined stays as it is, as install_es2015 does. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 34e09f8112..08e61774c1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1080,7 +1080,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 reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. 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. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file both globals; a `.jsx` file and a `source` string have neither in a new engine or in an engine that has not run a `.js` file. An engine that `#targetengine` keeps gets both globals at its first `.js` run and keeps them for later `.jsx` runs, which still read ES5.1. `cargo xtask test262` runs the suite's `Proxy` and `Reflect` tests whose features are present: 573 of 663 runs pass with the option (0 without it). Of the 90 failing runs, 4 do not parse because the tests use method definitions, and 86 expect function `name` properties and a configurable function `length`, `Object.setPrototypeOf`, and integer keys listed before other keys, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file both globals; a `.jsx` file and a `source` string have neither in a new engine or in an engine that has not run a `.js` file. An engine that `#targetengine` keeps gets both globals at its first `.js` run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and the first `.js` run does not replace it. `cargo xtask test262` runs the suite's `Proxy` and `Reflect` tests whose features are present: 573 of 663 runs pass with the option (0 without it). Of the 90 failing runs, 4 do not parse because the tests use method definitions, and 86 expect function `name` properties and a configurable function `length`, `Object.setPrototypeOf`, and integer keys listed before other keys, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.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), 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: 6,798 of 6,866 runs pass (the 34 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,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 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`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. From d1a1388f7cd0203b92b940fe0e80e96f41c08854 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 11:52:04 -0800 Subject: [PATCH 09/50] JavaScript: a prototype walk through proxies keeps only the prototype it has reached [[GetProperty]] and the for-in recheck kept a root for every prototype a getPrototypeOf trap gave, until the whole walk ended, so a chain of fresh proxies could reach the heap limit. Each walk now holds one root slot and replaces it at each hop. - A function a legacy run declares on the global object stays a root while declaring it runs a proxy's traps on the global object's prototype chain; a collection in a trap freed it before. - Proxy and Reflect become globals after their functions are added, so an install that stops part way leaves no global without them. - The test262 Proxy and Reflect and ES2015 runners name each run that panicked, with or without Options::es2015, its test path and mode. --- crates/js/src/builtins/reflect.rs | 10 ++++--- crates/js/src/interp.rs | 24 ++++++++++++---- crates/js/src/proxy_tests.rs | 46 +++++++++++++++++++++++++++++++ crates/js/tests/test262.rs | 21 ++++++++++++-- 4 files changed, 90 insertions(+), 11 deletions(-) diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index 450a9eb2f4..e55072775e 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -12,13 +12,15 @@ use crate::proxy::desc_values; use crate::value::Value; /// Defines `Proxy` and `Reflect` on the global object. With `keep`, for a realm that gets them -/// after earlier runs, a global of the same name that a script defined stays as it is. +/// after earlier runs, a global of the same name that a script defined stays as it is. Each +/// global is defined after its functions, so an install that stops part way leaves no global +/// that a later install would keep without them. pub(super) fn install(interp: &mut Interp, keep: bool) -> JsResult<()> { let global = interp.global; if !(keep && interp.get_own_property(global, &key("Proxy"))?.is_some()) { let proxy = native(interp, "Proxy", proxy_ctor, 2, NativeKind::Plain, true)?; - data(interp, global, "Proxy", Value::Object(proxy), HIDDEN)?; method(interp, proxy, "revocable", revocable, 2)?; + data(interp, global, "Proxy", Value::Object(proxy), HIDDEN)?; } if !(keep && interp.get_own_property(global, &key("Reflect"))?.is_some()) { install_reflect(interp)?; @@ -32,7 +34,6 @@ fn install_reflect(interp: &mut Interp) -> JsResult<()> { let global = interp.global; let object_proto = interp.intrinsics.object_proto; let reflect = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); - data(interp, global, "Reflect", Value::Object(reflect), HIDDEN)?; method(interp, reflect, "apply", apply, 3)?; method(interp, reflect, "construct", construct, 2)?; method(interp, reflect, "defineProperty", define_property, 3)?; @@ -45,7 +46,8 @@ fn install_reflect(interp: &mut Interp) -> JsResult<()> { method(interp, reflect, "ownKeys", own_keys, 1)?; method(interp, reflect, "preventExtensions", prevent_extensions, 1)?; method(interp, reflect, "set", set, 3)?; - method(interp, reflect, "setPrototypeOf", set_prototype_of, 2) + method(interp, reflect, "setPrototypeOf", set_prototype_of, 2)?; + data(interp, global, "Reflect", Value::Object(reflect), HIDDEN) } // ---- Proxy ---- diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index a7d2984e20..6eb37dbb0f 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1546,7 +1546,9 @@ impl Interp { /// [[GetProperty]]: the property found on the object or its prototype chain, through the /// `getOwnPropertyDescriptor` and `getPrototypeOf` traps of the proxies on it. pub(crate) fn find_property(&mut self, id: ObjId, k: &[u16]) -> JsResult> { + // One root slot holds the prototype the walk has reached; each hop replaces it. let mark = self.temp_roots.len(); + self.temp_roots.push(Value::Undefined); let r = (|| { let mut cur = id; loop { @@ -1558,8 +1560,10 @@ impl Interp { return Ok(Some(prop)); } let Some(next) = self.get_prototype_of(p)? else { return Ok(None) }; + if let Some(root) = self.temp_roots.get_mut(mark) { + *root = Value::Object(next); + } self.use_fuel()?; - self.temp_roots.push(Value::Object(next)); cur = next; } } @@ -2847,13 +2851,15 @@ impl Interp { /// names were listed is skipped, on an ordinary object as on a proxy. A proxy's `has` trap is /// not asked. Each proxy on the chain takes a unit of fuel. fn for_in_still_has(&mut self, o: ObjId, k: &[u16]) -> JsResult { + // One root slot holds the prototype the walk has reached; each hop replaces it. let mark = self.temp_roots.len(); - let r = self.for_in_still_has_rooted(o, k); + self.temp_roots.push(Value::Undefined); + let r = self.for_in_still_has_rooted(o, k, mark); self.temp_roots.truncate(mark); r } - fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &[u16]) -> JsResult { + fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &[u16], slot: usize) -> JsResult { loop { let p = match self.lookup(cur, k)? { Lookup::Found(prop) => return Ok(prop.enumerable()), @@ -2865,7 +2871,9 @@ impl Interp { return Ok(prop.enumerable()); } let Some(next) = self.get_prototype_of(p)? else { return Ok(false) }; - self.temp_roots.push(Value::Object(next)); + if let Some(root) = self.temp_roots.get_mut(slot) { + *root = Value::Object(next); + } cur = next; } } @@ -3799,7 +3807,13 @@ impl Interp { self.use_fuel()?; let Some(fcode) = code.functions.get(*fi as usize).cloned() else { return internal("function out of range") }; let f = self.make_closure(fcode, scope)?; - self.declare(var_env, name, Some(Value::Object(f)), configurable)?; + // Declaring it can run a proxy's traps on the global object's prototype chain, and + // their script can collect, so the new function is a root until it is declared. + let mark = self.temp_roots.len(); + self.temp_roots.push(Value::Object(f)); + let declared = self.declare(var_env, name, Some(Value::Object(f)), configurable); + self.temp_roots.truncate(mark); + declared?; if on_global { self.global_vars.insert(name.clone()); } diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index bc71623878..5b6cf0e950 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -481,6 +481,52 @@ fn for_in_reads_ordinary_and_proxy_names_by_the_same_rules() { ); } +/// A `getPrototypeOf` trap that gives a new proxy of a large array each time it is called, 40 +/// times, and then `null`: the chain it makes holds far more than the heap limit of +/// [`walk_limits`] at once. +const FRESH_CHAIN: &str = "var hops = 0; + function big() { var t = []; for (var i = 0; i < 3000; i++) t[i] = i; return t; } + var tail = { getPrototypeOf: function () { hops++; return hops > 40 ? null : new Proxy(big(), tail); } };"; + +fn walk_limits() -> Limits { + Limits { heap_bytes: 4 << 20, ..Limits::default() } +} + +#[test] +fn a_prototype_walk_keeps_only_the_prototype_it_has_reached() { + // Declaring a function without the option reads the global object's inherited property. + let mut realm = Realm::with_options(es_options(), walk_limits()); + assert_eq!(realm.run(&format!("{FRESH_CHAIN} Reflect.setPrototypeOf(this,new Proxy({{}}, tail)); 0")), Ok(JsValue::Number(0.0))); + realm.set_es2015(false); + assert_eq!(realm.run("function declared() { return 5; } declared() + hops"), Ok(JsValue::Number(46.0))); + // `for-in` reads the chain again for a name deleted during the loop. + let mut realm = Realm::with_options(es_options(), walk_limits()); + let src = format!( + "{FRESH_CHAIN} + var armed = false; + var head = new Proxy({{}}, {{ getPrototypeOf: function () {{ return armed ? new Proxy(big(), tail) : null; }} }}); + var o = Object.create(head); o.a = 1; o.b = 2; + var seen = []; + for (var k in o) {{ seen.push(k); if (k === 'a') {{ armed = true; delete o.b; }} }} + seen.join() + ' ' + hops" + ); + assert_eq!(realm.run(&src), Ok(JsValue::String("a 41".into()))); +} + +#[test] +fn a_function_stays_reachable_while_a_trap_runs_as_it_is_declared() { + let mut realm = es(); + let proto = "Reflect.setPrototypeOf(this, new Proxy(Object.prototype, { + getOwnPropertyDescriptor: function (t, k) { var junk = [[1], [2], [3]]; return Reflect.getOwnPropertyDescriptor(t, k); } })); 0"; + assert_eq!(realm.run(proto), Ok(JsValue::Number(0.0))); + realm.set_es2015(false); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let r = realm.run("function declared() { return 5; } declared()"); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert_eq!(r, Ok(JsValue::Number(5.0))); + assert!(realm.interp().heap.collections > 0); +} + #[test] fn spread_lets_a_proxy_shrink_the_array_it_reads() { // A proxy's `get` trap answers for the indices the array does not hold, so the length is not diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index c8b1d9b984..0d42a80a39 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -687,6 +687,15 @@ fn es2015_subset_runs() { handle.join().unwrap(); } +/// The runs that panicked, one line each with the setting of [`Options::es2015`], the test's path +/// and its mode, taken from the failures without the option and with it. +fn panic_lines(before: &str, after: &str) -> String { + [("without Options::es2015", before), ("with Options::es2015", after)] + .into_iter() + .flat_map(|(edition, failures)| failures.lines().filter(|l| l.ends_with(": PANIC")).map(move |l| format!("{edition}: {l}\n"))) + .collect() +} + /// The counts of the ES2015 subset read with one setting of [`Options::es2015`]. #[derive(Default)] struct Es2015Counts { @@ -798,7 +807,7 @@ fn run_es2015(dir: &Path) { line(&after), report.display() ); - assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display()); + assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked:\n{}", panic_lines(&before.failures, &after.failures)); } /// The feature tags of the `Proxy` and `Reflect` tests [`run_proxy_reflect`] runs: the two @@ -887,7 +896,7 @@ fn run_proxy_reflect(dir: &Path) { after.summary(), report.display() ); - assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display()); + assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked:\n{}", panic_lines(&before.failures, &after.failures)); } #[test] @@ -1173,3 +1182,11 @@ fn a_file_over_the_limit_is_refused_before_it_is_read() { assert_eq!(read_source(&path), Ok("\0\0\0\0".to_string())); std::fs::remove_dir_all(&dir).unwrap(); } + +#[test] +fn a_panic_without_the_option_is_named_with_its_test_and_mode() { + let before = "test/a.js (sloppy): PANIC\ntest/b.js (strict): expected 1\n"; + let after = "test/c.js (strict): PANIC\n"; + assert_eq!(panic_lines(before, after), "without Options::es2015: test/a.js (sloppy): PANIC\nwith Options::es2015: test/c.js (strict): PANIC\n"); + assert_eq!(panic_lines("test/b.js (strict): expected 1\n", ""), ""); +} From e2954a4ebbe8d26c3e86d1eb95685e9e914b1081 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:52:15 -0800 Subject: [PATCH 10/50] JavaScript: typeof reads the binding its first lookup found typeof on a name looked the name up once to decide between "undefined" and a read, then looked it up again to read it. A proxy used in a with statement could answer the two has queries differently, and typeof then threw a ReferenceError. It now reads the binding the first lookup found. --- crates/js/src/interp.rs | 2 +- crates/js/src/proxy_tests.rs | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 6eb37dbb0f..bada62b44e 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1377,7 +1377,7 @@ impl Interp { let name = self.name(n)?; let v = match self.resolve(&name)? { Resolved::Unresolved => Value::Undefined, - _ => self.get_var(&name)?.0, + r => self.get_resolved(r, &name)?.0, }; let t = self.type_of(&v); self.push(Value::str(t)) diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 5b6cf0e950..aed9fa3f90 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -407,6 +407,18 @@ fn a_proxy_works_as_a_prototype_and_a_with_scope() { truth("var o = {}; Object.prototype.isPrototypeOf.call(Object.prototype, new Proxy(o, {}))"); } +#[test] +fn typeof_reads_the_binding_a_with_scope_reported_once() { + truth( + "var asked = 0; + var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; }, + get: function (t, k) { return k === 'x' ? function () {} : undefined; } }); + var r; + with (p) { r = typeof x; } + r === 'function' && asked === 1", + ); +} + #[test] fn arrays_json_for_in_and_keys_read_a_proxy_through_its_traps() { truth( From d8dab0cd73fd05b5f9b4cc914b55da4f7416ac8a Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:04:25 +0700 Subject: [PATCH 11/50] docs: RFC-0052 Headless section and marking rules in UI parity --- AGENTS.md | 2 +- docs/ui-parity.md | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a8f8b84f7e..b5f51be2b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,7 +69,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator- - `crates/*`: engine, tools, format, svg, pdf, text, theme, mcp and the egui frontend `crates/ui-egui`; `apps/{vectorcraft, vectorcraft-cli, vectorcraft-web}`; `xtask`. `cargo xtask layers` enforces the layering: nothing below L6 depends on egui, eframe, winit or rfd. - Commands live in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`); UI-only commands in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). Colours come from `theme::Tokens`. - Control channel methods: `crates/ui-egui/src/control.rs`. MCP: `docs/mcp.md`. -- `ROADMAP.md` (stage, numbers, progress log), `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md` and the parity checklists in `docs/` track progress. Feature PRs update the rows they touch. +- `ROADMAP.md` (stage, numbers, progress log), `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md` and the parity checklists in `docs/` track progress. Feature PRs update the rows they touch. Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `docs/ui-parity.md` has a Headless section; the page has no command ids, so every area is `unknown`. A future row may mark `no ()` or `partial ()` with `window`, `os` or `engine-gap` (a `partial` row's notes say which part works); `yes` only when a row cites a registry command id (LightCraft's `cmd:` is the model). Desktop-only ids, including `crates/mcp/src/ui_catalog.rs`, do not count. - Build, test, fonts, localisation, cursors and robustness details: [`docs/development.md`](docs/development.md). Releases: [`docs/releasing.md`](docs/releasing.md). ### Checks diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1c491b9714..1b11dfc219 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,7 +1,7 @@ # UI and interaction parity > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (RFC-0052 Headless section, all unknown; earlier: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. > @@ -75,6 +75,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-28 | minor | Headless (RFC-0052) section under the summary: all areas unknown, with marking rules, until rows cite command ids | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | @@ -183,6 +184,14 @@ forbids launching or measuring Illustrator, so there has been **no side-by-side The overall figure is lower than the rows because what users notice first (small differences across many tools, never checked side by side) isn't captured row by row. +## Headless (RFC-0052) + +**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 0 yes, 0 no (window 0, os 0, engine-gap 0), 0 partial, all unknown.** + +This page is a scored behaviour list and an area summary, not a command checklist with ids, so no area can be marked `yes` yet. [RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md) fills `yes` only from the engine command registry that `vectorcraft-cli` and the MCP server load, and only once a row cites a command id (LightCraft's `cmd:` check is the model). Desktop-only command ids do not count, including the generated desktop-only list in `crates/mcp/src/ui_catalog.rs`. + +When a row cites a command id, a checked row that isn't fully reachable says `no ()` or `partial ()`, where the reach is `window` (needs the desktop window, a dialog or the pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be a command, isn't one yet). A `partial` row's notes say which part a headless client can do. Until then every area stays `unknown`. + ## Pen, Curvature and anchor tools | Behaviour (Illustrator, public docs) | Status | Notes | From af78458bde608afc702893a9d38d18dab6e95964 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:26:51 +0700 Subject: [PATCH 12/50] docs: Headless column and unknown counts on the area table (CodeRabbit) --- AGENTS.md | 2 +- docs/ui-parity.md | 36 +++++++++++++++++------------------- 2 files changed, 18 insertions(+), 20 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b5f51be2b6..e30148c572 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,7 +69,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator- - `crates/*`: engine, tools, format, svg, pdf, text, theme, mcp and the egui frontend `crates/ui-egui`; `apps/{vectorcraft, vectorcraft-cli, vectorcraft-web}`; `xtask`. `cargo xtask layers` enforces the layering: nothing below L6 depends on egui, eframe, winit or rfd. - Commands live in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`); UI-only commands in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). Colours come from `theme::Tokens`. - Control channel methods: `crates/ui-egui/src/control.rs`. MCP: `docs/mcp.md`. -- `ROADMAP.md` (stage, numbers, progress log), `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md` and the parity checklists in `docs/` track progress. Feature PRs update the rows they touch. Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `docs/ui-parity.md` has a Headless section; the page has no command ids, so every area is `unknown`. A future row may mark `no ()` or `partial ()` with `window`, `os` or `engine-gap` (a `partial` row's notes say which part works); `yes` only when a row cites a registry command id (LightCraft's `cmd:` is the model). Desktop-only ids, including `crates/mcp/src/ui_catalog.rs`, do not count. +- `ROADMAP.md` (stage, numbers, progress log), `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md` and the parity checklists in `docs/` track progress. Feature PRs update the rows they touch. Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `docs/ui-parity.md` has a Headless column on the Summary table; every area is `unknown` until checked (12 unknown today). A checked area may be marked `no ()` or `partial ()` with `window`, `os` or `engine-gap` (a `partial` row's notes say which part works); `yes` only when the area cites a registry command id (LightCraft's `cmd:` is the model). Some rows already cite ids such as `toolbar.show`, but no area has a registry command id yet, and desktop-only ids (including `crates/mcp/src/ui_catalog.rs`) do not count. Update the summary counts when you mark rows. - Build, test, fonts, localisation, cursors and robustness details: [`docs/development.md`](docs/development.md). Releases: [`docs/releasing.md`](docs/releasing.md). ### Checks diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1b11dfc219..92ce575af1 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -75,7 +75,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-28 | minor | Headless (RFC-0052) section under the summary: all areas unknown, with marking rules, until rows cite command ids | +| 2026-11-28 | minor | Headless (RFC-0052) column on the Summary table: 12 unknown, with marking rules | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | @@ -166,31 +166,29 @@ forbids launching or measuring Illustrator, so there has been **no side-by-side ## Summary -| Area | % | Remaining (h) | Kind | -|---|---:|---:|---| -| Pen, Curvature and anchor tools | 85% | 6–10 | estimated | -| Direct Selection, handles and anchors | 85% | 5–8 | estimated | -| Smart guides and snapping | 70% | 8–12 | estimated | -| Transform handles, bounding box, Free Transform | 80% | 5–8 | estimated | -| Nudging, numeric entry, precision, units | 85% | 3–5 | estimated | -| Modifier keys and temporary tools | 80% | 5–8 | estimated | -| Keyboard shortcuts (default set) | 70% | 6–10 | estimated; optional Switch Selection Tools is user-bindable with no default key (#7645), so default-set coverage is unchanged | -| Cursors | 75% | 3–5 | estimated | -| Panels, Control bar, Properties, context menus | 70% | 15–25 | estimated | -| Look and feel (layout, theme, metrics) | 80% | 5–10 | measured once against public screenshots on 2026-10-02; panels added since not re-measured | -| Accessibility (screen reader, keyboard-only canvas) | 20% | 15–25 | estimated: AccessKit on by default for egui widgets; canvas and custom panels not described, never tested with a screen reader | -| **UI/UX overall** | **~55%** | **~70–110** (overlaps the feature areas) | estimated | +| Area | % | Remaining (h) | Kind | Headless | +|---|---:|---:|---| --- | +| Pen, Curvature and anchor tools | 85% | 6–10 | estimated | unknown | +| Direct Selection, handles and anchors | 85% | 5–8 | estimated | unknown | +| Smart guides and snapping | 70% | 8–12 | estimated | unknown | +| Transform handles, bounding box, Free Transform | 80% | 5–8 | estimated | unknown | +| Nudging, numeric entry, precision, units | 85% | 3–5 | estimated | unknown | +| Modifier keys and temporary tools | 80% | 5–8 | estimated | unknown | +| Keyboard shortcuts (default set) | 70% | 6–10 | estimated; optional Switch Selection Tools is user-bindable with no default key (#7645), so default-set coverage is unchanged | unknown | +| Cursors | 75% | 3–5 | estimated | unknown | +| Panels, Control bar, Properties, context menus | 70% | 15–25 | estimated | unknown | +| Look and feel (layout, theme, metrics) | 80% | 5–10 | measured once against public screenshots on 2026-10-02; panels added since not re-measured | unknown | +| Accessibility (screen reader, keyboard-only canvas) | 20% | 15–25 | estimated: AccessKit on by default for egui widgets; canvas and custom panels not described, never tested with a screen reader | unknown | +| **UI/UX overall** | **~55%** | **~70–110** (overlaps the feature areas) | estimated | unknown | The overall figure is lower than the rows because what users notice first (small differences across many tools, never checked side by side) isn't captured row by row. ## Headless (RFC-0052) -**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 0 yes, 0 no (window 0, os 0, engine-gap 0), 0 partial, all unknown.** +**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 0 yes, 0 no (window 0, os 0, engine-gap 0), 0 partial, 12 unknown.** -This page is a scored behaviour list and an area summary, not a command checklist with ids, so no area can be marked `yes` yet. [RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md) fills `yes` only from the engine command registry that `vectorcraft-cli` and the MCP server load, and only once a row cites a command id (LightCraft's `cmd:` check is the model). Desktop-only command ids do not count, including the generated desktop-only list in `crates/mcp/src/ui_catalog.rs`. - -When a row cites a command id, a checked row that isn't fully reachable says `no ()` or `partial ()`, where the reach is `window` (needs the desktop window, a dialog or the pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be a command, isn't one yet). A `partial` row's notes say which part a headless client can do. Until then every area stays `unknown`. +The Summary table has a Headless column. Every area, including the overall row, is `unknown` until it is checked. A checked area may be marked `no ()` or `partial ()` by hand, where the reach is `window` (needs the desktop window, a dialog or the pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be a command, isn't one yet). A `partial` row's notes say which part a headless client can do. `yes` only when the area cites a command id from the engine registry that `vectorcraft-cli` and the MCP server load (LightCraft's `cmd:` check is the model). Some rows already cite command ids such as `toolbar.show`, `tool.select` and `guide.add`; those are not enough for `yes` until they are registry ids, and desktop-only ids (including the generated list in `crates/mcp/src/ui_catalog.rs`) do not count. Update the counts in this line when you mark rows. ## Pen, Curvature and anchor tools From 1d0011567bbb2cac43858bc247ae0515d6a80573 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 07:19:40 +0100 Subject: [PATCH 13/50] docs: Headless column on every behaviour table in UI parity (CodeRabbit) --- AGENTS.md | 2 +- docs/ui-parity.md | 712 +++++++++++++++++++++++----------------------- 2 files changed, 357 insertions(+), 357 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e30148c572..85a9cee8de 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,7 +69,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator- - `crates/*`: engine, tools, format, svg, pdf, text, theme, mcp and the egui frontend `crates/ui-egui`; `apps/{vectorcraft, vectorcraft-cli, vectorcraft-web}`; `xtask`. `cargo xtask layers` enforces the layering: nothing below L6 depends on egui, eframe, winit or rfd. - Commands live in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`); UI-only commands in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). Colours come from `theme::Tokens`. - Control channel methods: `crates/ui-egui/src/control.rs`. MCP: `docs/mcp.md`. -- `ROADMAP.md` (stage, numbers, progress log), `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md` and the parity checklists in `docs/` track progress. Feature PRs update the rows they touch. Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `docs/ui-parity.md` has a Headless column on the Summary table; every area is `unknown` until checked (12 unknown today). A checked area may be marked `no ()` or `partial ()` with `window`, `os` or `engine-gap` (a `partial` row's notes say which part works); `yes` only when the area cites a registry command id (LightCraft's `cmd:` is the model). Some rows already cite ids such as `toolbar.show`, but no area has a registry command id yet, and desktop-only ids (including `crates/mcp/src/ui_catalog.rs`) do not count. Update the summary counts when you mark rows. +- `ROADMAP.md` (stage, numbers, progress log), `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md` and the parity checklists in `docs/` track progress. Feature PRs update the rows they touch. Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `docs/ui-parity.md` has a Headless column on the Summary table and every behaviour table; every row is `unknown` until checked (349 unknown today). A checked row may be marked `no ()` or `partial ()` with `window`, `os` or `engine-gap` (a `partial` row's notes say which part works); `yes` only when the row cites a registry command id (LightCraft's `cmd:` is the model). Some rows already cite ids such as `toolbar.show`, but none is a registry command id yet, and desktop-only ids (including `crates/mcp/src/ui_catalog.rs`) do not count. Update the summary counts when you mark rows. - Build, test, fonts, localisation, cursors and robustness details: [`docs/development.md`](docs/development.md). Releases: [`docs/releasing.md`](docs/releasing.md). ### Checks diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1dbd6b3fb1..fec2dc4db0 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -75,7 +75,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-28 | minor | Headless (RFC-0052) column on the Summary table: 12 unknown, with marking rules | +| 2026-11-28 | minor | Headless (RFC-0052) column on the Summary table and every behaviour table: 349 unknown, with marking rules | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | @@ -186,237 +186,237 @@ tools, never checked side by side) isn't captured row by row. ## Headless (RFC-0052) -**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 0 yes, 0 no (window 0, os 0, engine-gap 0), 0 partial, 12 unknown.** +**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 0 yes, 0 no (window 0, os 0, engine-gap 0), 0 partial, 349 unknown.** -The Summary table has a Headless column. Every area, including the overall row, is `unknown` until it is checked. A checked area may be marked `no ()` or `partial ()` by hand, where the reach is `window` (needs the desktop window, a dialog or the pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be a command, isn't one yet). A `partial` row's notes say which part a headless client can do. `yes` only when the area cites a command id from the engine registry that `vectorcraft-cli` and the MCP server load (LightCraft's `cmd:` check is the model). Some rows already cite command ids such as `toolbar.show`, `tool.select` and `guide.add`; those are not enough for `yes` until they are registry ids, and desktop-only ids (including the generated list in `crates/mcp/src/ui_catalog.rs`) do not count. Update the counts in this line when you mark rows. +Every parity table on this page has a Headless column: the Summary table (12 area rows, including the overall row) and the behaviour tables (337 rows). Every row is `unknown` until it is checked. A checked row may be marked `no ()` or `partial ()` by hand, where the reach is `window` (needs the desktop window, a dialog or the pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be a command, isn't one yet). A `partial` row's notes say which part a headless client can do. `yes` only when the row cites a command id from the engine registry that `vectorcraft-cli` and the MCP server load (LightCraft's `cmd:` check is the model). Some rows already cite command ids such as `toolbar.show`, `tool.select` and `guide.add`; those are not enough for `yes` until they are registry ids, and desktop-only ids (including the generated list in `crates/mcp/src/ui_catalog.rs`) do not count. Update the counts in this line when you mark rows. ## Pen, Curvature and anchor tools -| Behaviour (Illustrator, public docs) | Status | Notes | -|---|---|---| -| Click: corner anchor; drag: smooth anchor with symmetric handles | done | `pen.rs`; the drag's preview follows every pointer position, back into the window after leaving it and in the release's frame, and the release commits where the pointer let go (#834) | -| A press that moves under 3 screen pixels is a click (a corner without handles) | done | #1663 | -| Shift constrains segments and handles to 45° | done | Illustrator's Constrain Angle preference is honoured (`constrainAngle`): segments, the Pen's handles, Shift moves with the selection tools, Free Transform, slices, Reshape and Measure (#394) | -| Alt mid-drag splits the handles (only the outgoing follows) | done | keeps the curve already shaped | -| Space mid-drag repositions the anchor, handles and all | done | | -| Click the first anchor to close; the drag shapes the closing curve | done | | -| Click the last anchor to retract its outgoing handle; drag from it to pull a new one | done | | -| Alt over a handle, anchor or segment acts as the Anchor Point tool | done | | -| Cmd/Ctrl lends the last-used selection tool | done | the path being drawn continues afterwards; with Direct Selection (the default until a selection tool is chosen) a Cmd drag moves an anchor of the path being drawn, moves a straight segment or bends a curved one, one undo step each, and a Cmd-click away from art ends the path; with Selection the hidden bounding box of the path being drawn takes no press, so the drag moves the path (#4980); anchors or segments the lent Direct Selection picks are what Copy and Cut take, as with Direct Selection chosen, while Copy with the Pen's own last anchor selected takes the whole path (#6123) | -| Click an open path's end to continue it; click another path's end to join | done | #776 | -| Rubber Band preview | done | Preferences option | -| P while the Pen draws a path ends the path, as Escape does | done | the [help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes P with the preview off; VectorCraft's own rules: it does the same with Rubber Band on, a click on the active Pen's button and `tool.select` do the same, and the Pen stays chosen | -| Auto Add/Delete on a selected path; Shift or the preference disables it | done | | -| Pen cursors (new path ×, continue /, close o, add +, delete −, convert ^) | done | the nib is a fountain-pen nib, tip on the hotspot, with the slit widening into the breather hole and the heel clipped square to its axis; bitmap tests at 1× and 2× pin the nib and the new-path asterisk, and in-app screenshots compare the Pen with Direct Selection | -| Node-editing cursors: Direct Selection's white arrow with a hollow or filled square over an anchor (path unselected or selected); the Reshape Segment cursor over a curved segment (Direct Selection, Anchor Point, the Pen with Alt); the Anchor Point caret for the Pen with Alt; Group Selection's plus (also Direct Selection with Alt); a filled arrow while dragging that turns hollow on a snap; a double arrowhead for an Alt-drag copy | partial | as the public manual describes them, drawn in code; no cue over handles (none documented) | -| Anchor Point and Curvature tools' own cursors | done | the caret on the anchor it converts; the pen nib with a curve badge | -| Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping (#6470) | implemented | Existing Smart Guides, Snap to Point, pixel and grid options apply; Pixel Preview turns off Smart Guides. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions: `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. | -| Scissors cut-point preview (#8655) | implemented | Native marker at the actual anchor or curve target; current snapping, cut and Alt Add Anchor behavior retained. `crates/tools/src/draw2/anchor/tests.rs`, `crates/engine/tests/scissors_snap.rs`. | -| Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it | -| Live Paint Bucket cursors | partial | a filled bucket over a face a click fills, a brush over an edge it paints, an empty bucket where it paints nothing, following Paint Fills, Paint Strokes and Shift; the Eyedropper with Alt; the crosshair with Use Precise Cursors. No cursor swatch preview | -| Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | -| Eraser: filled open paths and compound holes | partial | Fill-only open paths preserve fill outside sweeps and Alt-drag marquees and keep compound holes under their fill rule (#6582). Path or Compound clipping masks retain all surviving contours or empty geometry in the same node, preserving the mask role; Path Eraser shares this behavior. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Focused engine tests cover fixed and varied tips and Alt-drag marquees on open/closed geometry, raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. `crates/engine/tests/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Filled-and-stroked open paths retain main behavior; that fill behavior is not claimed fixed. See G11 in [gaps.md](gaps.md#g11-correctness-bugs-in-core-tools). | -| Knife cursor | done | a knife, the blade's point on the hotspot, white blade and black handle, for the Knife and the Trim at Crossings Tool; the crosshair with Use Precise Cursors; `the_knife_shows_a_knife_with_its_point_on_the_hotspot`, `drawing_tools_show_their_own_cursor` | -| Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests While the button is down a round Blob Brush shows the outline of the area it will add, rounded at both ends, not a line as wide as the brush that ends square (#4343). | -| Eraser: an Alt-drag draws a marquee and the release erases everything inside it (closed shapes and fill-only open paths lose the rectangle's area, other open paths are cut where they cross its edges); Alt+Shift keeps the marquee square; Escape cancels it, and a click erases nothing | done | `path.eraseRegion {rect}`; [public behavior reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133); `eraser_alt_drag_draws_a_marquee_and_erases_the_rectangle`, `eraser_alt_shift_drag_keeps_the_marquee_square`, `eraser_marquee_click_or_escape_erases_nothing`, `erase_region_rect_erases_everything_inside_it`, `erase_region_rect_refuses_bad_values` | -| Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | -| Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | -| Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | -| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end, drag the handle at a path's start or end to make its line or arc longer or shorter, drag anchors or segments to edit, right-click Delete ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the length handles in `quickpen/length.rs` and `path.quickPenLength`, on the path being drawn or the selected path (a line keeps its direction, an arc its circle, up to 359°); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`; with no path being drawn, drags on a selected path's anchors and segments move them (`quickpen/edit.rs`, `path.moveAnchors`), clicks select anchors, and the canvas context menu has Delete (`edit.clear`). Not yet: Ctrl+scroll for the arc size | -| Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | -| Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | -| Graphic Styles list fills a taller panel (#2992) | done | Docked, floating or in a resized flyout, the list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 220 pt; `the_list_fills_a_tall_panel_above_its_footer` | -| Library panels' lists fill a taller panel (#2992) | done | Swatch (Color Books among them), brush, symbol and graphic style library panels: docked, floating or in a resized flyout, the list takes the height above the panel's footer; outside a sized panel it stays 220 pt (280 pt for large thumbnails); `the_list_fills_a_tall_panel_above_its_footer` in `panels/library_panel/tests.rs` | -| Swatches list fills a taller panel (#1638) | done | Docked, floating or in a resized flyout, the swatch list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 150 pt (200 pt for large thumbnails); `the_list_fills_a_tall_panel_above_its_footer` in `panels/swatches/tests.rs` | -| Layers panel lists a blend's spine (#4820) | done | an open blend shows a `` row below its key objects, where Release leaves the spine; a click selects the blend (Shift/Cmd toggles it) so Direct Selection edits the spine; a locked blend's row selects nothing; no row while searching or filtering (`a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend`) | -| Layers panel: a layer whose Layer Options › Print is off shows its name italic (#5739) | done | the panel row and its drag ghost; a printing layer stays upright, and Print on again restores it; `panels::layers` test `a_layer_that_does_not_print_has_its_name_italic` | -| Layer/Object Options preserve automatic names and skip unchanged approval | done | Leaving Name untouched preserves the automatic name, including when another option changes. Approving without edits preserves the document revision and Undo history. | -| Layers panel: Alt-drag shows the copy cursor (#8217) | done | rows and the selected-art square dragged over the list show the copy cursor while Alt is held and the grabbing hand otherwise, following Alt mid-drag; on Windows and X11 the copy cursor is the white arrow with a plus (the panels' add cursor, #8241); over the trash and New Layer, which ignore Alt, the hand stays; guide rows keep theirs; `alt_shows_the_copy_cursor_while_rows_are_dragged`, `drag_cursor_shows_a_copy_only_where_the_drop_copies` | -| Gradient panel: add-stop cursor under the ramp (#8241) | done | the white arrow with a plus (the Group Selection glyph) over the strip under the ramp, handed to the OS on Windows and X11 (winit shows the plain arrow for the system copy cursor there), the system copy cursor elsewhere; over the ramp itself the arrow stays; `panels::gradient` test `the_strip_under_the_ramp_shows_the_add_cursor` | -| Layers panel: Alt-drag copies a row beside itself (#8237) | done | with Alt, rows held over one of their own rows copy above or below it, and the bottom layer dropped in the empty space under the list copies below itself, so the top layer dragged up, the bottom one dragged down and a document's only layer are copied; a move onto its own place, or a copy inside itself, still does nothing; `panels::layers` tests `alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it`, `a_lone_layer_alt_dragged_up_or_down_is_copied`; engine test `a_copy_goes_above_or_below_a_row_it_copies` | -| Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | -| Blend Replace Spine, move and Undo redraw (#5179) | CPU regression-tested | Renderer damage bounds include keys and steps rotated along a curved spine. Both original straight and curved CPU regressions pass, checking full-frame agreement and that every changed pixel lies inside the advertised redraw area. | -| Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee picks the spine points inside it on the topmost selected blend, and with Shift adds or takes them away | -| Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles; Alt held while dragging a handle links it with the opposite handle and makes the anchor smooth, on a blend's spine too | -| Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity is in screen pixels, the same at any zoom, and goes down to 0.01 px in the dialog and the tool, which sends `path.freehand` the value in points at the current zoom (#5729; the Smooth tool keeps 0.05 pt); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 px, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 px, tenths up to 1 px and whole pixels above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor (a short level line) while Shift or Alt is held before the press, and a path-continuation cursor (a short rising line) over an end of a selected open path, where the stroke continues the path, freehand or straight, and while a continuing stroke ends near an open end of another selected path it connects to; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the way round a closed path that leaves the bigger shape, so a stroke across a shape carves off its smaller part and an arch over a thin shape's side keeps the shape; on an open path the way the stroke runs along it at each end decides: where it starts it replaces the part it runs along, where it lands it joins the part it runs into, so it replaces the part between, closes the path round it without the closing cursor, or ends where the pen is lifted; #2850), the stroke's ends bent smoothly onto the path; a stroke lifted farther than the distance takes the path with it (a closed path opens where the stroke starts, an open one is cut there and drops the part the stroke heads along), one back to its starting point adds a loop, and a selected compound path's member paths are redrawn too (#3793); while such a stroke is drawn the preview shows the stroke as drawn and the path changes at the release; with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, or a stroke continuing a selected path (a straight line too) to within it of that path's other end, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path; a Pencil stroke from an end of one selected open path to an end of another connects the two into one path | -| Drop Shadow, Outer Glow and Inner Glow: Opacity, the offsets, Blur and Darkness have spinner arrows that step by one (a unit for distances), repeat when held and stop at the fields' ends (#5367, #5368) | done | dialogs::effect test drop_shadow_and_outer_glow_fields_have_spinner_arrows; other effect dialogs' number fields still have none | -| Effect dialogs' colour fields: a swatch beside the hex follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills it and Cancel comes back unchanged (#5365) | done | dialogs::effect tests outer_glow_colour_swatch_opens_the_color_picker and drop_shadow_colour_swatch_opens_the_color_picker (Drop Shadow's Color, #5364); the picker previews nothing itself, the effect dialog previews the returned colour | -| Join tool scrubbing, Average, Join | done | Join merges the direct-selected anchors lying on one another along a path, as after Average, into one (#1533); the Join tool trims two crossing open paths whose overhanging ends it scrubs over and joins them at the crossing, instead of drawing a segment between their ends (#5844) | -| Average and Join in one step, with a corner or smooth choice for the joined anchor | done | Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, "Create corner or smooth join" in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): two open path ends meet at their midpoint and join, a corner or smooth point as the dialog's Points choice asks (Corner first, then the last choice), in one undo step | -| Smooth tool smooths only the stretch of path under the drag | done | #1512 | -| Drawing modes apply to pastes: Draw Inside takes Paste, Paste in Place and Paste on All Artboards inside the object; Draw Behind puts Paste in Place and Paste on All Artboards behind the selection; Shift+D cycles past Draw Behind with any selection ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | done | #3705; `pasting_in_draw_inside_puts_the_copies_inside_the_object`, `paste_in_place_in_draw_behind_goes_behind_the_selection`, `shift_d_goes_past_draw_behind_whatever_is_selected` | -| Simplify (slider, auto, corner angle threshold), of a whole path or of the part of it selected with Direct Selection ([manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html)) | done | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, opening at the Auto-Simplify level for the selection with that result previewed, and the dialog's option to open it directly with its last settings. The canvas context menu's Simplify…, listed with Smooth… while the selection holds a path, opens the same slider or dialog (#8344, `right_click_on_a_path_opens_simplify_as_the_menu_item_does`). With anchors or segments direct-selected, the slider, Auto-Simplify and the dialog refit only each run of selected segments between its end anchors, a closed path's run across its start point included; the rest of the path stays exactly as it was (`tests/simplify_part.rs`, `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`) | -| Smooth (Object › Path › Smooth…: slider from minimum to maximum smoothing, Auto-Smooth) ([smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html)) | done | #4115: the slider under the selection previews `object.path.smooth {level}`, Auto-Smooth picks level 50 and takes a shaky line to one smooth curve, direct-selected anchors smooth only their section, Enter or a click outside keeps one undo step and Escape restores; the smoothing rule beyond the two ends is VectorCraft's own (`tests/smooth_path.rs`, `smooth_slider_previews_auto_smooth_and_keeps_the_result`) | -| Draw Inside in isolation mode: art drawn or pasted inside the isolated object takes isolation mode into its clip group, clickable and undimmed ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html), [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | done | #3705; `drawing_inside_an_isolated_object_keeps_the_new_art_in_isolation_mode` | -| Draw Inside marks the object it draws into: a dotted open rectangle round its corners, in its layer's colour, while the mode lasts, selected or not | done | #4319, `canvas::tests::draw_inside_marks_the_corners_of_its_object` ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | -| Simplify (slider, auto, corner angle threshold) | partial | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, and the dialog's option to open it directly with its last settings; the slider opens at 1 pt rather than at the Auto-Simplify level, and simplifying only a Direct Selection part of a path remains missing | -| Simplify (slider, auto, corner angle threshold) | partial | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, opening at the Auto-Simplify level for the selection with that result previewed, and the dialog's option to open it directly with its last settings; simplifying only a Direct Selection part of a path remains missing | +| Behaviour (Illustrator, public docs) | Status | Notes | Headless | +|---|---|---| --- | +| Click: corner anchor; drag: smooth anchor with symmetric handles | done | `pen.rs`; the drag's preview follows every pointer position, back into the window after leaving it and in the release's frame, and the release commits where the pointer let go (#834) | unknown | +| A press that moves under 3 screen pixels is a click (a corner without handles) | done | #1663 | unknown | +| Shift constrains segments and handles to 45° | done | Illustrator's Constrain Angle preference is honoured (`constrainAngle`): segments, the Pen's handles, Shift moves with the selection tools, Free Transform, slices, Reshape and Measure (#394) | unknown | +| Alt mid-drag splits the handles (only the outgoing follows) | done | keeps the curve already shaped | unknown | +| Space mid-drag repositions the anchor, handles and all | done | | unknown | +| Click the first anchor to close; the drag shapes the closing curve | done | | unknown | +| Click the last anchor to retract its outgoing handle; drag from it to pull a new one | done | | unknown | +| Alt over a handle, anchor or segment acts as the Anchor Point tool | done | | unknown | +| Cmd/Ctrl lends the last-used selection tool | done | the path being drawn continues afterwards; with Direct Selection (the default until a selection tool is chosen) a Cmd drag moves an anchor of the path being drawn, moves a straight segment or bends a curved one, one undo step each, and a Cmd-click away from art ends the path; with Selection the hidden bounding box of the path being drawn takes no press, so the drag moves the path (#4980); anchors or segments the lent Direct Selection picks are what Copy and Cut take, as with Direct Selection chosen, while Copy with the Pen's own last anchor selected takes the whole path (#6123) | unknown | +| Click an open path's end to continue it; click another path's end to join | done | #776 | unknown | +| Rubber Band preview | done | Preferences option | unknown | +| P while the Pen draws a path ends the path, as Escape does | done | the [help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes P with the preview off; VectorCraft's own rules: it does the same with Rubber Band on, a click on the active Pen's button and `tool.select` do the same, and the Pen stays chosen | unknown | +| Auto Add/Delete on a selected path; Shift or the preference disables it | done | | unknown | +| Pen cursors (new path ×, continue /, close o, add +, delete −, convert ^) | done | the nib is a fountain-pen nib, tip on the hotspot, with the slit widening into the breather hole and the heel clipped square to its axis; bitmap tests at 1× and 2× pin the nib and the new-path asterisk, and in-app screenshots compare the Pen with Direct Selection | unknown | +| Node-editing cursors: Direct Selection's white arrow with a hollow or filled square over an anchor (path unselected or selected); the Reshape Segment cursor over a curved segment (Direct Selection, Anchor Point, the Pen with Alt); the Anchor Point caret for the Pen with Alt; Group Selection's plus (also Direct Selection with Alt); a filled arrow while dragging that turns hollow on a snap; a double arrowhead for an Alt-drag copy | partial | as the public manual describes them, drawn in code; no cue over handles (none documented) | unknown | +| Anchor Point and Curvature tools' own cursors | done | the caret on the anchor it converts; the pen nib with a curve badge | unknown | +| Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping (#6470) | implemented | Existing Smart Guides, Snap to Point, pixel and grid options apply; Pixel Preview turns off Smart Guides. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions: `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. | unknown | +| Scissors cut-point preview (#8655) | implemented | Native marker at the actual anchor or curve target; current snapping, cut and Alt Add Anchor behavior retained. `crates/tools/src/draw2/anchor/tests.rs`, `crates/engine/tests/scissors_snap.rs`. | unknown | +| Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it | unknown | +| Live Paint Bucket cursors | partial | a filled bucket over a face a click fills, a brush over an edge it paints, an empty bucket where it paints nothing, following Paint Fills, Paint Strokes and Shift; the Eyedropper with Alt; the crosshair with Use Precise Cursors. No cursor swatch preview | unknown | +| Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | unknown | +| Eraser: filled open paths and compound holes | partial | Fill-only open paths preserve fill outside sweeps and Alt-drag marquees and keep compound holes under their fill rule (#6582). Path or Compound clipping masks retain all surviving contours or empty geometry in the same node, preserving the mask role; Path Eraser shares this behavior. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Focused engine tests cover fixed and varied tips and Alt-drag marquees on open/closed geometry, raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. `crates/engine/tests/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Filled-and-stroked open paths retain main behavior; that fill behavior is not claimed fixed. See G11 in [gaps.md](gaps.md#g11-correctness-bugs-in-core-tools). | unknown | +| Knife cursor | done | a knife, the blade's point on the hotspot, white blade and black handle, for the Knife and the Trim at Crossings Tool; the crosshair with Use Precise Cursors; `the_knife_shows_a_knife_with_its_point_on_the_hotspot`, `drawing_tools_show_their_own_cursor` | unknown | +| Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests While the button is down a round Blob Brush shows the outline of the area it will add, rounded at both ends, not a line as wide as the brush that ends square (#4343). | unknown | +| Eraser: an Alt-drag draws a marquee and the release erases everything inside it (closed shapes and fill-only open paths lose the rectangle's area, other open paths are cut where they cross its edges); Alt+Shift keeps the marquee square; Escape cancels it, and a click erases nothing | done | `path.eraseRegion {rect}`; [public behavior reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133); `eraser_alt_drag_draws_a_marquee_and_erases_the_rectangle`, `eraser_alt_shift_drag_keeps_the_marquee_square`, `eraser_marquee_click_or_escape_erases_nothing`, `erase_region_rect_erases_everything_inside_it`, `erase_region_rect_refuses_bad_values` | unknown | +| Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | unknown | +| Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | unknown | +| Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | unknown | +| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end, drag the handle at a path's start or end to make its line or arc longer or shorter, drag anchors or segments to edit, right-click Delete ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the length handles in `quickpen/length.rs` and `path.quickPenLength`, on the path being drawn or the selected path (a line keeps its direction, an arc its circle, up to 359°); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`; with no path being drawn, drags on a selected path's anchors and segments move them (`quickpen/edit.rs`, `path.moveAnchors`), clicks select anchors, and the canvas context menu has Delete (`edit.clear`). Not yet: Ctrl+scroll for the arc size | unknown | +| Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | unknown | +| Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | unknown | +| Graphic Styles list fills a taller panel (#2992) | done | Docked, floating or in a resized flyout, the list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 220 pt; `the_list_fills_a_tall_panel_above_its_footer` | unknown | +| Library panels' lists fill a taller panel (#2992) | done | Swatch (Color Books among them), brush, symbol and graphic style library panels: docked, floating or in a resized flyout, the list takes the height above the panel's footer; outside a sized panel it stays 220 pt (280 pt for large thumbnails); `the_list_fills_a_tall_panel_above_its_footer` in `panels/library_panel/tests.rs` | unknown | +| Swatches list fills a taller panel (#1638) | done | Docked, floating or in a resized flyout, the swatch list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 150 pt (200 pt for large thumbnails); `the_list_fills_a_tall_panel_above_its_footer` in `panels/swatches/tests.rs` | unknown | +| Layers panel lists a blend's spine (#4820) | done | an open blend shows a `` row below its key objects, where Release leaves the spine; a click selects the blend (Shift/Cmd toggles it) so Direct Selection edits the spine; a locked blend's row selects nothing; no row while searching or filtering (`a_blends_spine_is_a_row_below_its_keys_that_selects_the_blend`) | unknown | +| Layers panel: a layer whose Layer Options › Print is off shows its name italic (#5739) | done | the panel row and its drag ghost; a printing layer stays upright, and Print on again restores it; `panels::layers` test `a_layer_that_does_not_print_has_its_name_italic` | unknown | +| Layer/Object Options preserve automatic names and skip unchanged approval | done | Leaving Name untouched preserves the automatic name, including when another option changes. Approving without edits preserves the document revision and Undo history. | unknown | +| Layers panel: Alt-drag shows the copy cursor (#8217) | done | rows and the selected-art square dragged over the list show the copy cursor while Alt is held and the grabbing hand otherwise, following Alt mid-drag; on Windows and X11 the copy cursor is the white arrow with a plus (the panels' add cursor, #8241); over the trash and New Layer, which ignore Alt, the hand stays; guide rows keep theirs; `alt_shows_the_copy_cursor_while_rows_are_dragged`, `drag_cursor_shows_a_copy_only_where_the_drop_copies` | unknown | +| Gradient panel: add-stop cursor under the ramp (#8241) | done | the white arrow with a plus (the Group Selection glyph) over the strip under the ramp, handed to the OS on Windows and X11 (winit shows the plain arrow for the system copy cursor there), the system copy cursor elsewhere; over the ramp itself the arrow stays; `panels::gradient` test `the_strip_under_the_ramp_shows_the_add_cursor` | unknown | +| Layers panel: Alt-drag copies a row beside itself (#8237) | done | with Alt, rows held over one of their own rows copy above or below it, and the bottom layer dropped in the empty space under the list copies below itself, so the top layer dragged up, the bottom one dragged down and a document's only layer are copied; a move onto its own place, or a copy inside itself, still does nothing; `panels::layers` tests `alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it`, `a_lone_layer_alt_dragged_up_or_down_is_copied`; engine test `a_copy_goes_above_or_below_a_row_it_copies` | unknown | +| Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | unknown | +| Blend Replace Spine, move and Undo redraw (#5179) | CPU regression-tested | Renderer damage bounds include keys and steps rotated along a curved spine. Both original straight and curved CPU regressions pass, checking full-frame agreement and that every changed pixel lies inside the advertised redraw area. | unknown | +| Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee picks the spine points inside it on the topmost selected blend, and with Shift adds or takes them away | unknown | +| Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles; Alt held while dragging a handle links it with the opposite handle and makes the anchor smooth, on a blend's spine too | unknown | +| Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity is in screen pixels, the same at any zoom, and goes down to 0.01 px in the dialog and the tool, which sends `path.freehand` the value in points at the current zoom (#5729; the Smooth tool keeps 0.05 pt); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 px, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 px, tenths up to 1 px and whole pixels above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor (a short level line) while Shift or Alt is held before the press, and a path-continuation cursor (a short rising line) over an end of a selected open path, where the stroke continues the path, freehand or straight, and while a continuing stroke ends near an open end of another selected path it connects to; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the way round a closed path that leaves the bigger shape, so a stroke across a shape carves off its smaller part and an arch over a thin shape's side keeps the shape; on an open path the way the stroke runs along it at each end decides: where it starts it replaces the part it runs along, where it lands it joins the part it runs into, so it replaces the part between, closes the path round it without the closing cursor, or ends where the pen is lifted; #2850), the stroke's ends bent smoothly onto the path; a stroke lifted farther than the distance takes the path with it (a closed path opens where the stroke starts, an open one is cut there and drops the part the stroke heads along), one back to its starting point adds a loop, and a selected compound path's member paths are redrawn too (#3793); while such a stroke is drawn the preview shows the stroke as drawn and the path changes at the release; with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, or a stroke continuing a selected path (a straight line too) to within it of that path's other end, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path; a Pencil stroke from an end of one selected open path to an end of another connects the two into one path | unknown | +| Drop Shadow, Outer Glow and Inner Glow: Opacity, the offsets, Blur and Darkness have spinner arrows that step by one (a unit for distances), repeat when held and stop at the fields' ends (#5367, #5368) | done | dialogs::effect test drop_shadow_and_outer_glow_fields_have_spinner_arrows; other effect dialogs' number fields still have none | unknown | +| Effect dialogs' colour fields: a swatch beside the hex follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills it and Cancel comes back unchanged (#5365) | done | dialogs::effect tests outer_glow_colour_swatch_opens_the_color_picker and drop_shadow_colour_swatch_opens_the_color_picker (Drop Shadow's Color, #5364); the picker previews nothing itself, the effect dialog previews the returned colour | unknown | +| Join tool scrubbing, Average, Join | done | Join merges the direct-selected anchors lying on one another along a path, as after Average, into one (#1533); the Join tool trims two crossing open paths whose overhanging ends it scrubs over and joins them at the crossing, instead of drawing a segment between their ends (#5844) | unknown | +| Average and Join in one step, with a corner or smooth choice for the joined anchor | done | Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, "Create corner or smooth join" in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): two open path ends meet at their midpoint and join, a corner or smooth point as the dialog's Points choice asks (Corner first, then the last choice), in one undo step | unknown | +| Smooth tool smooths only the stretch of path under the drag | done | #1512 | unknown | +| Drawing modes apply to pastes: Draw Inside takes Paste, Paste in Place and Paste on All Artboards inside the object; Draw Behind puts Paste in Place and Paste on All Artboards behind the selection; Shift+D cycles past Draw Behind with any selection ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | done | #3705; `pasting_in_draw_inside_puts_the_copies_inside_the_object`, `paste_in_place_in_draw_behind_goes_behind_the_selection`, `shift_d_goes_past_draw_behind_whatever_is_selected` | unknown | +| Simplify (slider, auto, corner angle threshold), of a whole path or of the part of it selected with Direct Selection ([manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html)) | done | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, opening at the Auto-Simplify level for the selection with that result previewed, and the dialog's option to open it directly with its last settings. The canvas context menu's Simplify…, listed with Smooth… while the selection holds a path, opens the same slider or dialog (#8344, `right_click_on_a_path_opens_simplify_as_the_menu_item_does`). With anchors or segments direct-selected, the slider, Auto-Simplify and the dialog refit only each run of selected segments between its end anchors, a closed path's run across its start point included; the rest of the path stays exactly as it was (`tests/simplify_part.rs`, `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`) | unknown | +| Smooth (Object › Path › Smooth…: slider from minimum to maximum smoothing, Auto-Smooth) ([smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html)) | done | #4115: the slider under the selection previews `object.path.smooth {level}`, Auto-Smooth picks level 50 and takes a shaky line to one smooth curve, direct-selected anchors smooth only their section, Enter or a click outside keeps one undo step and Escape restores; the smoothing rule beyond the two ends is VectorCraft's own (`tests/smooth_path.rs`, `smooth_slider_previews_auto_smooth_and_keeps_the_result`) | unknown | +| Draw Inside in isolation mode: art drawn or pasted inside the isolated object takes isolation mode into its clip group, clickable and undimmed ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html), [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | done | #3705; `drawing_inside_an_isolated_object_keeps_the_new_art_in_isolation_mode` | unknown | +| Draw Inside marks the object it draws into: a dotted open rectangle round its corners, in its layer's colour, while the mode lasts, selected or not | done | #4319, `canvas::tests::draw_inside_marks_the_corners_of_its_object` ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | unknown | +| Simplify (slider, auto, corner angle threshold) | partial | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, and the dialog's option to open it directly with its last settings; the slider opens at 1 pt rather than at the Auto-Simplify level, and simplifying only a Direct Selection part of a path remains missing | unknown | +| Simplify (slider, auto, corner angle threshold) | partial | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, opening at the Auto-Simplify level for the selection with that result previewed, and the dialog's option to open it directly with its last settings; simplifying only a Direct Selection part of a path remains missing | unknown | ## Direct Selection, anchors and handles -| Behaviour | Status | Notes | -|---|---|---| -| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/path_fill_hits.rs`; hidden-fill and no-fill stroke cap/join CPU regressions passed | -| Backquote/~ arrow nudges move selected pattern fills and strokes | done | #7717: Selection, partial-anchor Direct Selection and other idle tools; Keyboard Increment/Shift; geometry, guides and anchor selection stay fixed. Tests: `crates/ui-egui/tests/pattern_only_nudge.rs` | -| Deleting segments or anchors that disconnect an ordinary path creates independent selected objects | done | #3380, deletion only: first piece retains its ID, styles and transforms carry over in sibling order, bounds-fitted gradients keep their original placement, and one Undo restores the original. Existing multi-subpath paths and compound members stay intact. `delete_path_pieces` covers transformed/styled rectangles, cubic handles and Undo/Redo. Endpoint highlighting remains open. | -| Click/Shift-click anchors; marquee toggles with Shift | done | #483 | -| Align selected anchors to their bounds or the artboard; repeating an alignment that moves nothing keeps Undo, Redo and saved state | done | #1180 follow-up; engine regressions include rounding-only moves and unchanged handles; #1641 (fixes #1636): Align and Distribute act on the anchors selected with Direct Selection, the points of one path aligning to each other and Distribute spacing them | -| Align selected anchors to a key anchor | done | #1636; with multiple anchors selected via Direct Selection, clicking an already-selected anchor without modifiers designates it as the key anchor (or clears it if clicked again); drawn as a filled square with a distinct double outline; pressing Escape, clicking the canvas, or deselecting clears the key anchor; Align moves the other points to it and Distribute with a spacing places them from it; `select.key {id, anchor}` | -| A ruler guide as the key object: a click on a guide selected with objects (or Align to Key Object with one object and a guide) makes it the key, drawn thicker; Align lines the objects (or selected anchors) up on it and the guide stays put | done | #2143; `select.key {guide}`; a vertical guide sets x only, a horizontal one y | -| Distribute Objects and Distribute Spacing with a spacing from a key guide: the guide stays put and the other items are spaced the Distribute Spacing value from it, as from a key object with no size | done | Key guide from #3165; a vertical guide spaces the horizontal options, a horizontal one the vertical ones, and a guide along the axis leaves everything | -| Distribute ruler guides: the Distribute Objects and Distribute Spacing buttons space the selected guides across the axis with the selected objects, as items with no size; two or more guides selected alone are enough | done | #1597 in part; guides alone: select them, choose Align to Artboard and click Horizontal (Vertical) Distribute Center for equal columns (rows) ([public forum answer, 2017](https://community.adobe.com/questions-652/illustrator-equal-guides-822924)); with objects: a guide on each artboard edge, included in the selection, keeps the outermost lines there ([public forum answer, 2025](https://www.signs101.com/threads/is-there-a-way-to-distribute-shapes-like-this-in-illustrator.179556/)); a guide has no width, so the three options of an axis are the same for it; guides along the axis stay | -| Ruler guides align to a key object: a click on an object selected with guides makes it the key (one object is enough); Align moves the selected guides to its edge or centre (vertical guides to left, centre or right, horizontal ones to top, centre or bottom) and the key stays put | done | #2143; aligning to the selection or the artboard leaves guides alone | -| Align panel menu › Align to Glyph Bounds › Point Text and Area Text (checked while on): Align and Distribute measure point type or area type by the ink of its glyphs instead of its em box or frame | done | #4231; `alignGlyphBoundsPoint`, `alignGlyphBoundsArea` ([Align text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/align-text.html)); `tests::glyphbounds`, `panels::align::tests::align_to_glyph_bounds_toggles_point_and_area_text`; the Character and Properties panels' Align to Glyph Bounds controls are not done | -| Align and distribute artboards: with the Artboard tool chosen, the Align panel's Align Objects, Distribute Objects and Distribute Spacing buttons, and the Control bar's, move the selected artboards with the art inside them (Move Artwork with Artboard) | done | `artboard.align`, `artboard.distribute`, `artboard.distributeSpacing` ([Align and distribute artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/align-and-distribute-artboards.html)); VectorCraft's own rules: Align to Artboard keeps the active artboard in place and sends the Distribute Spacing value, Align to Key Object is off, a locked artboard stays where it is; `cmd::artboardalign::tests`, `panels::align::tests::the_align_buttons_align_the_selected_artboards` | -| Object › Distribute, below Object › Align: Horizontal Distribute Left, Center and Right, Vertical Distribute Top, Center and Bottom, Horizontal Distribute Space and Vertical Distribute Space, each running what a click on its Align panel button runs (Align To, the key object, the Distribute Spacing value and, with the Artboard tool chosen, the selected artboards) | done | The `align.distribute*` commands; the public page names Object › Distribute beside Object › Align for the Align and Distribute commands ([Align and distribute objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/align-and-distribute-objects.html)); the items and their order are VectorCraft's own, taken from the Align panel; `menus::tests::object_distribute_runs_the_distribute_buttons` | -| Object › Align's Align to Selection, Align to Key Object and Align to Artboard, after the align items: each sets the Align panel's Align To choice as its button does, the choice the panel shows is checked, and Edit › Keyboard Shortcuts lists them under Align with no default key | done | `align.toSelection`, `align.toKeyObject`, `align.toArtboard`; the public page has shortcuts for the Align commands set under Object › Align ([Align and distribute objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/align-and-distribute-objects.html)); placing the Align To choices there is VectorCraft's own; `panels::align::tests::object_align_lists_the_align_to_choices` | -| A marquee selects the objects whose paths it touches (anchors or segments): drawn inside a filled shape, over a background, it leaves that shape (Preview and Outline) | done | #1103 | -| Click a segment independently of its endpoint anchors; only its direction handles show | done | #1278: hollow endpoint squares, selected edge emphasized; headless egui checked | -| Drag a curved segment to bend it, a straight one to move its anchors | done | | -| Drag by an anchor of a path selected whole moves the whole path; Alt-drag by an anchor or a segment copies it, Alt toggles the copy during the drag, and the copy snaps by the anchor pressed, onto the original too | done | #1104 | -| Handles shown are the handles that drag; tolerance from Selection & Anchor Display | done | #494 | -| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | -| Show handles when multiple anchors are selected; Highlight anchors on mouse over; anchor and handle size | done | Preferences › Selection & Anchor Display | -| Convert selected anchors to corner/smooth from the Control bar and Properties | done | | -| Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; #3380 (deletion only): disconnected survivors of an ordinary contour become independent selected sibling objects, while multi-subpath paths and compound members stay intact; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes all selected surviving objects; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the surviving objects selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor | -| Direct Selection and Group Selection pick only inside the isolated object in isolation mode | done | #1666 | -| Group Selection picks one path of a compound path (the outer shape or a hole) and moves it on its own; a second click adds the compound path | done | #2441; Shift-click on a selected member deselects it on release | -| Direct Selection, Group Selection and the Selection tool take a clipping path (a clip group's, or a layer's clipping mask) on its outline, within the selection tolerance, even where the art it clips lies over its edge | done | `HitOptions::clip_outlines`; Select Behind lists the same; the eyedropper and the tools that act on what is drawn take the art | -| Alt with Direct Selection makes a marquee Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), and the Group Selection pointer stays until the release | done | #4890 | -| Direct Selection: a click on a selected object's centre point (Attributes › Show Center) selects the object whole, and a drag from it moves the object in one undo step | done | #4891 | -| Escape cancels a Direct Selection drag | done | #1803 (#1743) | -| Live Corners widgets (radius readout, Alt-click cycles kind, Direct Selection double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; a double-click on a selected live shape's corner widget shows the Transform panel ([Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)) and a Direct Selection double-click opens Corners ([Create and modify live shapes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)); giving the Transform panel to the Selection tool and Corners to Direct Selection is VectorCraft's own rule; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | -| Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | -| Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets | -| Side widget on a live polygon: drag it to set the number of sides from 3 to 11 | done | Selection tool and the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets; a drag down adds sides and a drag up removes them; Escape cancels ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html)) | -| A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing (the corner and pie widgets only while the Control bar's Hide Shape Widgets has not hidden them; the bounding box stays); a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). A drag on one of the box's handles scales the selection as the Selection tool's handles do. A double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel where it is (closed, docked, floating or in an icon column; a second double-click keeps it on show), and leaves the tool, the selection and the document as they were; a double-click on a pie widget, off the widgets, with Show Corner Widget off or with Line Segment does nothing; the Selection tool's double-click on a corner widget shows the Transform panel too, and a Direct Selection double-click opens the Corners dialog. Public description: [Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) (a double-click on a corner widget of a selected live shape opens the Transform panel). Tests `a_shape_tool_drags_the_selected_shapes_widgets`, `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner`, `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_double_click_on_a_corner_widget_shows_the_transform_panel`, `a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel` (engine), `a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel` (MCP: the `pointer_gesture` reply's `requests` carry `{"panel": "transform"}`) and `a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown` (UI) | -| Isolation mode by double-click (groups and single objects), breadcrumbs, Esc to exit | done | Single paths, compound paths, images, meshes and placed files isolate too ([helpx: Isolate objects](https://helpx.adobe.com/africa/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)); locking or hiding the layer (or a group) around the isolated object afterwards keeps clicks and marquees off it, as outside isolation mode (#5309) | -| "Magnetic" moves of selected anchors with a modifier (#955 request) | missing | not a feature of the reference app as documented; under discussion | -| Coinciding anchors of overlapping objects: the selected object's anchor is taken, also under another object | done | #1508 | +| Behaviour | Status | Notes | Headless | +|---|---|---| --- | +| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/path_fill_hits.rs`; hidden-fill and no-fill stroke cap/join CPU regressions passed | unknown | +| Backquote/~ arrow nudges move selected pattern fills and strokes | done | #7717: Selection, partial-anchor Direct Selection and other idle tools; Keyboard Increment/Shift; geometry, guides and anchor selection stay fixed. Tests: `crates/ui-egui/tests/pattern_only_nudge.rs` | unknown | +| Deleting segments or anchors that disconnect an ordinary path creates independent selected objects | done | #3380, deletion only: first piece retains its ID, styles and transforms carry over in sibling order, bounds-fitted gradients keep their original placement, and one Undo restores the original. Existing multi-subpath paths and compound members stay intact. `delete_path_pieces` covers transformed/styled rectangles, cubic handles and Undo/Redo. Endpoint highlighting remains open. | unknown | +| Click/Shift-click anchors; marquee toggles with Shift | done | #483 | unknown | +| Align selected anchors to their bounds or the artboard; repeating an alignment that moves nothing keeps Undo, Redo and saved state | done | #1180 follow-up; engine regressions include rounding-only moves and unchanged handles; #1641 (fixes #1636): Align and Distribute act on the anchors selected with Direct Selection, the points of one path aligning to each other and Distribute spacing them | unknown | +| Align selected anchors to a key anchor | done | #1636; with multiple anchors selected via Direct Selection, clicking an already-selected anchor without modifiers designates it as the key anchor (or clears it if clicked again); drawn as a filled square with a distinct double outline; pressing Escape, clicking the canvas, or deselecting clears the key anchor; Align moves the other points to it and Distribute with a spacing places them from it; `select.key {id, anchor}` | unknown | +| A ruler guide as the key object: a click on a guide selected with objects (or Align to Key Object with one object and a guide) makes it the key, drawn thicker; Align lines the objects (or selected anchors) up on it and the guide stays put | done | #2143; `select.key {guide}`; a vertical guide sets x only, a horizontal one y | unknown | +| Distribute Objects and Distribute Spacing with a spacing from a key guide: the guide stays put and the other items are spaced the Distribute Spacing value from it, as from a key object with no size | done | Key guide from #3165; a vertical guide spaces the horizontal options, a horizontal one the vertical ones, and a guide along the axis leaves everything | unknown | +| Distribute ruler guides: the Distribute Objects and Distribute Spacing buttons space the selected guides across the axis with the selected objects, as items with no size; two or more guides selected alone are enough | done | #1597 in part; guides alone: select them, choose Align to Artboard and click Horizontal (Vertical) Distribute Center for equal columns (rows) ([public forum answer, 2017](https://community.adobe.com/questions-652/illustrator-equal-guides-822924)); with objects: a guide on each artboard edge, included in the selection, keeps the outermost lines there ([public forum answer, 2025](https://www.signs101.com/threads/is-there-a-way-to-distribute-shapes-like-this-in-illustrator.179556/)); a guide has no width, so the three options of an axis are the same for it; guides along the axis stay | unknown | +| Ruler guides align to a key object: a click on an object selected with guides makes it the key (one object is enough); Align moves the selected guides to its edge or centre (vertical guides to left, centre or right, horizontal ones to top, centre or bottom) and the key stays put | done | #2143; aligning to the selection or the artboard leaves guides alone | unknown | +| Align panel menu › Align to Glyph Bounds › Point Text and Area Text (checked while on): Align and Distribute measure point type or area type by the ink of its glyphs instead of its em box or frame | done | #4231; `alignGlyphBoundsPoint`, `alignGlyphBoundsArea` ([Align text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/align-text.html)); `tests::glyphbounds`, `panels::align::tests::align_to_glyph_bounds_toggles_point_and_area_text`; the Character and Properties panels' Align to Glyph Bounds controls are not done | unknown | +| Align and distribute artboards: with the Artboard tool chosen, the Align panel's Align Objects, Distribute Objects and Distribute Spacing buttons, and the Control bar's, move the selected artboards with the art inside them (Move Artwork with Artboard) | done | `artboard.align`, `artboard.distribute`, `artboard.distributeSpacing` ([Align and distribute artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/align-and-distribute-artboards.html)); VectorCraft's own rules: Align to Artboard keeps the active artboard in place and sends the Distribute Spacing value, Align to Key Object is off, a locked artboard stays where it is; `cmd::artboardalign::tests`, `panels::align::tests::the_align_buttons_align_the_selected_artboards` | unknown | +| Object › Distribute, below Object › Align: Horizontal Distribute Left, Center and Right, Vertical Distribute Top, Center and Bottom, Horizontal Distribute Space and Vertical Distribute Space, each running what a click on its Align panel button runs (Align To, the key object, the Distribute Spacing value and, with the Artboard tool chosen, the selected artboards) | done | The `align.distribute*` commands; the public page names Object › Distribute beside Object › Align for the Align and Distribute commands ([Align and distribute objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/align-and-distribute-objects.html)); the items and their order are VectorCraft's own, taken from the Align panel; `menus::tests::object_distribute_runs_the_distribute_buttons` | unknown | +| Object › Align's Align to Selection, Align to Key Object and Align to Artboard, after the align items: each sets the Align panel's Align To choice as its button does, the choice the panel shows is checked, and Edit › Keyboard Shortcuts lists them under Align with no default key | done | `align.toSelection`, `align.toKeyObject`, `align.toArtboard`; the public page has shortcuts for the Align commands set under Object › Align ([Align and distribute objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/align-and-distribute-objects.html)); placing the Align To choices there is VectorCraft's own; `panels::align::tests::object_align_lists_the_align_to_choices` | unknown | +| A marquee selects the objects whose paths it touches (anchors or segments): drawn inside a filled shape, over a background, it leaves that shape (Preview and Outline) | done | #1103 | unknown | +| Click a segment independently of its endpoint anchors; only its direction handles show | done | #1278: hollow endpoint squares, selected edge emphasized; headless egui checked | unknown | +| Drag a curved segment to bend it, a straight one to move its anchors | done | | unknown | +| Drag by an anchor of a path selected whole moves the whole path; Alt-drag by an anchor or a segment copies it, Alt toggles the copy during the drag, and the copy snaps by the anchor pressed, onto the original too | done | #1104 | unknown | +| Handles shown are the handles that drag; tolerance from Selection & Anchor Display | done | #494 | unknown | +| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | unknown | +| Show handles when multiple anchors are selected; Highlight anchors on mouse over; anchor and handle size | done | Preferences › Selection & Anchor Display | unknown | +| Convert selected anchors to corner/smooth from the Control bar and Properties | done | | unknown | +| Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; #3380 (deletion only): disconnected survivors of an ordinary contour become independent selected sibling objects, while multi-subpath paths and compound members stay intact; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes all selected surviving objects; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the surviving objects selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor | unknown | +| Direct Selection and Group Selection pick only inside the isolated object in isolation mode | done | #1666 | unknown | +| Group Selection picks one path of a compound path (the outer shape or a hole) and moves it on its own; a second click adds the compound path | done | #2441; Shift-click on a selected member deselects it on release | unknown | +| Direct Selection, Group Selection and the Selection tool take a clipping path (a clip group's, or a layer's clipping mask) on its outline, within the selection tolerance, even where the art it clips lies over its edge | done | `HitOptions::clip_outlines`; Select Behind lists the same; the eyedropper and the tools that act on what is drawn take the art | unknown | +| Alt with Direct Selection makes a marquee Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), and the Group Selection pointer stays until the release | done | #4890 | unknown | +| Direct Selection: a click on a selected object's centre point (Attributes › Show Center) selects the object whole, and a drag from it moves the object in one undo step | done | #4891 | unknown | +| Escape cancels a Direct Selection drag | done | #1803 (#1743) | unknown | +| Live Corners widgets (radius readout, Alt-click cycles kind, Direct Selection double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; a double-click on a selected live shape's corner widget shows the Transform panel ([Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)) and a Direct Selection double-click opens Corners ([Create and modify live shapes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)); giving the Transform panel to the Selection tool and Corners to Direct Selection is VectorCraft's own rule; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | unknown | +| Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | unknown | +| Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets | unknown | +| Side widget on a live polygon: drag it to set the number of sides from 3 to 11 | done | Selection tool and the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets; a drag down adds sides and a drag up removes them; Escape cancels ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html)) | unknown | +| A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing (the corner and pie widgets only while the Control bar's Hide Shape Widgets has not hidden them; the bounding box stays); a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). A drag on one of the box's handles scales the selection as the Selection tool's handles do. A double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel where it is (closed, docked, floating or in an icon column; a second double-click keeps it on show), and leaves the tool, the selection and the document as they were; a double-click on a pie widget, off the widgets, with Show Corner Widget off or with Line Segment does nothing; the Selection tool's double-click on a corner widget shows the Transform panel too, and a Direct Selection double-click opens the Corners dialog. Public description: [Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) (a double-click on a corner widget of a selected live shape opens the Transform panel). Tests `a_shape_tool_drags_the_selected_shapes_widgets`, `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner`, `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_double_click_on_a_corner_widget_shows_the_transform_panel`, `a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel` (engine), `a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel` (MCP: the `pointer_gesture` reply's `requests` carry `{"panel": "transform"}`) and `a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown` (UI) | unknown | +| Isolation mode by double-click (groups and single objects), breadcrumbs, Esc to exit | done | Single paths, compound paths, images, meshes and placed files isolate too ([helpx: Isolate objects](https://helpx.adobe.com/africa/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)); locking or hiding the layer (or a group) around the isolated object afterwards keeps clicks and marquees off it, as outside isolation mode (#5309) | unknown | +| "Magnetic" moves of selected anchors with a modifier (#955 request) | missing | not a feature of the reference app as documented; under discussion | unknown | +| Coinciding anchors of overlapping objects: the selected object's anchor is taken, also under another object | done | #1508 | unknown | ## Smart guides and snapping -| Behaviour | Status | Notes | -|---|---|---| -| Snap to anchors, centres, edges, artboards, bleed and ruler guides with magenta lines | done | `guides.rs` kinds: Anchor, Center, Edge, Artboard, Bleed, Guide | -| Anchor/Path labels ("anchor", "center", "path", "align") | done | | -| "intersect" label and snapping to path intersections | partial | #1658 (part of #1602): a point drawn with the Pen, the shape tools or the other drawing tools and an anchor dragged with Direct Selection snap to where paths and ruler guides cross; a moved selection's own anchors and the Width tool don't | -| Construction guides at preference angles while drawing | done | #506 | -| Line extension: the dragged end of a straight segment snaps to the segment's own direction at any angle, past its other end or short of it, with the guide along it | done | #2120; Direct Selection and Curvature, one anchor dragged (with several, the move has no single direction); nearer the horizontal or vertical through the other end, the point lines up with it ("align"), so a nearly level segment can still be straightened | -| Measurement labels while drawing, moving and resizing | done | sizes and offsets; the segment being drawn is labeled with its distance, angle and offsets by the Line Segment tool, and by the Pen, Curvature and Smart Pen tools with Enable Rubber Band on or off (#2983) | -| Spacing guides (equal distances) | partial | for moves and bounding-box resizes (#394); not while drawing | -| Distance Guides: Alt/Option over another object, or an empty part of an artboard, shows the selection's distances to it (Smart Guides › Invoke Distance Guides) | done | Selection tool hover with Smart Guides on: the gap between facing edges, else the offsets of matching edges, to another object; the left, right, top and bottom distances to the artboard; labelled in the General unit. The selection is measured as a whole. Nothing while moving or nudging, which the public pages don't describe. [Use Distance Guides](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html), [Smart Guides options](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html) | -| Snapping tolerance preference | done | | -| Snap to Point, Snap to Grid, Snap to Pixel; Pixel Preview | done | #1840: with Snap to Grid on, anchors and objects snap to the grid even when Snap to Pixel is also ticked (#1816 waits for the reporter); #3835: a straight segment dragged with Direct Selection lands its anchors on the grid, the box round them putting an edge on a gridline on each axis, as a moved object does | -| Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`); new type and drawing snap to live-text baselines and glyph bounds when Smart Guides are on (#3124). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to them too; that is VectorCraft's choice. Character panel menu › Show Snap to Glyph Options: a Snap to Glyph checkbox (View › Snap to Glyph), then a checkbox for each guide (Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides, Anchor Point), dimmed while Snap to Glyph is off (#4232); showing them scrolls the panel to them (#5273) | -| Tangent and perpendicular snapping for line endpoints (new in 30.0) | done | #2530: tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Line Segment, Pen and Curvature tools, and for an existing line whose end anchor is dragged with Direct Selection (the only anchor selected, an open path's end on a straight segment; Shift keeps its angle step instead; Group Selection moves the path whole and does not snap so); mid-line anchors, curved segments' ends and curves as perpendicular targets are excluded, as the pages say. Saved Preferences › Smart Guides › Geometric Guides controls, on by default. [Perpendicular](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-perpendicular.html) and [tangent](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-tangent.html) pages; test `dragged_line_ends_snap_perpendicular_to_segments_and_tangent_to_curves` | -| Snapping panel/popover consolidating the snap options (30.0) | done | Control bar › Snapping provides quick access through existing view commands and prefs.set, including Snap to Glyph and Alignment Guides (#6164). View › Snapping groups Smart Guides, Snap to Point/Grid/Pixel/Glyph and Pixel Snapping Options… using existing commands, localization and checkmarks; top-level View commands and shortcuts remain. Structure, pointer clicks and painted checkmarks: `menus/tests.rs`. Floating-panel parity remains separately unverified. | -| Customisable rotation snap angle (#973) | missing | Illustrator: Constrain Angle and construction angles only | -| Ruler guides: drag out, select, move, delete, lock, Make/Release Guides | done | #414, #451; marquee selects unlocked ruler guides | -| A double-click on a ruler adds a guide at the pointer: a vertical one on the top ruler, a horizontal one on the left ruler (swapped in a view turned 90°, where the rulers read the other document axis; the nearer axis in between), exactly where the pointer is (no snapping), shown even with guides hidden, one undo step (`guide.add`); both clicks of the pair must be on that ruler, and the first adds nothing. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe this gesture, so it follows the request in #5239 | done | #5239; an artboard guide with the Artboard tool, as a drag from a ruler makes one; `canvas/tests.rs` `double_clicking_a_ruler_adds_a_guide_at_that_position`, `a_canvas_click_then_a_ruler_click_adds_no_guide`, `a_ruler_double_click_follows_a_rotated_view` | -| Escape cancels an existing ruler-guide press, move or copy | done | Selection and Direct/Group Selection; app-input regressions cover preselected guides, document/interaction-start selection, Undo/Redo and saved state, later on-canvas motion/release and temporary borrowing from idle Pen. All eight checks and the Direct Selection Escape control passed in current full CI. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | -| Ruler origin: corner drag with preview, snapped as a drawn point is (Smart Guides, Snap to Point and the ruler guides, pixels, the grid), double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | -| Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer; each row's own eye and lock; a row dropped on the trash deletes its guide; selected guide rows keep their highlight away from the pointer (#7344); a plain click on another row lets go of the guide | done | `guide.setLayer`; guides from older files go on a layer; `layer.setProps` on a guide's id hides or locks it alone; Object › Lock/Hide › Selection, Unlock All and Show All reach guides; `guide.remove {indexes}`; #7340 | -| Objects made into guides: drawn in the guide colour and style of Preferences; Lock Guides locks them too (no select, move or delete), in groups as well: a marquee leaves them out, so it does not take their group, and they still move with their group; a dragged selection snaps to ruler guides with Smart Guides on, by the nearest point of the path when pressed on its stroke or beside its edge, so the path lands exactly on the guide | done | #1534 (#1543, #1583); #3701; #8538 | -| View › Trim View hides the ruler guides, the guide paths and the grid while it is on, and View › Guides › Show/Hide Guides and View › Show/Hide Grid are greyed out until it is off (#8363) | done | As public forum threads describe ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). The Show/Hide choices are kept and come back as they were; the items stay greyed in the canvas context menu and the Properties panel's buttons, and refuse to run from keys, the palette or MCP. Hidden guides are neither snapped to nor picked, as with Hide Guides, and a selected guide path is deselected. The rulers stay as they are, but a drag or double-click on them makes no guide, since it could not be seen: no preview line, no undo step, a status message instead. `menus::tests::trim_view_greys_out_show_guides_and_show_grid`, `canvas::tests::{trim_view_hides_the_guides_and_the_grid, trim_view_deselects_selected_guide_paths, trim_view_makes_no_guide_from_the_rulers}` | -| A selected ruler guide's X or Y in the Transform panel; typing a value moves it | not scored | #1659 (part of #1597); several guides move together; not in Properties or the Control bar. Not established by the documentation we could find: the help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) don't describe it, and the one public statement is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. Kept as a convenience pending the owner's decision; no parity claim | -| Alt swaps a ruler guide's orientation while dragging | missing | Alt-drag copies the selected guides ([Use rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html)); `guide.move` `{copy: true}` | -| Alt swaps a new ruler guide's orientation while dragging | done | Both rulers; preview, snapping and final placement follow the current modifier ([public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). | -| Global/artboard ruler mode switch (View › Rulers › Change to Global / Artboard Rulers, Cmd+Alt+R) | done | `view.globalRulers`; a new document has artboard rulers, counting from the active artboard's top-left corner or the zero point set for it (kept relative to the artboard); global rulers keep one document zero point. Rulers, Transform, Properties, Control and Info X/Y, status-bar pointer X/Y, guide readouts and Shift ruler-tick snapping follow the mode; saved with the document, older files open with global rulers. Behaviour from [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html) and [Use rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) | -| Video rulers (View › Rulers › Show Video Rulers) | done | #2849; `view.videoRulers`: the rulers show and count the active artboard in video pixels from its top-left corner, whatever the ruler origin, a pixel as many points wide as the artboard's Video Ruler Pixel Aspect Ratio and one point tall ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)); the item then reads Hide Video Rulers, which returns them to the General unit. Shift ruler-tick snapping of new guides keeps the General unit. Tests `video_rulers_count_the_artboard_in_pixels_of_its_aspect_ratio`, `show_video_rulers_counts_the_active_artboard_in_pixels` | +| Behaviour | Status | Notes | Headless | +|---|---|---| --- | +| Snap to anchors, centres, edges, artboards, bleed and ruler guides with magenta lines | done | `guides.rs` kinds: Anchor, Center, Edge, Artboard, Bleed, Guide | unknown | +| Anchor/Path labels ("anchor", "center", "path", "align") | done | | unknown | +| "intersect" label and snapping to path intersections | partial | #1658 (part of #1602): a point drawn with the Pen, the shape tools or the other drawing tools and an anchor dragged with Direct Selection snap to where paths and ruler guides cross; a moved selection's own anchors and the Width tool don't | unknown | +| Construction guides at preference angles while drawing | done | #506 | unknown | +| Line extension: the dragged end of a straight segment snaps to the segment's own direction at any angle, past its other end or short of it, with the guide along it | done | #2120; Direct Selection and Curvature, one anchor dragged (with several, the move has no single direction); nearer the horizontal or vertical through the other end, the point lines up with it ("align"), so a nearly level segment can still be straightened | unknown | +| Measurement labels while drawing, moving and resizing | done | sizes and offsets; the segment being drawn is labeled with its distance, angle and offsets by the Line Segment tool, and by the Pen, Curvature and Smart Pen tools with Enable Rubber Band on or off (#2983) | unknown | +| Spacing guides (equal distances) | partial | for moves and bounding-box resizes (#394); not while drawing | unknown | +| Distance Guides: Alt/Option over another object, or an empty part of an artboard, shows the selection's distances to it (Smart Guides › Invoke Distance Guides) | done | Selection tool hover with Smart Guides on: the gap between facing edges, else the offsets of matching edges, to another object; the left, right, top and bottom distances to the artboard; labelled in the General unit. The selection is measured as a whole. Nothing while moving or nudging, which the public pages don't describe. [Use Distance Guides](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html), [Smart Guides options](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html) | unknown | +| Snapping tolerance preference | done | | unknown | +| Snap to Point, Snap to Grid, Snap to Pixel; Pixel Preview | done | #1840: with Snap to Grid on, anchors and objects snap to the grid even when Snap to Pixel is also ticked (#1816 waits for the reporter); #3835: a straight segment dragged with Direct Selection lands its anchors on the grid, the box round them putting an edge on a gridline on each axis, as a moved object does | unknown | +| Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`); new type and drawing snap to live-text baselines and glyph bounds when Smart Guides are on (#3124). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to them too; that is VectorCraft's choice. Character panel menu › Show Snap to Glyph Options: a Snap to Glyph checkbox (View › Snap to Glyph), then a checkbox for each guide (Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides, Anchor Point), dimmed while Snap to Glyph is off (#4232); showing them scrolls the panel to them (#5273) | unknown | +| Tangent and perpendicular snapping for line endpoints (new in 30.0) | done | #2530: tangent snapping to curves and perpendicular snapping to straight segments for lines drawn with the Line Segment, Pen and Curvature tools, and for an existing line whose end anchor is dragged with Direct Selection (the only anchor selected, an open path's end on a straight segment; Shift keeps its angle step instead; Group Selection moves the path whole and does not snap so); mid-line anchors, curved segments' ends and curves as perpendicular targets are excluded, as the pages say. Saved Preferences › Smart Guides › Geometric Guides controls, on by default. [Perpendicular](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-perpendicular.html) and [tangent](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/snap-to-tangent.html) pages; test `dragged_line_ends_snap_perpendicular_to_segments_and_tangent_to_curves` | unknown | +| Snapping panel/popover consolidating the snap options (30.0) | done | Control bar › Snapping provides quick access through existing view commands and prefs.set, including Snap to Glyph and Alignment Guides (#6164). View › Snapping groups Smart Guides, Snap to Point/Grid/Pixel/Glyph and Pixel Snapping Options… using existing commands, localization and checkmarks; top-level View commands and shortcuts remain. Structure, pointer clicks and painted checkmarks: `menus/tests.rs`. Floating-panel parity remains separately unverified. | unknown | +| Customisable rotation snap angle (#973) | missing | Illustrator: Constrain Angle and construction angles only | unknown | +| Ruler guides: drag out, select, move, delete, lock, Make/Release Guides | done | #414, #451; marquee selects unlocked ruler guides | unknown | +| A double-click on a ruler adds a guide at the pointer: a vertical one on the top ruler, a horizontal one on the left ruler (swapped in a view turned 90°, where the rulers read the other document axis; the nearer axis in between), exactly where the pointer is (no snapping), shown even with guides hidden, one undo step (`guide.add`); both clicks of the pair must be on that ruler, and the first adds nothing. The [public page on rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) doesn't describe this gesture, so it follows the request in #5239 | done | #5239; an artboard guide with the Artboard tool, as a drag from a ruler makes one; `canvas/tests.rs` `double_clicking_a_ruler_adds_a_guide_at_that_position`, `a_canvas_click_then_a_ruler_click_adds_no_guide`, `a_ruler_double_click_follows_a_rotated_view` | unknown | +| Escape cancels an existing ruler-guide press, move or copy | done | Selection and Direct/Group Selection; app-input regressions cover preselected guides, document/interaction-start selection, Undo/Redo and saved state, later on-canvas motion/release and temporary borrowing from idle Pen. All eight checks and the Direct Selection Escape control passed in current full CI. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | unknown | +| Ruler origin: corner drag with preview, snapped as a drawn point is (Smart Guides, Snap to Point and the ruler guides, pixels, the grid), double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | unknown | +| Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer; each row's own eye and lock; a row dropped on the trash deletes its guide; selected guide rows keep their highlight away from the pointer (#7344); a plain click on another row lets go of the guide | done | `guide.setLayer`; guides from older files go on a layer; `layer.setProps` on a guide's id hides or locks it alone; Object › Lock/Hide › Selection, Unlock All and Show All reach guides; `guide.remove {indexes}`; #7340 | unknown | +| Objects made into guides: drawn in the guide colour and style of Preferences; Lock Guides locks them too (no select, move or delete), in groups as well: a marquee leaves them out, so it does not take their group, and they still move with their group; a dragged selection snaps to ruler guides with Smart Guides on, by the nearest point of the path when pressed on its stroke or beside its edge, so the path lands exactly on the guide | done | #1534 (#1543, #1583); #3701; #8538 | unknown | +| View › Trim View hides the ruler guides, the guide paths and the grid while it is on, and View › Guides › Show/Hide Guides and View › Show/Hide Grid are greyed out until it is off (#8363) | done | As public forum threads describe ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). The Show/Hide choices are kept and come back as they were; the items stay greyed in the canvas context menu and the Properties panel's buttons, and refuse to run from keys, the palette or MCP. Hidden guides are neither snapped to nor picked, as with Hide Guides, and a selected guide path is deselected. The rulers stay as they are, but a drag or double-click on them makes no guide, since it could not be seen: no preview line, no undo step, a status message instead. `menus::tests::trim_view_greys_out_show_guides_and_show_grid`, `canvas::tests::{trim_view_hides_the_guides_and_the_grid, trim_view_deselects_selected_guide_paths, trim_view_makes_no_guide_from_the_rulers}` | unknown | +| A selected ruler guide's X or Y in the Transform panel; typing a value moves it | not scored | #1659 (part of #1597); several guides move together; not in Properties or the Control bar. Not established by the documentation we could find: the help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) don't describe it, and the one public statement is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. Kept as a convenience pending the owner's decision; no parity claim | unknown | +| Alt swaps a ruler guide's orientation while dragging | missing | Alt-drag copies the selected guides ([Use rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html)); `guide.move` `{copy: true}` | unknown | +| Alt swaps a new ruler guide's orientation while dragging | done | Both rulers; preview, snapping and final placement follow the current modifier ([public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). | unknown | +| Global/artboard ruler mode switch (View › Rulers › Change to Global / Artboard Rulers, Cmd+Alt+R) | done | `view.globalRulers`; a new document has artboard rulers, counting from the active artboard's top-left corner or the zero point set for it (kept relative to the artboard); global rulers keep one document zero point. Rulers, Transform, Properties, Control and Info X/Y, status-bar pointer X/Y, guide readouts and Shift ruler-tick snapping follow the mode; saved with the document, older files open with global rulers. Behaviour from [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html) and [Use rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) | unknown | +| Video rulers (View › Rulers › Show Video Rulers) | done | #2849; `view.videoRulers`: the rulers show and count the active artboard in video pixels from its top-left corner, whatever the ruler origin, a pixel as many points wide as the artboard's Video Ruler Pixel Aspect Ratio and one point tall ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)); the item then reads Hide Video Rulers, which returns them to the General unit. Shift ruler-tick snapping of new guides keeps the General unit. Tests `video_rulers_count_the_artboard_in_pixels_of_its_aspect_ratio`, `show_video_rulers_counts_the_active_artboard_in_pixels` | unknown | ## Transform handles, bounding box, Free Transform -| Behaviour | Status | Notes | -|---|---|---| -| Moving a rounded rectangle with Craquelure at high DPI | partial | Distance searches optimized; moved-viewport pixels unchanged for three texture effects; `texture_drag_perf` probe available. Idle Windows mouse-drag QA remains (#1257) | -| Bounding-box handles: Shift proportional, Alt from centre, rotate outside the corners | done | | -| Rotated objects keep a rotated bounding box and their angle; Reset Bounding Box | done | | -| Vector Halftone Preview keeps the selection box and hides selection marks on the temporary dots | done | #6369; Preview off and Cancel restore the original marks. | -| Free Transform, Scale and Reflect along a rotated box | done | The Scale and Reflect tools, dialogs and commands and the Transform and Properties panels' flips act along the turned box until Reset Bounding Box; `basis: "page"` keeps the page's axes | -| Free Transform widget: constrain, free distort, perspective distort; the key-held variants | done | | -| Transform tools: click sets the reference point (snaps to anchors/centres), Alt-click opens the dialog, Alt-release copies | done | with anchors selected with Direct Selection, the tools, the dialogs and Move transform those anchors alone, about the centre of their box by default (#1408; the default point and whole-object copies are our choices) | -| Reflect tool: a second click reflects across the line through both clicked points; Alt on it reflects a copy | done | [the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html); one undo step; a second click whose snapped point is within 3 screen pixels of the first one's, Escape or a changed selection leaves nothing reflected (our choices) | -| Move, Rotate, Scale, Reflect and Shear dialogs: live Preview; Up/Down step angles and percentages by 1, Shift by 10 | done | #1412; Preview starts off (our choice: the public documentation gives no default), Move's as it was last confirmed; OK is one undo step and Transform Again repeats it | -| Transform Again, Transform Each, Scale Strokes & Effects, Scale Corners | done | | -| The Transform effect dialog previews valid typed scale, move, rotation, and Copies values while fields remain focused. Preview off defers the artwork change until OK; Cancel restores the original artwork. | done | `crates/ui-egui/src/panels/tests_appearance.rs` covers numeric input, sliders, artwork targets, preview, and undo. | -| Move opens on the offset of the last move (a drag of the selection or Move) and with the Copy, Transform Objects and Preview it was last confirmed with, so Enter, Enter repeats a move or a copy | done | the public source: [an Adobe Community thread](https://community.adobe.com/questions-652/move-tool-771221) (the dialog shows the last move, drags included); that the checkboxes are kept, Preview among them, and that a nudge with the arrow keys is not a move here are our choices; Transform Patterns is General › Transform Pattern Tiles, which Move's OK sets; the offset is the session's (not kept between launches) | -| Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with, and has a Copy button left of Cancel that transforms a copy of each object (no Copy checkbox) | done | #1732; the Copy button: [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html); the remembered values: a maintainer's call on [#1732](https://github.com/storytold/vectorcraft/issues/1732#issuecomment-6157505075), not the help page; Copy itself is never kept; Preview still starts off on first use (the owner's call) | -| Transform Each's Scale has Relative and Absolute: percentages of each object's size, or the width and height it becomes | done | `object.transformEach` `relative`; behaviour reference: [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html), "Switch between Relative and Absolute… exact values"; Absolute measures each object's own box; the scales act along its axes, about that box's reference point, so a turned shape keeps its shape; the fields show the width and height the selected objects share (not the selection's bounds) and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), a size typed setting every object to it, our choices where the page leaves them open (a side left Mixed is left as it is); Relative keeps its own percentages, and Transform Again repeats the Absolute target, which leaves objects that already have that size as they are; a live Repeat scales its spacing by the geometric mean of the two factors, so Absolute reaches its size only approximately (its layout is its own) | -| Transform Each's Scale has the link that keeps its two values in proportion, and the panel lists Scale, Move, Rotate, the Options, the Reference Point and Preview in the documented order (Preview level with Copy, Cancel and OK) | done | the link (`__constrain`, as the shape dialogs' Width and Height link): on, a scale sets the other so the two keep the proportions they had when it was turned on, and the dialog opens with it as it was last confirmed; the order and Preview's place in the button row follow the owner's mockup; the link's placement beside the two rows is our choice (the public pages don't establish it) | -| Transform Objects beside Transform Patterns in the Move, Rotate, Scale, Reflect and Shear dialogs and Transform Each; Reflect across an angle | done | #1448, #1460; off, only the pattern tiles transform; the checkboxes are always enabled (our choice) | -| Split Into Grid dialog: number, height or width, gutter and total for rows and columns, Add Guides, Preview | done | #1462; opens at the selection's size; several paths become one grid painted as the topmost one; a typed height or width keeps the gutter and changes the total (our choice) | -| Reference point locator (nine squares) in Control bar and Transform panel | done | | -| Transform panel menu: Transform Object Only, Transform Pattern Only, Transform Both (one checked), Use Registration Point for Symbol | done | `transformPanelPatterns` (`object`, `pattern`, `both`) sends `objects` and `patterns` with every field, flip and menu flip of the Transform panel and the Properties panel's Transform section; `useRegistrationPointForSymbol` makes them measure and transform one selected symbol instance from its symbol's registration point (Symbol Options › Registration), where the instance's flips, rotations and shears put it, instead of the reference point; the Properties panel's rotation and flips turn and mirror about it too ([Transform panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/transform-panel-overview.html)); until a choice is made (`default`) the panels follow General › Transform Pattern Tiles as before, the menu checking Transform Both while it is on and Transform Object Only while it is off | -| Transform panel menu and New Document › Advanced Options: Align New Objects to Pixel Grid | done | `document.setup {alignNewObjectsToPixelGrid}` and `file.new {alignNewObjectsToPixelGrid}`: paths and compound paths drawn while it is on are pixel-aligned; on in the Mobile and Web presets; art already in the document, pasted, duplicated or placed keeps its own property (our choice) | -| Transform panel, Properties and Control bar X/Y/W/H of the anchor points selected with Direct Selection | done | #1839 (fixes #1824): they show and edit the selected points' bounds; a whole-object selection is unchanged | +| Behaviour | Status | Notes | Headless | +|---|---|---| --- | +| Moving a rounded rectangle with Craquelure at high DPI | partial | Distance searches optimized; moved-viewport pixels unchanged for three texture effects; `texture_drag_perf` probe available. Idle Windows mouse-drag QA remains (#1257) | unknown | +| Bounding-box handles: Shift proportional, Alt from centre, rotate outside the corners | done | | unknown | +| Rotated objects keep a rotated bounding box and their angle; Reset Bounding Box | done | | unknown | +| Vector Halftone Preview keeps the selection box and hides selection marks on the temporary dots | done | #6369; Preview off and Cancel restore the original marks. | unknown | +| Free Transform, Scale and Reflect along a rotated box | done | The Scale and Reflect tools, dialogs and commands and the Transform and Properties panels' flips act along the turned box until Reset Bounding Box; `basis: "page"` keeps the page's axes | unknown | +| Free Transform widget: constrain, free distort, perspective distort; the key-held variants | done | | unknown | +| Transform tools: click sets the reference point (snaps to anchors/centres), Alt-click opens the dialog, Alt-release copies | done | with anchors selected with Direct Selection, the tools, the dialogs and Move transform those anchors alone, about the centre of their box by default (#1408; the default point and whole-object copies are our choices) | unknown | +| Reflect tool: a second click reflects across the line through both clicked points; Alt on it reflects a copy | done | [the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html); one undo step; a second click whose snapped point is within 3 screen pixels of the first one's, Escape or a changed selection leaves nothing reflected (our choices) | unknown | +| Move, Rotate, Scale, Reflect and Shear dialogs: live Preview; Up/Down step angles and percentages by 1, Shift by 10 | done | #1412; Preview starts off (our choice: the public documentation gives no default), Move's as it was last confirmed; OK is one undo step and Transform Again repeats it | unknown | +| Transform Again, Transform Each, Scale Strokes & Effects, Scale Corners | done | | unknown | +| The Transform effect dialog previews valid typed scale, move, rotation, and Copies values while fields remain focused. Preview off defers the artwork change until OK; Cancel restores the original artwork. | done | `crates/ui-egui/src/panels/tests_appearance.rs` covers numeric input, sliders, artwork targets, preview, and undo. | unknown | +| Move opens on the offset of the last move (a drag of the selection or Move) and with the Copy, Transform Objects and Preview it was last confirmed with, so Enter, Enter repeats a move or a copy | done | the public source: [an Adobe Community thread](https://community.adobe.com/questions-652/move-tool-771221) (the dialog shows the last move, drags included); that the checkboxes are kept, Preview among them, and that a nudge with the arrow keys is not a move here are our choices; Transform Patterns is General › Transform Pattern Tiles, which Move's OK sets; the offset is the session's (not kept between launches) | unknown | +| Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with, and has a Copy button left of Cancel that transforms a copy of each object (no Copy checkbox) | done | #1732; the Copy button: [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html); the remembered values: a maintainer's call on [#1732](https://github.com/storytold/vectorcraft/issues/1732#issuecomment-6157505075), not the help page; Copy itself is never kept; Preview still starts off on first use (the owner's call) | unknown | +| Transform Each's Scale has Relative and Absolute: percentages of each object's size, or the width and height it becomes | done | `object.transformEach` `relative`; behaviour reference: [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html), "Switch between Relative and Absolute… exact values"; Absolute measures each object's own box; the scales act along its axes, about that box's reference point, so a turned shape keeps its shape; the fields show the width and height the selected objects share (not the selection's bounds) and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), a size typed setting every object to it, our choices where the page leaves them open (a side left Mixed is left as it is); Relative keeps its own percentages, and Transform Again repeats the Absolute target, which leaves objects that already have that size as they are; a live Repeat scales its spacing by the geometric mean of the two factors, so Absolute reaches its size only approximately (its layout is its own) | unknown | +| Transform Each's Scale has the link that keeps its two values in proportion, and the panel lists Scale, Move, Rotate, the Options, the Reference Point and Preview in the documented order (Preview level with Copy, Cancel and OK) | done | the link (`__constrain`, as the shape dialogs' Width and Height link): on, a scale sets the other so the two keep the proportions they had when it was turned on, and the dialog opens with it as it was last confirmed; the order and Preview's place in the button row follow the owner's mockup; the link's placement beside the two rows is our choice (the public pages don't establish it) | unknown | +| Transform Objects beside Transform Patterns in the Move, Rotate, Scale, Reflect and Shear dialogs and Transform Each; Reflect across an angle | done | #1448, #1460; off, only the pattern tiles transform; the checkboxes are always enabled (our choice) | unknown | +| Split Into Grid dialog: number, height or width, gutter and total for rows and columns, Add Guides, Preview | done | #1462; opens at the selection's size; several paths become one grid painted as the topmost one; a typed height or width keeps the gutter and changes the total (our choice) | unknown | +| Reference point locator (nine squares) in Control bar and Transform panel | done | | unknown | +| Transform panel menu: Transform Object Only, Transform Pattern Only, Transform Both (one checked), Use Registration Point for Symbol | done | `transformPanelPatterns` (`object`, `pattern`, `both`) sends `objects` and `patterns` with every field, flip and menu flip of the Transform panel and the Properties panel's Transform section; `useRegistrationPointForSymbol` makes them measure and transform one selected symbol instance from its symbol's registration point (Symbol Options › Registration), where the instance's flips, rotations and shears put it, instead of the reference point; the Properties panel's rotation and flips turn and mirror about it too ([Transform panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/transform-panel-overview.html)); until a choice is made (`default`) the panels follow General › Transform Pattern Tiles as before, the menu checking Transform Both while it is on and Transform Object Only while it is off | unknown | +| Transform panel menu and New Document › Advanced Options: Align New Objects to Pixel Grid | done | `document.setup {alignNewObjectsToPixelGrid}` and `file.new {alignNewObjectsToPixelGrid}`: paths and compound paths drawn while it is on are pixel-aligned; on in the Mobile and Web presets; art already in the document, pasted, duplicated or placed keeps its own property (our choice) | unknown | +| Transform panel, Properties and Control bar X/Y/W/H of the anchor points selected with Direct Selection | done | #1839 (fixes #1824): they show and edit the selected points' bounds; a whole-object selection is unchanged | unknown | ## Nudging, numeric entry and precision -| Behaviour | Status | Notes | -|---|---|---| -| Wheel over a closed font-family field in Character, Properties or Control | done | #5253: applies the next or previous family to selected text, one undo step per notch; uses saved font filters, ignores search text and stops at the list's ends. Escape and pointer departure keep the change. The field takes the wheel only when the pointer was moved onto it after the field last moved or was covered by a window or overlay, and the wheel stream began there; a stream that began elsewhere stays there until 0.5 s pass with no wheel input. This rule and its 0.5 s are VectorCraft's choices. Other font-picking menus and modifier-wheel input keep their existing behavior. | -| Arrow keys nudge by Keyboard Increment (0.001–1296 pt); Shift ×10; Alt copies | done | | -| Fields commit what was typed on a click away or a move to another field, as Enter does; Escape discards it | done | #1787 | -| Number fields: Up/Down step, Shift ×10, Cmd/Ctrl ÷10, wheel over a hovered field without a click; steps, the wheel and label scrubs stop at the field's bounds (a stroke weight at 0, a miter limit at 1) | done | Shift+arrow in the Stroke weight field doesn't step by 10 (#991); bounds #3370. The field takes the wheel only when the pointer was moved onto it after the field last moved or was covered by a window or overlay, and the wheel stream began there; a stream that began elsewhere stays there until 0.5 s pass with no wheel input or the pointer is pressed on a field, so a panel scrolled under a still pointer keeps scrolling past the field. This rule and its 0.5 s are VectorCraft's choices. | -| Numeric spinner arrows step once on a click and keep repeating while held with the mouse | done | #6307; headless test `a_held_spinner_arrow_repeats` holds past egui's click timeout and checks release. | -| Arithmetic in fields (`+ - * /`, `x`, `X` or `×` for `*`, and `%` of the value before it: `3cm*50%`, `50pt+25%`) and unit suffixes (`3 mm`, `1in`, `2p6`) | done | `Unit::parse` and `parse_number`; mixed units in one expression not verified | -| Numeric fields: focus click selects the whole value; dragging selects from the pressed character | partial | #1326; select-all waits for click release; px/pt/plain/optional fields, both directions and replacement text tested; native API input, 17 px partial replacement, Undo/Redo, saved-file round trip and screenshots verified; Tab, double-click, arrows and wheel preserved; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all (#6659) | -| Units: pt, pc, in, mm, cm, px, ft-in, m, yd, ft; General/Stroke/Type units | done | units preference reverting to points on SVG output reported (#864). A file that records no units (PDF, EPS or `.ai` without ruler units, raster images, metafiles, Affinity files) opens and reverts in General units; native, SVG and DXF files and a `.ai` or EPS with ruler units keep theirs, as a [Community Expert's answer](https://community.adobe.com/questions-652/change-units-from-points-to-inches-won-t-stick-765372) describes (#5820) | -| Units › East Asian Type (Q and Ha) | done | #394: `unitsAsianType` offers every unit and Q and Ha, a quarter of a millimetre each ([Scripting Guide's Measurement Units](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/): 0.709 pt per Q; [InDesign's unit notation](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html): `q`, `h`); only it lists Q and Ha. The public pages do not say which fields use it, so no field uses it yet and that waits for a source. Tests `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` | -| Field precision: 3 decimals for steps; values kept as f64 | done | | -| Scrubby labels (beyond Illustrator) | done | #400; the labels that are links (the Control bar's Stroke: and Opacity:, the Properties panel's Stroke) scrub too, and a click on them still opens their panel (#4088) | -| 3D Lighting Color picker, preview, reset dot and Reset all | initial | One to ten opaque RGB lights for Revolve, Extrude & Bevel, Inflate and Rotate; select, add or delete a light and edit its settings or gizmo; Standard, Diffuse, Top Left and Right select original rigs, with Custom for manual changes; Cancel restores all lights | -| Classic 3D Track Cube preserves untouched rotation precision | done | Editing Z preserves the original fractional X and Y angles. | -| Dialogs open with the first field focused and selected; Enter confirms | done | on every open, not only the first (#1367); a first field that starts greyed out takes the focus once enabled (#1395) | -| Value fields: selected text readable in every brightness; a focused field follows its value when a slider or preview changes it | partial | #1490, #1457; hover wheel stepping #5949 | -| Sliders in dialogs and popups (Save for Web, raster export options, Preferences, the opacity popup) show their rail, filled up to the handle | done | #1483 | -| Rectangular Grid and Polar Grid click dialogs: size, divider counts with a skew slider each, Use Outside Rectangle As Frame / Create Compound Path From Ellipses, Fill Grid; kept as the tool's options, used by drags too | done | #1377. The options are the documented ones; how far a skew percentage moves the dividers and which way the radial skew turns are our own choice (the public documentation gives neither). The reference point locator is in the dialog, and a double-click on the tool opens it as the tool's Tool Options (next row) | -| Double-click the Line Segment, Arc, Rectangular Grid or Polar Grid tool: its Tool Options ([Rectangular Grid tool](https://helpx.adobe.com/illustrator/using/tool-techniques/rectangular-grid-tool.html) and [Arc tool](https://helpx.adobe.com/illustrator/using/tool-techniques/arc-tool.html) step 3, [Tools](https://helpx.adobe.com/illustrator/using/tools.html)) | done | #2691. The tool's click dialog without a place to draw: Line Segment's Length, Angle and Fill Line; Arc's lengths, Reference Point, Type, Base Along, Slope and Fill Arc; the grids' Reference Point, Default Size, dividers, skews and switches. OK draws nothing and sets what the next drag draws with (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and what a click's dialog opens at (with the Length, Angle and Default Size); Cancel changes nothing (`double_clicking_the_line_arc_and_grid_tools_opens_their_tool_options`) | -| Three-Point Arc tool (VectorCraft addition), after the Arc tool: two ends, then a third point the open arc passes through or, with Third Point Sets Direction (its Tool Options, or `]` while drawing), the direction it leaves an end in; a preview with the center and, with Measurement Labels on, the radius; one undo step | done | `shape.threePointArc` (`crates/engine/src/cmd/create.rs`), the tool in `crates/tools/src/three_point_arc.rs`, the geometry in `crates/geom/src/shapes.rs` (`CircularArc`), and their tests; a VectorCraft addition, so it is not scored | +| Behaviour | Status | Notes | Headless | +|---|---|---| --- | +| Wheel over a closed font-family field in Character, Properties or Control | done | #5253: applies the next or previous family to selected text, one undo step per notch; uses saved font filters, ignores search text and stops at the list's ends. Escape and pointer departure keep the change. The field takes the wheel only when the pointer was moved onto it after the field last moved or was covered by a window or overlay, and the wheel stream began there; a stream that began elsewhere stays there until 0.5 s pass with no wheel input. This rule and its 0.5 s are VectorCraft's choices. Other font-picking menus and modifier-wheel input keep their existing behavior. | unknown | +| Arrow keys nudge by Keyboard Increment (0.001–1296 pt); Shift ×10; Alt copies | done | | unknown | +| Fields commit what was typed on a click away or a move to another field, as Enter does; Escape discards it | done | #1787 | unknown | +| Number fields: Up/Down step, Shift ×10, Cmd/Ctrl ÷10, wheel over a hovered field without a click; steps, the wheel and label scrubs stop at the field's bounds (a stroke weight at 0, a miter limit at 1) | done | Shift+arrow in the Stroke weight field doesn't step by 10 (#991); bounds #3370. The field takes the wheel only when the pointer was moved onto it after the field last moved or was covered by a window or overlay, and the wheel stream began there; a stream that began elsewhere stays there until 0.5 s pass with no wheel input or the pointer is pressed on a field, so a panel scrolled under a still pointer keeps scrolling past the field. This rule and its 0.5 s are VectorCraft's choices. | unknown | +| Numeric spinner arrows step once on a click and keep repeating while held with the mouse | done | #6307; headless test `a_held_spinner_arrow_repeats` holds past egui's click timeout and checks release. | unknown | +| Arithmetic in fields (`+ - * /`, `x`, `X` or `×` for `*`, and `%` of the value before it: `3cm*50%`, `50pt+25%`) and unit suffixes (`3 mm`, `1in`, `2p6`) | done | `Unit::parse` and `parse_number`; mixed units in one expression not verified | unknown | +| Numeric fields: focus click selects the whole value; dragging selects from the pressed character | partial | #1326; select-all waits for click release; px/pt/plain/optional fields, both directions and replacement text tested; native API input, 17 px partial replacement, Undo/Redo, saved-file round trip and screenshots verified; Tab, double-click, arrows and wheel preserved; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all (#6659) | unknown | +| Units: pt, pc, in, mm, cm, px, ft-in, m, yd, ft; General/Stroke/Type units | done | units preference reverting to points on SVG output reported (#864). A file that records no units (PDF, EPS or `.ai` without ruler units, raster images, metafiles, Affinity files) opens and reverts in General units; native, SVG and DXF files and a `.ai` or EPS with ruler units keep theirs, as a [Community Expert's answer](https://community.adobe.com/questions-652/change-units-from-points-to-inches-won-t-stick-765372) describes (#5820) | unknown | +| Units › East Asian Type (Q and Ha) | done | #394: `unitsAsianType` offers every unit and Q and Ha, a quarter of a millimetre each ([Scripting Guide's Measurement Units](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/): 0.709 pt per Q; [InDesign's unit notation](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html): `q`, `h`); only it lists Q and Ha. The public pages do not say which fields use it, so no field uses it yet and that waits for a source. Tests `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` | unknown | +| Field precision: 3 decimals for steps; values kept as f64 | done | | unknown | +| Scrubby labels (beyond Illustrator) | done | #400; the labels that are links (the Control bar's Stroke: and Opacity:, the Properties panel's Stroke) scrub too, and a click on them still opens their panel (#4088) | unknown | +| 3D Lighting Color picker, preview, reset dot and Reset all | initial | One to ten opaque RGB lights for Revolve, Extrude & Bevel, Inflate and Rotate; select, add or delete a light and edit its settings or gizmo; Standard, Diffuse, Top Left and Right select original rigs, with Custom for manual changes; Cancel restores all lights | unknown | +| Classic 3D Track Cube preserves untouched rotation precision | done | Editing Z preserves the original fractional X and Y angles. | unknown | +| Dialogs open with the first field focused and selected; Enter confirms | done | on every open, not only the first (#1367); a first field that starts greyed out takes the focus once enabled (#1395) | unknown | +| Value fields: selected text readable in every brightness; a focused field follows its value when a slider or preview changes it | partial | #1490, #1457; hover wheel stepping #5949 | unknown | +| Sliders in dialogs and popups (Save for Web, raster export options, Preferences, the opacity popup) show their rail, filled up to the handle | done | #1483 | unknown | +| Rectangular Grid and Polar Grid click dialogs: size, divider counts with a skew slider each, Use Outside Rectangle As Frame / Create Compound Path From Ellipses, Fill Grid; kept as the tool's options, used by drags too | done | #1377. The options are the documented ones; how far a skew percentage moves the dividers and which way the radial skew turns are our own choice (the public documentation gives neither). The reference point locator is in the dialog, and a double-click on the tool opens it as the tool's Tool Options (next row) | unknown | +| Double-click the Line Segment, Arc, Rectangular Grid or Polar Grid tool: its Tool Options ([Rectangular Grid tool](https://helpx.adobe.com/illustrator/using/tool-techniques/rectangular-grid-tool.html) and [Arc tool](https://helpx.adobe.com/illustrator/using/tool-techniques/arc-tool.html) step 3, [Tools](https://helpx.adobe.com/illustrator/using/tools.html)) | done | #2691. The tool's click dialog without a place to draw: Line Segment's Length, Angle and Fill Line; Arc's lengths, Reference Point, Type, Base Along, Slope and Fill Arc; the grids' Reference Point, Default Size, dividers, skews and switches. OK draws nothing and sets what the next drag draws with (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and what a click's dialog opens at (with the Length, Angle and Default Size); Cancel changes nothing (`double_clicking_the_line_arc_and_grid_tools_opens_their_tool_options`) | unknown | +| Three-Point Arc tool (VectorCraft addition), after the Arc tool: two ends, then a third point the open arc passes through or, with Third Point Sets Direction (its Tool Options, or `]` while drawing), the direction it leaves an end in; a preview with the center and, with Measurement Labels on, the radius; one undo step | done | `shape.threePointArc` (`crates/engine/src/cmd/create.rs`), the tool in `crates/tools/src/three_point_arc.rs`, the geometry in `crates/geom/src/shapes.rs` (`CircularArc`), and their tests; a VectorCraft addition, so it is not scored | unknown | ## Modifier keys and temporary tools -| Behaviour | Status | Notes | -|---|---|---| -| Space: Hand; Cmd+Space / Cmd+Alt+Space: zoom in/out; middle button pans | done | Space pressed after a tool takes a drag keeps the view still and shows that tool's cursor. Shape and anchor tools may use Space to move the geometry being drawn. Cmd+Space pressed mid-drag likewise keeps the active tool cursor. Space held before a press starts a view gesture, and its view cursor returns after release. `space_during_a_pencil_drag_keeps_the_pencil_cursor`, `cmd_space_mid_tool_drag_keeps_the_active_tool_cursor` | -| Document window scroll bars along the right and bottom edges (Normal and Full Screen Mode with Menu Bar; none in Full Screen and Presentation Mode): a thumb as long as the view against the art and the artboards; dragging it scrolls, a click on the track pages, the wheel over a bar scrolls along it; in a rotated view they follow the screen's axes | partial | #2322. The span is the art and the artboards with half a window around them, not Illustrator's 227 in canvas: VectorCraft has no bounded drawing area (#2284). A track click pages rather than jumping to the click; the page size and the rotated-view behaviour are our own choice (the public documentation gives neither) | -| A tool drag held near an edge of the canvas scrolls the view (#8551): zoomed in, a selection moved, a shape drawn or a marquee dragged towards the panels goes on past what shows | partial | Within 24 points of the canvas edge, once the pointer has moved 3 points from the press, the view scrolls away from that edge, faster nearer it (up to 900 points a second at the edge, and no faster in a corner, where it scrolls both ways), and keeps scrolling while the pointer stays still; the tool gets the pointer's new place in the document, so moved art stays under the pointer. Back away from the edge it stops. A click near the edge, the Hand, Zoom and Rotate View drags and Space panning do not scroll. The pointer past the canvas edge does not scroll: over a panel the Selection tools hand the art to the panels (#2826). The zone and speeds are VectorCraft's own (the public documentation gives none). Tests: `canvas::tests_edge_scroll` | -| Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); Cmd lends Group Selection the Selection tool, and the Selection tool Direct Selection or Group Selection, whichever was chosen last, except that once a first Cmd press has armed Select Behind (Command Click to Select Objects Behind on), a Cmd press on a selected object, or on an object inside one, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, selects the next object under the pointer until Cmd is let go, members of groups one by one and back to the topmost after the last, as "Select behind an object" (Ctrl+click twice, Command+click twice on macOS) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) and "Select behind objects" in [Select objects](https://helpx.adobe.com/illustrator/using/selecting-objects.html) describe; Cmd pressed once a drag is under way lends nothing; while Cmd is held, the status bar's Current Tool and the help bar name the tool a press at the pointer takes; engine pointer and canvas regressions | -| Eyedropper copies effective character dimensions between transformed text objects | done | Point/area and grouped text, highlighted ranges, reverse/remembered sampling, opt-outs and atomic invalid-transform rejection; `scaled_type_pick_*` (#6404) | -| Eyedropper styles highlighted characters only and preserves ranges across Type switches | done | Font/paint, Shift color-only, Unicode, Undo/Redo and stale-range regression tests; enabled non-neutral source or target object transparency is refused atomically; disable Transparency to sample supported attributes | -| Gradient mesh: a solid color dropped from the Color or Swatches panel or a Fill proxy on a selected mesh recolors the mesh point under the pointer, else the patch's four points; with the mesh selected, an Eyedropper click applies the fill color the same way | done | [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); `object.mesh.setPointColor`, one undo step, none when the color is unchanged. The 5-pixel reach for a point is VectorCraft's own. Tests `a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it`, `a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color`, `a_click_on_an_object_over_a_selected_mesh_copies_that_object` | -| Eyedropper reads visible sources while their layer/object is locked or outside isolation | done | Ordinary/Shift/Shift+Alt and gradient-stop reads preserve the source and selection; Alt reverse remains editable-only; hidden art stays excluded (`eyedropper_sources.rs`, #1251) | -| Add a visible stroke after drawing with inherited None/zero-width paint | done | Paint and Swap Fill/Stroke restore the existing 1 pt default; positive widths and painted zero widths stay as set; Undo/Redo and targeted appearance items tested (`stroke_visibility.rs`, #1253) | -| Double-click a stroked segment to create a width point in Width Point Edit | done | Finite-arithmetic follow-up: engine regressions and full CI passed; [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). Command and pointer regressions cover opening, sampled widths, adjoining adjustment on/off through checkbox/OK, compound paths, Cancel/Delete and Undo/Redo; dialog layout reviewed. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | -| Shift-double-click a width point enables adjoining adjustment in Width Point Edit | done | Tool dispatch, plain double-click control, neighboring widths, Undo/Redo and Cancel in `dialogs/width_point.rs` | -| Alt-drag duplicates (objects, artboards with their art) | done | | -| Artboard tool: Shift held once a move or an Alt-drag copy is under way keeps it to the level, upright or 45° line from General › Constrain Angle, as a Selection tool move does; a Shift-press still draws an artboard inside another or marquee-selects (#2497) | done | #8580; no public page describes Shift held during an artboard move, so it follows the request in #8580. Smart Guides, the grid and whole pixels slide the move along its line; the cursor stays the move cursor. `xform/artboard/tests.rs` `shift_held_during_a_move_keeps_it_to_its_line`, `shift_keeps_an_alt_drag_copy_to_its_line_from_the_constrain_angle`, `snaps_keep_a_shift_move_on_its_line`, `shift_during_a_move_keeps_the_move_cursor` | -| Artboard tool: the canvas right-click menu has Lock Artboards (Lock Selected, Lock All Except Selected, Lock All) and Unlock Artboards (Unlock Selected, Unlock All) | done | #2531; `artboard.setProps` with `locked` for each artboard named; the lock itself is #2592 | -| Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool | done | Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. | -| Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture | done | Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. | -| Escape while typing ends the edit, keeps the type selected and switches back to the tool whose double-click on type chose the Type tool (kept until another tool is chosen or another document or window becomes active, so later edits with the Type tool return there too), or to the Selection tool when there is no such tool, as when the Type tool was chosen from the toolbar or after such a switch | done | #1802 (#1686, #1656) | -| Selection tool: selected area type and type on a path show an in port and an out port (empty, an arrow where threaded, the red "+" of overflow); a click on either loads the text cursor; a click on a closed path, on empty canvas or a drag threads the text there, after the clicked frame from its out port, before it from its in port; Escape or another tool drops it; a double-click on a threaded port breaks the thread there | partial | #2572 (`text.thread.add`, `before` for the in port); the out port sits on the frame's right side above the bottom-right corner handle and the in port on its left side below the top-left one, so the handles can still be grabbed; a double-click on a threaded port breaks the thread (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)); the loaded text has a cursor of its own, with a link badge over a closed path, area type or type on a path that a click threads it into | -| Shift-click selects several artboards (Artboard tool, Artboards panel); they move, Alt-copy and delete together | done | `artboard.move`/`artboard.delete` `indices` (#1139); in the panel, Shift- and Ctrl/Cmd-click work with any tool by switching to the Artboard tool (#5698); panel menu, trash and Properties share selected-set deletion; all-selected retains artboard 1 and a single board cannot be deleted, with pointer-event and Undo/Redo coverage | -| Artboards panel: drag a row above or below another to reorder the artboards (as Move Up / Move Down do) | done | #4687; a line shows where the row lands, `artboard.reorder` in one undo step, the moved artboard becomes active; public forum answers describe the drag | -| Artboards panel › Delete Empty Artboards | done | `artboard.deleteEmpty`; one undo step, guides go too, locked artboards stay, and artboard 1 when every artboard is empty and none is locked; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule); [spec](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html) | -| Artboard Delete/Backspace delete selected boards while protecting artwork, the last board and active drags | done | Headless shortcut regressions in `tests/distortkeys.rs` cover retaining the original first board when all are selected, single-board protection, artwork, saved state and Undo/Redo; the navigator follows the tool’s surviving board through repeated deletion and history changes. | -| Artboard navigator synchronizes the active tool selection before deletion | done | Actual status-bar Next → Delete/Backspace and Next → Properties Delete regressions in `chrome.rs` cover surviving board records, preserved artwork and Undo/Redo; other tools keep object selection and history. **Tab-switch follow-up:** document-tab changes align the Artboard tool with the displayed board. Actual A → B → A tab clicks followed by Properties Delete and controls for same-tab multiselection, Move/Scale Artwork options and other tools passed, along with historical full CI on `a0671777`. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). **Clean-tab close:** with the Artboard tool active, closing a clean active tab restores the surviving document's displayed board before Properties Delete. | -| Artboard history prunes removed indices while preserving valid multiselection and tool options | tested | Headless pointer/key tests in `panels/properties.rs` cover panel New → Undo → Delete/Backspace/Properties, Duplicate → Undo → Delete, partial pruning and valid multiselection. They check surviving board records, artwork, object selection, Move/Scale Artwork options, saved state and Undo/Redo. Full workspace CI passes. | -| Click an object with the Artboard tool to create an artboard fitted to its visible bounds | done | Topmost editable object or group; drag and modified clicks retain their meaning; one undo step (`artboard_click.rs`, #1227) | -| Artboard Options: X and Y beside a reference point locator, counted from the ruler origin; a typed X or Y moves the artboard's reference point there, a new Width or Height keeps it in place | done | #1876; as the Transform panel's and the Control bar's artboard X and Y, with the locator they and Properties share; the shape dialogs' X and Y (the click position) stay hidden. Pointer and key tests in `dialogs/tests.rs` | -| Artboard Options shares existing presets/orientation and drafts artwork or selected-art fitting until OK | done | Fit changes only the active artboard and preserves artwork positions; Cancel leaves the document unchanged; newer multi-artboard behavior retained; fitting after draft resizing uses all drawn document artwork and document/revision-scoped bounds; selected art may span boards | -| Artboard Options › Display: Show Center Mark and Show Cross Hairs ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/modify-display-settings-of-artboards.html)) | done | Per-artboard checkboxes (`artboard.setProps`/`artboard.new` `showCenterMark`, `showCrossHairs`, one undo step); the canvas draws a cross 12 points across on screen at the center and lines from the middle of each side through it, 1 point wide on screen at any zoom and turned with the view; exports and print leave them out; tests `an_artboard_shows_its_center_mark_and_cross_hairs`, `artboard_options_show_center_mark_and_cross_hairs` | -| View › Hide Artboards (Ctrl/Cmd+Shift+H) hides the artboards' edges, bleeds, marks and names and shows the whole canvas as paper (white, or Simulate Colored Paper's colour); the Artboard tool still shows them | done | #4038, `canvas::tests::hidden_artboards_leave_a_paper_canvas_without_edges` | -| Artboard Options › Display: Show Video Safe Areas and Video Ruler Pixel Aspect Ratio ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)) | done | #2849; per artboard (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1; one undo step; native format). The page gives no safe-area numbers: our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s, the action-safe area 3.5% and the title-safe area 5% in from each edge, outlined 1 point wide on the canvas and turned with the view; exports and print leave them out. Tests `an_artboard_shows_its_video_safe_areas`, `artboard_options_show_video_display_options`, `artboard_video_display_options_*` | -| Shape tools: Shift constrains, Alt from centre, Space moves while dragging, arrows change sides/points/rows and Ellipse anchors | done | #7840: Ellipse Up/Down changes the remembered Anchors count within 2…1000; four anchors keep a live ellipse, other counts a plain path. Release is one undo step; Escape restores the earlier count unless explicitly updated with `tool.setOption`. `crates/engine/tests/ellipse_drag_anchors.rs` | -| Eraser: Shift-drag erases along a horizontal, vertical or diagonal line ([public source](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=82)) | done | the line runs from the press point at the 45° step from the Constrain Angle nearest the pointer, taken once the pointer is 3 screen pixels from the press and kept until Shift is released; the tip outline follows the line; released, the drag goes on freehand from the last point on the line, and Shift again takes a new step from the press point (VectorCraft's own rules); `eraser_shift_keeps_the_stroke_on_a_45_degree_line` in `crates/tools/src/draw2/gesture/tests.rs` | -| Polygon/Star exact-size placement remembers the chosen sides/points for later drags and dialog openings; Cancel preserves the previous count | done | Session tool options; existing dialog-opening gestures retained; regression in `toolbar.rs` | -| Tool double-click opens its options | done | | -| Per-platform mapping (Cmd ↔ Ctrl, Option ↔ Alt) | done | | -| Eyedropper cursor; Use Precise Cursors | partial | original pipette at the sampling tip, distinct from the precise crosshair at five DPI scales (#1269); OS cursor display unverified; while Caps Lock is on, the tools that Use Precise Cursors changes show the crosshair, and the saved preference does not change (the desktop app reads the lock state on macOS, Windows and Linux X11, not on native Wayland; `view.capsLock` reads or sets it); a Use Precise Cursors command toggles the preference and can take a shortcut (#1663); cursors are painted into the window on Wayland (#1652, not run on Linux) | -| macOS canvas cursor delivery (#2292) | partial | The UI prepares the existing glyphs as aligned 1×/2× RGBA requests; the desktop host builds AppKit cursors and owns cursor rectangles for the root document window. While it owns the cursor, the host sets it again on every pass, so the tool's cursor stays when the pointer moves (#6362). Detached document viewports and requests without a usable native bitmap retain the visible system fallback; precise-cursor and UI-scale preferences retained. Headless regressions cover routing, pixels/hotspots and lifecycle; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain unverified. Wayland still paints its glyphs. | -| Every tool's modifiers checked against the shortcut reference | missing | this is the fidelity pass | +| Behaviour | Status | Notes | Headless | +|---|---|---| --- | +| Space: Hand; Cmd+Space / Cmd+Alt+Space: zoom in/out; middle button pans | done | Space pressed after a tool takes a drag keeps the view still and shows that tool's cursor. Shape and anchor tools may use Space to move the geometry being drawn. Cmd+Space pressed mid-drag likewise keeps the active tool cursor. Space held before a press starts a view gesture, and its view cursor returns after release. `space_during_a_pencil_drag_keeps_the_pencil_cursor`, `cmd_space_mid_tool_drag_keeps_the_active_tool_cursor` | unknown | +| Document window scroll bars along the right and bottom edges (Normal and Full Screen Mode with Menu Bar; none in Full Screen and Presentation Mode): a thumb as long as the view against the art and the artboards; dragging it scrolls, a click on the track pages, the wheel over a bar scrolls along it; in a rotated view they follow the screen's axes | partial | #2322. The span is the art and the artboards with half a window around them, not Illustrator's 227 in canvas: VectorCraft has no bounded drawing area (#2284). A track click pages rather than jumping to the click; the page size and the rotated-view behaviour are our own choice (the public documentation gives neither) | unknown | +| A tool drag held near an edge of the canvas scrolls the view (#8551): zoomed in, a selection moved, a shape drawn or a marquee dragged towards the panels goes on past what shows | partial | Within 24 points of the canvas edge, once the pointer has moved 3 points from the press, the view scrolls away from that edge, faster nearer it (up to 900 points a second at the edge, and no faster in a corner, where it scrolls both ways), and keeps scrolling while the pointer stays still; the tool gets the pointer's new place in the document, so moved art stays under the pointer. Back away from the edge it stops. A click near the edge, the Hand, Zoom and Rotate View drags and Space panning do not scroll. The pointer past the canvas edge does not scroll: over a panel the Selection tools hand the art to the panels (#2826). The zone and speeds are VectorCraft's own (the public documentation gives none). Tests: `canvas::tests_edge_scroll` | unknown | +| Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); Cmd lends Group Selection the Selection tool, and the Selection tool Direct Selection or Group Selection, whichever was chosen last, except that once a first Cmd press has armed Select Behind (Command Click to Select Objects Behind on), a Cmd press on a selected object, or on an object inside one, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, selects the next object under the pointer until Cmd is let go, members of groups one by one and back to the topmost after the last, as "Select behind an object" (Ctrl+click twice, Command+click twice on macOS) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) and "Select behind objects" in [Select objects](https://helpx.adobe.com/illustrator/using/selecting-objects.html) describe; Cmd pressed once a drag is under way lends nothing; while Cmd is held, the status bar's Current Tool and the help bar name the tool a press at the pointer takes; engine pointer and canvas regressions | unknown | +| Eyedropper copies effective character dimensions between transformed text objects | done | Point/area and grouped text, highlighted ranges, reverse/remembered sampling, opt-outs and atomic invalid-transform rejection; `scaled_type_pick_*` (#6404) | unknown | +| Eyedropper styles highlighted characters only and preserves ranges across Type switches | done | Font/paint, Shift color-only, Unicode, Undo/Redo and stale-range regression tests; enabled non-neutral source or target object transparency is refused atomically; disable Transparency to sample supported attributes | unknown | +| Gradient mesh: a solid color dropped from the Color or Swatches panel or a Fill proxy on a selected mesh recolors the mesh point under the pointer, else the patch's four points; with the mesh selected, an Eyedropper click applies the fill color the same way | done | [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); `object.mesh.setPointColor`, one undo step, none when the color is unchanged. The 5-pixel reach for a point is VectorCraft's own. Tests `a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it`, `a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color`, `a_click_on_an_object_over_a_selected_mesh_copies_that_object` | unknown | +| Eyedropper reads visible sources while their layer/object is locked or outside isolation | done | Ordinary/Shift/Shift+Alt and gradient-stop reads preserve the source and selection; Alt reverse remains editable-only; hidden art stays excluded (`eyedropper_sources.rs`, #1251) | unknown | +| Add a visible stroke after drawing with inherited None/zero-width paint | done | Paint and Swap Fill/Stroke restore the existing 1 pt default; positive widths and painted zero widths stay as set; Undo/Redo and targeted appearance items tested (`stroke_visibility.rs`, #1253) | unknown | +| Double-click a stroked segment to create a width point in Width Point Edit | done | Finite-arithmetic follow-up: engine regressions and full CI passed; [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). Command and pointer regressions cover opening, sampled widths, adjoining adjustment on/off through checkbox/OK, compound paths, Cancel/Delete and Undo/Redo; dialog layout reviewed. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | unknown | +| Shift-double-click a width point enables adjoining adjustment in Width Point Edit | done | Tool dispatch, plain double-click control, neighboring widths, Undo/Redo and Cancel in `dialogs/width_point.rs` | unknown | +| Alt-drag duplicates (objects, artboards with their art) | done | | unknown | +| Artboard tool: Shift held once a move or an Alt-drag copy is under way keeps it to the level, upright or 45° line from General › Constrain Angle, as a Selection tool move does; a Shift-press still draws an artboard inside another or marquee-selects (#2497) | done | #8580; no public page describes Shift held during an artboard move, so it follows the request in #8580. Smart Guides, the grid and whole pixels slide the move along its line; the cursor stays the move cursor. `xform/artboard/tests.rs` `shift_held_during_a_move_keeps_it_to_its_line`, `shift_keeps_an_alt_drag_copy_to_its_line_from_the_constrain_angle`, `snaps_keep_a_shift_move_on_its_line`, `shift_during_a_move_keeps_the_move_cursor` | unknown | +| Artboard tool: the canvas right-click menu has Lock Artboards (Lock Selected, Lock All Except Selected, Lock All) and Unlock Artboards (Unlock Selected, Unlock All) | done | #2531; `artboard.setProps` with `locked` for each artboard named; the lock itself is #2592 | unknown | +| Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool | done | Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. | unknown | +| Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture | done | Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. | unknown | +| Escape while typing ends the edit, keeps the type selected and switches back to the tool whose double-click on type chose the Type tool (kept until another tool is chosen or another document or window becomes active, so later edits with the Type tool return there too), or to the Selection tool when there is no such tool, as when the Type tool was chosen from the toolbar or after such a switch | done | #1802 (#1686, #1656) | unknown | +| Selection tool: selected area type and type on a path show an in port and an out port (empty, an arrow where threaded, the red "+" of overflow); a click on either loads the text cursor; a click on a closed path, on empty canvas or a drag threads the text there, after the clicked frame from its out port, before it from its in port; Escape or another tool drops it; a double-click on a threaded port breaks the thread there | partial | #2572 (`text.thread.add`, `before` for the in port); the out port sits on the frame's right side above the bottom-right corner handle and the in port on its left side below the top-left one, so the handles can still be grabbed; a double-click on a threaded port breaks the thread (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)); the loaded text has a cursor of its own, with a link badge over a closed path, area type or type on a path that a click threads it into | unknown | +| Shift-click selects several artboards (Artboard tool, Artboards panel); they move, Alt-copy and delete together | done | `artboard.move`/`artboard.delete` `indices` (#1139); in the panel, Shift- and Ctrl/Cmd-click work with any tool by switching to the Artboard tool (#5698); panel menu, trash and Properties share selected-set deletion; all-selected retains artboard 1 and a single board cannot be deleted, with pointer-event and Undo/Redo coverage | unknown | +| Artboards panel: drag a row above or below another to reorder the artboards (as Move Up / Move Down do) | done | #4687; a line shows where the row lands, `artboard.reorder` in one undo step, the moved artboard becomes active; public forum answers describe the drag | unknown | +| Artboards panel › Delete Empty Artboards | done | `artboard.deleteEmpty`; one undo step, guides go too, locked artboards stay, and artboard 1 when every artboard is empty and none is locked; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule); [spec](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html) | unknown | +| Artboard Delete/Backspace delete selected boards while protecting artwork, the last board and active drags | done | Headless shortcut regressions in `tests/distortkeys.rs` cover retaining the original first board when all are selected, single-board protection, artwork, saved state and Undo/Redo; the navigator follows the tool’s surviving board through repeated deletion and history changes. | unknown | +| Artboard navigator synchronizes the active tool selection before deletion | done | Actual status-bar Next → Delete/Backspace and Next → Properties Delete regressions in `chrome.rs` cover surviving board records, preserved artwork and Undo/Redo; other tools keep object selection and history. **Tab-switch follow-up:** document-tab changes align the Artboard tool with the displayed board. Actual A → B → A tab clicks followed by Properties Delete and controls for same-tab multiselection, Move/Scale Artwork options and other tools passed, along with historical full CI on `a0671777`. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). **Clean-tab close:** with the Artboard tool active, closing a clean active tab restores the surviving document's displayed board before Properties Delete. | unknown | +| Artboard history prunes removed indices while preserving valid multiselection and tool options | tested | Headless pointer/key tests in `panels/properties.rs` cover panel New → Undo → Delete/Backspace/Properties, Duplicate → Undo → Delete, partial pruning and valid multiselection. They check surviving board records, artwork, object selection, Move/Scale Artwork options, saved state and Undo/Redo. Full workspace CI passes. | unknown | +| Click an object with the Artboard tool to create an artboard fitted to its visible bounds | done | Topmost editable object or group; drag and modified clicks retain their meaning; one undo step (`artboard_click.rs`, #1227) | unknown | +| Artboard Options: X and Y beside a reference point locator, counted from the ruler origin; a typed X or Y moves the artboard's reference point there, a new Width or Height keeps it in place | done | #1876; as the Transform panel's and the Control bar's artboard X and Y, with the locator they and Properties share; the shape dialogs' X and Y (the click position) stay hidden. Pointer and key tests in `dialogs/tests.rs` | unknown | +| Artboard Options shares existing presets/orientation and drafts artwork or selected-art fitting until OK | done | Fit changes only the active artboard and preserves artwork positions; Cancel leaves the document unchanged; newer multi-artboard behavior retained; fitting after draft resizing uses all drawn document artwork and document/revision-scoped bounds; selected art may span boards | unknown | +| Artboard Options › Display: Show Center Mark and Show Cross Hairs ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/modify-display-settings-of-artboards.html)) | done | Per-artboard checkboxes (`artboard.setProps`/`artboard.new` `showCenterMark`, `showCrossHairs`, one undo step); the canvas draws a cross 12 points across on screen at the center and lines from the middle of each side through it, 1 point wide on screen at any zoom and turned with the view; exports and print leave them out; tests `an_artboard_shows_its_center_mark_and_cross_hairs`, `artboard_options_show_center_mark_and_cross_hairs` | unknown | +| View › Hide Artboards (Ctrl/Cmd+Shift+H) hides the artboards' edges, bleeds, marks and names and shows the whole canvas as paper (white, or Simulate Colored Paper's colour); the Artboard tool still shows them | done | #4038, `canvas::tests::hidden_artboards_leave_a_paper_canvas_without_edges` | unknown | +| Artboard Options › Display: Show Video Safe Areas and Video Ruler Pixel Aspect Ratio ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)) | done | #2849; per artboard (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1; one undo step; native format). The page gives no safe-area numbers: our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s, the action-safe area 3.5% and the title-safe area 5% in from each edge, outlined 1 point wide on the canvas and turned with the view; exports and print leave them out. Tests `an_artboard_shows_its_video_safe_areas`, `artboard_options_show_video_display_options`, `artboard_video_display_options_*` | unknown | +| Shape tools: Shift constrains, Alt from centre, Space moves while dragging, arrows change sides/points/rows and Ellipse anchors | done | #7840: Ellipse Up/Down changes the remembered Anchors count within 2…1000; four anchors keep a live ellipse, other counts a plain path. Release is one undo step; Escape restores the earlier count unless explicitly updated with `tool.setOption`. `crates/engine/tests/ellipse_drag_anchors.rs` | unknown | +| Eraser: Shift-drag erases along a horizontal, vertical or diagonal line ([public source](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=82)) | done | the line runs from the press point at the 45° step from the Constrain Angle nearest the pointer, taken once the pointer is 3 screen pixels from the press and kept until Shift is released; the tip outline follows the line; released, the drag goes on freehand from the last point on the line, and Shift again takes a new step from the press point (VectorCraft's own rules); `eraser_shift_keeps_the_stroke_on_a_45_degree_line` in `crates/tools/src/draw2/gesture/tests.rs` | unknown | +| Polygon/Star exact-size placement remembers the chosen sides/points for later drags and dialog openings; Cancel preserves the previous count | done | Session tool options; existing dialog-opening gestures retained; regression in `toolbar.rs` | unknown | +| Tool double-click opens its options | done | | unknown | +| Per-platform mapping (Cmd ↔ Ctrl, Option ↔ Alt) | done | | unknown | +| Eyedropper cursor; Use Precise Cursors | partial | original pipette at the sampling tip, distinct from the precise crosshair at five DPI scales (#1269); OS cursor display unverified; while Caps Lock is on, the tools that Use Precise Cursors changes show the crosshair, and the saved preference does not change (the desktop app reads the lock state on macOS, Windows and Linux X11, not on native Wayland; `view.capsLock` reads or sets it); a Use Precise Cursors command toggles the preference and can take a shortcut (#1663); cursors are painted into the window on Wayland (#1652, not run on Linux) | unknown | +| macOS canvas cursor delivery (#2292) | partial | The UI prepares the existing glyphs as aligned 1×/2× RGBA requests; the desktop host builds AppKit cursors and owns cursor rectangles for the root document window. While it owns the cursor, the host sets it again on every pass, so the tool's cursor stays when the pointer moves (#6362). Detached document viewports and requests without a usable native bitmap retain the visible system fallback; precise-cursor and UI-scale preferences retained. Headless regressions cover routing, pixels/hotspots and lifecycle; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain unverified. Wayland still paints its glyphs. | unknown | +| Every tool's modifiers checked against the shortcut reference | missing | this is the fidelity pass | unknown | ## Keyboard shortcuts @@ -452,150 +452,150 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. -| Interaction | Status | Evidence | -|---|---|---| -| Brush Options › Key Color eyedropper yields to one canvas click, then resumes the same draft and previous tool | done | #8284; the pick changes the dialog draft without painting or editing the document. OK applies the brush options; Cancel discards them. Escape ends the pick without sampling before a later Escape cancels the dialog. Six full-app input regressions in `crates/ui-egui/tests/brush_keycolor_modal_repro.rs` cover the actual pick, OK/reopen/Cancel, Escape, reentry, held clicks, stale releases and ordinary modal blocking. | -| Ordinary Save refused by filesystem permissions/read-only storage offers Save As | focused UI regressions passed; native acceptance pending | #6146; `io::tests_read_only_save`; same name/format suggested; unchanged format keeps options, changed format opens its Save options; Documents folder, UID-bound continuation; cancellation and automation isolation | -| Selection artwork drag hovers a visible document tab to activate it, then drops editable artwork on its canvas | done | `tests_document_drag`, `edit.dropSelection`, lossless resource and one-step Undo regressions; a release over another document's tiled pane copies it there too (`canvas::panes` tests), and so does a release over a floating window drawn inside the main window (`doc_windows` tests); overflow-menu drag and floating OS windows remain separate | -| A document tab dragged along the tab strip moves its document; a line marks where it goes, the current document and every document's view stay as they were, and a drag off the strip still floats it | done | #5663, [public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html); `document.move`; `tests::tab_reorder`, `chrome::tests` (drop index with floating and view tabs), `engine` `tests::document_move` | -| A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | -| When the document tabs don't all fit, the first tab that doesn't fit whole fills the room before the » button with its title shortened and ending in "…", once that room leaves at least 40 pt for the title; with the active tab among the last ones, the tab before the ones shown fills the room left at the start instead; an active tab wider than the strip is shortened to it, and a tab narrower than 25 pt shows no ×; the tooltip of a shortened tab shows the whole title, wrapped to the window (VectorCraft's own rule) | done | #8584; `tests::tab_overflow`; not scored | -| An inactive document tab shows the document's name, the view number and the unsaved-changes mark, without the zoom and the mode in parentheses (the color mode and view, or the opacity mask being edited); the active tab keeps its whole title, and an inactive tab's tooltip shows the whole title (VectorCraft's own rule) | done | #8582; `tests::tab_overflow::inactive_tabs_show_the_name_alone_so_more_tabs_fit`; not scored | -| Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | +| Interaction | Status | Evidence | Headless | +|---|---|---| --- | +| Brush Options › Key Color eyedropper yields to one canvas click, then resumes the same draft and previous tool | done | #8284; the pick changes the dialog draft without painting or editing the document. OK applies the brush options; Cancel discards them. Escape ends the pick without sampling before a later Escape cancels the dialog. Six full-app input regressions in `crates/ui-egui/tests/brush_keycolor_modal_repro.rs` cover the actual pick, OK/reopen/Cancel, Escape, reentry, held clicks, stale releases and ordinary modal blocking. | unknown | +| Ordinary Save refused by filesystem permissions/read-only storage offers Save As | focused UI regressions passed; native acceptance pending | #6146; `io::tests_read_only_save`; same name/format suggested; unchanged format keeps options, changed format opens its Save options; Documents folder, UID-bound continuation; cancellation and automation isolation | unknown | +| Selection artwork drag hovers a visible document tab to activate it, then drops editable artwork on its canvas | done | `tests_document_drag`, `edit.dropSelection`, lossless resource and one-step Undo regressions; a release over another document's tiled pane copies it there too (`canvas::panes` tests), and so does a release over a floating window drawn inside the main window (`doc_windows` tests); overflow-menu drag and floating OS windows remain separate | unknown | +| A document tab dragged along the tab strip moves its document; a line marks where it goes, the current document and every document's view stay as they were, and a drag off the strip still floats it | done | #5663, [public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html); `document.move`; `tests::tab_reorder`, `chrome::tests` (drop index with floating and view tabs), `engine` `tests::document_move` | unknown | +| A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | unknown | +| When the document tabs don't all fit, the first tab that doesn't fit whole fills the room before the » button with its title shortened and ending in "…", once that room leaves at least 40 pt for the title; with the active tab among the last ones, the tab before the ones shown fills the room left at the start instead; an active tab wider than the strip is shortened to it, and a tab narrower than 25 pt shows no ×; the tooltip of a shortened tab shows the whole title, wrapped to the window (VectorCraft's own rule) | done | #8584; `tests::tab_overflow`; not scored | unknown | +| An inactive document tab shows the document's name, the view number and the unsaved-changes mark, without the zoom and the mode in parentheses (the color mode and view, or the opacity mask being edited); the active tab keeps its whole title, and an inactive tab's tooltip shows the whole title (VectorCraft's own rule) | done | #8582; `tests::tab_overflow::inactive_tabs_show_the_name_alone_so_more_tabs_fit`; not scored | unknown | +| Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | unknown | -| Behaviour | Status | Notes | -|---|---|---| -| Effect > Warp Options: style previews, orientation choices and percent controls | done | #1760; focused input, mixed-style and history checks passed; original captures reviewed. No geometry or optional Properties changes. | -| Command search: Up and Down move through the results, Enter runs the highlighted one | done | #1798 (#1757) | -| Help › VectorCraft Help… and F1 show in-app search for tools, menu commands, and built-in tutorials. Tool results mark their toolbar location; command results show their menu path and shortcut without running them; tutorial results show their steps. Home clears the search, Back returns to the results, and Escape in the search field closes the panel. | partial | [Public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-with-discover-panel.html); `help.discover`, `help.discover.search`, `help.discover.choose`, `help.discover.back`; `menus::tests::help_f1_opens_discover_without_a_document`. Articles, Quick Actions, and Discover preferences are not implemented. Menu-path text instead of a menu location marker is VectorCraft's current guidance. | -| Learn panel: Window › Learn opens it; For you holds a Quick skill guide card, Skills lists VectorCraft's own skills with progress rings that fill and counts of tutorials finished, a tutorial shows its numbered steps with a check box each that marks the step done once its sample is open, a finished tutorial has a check mark, Back goes up a level; a tool's name in a step is a link that marks the tool where the toolbars show it (its button, its group's flyout, a torn-off strip, a toolbar made with New Toolbar or the All Tools drawer) without choosing it; View more opens the tutorial's practice sample as a new untitled document, Finish tutorial then marks it finished with all its steps, and Next Up shows the next tutorial in the same skill; Reset progress clears the progress (no video) | done | [the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `learn.list`, `learn.tab`, `learn.skills`, `learn.skill`, `learn.show`, `learn.back`, `learn.locateTool`, `learn.openSample`, `learn.markStep`, `learn.finish`, `learn.next`, `learn.resetProgress`; the mark's look and 3-second lifetime, marking steps by hand, keeping the progress in the preferences and Reset progress are VectorCraft's own rules; `panels::learn::tests`, `toolbar::tests` | -| Pathfinder panel: a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled | done | #1642 (#1635) | -| Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; a selected Radial Repeat shows an instances handle below it (16 px of drag per instance, 1 to 1,000) and a radius handle on its circle the same way (`tools/src/repeat_radial.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)), and a splitter on its circle that hides the instances it is dragged back past while the others keep their places, and shows them again when dragged forward (its place half a step past the last instance shown and its limit of one instance shown are VectorCraft's own rules) | -| Grid Repeat Options (Object › Repeat › Options…) has a Preview checkbox: the repeat on the canvas follows the fields while the dialog is open, Cancel puts the original back without a history step, OK keeps the previewed values as one undo step | done | #2651; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html) lists the Preview option for the grid options only, so Radial and Mirror Repeat Options have none; `dialogs/command.rs` tests | -| Type on a Path Options (Type › Type on a Path › Type on a Path Options…, or a double-click on the Type on a Path tools) has a Preview checkbox, off when it opens: the selected type on a path follows Effect, Flip, Align to Path and Spacing while the dialog is open, Cancel puts it back without a history step, OK keeps the previewed values as one undo step | done | #5360; the [public page](https://helpx.adobe.com/illustrator/using/creating-type-path.html) lists the dialog's options, and public tutorials of the dialog show its Preview checkbox; `tests/pathtype.rs` | -| Graph Type (Object › Graph › Type…, or a double-click on a graph tool) is a dialog of its own: a menu at the top shows Graph Options or the page of an axis; Graph Options has a button per graph type, Value Axis with Separate Scales, the Style checkboxes (Add Drop Shadow, Add Legend Across Top, First Row in Front, First Column in Front) and the options of the type picked (Column or Bar Width and Cluster Width; Mark Data Points, Connect Data Points, Edge-to-Edge Lines and Draw Filled Lines; a pie graph's Legend, Position and Sort); the Value Axis page (Left Axis and Right Axis with the value axis on both sides) has Tick Values with Override Calculated Values, Tick Marks and Add Labels, and the Category Axis page has Tick Marks with Draw Tick Marks Between Labels; with series picked by Group Selection the type and value axis go to those series | done | Public pages: [graph types](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/change-graph-types.html), [value axes](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/change-graph-value-axes.html), [columns, bars and lines](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-columns-bars-and-lines.html), [pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html), [separate scales](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/assign-different-scales-to-value-axes.html), [combined types](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/combine-different-graph-types.html). The options dimmed for a type, the pages listed and the Legend checkbox are VectorCraft's own rules. Dialog `graphType`; `dialogs/graph_type.rs` and its tests | -| Selected Mirror Repeat shows a prominent axis with move and rotation handles; bounding-box handles take priority over the axis line | done | #2877, `tools/src/mirror.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html) | -| Object › Expand on radial, grid and mirror repeats makes groups of their instances | done | #1765 (#1756) | -| Object › Expand… is dimmed while the selection has appearance attributes (effects, several fills or strokes, a fill or stroke with its own transparency or effects, a brush); its tooltip and the status bar say to use Object › Expand Appearance first, which leaves a stroked line with Zig Zag a stroked zig-zag line that Expand then outlines | done | #3089; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html); `dialogs/expand.rs` tests, engine `tests_objexpand`. `object.expand` (agents, scripts) still bakes effects in one step | -| Select › Same matches type on its characters' fill and stroke | done | #1746 (#1737) | -| ~40 panels with ≡ menus; dock, icon column, collapse, tabs | done | 51 panel modules incl. tests | -| Panels float, stack and dock back; on the desktop a floating group is an OS window of its own, inside the window on the web and on Wayland | done | #495, #4135 | -| Floating groups stack into sets; sets dock as extra dock columns (a multi-column dock); groups drop anywhere in a set or column, or onto its tabs; a column taller than the window scrolls | done | `window.panel.float {below, above}`, `window.panel.dock {column}` | -| Panels dragged onto a dock group's tabs join it; onto its upper or lower half they make a new group above or below it (a top/bottom split, resizable); onto the icon column they become icons, the tabbed group's panels too; a dock tab's context menu closes it (Window menu reopens it) | done | `window.panel.dock {anchor, zone}`, `window.panel.dock {icon: true}`, `window.panel.close` | -| A double-click on a dock group's tab collapses the group to its tabs (a group below it moves up into the room) and a second one expands it; a click on another of its tabs expands it showing that panel ([helpx: Workspace basics](https://helpx.adobe.com/illustrator/using/workspace-basics.html), panel groups) | done | `window.panel.collapse {panel, collapsed?}`; in dock groups and floating windows; a group beside another (a left/right split) doesn't collapse | -| The double triangle at the right end of a panel's tab strip cycles the panel's display sizes, the states its Show/Hide Options (and Transparency's Show/Hide Thumbnails) panel-menu items set ([archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=189), Transparency; [archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479), Character and Paragraph) | done | `window.panel.cycleOptions {panel}`; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency; the order of the sizes, the glyph and where it sits are VectorCraft's own (#3041) | -| Panels outside the app window (another monitor) | done | floating groups in OS windows of their own on the desktop (#4135) | -| Edit Toolbar (•••): the All Tools drawer opens beside the toolbar by its button (Escape or a click outside closes it), dims the tools already in the toolbar; while it is open, tools drag from it onto the toolbar (between two tools, or onto one to join its group), from the toolbar into it, and within the toolbar; each toolbar keeps its edits | done | #1018; `window.editToolbar`, `toolbar.addTool`/`removeTool`/`reset`; the drawer's Reset (Illustrator has it in a drawer menu); dragging a toolbar button moves the tool it shows, not its whole group; tool flyouts are as wide as their longest translated name and shortcut need (#1616) | -| Window › Toolbars › New Toolbar… (also in the All Tools drawer's menu): a name and OK make a blank floating toolbar, listed under Window › Toolbars (its item shows or hides it); its title bar moves it, its × hides it and its double arrow shows its tools in one column or two; its ••• button opens the All Tools drawer beside it to fill it; kept with the workspace it was made in | done | #1759 in part; `window.toolbar.new`, `window.toolbar.custom`, `window.toolbar.list`, the `toolbar` param of `window.toolbarColumns`, `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset` | -| Window › Toolbars › Manage Toolbars… (also in the All Tools drawer's menu): the dialog lists the toolbars made with New Toolbar; a new name typed for the selected one renames it, + copies it (none selected: a blank toolbar) and the trash can deletes it; the changes stay in the workspace | done | #1759 in part; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete` | -| Quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the editable controls | done | Per the public documentation, choosing a preset traces the image with it straight away, and the panel is opened with the Image Trace button in the Control panel or in Properties' Image Trace section (). The controls show Threshold, Paths, Corners and Noise with Advanced open; `panels/image_trace.rs` headless tests (`a_quick_trace_leaves_the_panel_as_it_was`, `sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source` for the button's route). No algorithm parity claim. | -| Image Trace panel: holding the eye button next to View down shows the selected Image Trace objects' source image on the canvas | done | Per the public documentation, the control next to View is pressed and held to compare the trace result with the source image (). On release the objects show their View again; the document, its View and the undo history are unchanged. `RenderOptions::trace_source`; `panels/image_trace.rs` headless test `holding_the_eye_button_shows_the_source_image_until_released`, render test `trace_source_draws_the_source_image_of_the_listed_objects`. The Control bar and Properties have no such button | -| Image Trace panel: Ignore Color has a canvas eyedropper beside its color picker | done | #8068. Samples original pixels of the selected placed image or the retained source of a live trace without changing the displayed canvas View. The existing color picker remains available. Preview off keeps a draft; Preview on retraces a live trace as one undo step. An outside or transparent miss leaves the pick armed; a valid sample or Escape restores the previous tool, and changing the target or explicitly choosing a tool cancels. Paint defaults and selection are retained. `tests/image_trace_ignore_sampler.rs`; no algorithm parity claim. Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; runtime pending). | -| Live trace result bounds and selection highlights exclude the retained bitmap; source-image views retain it | done | All TraceView modes and rotated result bounds regression-covered; ordinary hidden group behavior retained | -| Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) | -| Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls; Window > Toolbars > Compact Tools adds optional denser spacing for the main Tools panel while retaining the existing default (#7234) | -| Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | done | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON | -| Actions panel: ≡ › Replace Actions… puts the set of a saved file in place of every set in the panel ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | done | `ui.actionSet.replace`; `panels/actions.rs` tests. The file is read as Load Actions… reads it; the item asks no question first | -| Actions panel: ≡ › Clear Actions deletes every set loaded in the panel ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | done | `ui.actionSet.clear`; `panels/actions.rs` tests. The item asks first, and the built-in Default Actions set goes too | -| Actions panel: ≡ › Reset Actions asks first; OK replaces the sets in the panel with the default set and Append adds the default set after them ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | done | `ui.actionSet.reset`; `panels/actions.rs` and `dialogs/tests.rs` tests. The default set is VectorCraft's own Default Actions set | -| Actions panel: ≡ › Load Actions… also reads action sets saved as `.aia` files ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `actionSet.read`, `ui.actionSet.load`; `tests/actionset.rs`, `panels/actions.rs` tests, `import_fuzz`. Steps with a label and no recorded values come in as menu commands that run with no values and open no dialog, matched by label, and Set Selection steps come in as Select Object steps; the other steps, recorded menu items included, are left out and counted | -| Actions panel: ≡ › Action Options… renames the selected action and sets its function key and color ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.action.options`; `panels/actions.rs` tests (part of #1629). Button Mode shows the color | -| Actions panel: ≡ › Button Mode shows each action by name as a button in its Action Options color, without sets or steps; a click on a button plays the action, and choosing Button Mode again shows the list ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | done | `ui.action.buttonMode`, `ui.action.playAt`; `panels/actions.rs` tests. VectorCraft's own rules: every set's actions show in set order, an action without a color is an ordinary button, the mode is kept with the UI preferences, and it cannot be turned on while an action records | -| Actions panel: ≡ › Playback Options… plays actions Accelerated, Step by Step or with a pause between steps ([Specify playback speed](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/specify-playback-speed.html)) | done | `ui.action.playbackOptions`; `panels/actions.rs` tests. The pause is a whole number of seconds from 1 to 60 (VectorCraft's own range); Batch… plays at full speed | -| Actions panel: a clicked action stays selected for Play Current Selection and Delete Selection | partial | #1853 (part of #1629); editing actions and action shortcuts remain | -| Actions panel: Create New Set (bottom bar, ≡ › New Set…) names a new set and Set Options… renames the current one; a click on a set's name makes it current and a recording goes into the current set ([helpx: Automation with actions](https://helpx.adobe.com/illustrator/using/automation-actions.html)); the current set is kept with the UI preferences, and with no set current a recording goes into the first set, which becomes current | partial | #3712; dragging actions between sets remains | -| Actions panel: Create New Action (bottom bar, ≡ › New Action…) asks for the name, set, function key and color, and Record adds the action and records into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html)) | partial | `ui.action.new`, `ui.action.play`; `panels/actions.rs` tests. A function key plays its action, even when a command has the same shortcut, and the command keeps it. Button Mode shows the color | -| Actions panel: Delete Selection (bottom bar) deletes the selected set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.actionSet.delete`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: deleting a set asks first (a selected action is still deleted at once), Shift-click on a set's name selects a range of sets, ≡ › Delete does the same as the button, and Default Actions and the last set can be deleted. Undo does not restore a deleted set, and recorded commands cannot be selected or deleted | -| Actions panel: ≡ › Duplicate copies the selected action or set ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.actionSet.duplicate`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected, and a copied set holds copies of all its actions. Undo does not remove the copy, and recorded commands cannot be duplicated | -| Asset Export tile context menus | done | Export / Remove selected assets, Rename inline, Select Artwork on Canvas, and collect selected artwork as one/multiple assets; right-click selection and multi-selection preservation; `panels::tests_asset_export` | -| Properties panel per context (every selection type's Quick Actions) | partial | Ungroup when any selected object is a group, Isolate Group only for that one group, and Unite only for selections of at least two objects, each a non-guide path or a compound path (`panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`); one clip group: Edit Clipping Path and Edit Contents, at the top of the panel rather than in Quick Actions (G1); the overview's additional controls ([Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html)): Blend Options (one blend selected, with any tool, #4817), Repeat Options (one radial, grid or mirror repeat selected: Object › Repeat › Options, #5181; the overview does not list it) and Merge Live Paint (a Live Paint group with more) in Quick Actions, text Quick Actions (live type selected: Create Outlines, Retype, Find and Replace…; `panels::properties::tests::type_quick_actions_show_text_commands_and_create_outlines`), the Width Profile list (Width tool or a variable-width stroke) and an applied effect's Delete icon in Appearance, Corner and Corner Radius for corners selected with Direct Selection; Variable Font was already there; Edit Artboards: a Transform section (reference point, X, Y, W, H, preset, orientation) above the Artboards section (#5219) | -| Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs; a Shift-click on a highlighted match leaves it out | partial | #3521, `select.globalEdit` / `select.globalEditOptions` / `select.globalEditExclude`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); a group holding type or an image is not taken, as Global Edit does not take images or text; Shift-click to leave a match out ([public source](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)); the Control bar's Global Edit Options dropdown opens the same options; the matches are highlighted before the start (`selecting_one_object_highlights_the_similar_objects_before_global_edit_starts`); rotated copies are matched and take an edit turned by their angle ([public source](https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html); `start_global_edit_takes_rotated_copies_and_an_edit_reaches_each_turned_by_its_angle`); reflected copies are not matched (VectorCraft's own rule) | -| Contextual task bar | done | | -| Control bar with Transform and Stroke popovers | done | | -| Control bar and Properties panel: Corners link and pop-up for the picked corners (part of #1232) | done | the link opens the corner kind, the radius (blank while the picked corners differ) and the Relative or Absolute rounding; each change sets the picked corners of every selected path in one `object.setLiveShape {items}`, one undo step | -| Control bar: numeric Corner Radius for eligible selected ordinary and live corners (part of #7238, request 3 only) | done | Anchor Points visibility group; common/mixed values, general document units and multi-object edits through `object.setLiveShape`, one Undo. A partial selection containing no eligible corners contributes no target. Corner kind and relative mode are retained; existing corner-widget selection, widget visibility and maximum-radius behavior are unchanged. Requests 1/2 remain open. | -| Stroke panel: custom arrowheads after the built-in ones in both arrowhead menus, from the arrowheads file that the panel menu's Edit Arrowheads… opens; saving the file reloads the menus, and a stroke keeps a copy of its custom head's art | done | [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html) (Customize arrowheads); the file's layout (one symbol per head, pointing right, tip at the registration point, height drawn as wide as the built-in heads) is VectorCraft's own; `stroke.arrowheads.edit`, `stroke.arrowheads.list`, `stroke.arrowheads.reload`, `stroke.set` `{custom: name}`; engine `tests::arrowheads`, `stroke::tests_arrows::custom_heads_draw_their_own_art_at_the_tip` | -| Control bar: Paragraph: link and Align left/center/right while type is selected (#5372) | done | After the Character controls, as the public documentation has the Control panel format paragraphs ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html), [Align text](https://helpx.adobe.com/illustrator/using/align-text.html)); the link opens the Paragraph panel in a popover, as Character: does with the Character panel. The bar trims from its right end: X/Y/W/H, Distribute, Align, area type vertical alignment, then these buttons, then the link. The three-button set is our choice for room; all seven alignments are in the popover. `panels/paragraph/tests.rs` headless tests (`the_control_bar_shows_the_paragraph_alignment_of_the_selected_type`, `the_control_bar_trims_its_paragraph_section_after_the_controls_to_its_right`) | -| Pathfinder shape results keep their source names and SVG IDs | done | #1293; Minus Front keeps the back name, Minus Back the front name; Unite/Intersect/Exclude use the backmost named input; compound output carries it once; geometry and paint unchanged | -| Attributes fill-rule controls with a compound member selected | done | Edits the compound's rule; direction still edits only the member; rendered-hole and Undo/Redo regression tests (#1197) | -| Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves, the Gradient tool draws a vector or a Pen drag pulls out an anchor's handle; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | -| Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | -| Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | -| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Decorative, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; fifteen built-in libraries (original, generated in code) | -| Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | -| Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | -| Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | -| Pathfinder Trim, Merge and Crop remove strokes; Merge joins same-fill objects whatever their strokes | done | #1570 (#1572) | -| Pathfinder panel on one group selected alone; a greyed-out button says what it needs | partial | #1450; the group's members are combined; one plain path selected alone stays disabled (the public documentation doesn't say what the operations do to a single path) | -| Pathfinder Divide: an open cutting line splits a filled path | done | #1307; straight, crossed, bent and curved cutters, holes and frontmost appearance regression-tested; native automation: independent piece movement, one Undo/Redo, saved-document round trip and window capture; existing bounded-map fallback remains | -| Pathfinder panel › Pathfinder Options…: Precision, Remove Redundant Points, Divide and Outline Will Remove Unpainted Artwork | done | #3426; `object.pathfinder.options`, kept in the preferences; defaults (0.01 pt, both off) keep the earlier results; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | -| Cmd/Ctrl+4 repeats the last successful Shape Mode or Pathfinder operation on the selection | done | Panel operations, direct `object.pathfinder.*` commands and `command.batch` steps (Actions playback) set history; `action.batch`, Trap, compound-shape edits and live effects do not. Repeat uses current Pathfinder Options; [key spec](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [menu spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | -| Pathfinder panel: compound shapes (Make, Release and Expand Compound Shape in the panel menu, Alt-click a Shape Mode, a Shape Mode for selected members, the Expand button) | partial | #4522; `object.compoundShape.make`/`setMode`/`release`/`expand`; members stay editable, the area draws, exports and saves; the button of the members' shared mode is lit, and members in different modes put a question mark on each Shape Mode button; blends, envelopes and warped objects are members as they draw; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html); missing: hit-testing by the area | -| Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). A selection with a visible stroke to outline (a path, compound path or group holding one; not type) adds Outline Stroke (`object.path.outlineStroke`, the Object › Path item, no shortcut), after the path operations (#5267). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | -| Layers panel row context menu | done | Right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export; right-clicking a ruler guide row shows Hide/Show, Lock/Unlock, Release Guides, Delete and Locate Object; right-clicking a blend spine row shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object (#8592). | -| Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. | -| History panel row context menu (G12) | done | New Document from State, Step to This State, and Clear History; current-row stepping and empty-history clearing are disabled. Snapshot identity is checked after pending tool edits, and jumps settle typing before counting undo/redo. A state discarded while an edit settles reports that it is unavailable. Shift+F10 opens the focused row menu; Escape returns focus to the row. Switching documents dismisses the menu. Headless tests: `panels::history::tests`. | -| Links panel row context menu (G12) | done | Right-clicking a link row presents an item context menu offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, and Embed Image / Unembed…; right-clicking an unselected row selects it first, preserving selection if already part of a multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. | -| Appearance panel row context menu (G12) | done | Right-clicking a stroke or fill row offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide/Show Stroke / Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide/Show Effect; root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets it first before opening the context menu. Tests: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance`. | -| SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | -| Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). Installed fonts not loaded yet are compared too, read in the background with Cancel (`retype.cancelSearch`). Opening it from the Type menu, the context menu, and the Properties panel for outlined shapes (the Properties panel Quick Action opens it for text selections only), filtering by font source and favorites, near matches and text in images are missing (#4934) | -| Comments, Version History panels | missing | cloud features (out of scope) | -| Blend panel (30.7) | partial | Window › Blend provides Type (Ease In, Ease Out, Ease In Out, Ease Out In), Ramp 0–100% and independent color Shift, alongside the existing blend controls. Easing is disabled without a spine. Original polynomial distributions approximate the publicly documented behavior. On-canvas Appearance and Easing widgets set Shift and Ramp; a blend without a spine shows the Appearance widget alone. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) | -| Gradient panel: Dither (30.0) | done | Dither box under the stops (`paint.editGradient` `dither`); dimmed behind the Stroke proxy, fills only; `panels::gradient` test | -| Gradient panel: Method, Classic or Perceptual (30.0) | done | Method menu under the Stroke buttons for linear and radial gradients (`paint.editGradient` `method`); [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/control-perceptual-interpolation-in-gradients.html); `panels::gradient` test | -| Gradient panel: Presets (30.0) | done | Presets menu by library (theme) plus Saved: applies a preset to the gradient behind the active proxy, keeping its placement, one undo step; panel menu Save Gradient Preset…, Delete Gradient Preset, Hide/Show Presets (`gradient.presets.*`); `panels::gradient` tests | -| Gradient panel: delete a stop | done | Delete Stop at the right end of the ramp deletes the selected stop, and a stop dragged down off the ramp is deleted on release, never below two stops, one undo step each; [Gradient panel options](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/gradient-tool-and-panel.html); `panels::gradient` test | -| Gradient stop editor: Color mode menu | done | Compact current-mode menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion; a choice keeps the editor open, Escape closes the menu first, and clicking outside both dismisses the editor (#7918); `crates/ui-egui/tests/gradient_stop_color_mode_menu.rs` | -| Gradient tool: the annotator's end handle changes the length; Alt-drag changes the length and angle together | done | A plain drag keeps the end on the bar's line, at least 10 px from the start (VectorCraft's own minimum); Alt-drag moves it freely, Shift with Alt at 45° steps; [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html); `xform::gradient` tests | -| Workspaces (save, reset, switch); each remembers the layout changes made in it across switches and restarts until Reset | done | `UiState::workspace_changes` | -| Opening a file: after 0.4 s a progress window with the file name, a moving bar (reading counts no steps), how many more files wait, Cancel (Esc: the file doesn't open) and Continue in Background; never over another dialog or progress window | done | #5930; `opening::show`, `file.cancelOpen`, `file.openInBackground`. A save that runs in the background shows the same window, with how many more saves wait; its Cancel (`file.cancelSave`) stops the save before it replaces the file, which stays as it was. A save whose file is already being replaced finishes and is reported as saved, and a save of several files (EPS with Use Artboards) whose first file is in place writes the rest. Its Continue in Background is `file.saveInBackground` (the help page lists each background save's progress with a Cancel button: https://helpx.adobe.com/illustrator/using/saving-artwork.html). A place that takes longer than 0.4 s shows the progress window with Cancel (`placing::show`, `file.cancelPlace`); Close still shows only the status bar's spinner (Close is immediate) | -| Window › Help Bar shows or hides the tool-help strip apart from the status bar; kept with the preferences and in saved workspaces; Presentation Mode hides both bars | done | `window.helpBar`; `help_bar_toggle_is_independent_and_saved_in_workspaces`, `help_bar_and_status_bar_render_independently`, `legacy_help_bar_visibility_follows_each_layouts_status_bar` | -| Status bar: a click on the info field opens a Show menu that chooses its readout: Artboard Name, Current Tool (the default), Date and Time, Number of Undos (undo and redo counts) or Document Color Profile; kept with the UI state | done | `view.statusBarShow`; [public behavior reference](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html); `the_status_bar_info_field_shows_the_chosen_readout`, `a_click_on_the_info_field_opens_the_show_menu`, `the_status_bar_show_choice_is_checked_and_saved`. The menu labels are VectorCraft's own | -| Background Export: a progress dialog with the file name, the artboard count and a bar (busy for one artboard and for formats made in one go), Cancel (Esc) and Continue in Background; it opens after 0.4 s and never over another dialog. A cancelled export writes no file | done | #2564; on the shared `vectorcraft_doc::cancel` token (#2546), so a cancelled render keeps no half-drawn pattern tile or effect raster. The bar moves between artboards, not within one. Save As, Export for Screens and Export Selection don't show it yet | -| Swatch, graphic style and symbol library panels: each library opens in a panel of its own, several at once, that floats, groups, docks and closes like any panel; opening an open library brings its panel forward; Previous / Next Library change the library in place; the panel menu's Persistent reopens the panel at startup with its view and find field (a library loaded from a file is read again; when its file is missing the panel reopens showing the file's path with Locate Library…, and the status bar names the file) | done | #2603; panel ids `library::`, `ui.libraryPanel {panel, library?, view?, showFind?, persistent?}`, `ui.libraryPanel.locate {panel, path?}`; the library panels have no sort option, as before | -| Raster export dialogs retain supplied values for their controls and apply defaults only to omitted values | done | #8324; `tests_raster_supplied_options` checks PNG resolution, background, anti-aliasing and interlacing through `file.export.png`, JPEG quality, omitted defaults, and invalid resolution rejection | -| DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500) | -| macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | -| Preferences: every option acts | partial | 2 stored but unused (#394, audited 2026-10-30): Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | -| Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, ); flares and Pen paths are not turned | -| Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | -| Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | -| Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | -| Overprint Preview draws a white canvas around the artboards, with no artboard shadows | done | VectorCraft's own rule, in Overprint Preview and in Separations Preview, which turns it on: while the artboards show, the canvas outside the artboards is white in every interface brightness and Canvas Color, and the artboards keep their paper and edges and draw no shadows. With a display profile, translucent art around the artboards is blended with the white canvas. Turning the preview off brings back the pasteboard color and the shadows. Tests `overprint_preview_draws_a_white_canvas_without_shadows`, `translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas`, `translucent_pixels_around_the_artboards_are_blended_with_the_white_canvas` | -| Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` | -| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Preview mode and output draw them as before. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | -| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | -| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | -| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | -| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | -| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `_YYYY-MM-DD_HH-MM.` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | -| Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | -| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | -| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › New Symbols from Layers makes a symbol of each layer's art named after the layer (the highlighted layers when two or more are, else all); Convert Layers to Symbols also replaces each layer's art with an instance in place; empty layers skipped, one undo step | done | #4927; `addon.document.symbolsFromLayers`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | -| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool (also in the Pen tool's group in both shipped toolbars, after the Quick Pen; the All Tools drawer lists it under Draw; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its nine tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool, Tangent Circle Tool, Trim at Crossings Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped (except Trim at Crossings, which both shipped toolbars and the drawer show in the Scissors tool's group), opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush, Extend Path or Tangent Circle tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | -| Corner and Shared Edge Merge options restore canceled edits | done | Canceling a control gesture restores its opening draft values. Confirmed changes remain available to the tool. | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none (its options show or hide the center cross and the radii, set their color, and set how near a segment is picked with Smart Guides on or off); Add Points to Existing Paths (in its options; Alt at the release turns it the other way, a dot beside the pointer while it is in effect) also adds an anchor point where the circle touches each segment; one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… draw a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, from a dialog with Offset, One per Object (a shape around each object instead of one around the whole selection) and Preview; one undo step | done | `addon.pathtools.boundingRectangle` and `addon.pathtools.boundingCircle` (in `crates/engine/src/cmd/addons/pathtools/bounding.rs`, the circle in `crates/geom/src/shapes.rs`, `enclosing_circle`; the dialog is the command dialog, `crates/ui-egui/src/dialogs/command.rs`) and their tests, with the menu items' test `add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests, with the menu item's test `add_inscribed_circle_draws_its_circles_without_a_dialog` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | -| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool (also in the Pen tool's group in both shipped toolbars, after the Quick Pen; the All Tools drawer lists it under Draw; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point); an Alt-drag away from paths selects the points inside a marquee | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its three tools (Anchor Eraser Brush, Extend Path, Measure & Inspect), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and runs Add Points at / Split at Crossings; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | -| Artwork Cleanup add-on (VectorCraft addition): Object › Plug-ins › Artwork Cleanup opens its panel, which checks the selection or the document for 16 kinds of issue, lists them with counts, and shows or fixes the picked rows or all of them, each fix one undo step; Simplify Anchors (Keep Shape), Rejoin Path Pieces and Deep Ungroup open their options first | done | `addon.cleanup.*`, `crates/ui-egui/src/addons/cleanup.rs` and its tests; not a feature of the reference app, so it is not scored | -| Artwork Cleanup add-on text tools (VectorCraft addition): the panel's Text row, which the panel can hide, and Object › Plug-ins › Artwork Cleanup set the alignment of point type keeping its place, break type into lines (Shift-click: paragraphs), words or glyphs, split type at the cursor, reset a text transform (Alt-click: and its horizontal scale), combine point type, remove line or paragraph breaks and replace missing fonts, each one undo step | done | `addon.cleanup.*` text commands, `crates/ui-egui/src/addons/cleanup.rs` and its tests; a VectorCraft addition, so it is not scored | -| Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step; Select by Color Kind selects the objects that use spot colours, carry colour effects, or are RGB, CMYK or grayscale images; Vector Halftone draws an object as halftone dots live (the dots Object › Vector Halftone makes), which Expand Appearance and the exporters write as paths; Duotone prints each colour's tone with one to four inks (a tint of a spot tone's swatch, or the CMYK mix of several), live or as a filter, its dialog a row per tone and the picked tone's curve; Print Ink Fixes (a CMYK document's ink limit, white overprint removed, black overprint set) opens its options from the submenu and the panel's Inks | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not a feature of the reference app, so it is not scored | -| Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Find Nearest Swatch… picks a Library (Document Swatches, a built-in library, or a library or colour book the user saved or loaded) and Fill and Stroke, lists each colour of the selection with its three closest swatches (chip, name, ΔE 2000), and Apply gives each colour its nearest swatch (global and spot swatches linked; a library's swatches added to the document first), one undo step | done | #4923; `addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, `crates/engine/src/cmd/addons/color/nearest.rs`, `crates/ui-egui/src/addons/color/nearest.rs` and their tests; not a feature of the reference app, so it is not scored | -| Selection Tools add-on (VectorCraft addition): Object › Plug-ins › Selection Tools › Select by Artboards… lists every artboard (number, name, width × height in the document's units), filters them by name, chooses several (click, Shift-click for a range, Cmd/Ctrl-click to toggle; Select All / None act on the rows shown; a count of those chosen), fits a row's artboard in the window on double-click and makes it active, and on OK selects the objects overlapping, fully inside or fully outside the chosen artboards (Overlapping is All on Active Artboard's test) | done | #5525, #5548, #5549; `addon.select.byArtboards`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select.rs` and their tests; not a feature of the reference app | -| Selection Tools add-on (VectorCraft addition): Select Linked, Select Embedded, Select Missing and Select Modified in Object › Plug-ins › Selection Tools and the Links panel menu (off when no image has that status; Shift adds to the selection) select the images and placed documents with that link status, leaving out hidden, locked, template-layer and outside-isolation ones, which the status bar counts (e.g. "Selected 9 missing images; 3 more are hidden or locked"); Select by Link Status… lists them with name, status and format, searches by name, filters by status, picks with checkboxes and All / None, and selects with Zoom to Selection on by default | done | #5526; `addon.select.byLinkStatus`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select/link_status.rs` and their tests; not a feature of the reference app | -| Style panels: a double-click on a user character style's row opens its Character Style Options, and on a paragraph style's row opens the same Paragraph Style Options as the panel menu, with General, Basic Paragraph Formats, Tabs, Composition, Hyphenation, Justification and East Asian Composition Settings; the Character Style Options dialog keeps a fixed width, its sections scrolling when the window is shorter so OK and Cancel stay on screen | done | `ui.charStyleOptions`, `ui.paraStyleOptions` (`paraStyle.edit`); `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`, `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`, `dialogs::para_style_options::tests::every_section_draws_its_fields`, `dialogs::para_style_options::tests::tabs_section_edits_the_style_stops` | +| Behaviour | Status | Notes | Headless | +|---|---|---| --- | +| Effect > Warp Options: style previews, orientation choices and percent controls | done | #1760; focused input, mixed-style and history checks passed; original captures reviewed. No geometry or optional Properties changes. | unknown | +| Command search: Up and Down move through the results, Enter runs the highlighted one | done | #1798 (#1757) | unknown | +| Help › VectorCraft Help… and F1 show in-app search for tools, menu commands, and built-in tutorials. Tool results mark their toolbar location; command results show their menu path and shortcut without running them; tutorial results show their steps. Home clears the search, Back returns to the results, and Escape in the search field closes the panel. | partial | [Public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-with-discover-panel.html); `help.discover`, `help.discover.search`, `help.discover.choose`, `help.discover.back`; `menus::tests::help_f1_opens_discover_without_a_document`. Articles, Quick Actions, and Discover preferences are not implemented. Menu-path text instead of a menu location marker is VectorCraft's current guidance. | unknown | +| Learn panel: Window › Learn opens it; For you holds a Quick skill guide card, Skills lists VectorCraft's own skills with progress rings that fill and counts of tutorials finished, a tutorial shows its numbered steps with a check box each that marks the step done once its sample is open, a finished tutorial has a check mark, Back goes up a level; a tool's name in a step is a link that marks the tool where the toolbars show it (its button, its group's flyout, a torn-off strip, a toolbar made with New Toolbar or the All Tools drawer) without choosing it; View more opens the tutorial's practice sample as a new untitled document, Finish tutorial then marks it finished with all its steps, and Next Up shows the next tutorial in the same skill; Reset progress clears the progress (no video) | done | [the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `learn.list`, `learn.tab`, `learn.skills`, `learn.skill`, `learn.show`, `learn.back`, `learn.locateTool`, `learn.openSample`, `learn.markStep`, `learn.finish`, `learn.next`, `learn.resetProgress`; the mark's look and 3-second lifetime, marking steps by hand, keeping the progress in the preferences and Reset progress are VectorCraft's own rules; `panels::learn::tests`, `toolbar::tests` | unknown | +| Pathfinder panel: a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled | done | #1642 (#1635) | unknown | +| Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; a selected Radial Repeat shows an instances handle below it (16 px of drag per instance, 1 to 1,000) and a radius handle on its circle the same way (`tools/src/repeat_radial.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)), and a splitter on its circle that hides the instances it is dragged back past while the others keep their places, and shows them again when dragged forward (its place half a step past the last instance shown and its limit of one instance shown are VectorCraft's own rules) | unknown | +| Grid Repeat Options (Object › Repeat › Options…) has a Preview checkbox: the repeat on the canvas follows the fields while the dialog is open, Cancel puts the original back without a history step, OK keeps the previewed values as one undo step | done | #2651; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html) lists the Preview option for the grid options only, so Radial and Mirror Repeat Options have none; `dialogs/command.rs` tests | unknown | +| Type on a Path Options (Type › Type on a Path › Type on a Path Options…, or a double-click on the Type on a Path tools) has a Preview checkbox, off when it opens: the selected type on a path follows Effect, Flip, Align to Path and Spacing while the dialog is open, Cancel puts it back without a history step, OK keeps the previewed values as one undo step | done | #5360; the [public page](https://helpx.adobe.com/illustrator/using/creating-type-path.html) lists the dialog's options, and public tutorials of the dialog show its Preview checkbox; `tests/pathtype.rs` | unknown | +| Graph Type (Object › Graph › Type…, or a double-click on a graph tool) is a dialog of its own: a menu at the top shows Graph Options or the page of an axis; Graph Options has a button per graph type, Value Axis with Separate Scales, the Style checkboxes (Add Drop Shadow, Add Legend Across Top, First Row in Front, First Column in Front) and the options of the type picked (Column or Bar Width and Cluster Width; Mark Data Points, Connect Data Points, Edge-to-Edge Lines and Draw Filled Lines; a pie graph's Legend, Position and Sort); the Value Axis page (Left Axis and Right Axis with the value axis on both sides) has Tick Values with Override Calculated Values, Tick Marks and Add Labels, and the Category Axis page has Tick Marks with Draw Tick Marks Between Labels; with series picked by Group Selection the type and value axis go to those series | done | Public pages: [graph types](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/change-graph-types.html), [value axes](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/change-graph-value-axes.html), [columns, bars and lines](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-columns-bars-and-lines.html), [pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html), [separate scales](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/assign-different-scales-to-value-axes.html), [combined types](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/combine-different-graph-types.html). The options dimmed for a type, the pages listed and the Legend checkbox are VectorCraft's own rules. Dialog `graphType`; `dialogs/graph_type.rs` and its tests | unknown | +| Selected Mirror Repeat shows a prominent axis with move and rotation handles; bounding-box handles take priority over the axis line | done | #2877, `tools/src/mirror.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html) | unknown | +| Object › Expand on radial, grid and mirror repeats makes groups of their instances | done | #1765 (#1756) | unknown | +| Object › Expand… is dimmed while the selection has appearance attributes (effects, several fills or strokes, a fill or stroke with its own transparency or effects, a brush); its tooltip and the status bar say to use Object › Expand Appearance first, which leaves a stroked line with Zig Zag a stroked zig-zag line that Expand then outlines | done | #3089; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html); `dialogs/expand.rs` tests, engine `tests_objexpand`. `object.expand` (agents, scripts) still bakes effects in one step | unknown | +| Select › Same matches type on its characters' fill and stroke | done | #1746 (#1737) | unknown | +| ~40 panels with ≡ menus; dock, icon column, collapse, tabs | done | 51 panel modules incl. tests | unknown | +| Panels float, stack and dock back; on the desktop a floating group is an OS window of its own, inside the window on the web and on Wayland | done | #495, #4135 | unknown | +| Floating groups stack into sets; sets dock as extra dock columns (a multi-column dock); groups drop anywhere in a set or column, or onto its tabs; a column taller than the window scrolls | done | `window.panel.float {below, above}`, `window.panel.dock {column}` | unknown | +| Panels dragged onto a dock group's tabs join it; onto its upper or lower half they make a new group above or below it (a top/bottom split, resizable); onto the icon column they become icons, the tabbed group's panels too; a dock tab's context menu closes it (Window menu reopens it) | done | `window.panel.dock {anchor, zone}`, `window.panel.dock {icon: true}`, `window.panel.close` | unknown | +| A double-click on a dock group's tab collapses the group to its tabs (a group below it moves up into the room) and a second one expands it; a click on another of its tabs expands it showing that panel ([helpx: Workspace basics](https://helpx.adobe.com/illustrator/using/workspace-basics.html), panel groups) | done | `window.panel.collapse {panel, collapsed?}`; in dock groups and floating windows; a group beside another (a left/right split) doesn't collapse | unknown | +| The double triangle at the right end of a panel's tab strip cycles the panel's display sizes, the states its Show/Hide Options (and Transparency's Show/Hide Thumbnails) panel-menu items set ([archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=189), Transparency; [archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479), Character and Paragraph) | done | `window.panel.cycleOptions {panel}`; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency; the order of the sizes, the glyph and where it sits are VectorCraft's own (#3041) | unknown | +| Panels outside the app window (another monitor) | done | floating groups in OS windows of their own on the desktop (#4135) | unknown | +| Edit Toolbar (•••): the All Tools drawer opens beside the toolbar by its button (Escape or a click outside closes it), dims the tools already in the toolbar; while it is open, tools drag from it onto the toolbar (between two tools, or onto one to join its group), from the toolbar into it, and within the toolbar; each toolbar keeps its edits | done | #1018; `window.editToolbar`, `toolbar.addTool`/`removeTool`/`reset`; the drawer's Reset (Illustrator has it in a drawer menu); dragging a toolbar button moves the tool it shows, not its whole group; tool flyouts are as wide as their longest translated name and shortcut need (#1616) | unknown | +| Window › Toolbars › New Toolbar… (also in the All Tools drawer's menu): a name and OK make a blank floating toolbar, listed under Window › Toolbars (its item shows or hides it); its title bar moves it, its × hides it and its double arrow shows its tools in one column or two; its ••• button opens the All Tools drawer beside it to fill it; kept with the workspace it was made in | done | #1759 in part; `window.toolbar.new`, `window.toolbar.custom`, `window.toolbar.list`, the `toolbar` param of `window.toolbarColumns`, `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset` | unknown | +| Window › Toolbars › Manage Toolbars… (also in the All Tools drawer's menu): the dialog lists the toolbars made with New Toolbar; a new name typed for the selected one renames it, + copies it (none selected: a blank toolbar) and the trash can deletes it; the changes stay in the workspace | done | #1759 in part; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete` | unknown | +| Quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the editable controls | done | Per the public documentation, choosing a preset traces the image with it straight away, and the panel is opened with the Image Trace button in the Control panel or in Properties' Image Trace section (). The controls show Threshold, Paths, Corners and Noise with Advanced open; `panels/image_trace.rs` headless tests (`a_quick_trace_leaves_the_panel_as_it_was`, `sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source` for the button's route). No algorithm parity claim. | unknown | +| Image Trace panel: holding the eye button next to View down shows the selected Image Trace objects' source image on the canvas | done | Per the public documentation, the control next to View is pressed and held to compare the trace result with the source image (). On release the objects show their View again; the document, its View and the undo history are unchanged. `RenderOptions::trace_source`; `panels/image_trace.rs` headless test `holding_the_eye_button_shows_the_source_image_until_released`, render test `trace_source_draws_the_source_image_of_the_listed_objects`. The Control bar and Properties have no such button | unknown | +| Image Trace panel: Ignore Color has a canvas eyedropper beside its color picker | done | #8068. Samples original pixels of the selected placed image or the retained source of a live trace without changing the displayed canvas View. The existing color picker remains available. Preview off keeps a draft; Preview on retraces a live trace as one undo step. An outside or transparent miss leaves the pick armed; a valid sample or Escape restores the previous tool, and changing the target or explicitly choosing a tool cancels. Paint defaults and selection are retained. `tests/image_trace_ignore_sampler.rs`; no algorithm parity claim. Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; runtime pending). | unknown | +| Live trace result bounds and selection highlights exclude the retained bitmap; source-image views retain it | done | All TraceView modes and rotated result bounds regression-covered; ordinary hidden group behavior retained | unknown | +| Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) | unknown | +| Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls; Window > Toolbars > Compact Tools adds optional denser spacing for the main Tools panel while retaining the existing default (#7234) | unknown | +| Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | done | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON | unknown | +| Actions panel: ≡ › Replace Actions… puts the set of a saved file in place of every set in the panel ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | done | `ui.actionSet.replace`; `panels/actions.rs` tests. The file is read as Load Actions… reads it; the item asks no question first | unknown | +| Actions panel: ≡ › Clear Actions deletes every set loaded in the panel ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | done | `ui.actionSet.clear`; `panels/actions.rs` tests. The item asks first, and the built-in Default Actions set goes too | unknown | +| Actions panel: ≡ › Reset Actions asks first; OK replaces the sets in the panel with the default set and Append adds the default set after them ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | done | `ui.actionSet.reset`; `panels/actions.rs` and `dialogs/tests.rs` tests. The default set is VectorCraft's own Default Actions set | unknown | +| Actions panel: ≡ › Load Actions… also reads action sets saved as `.aia` files ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `actionSet.read`, `ui.actionSet.load`; `tests/actionset.rs`, `panels/actions.rs` tests, `import_fuzz`. Steps with a label and no recorded values come in as menu commands that run with no values and open no dialog, matched by label, and Set Selection steps come in as Select Object steps; the other steps, recorded menu items included, are left out and counted | unknown | +| Actions panel: ≡ › Action Options… renames the selected action and sets its function key and color ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.action.options`; `panels/actions.rs` tests (part of #1629). Button Mode shows the color | unknown | +| Actions panel: ≡ › Button Mode shows each action by name as a button in its Action Options color, without sets or steps; a click on a button plays the action, and choosing Button Mode again shows the list ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | done | `ui.action.buttonMode`, `ui.action.playAt`; `panels/actions.rs` tests. VectorCraft's own rules: every set's actions show in set order, an action without a color is an ordinary button, the mode is kept with the UI preferences, and it cannot be turned on while an action records | unknown | +| Actions panel: ≡ › Playback Options… plays actions Accelerated, Step by Step or with a pause between steps ([Specify playback speed](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/specify-playback-speed.html)) | done | `ui.action.playbackOptions`; `panels/actions.rs` tests. The pause is a whole number of seconds from 1 to 60 (VectorCraft's own range); Batch… plays at full speed | unknown | +| Actions panel: a clicked action stays selected for Play Current Selection and Delete Selection | partial | #1853 (part of #1629); editing actions and action shortcuts remain | unknown | +| Actions panel: Create New Set (bottom bar, ≡ › New Set…) names a new set and Set Options… renames the current one; a click on a set's name makes it current and a recording goes into the current set ([helpx: Automation with actions](https://helpx.adobe.com/illustrator/using/automation-actions.html)); the current set is kept with the UI preferences, and with no set current a recording goes into the first set, which becomes current | partial | #3712; dragging actions between sets remains | unknown | +| Actions panel: Create New Action (bottom bar, ≡ › New Action…) asks for the name, set, function key and color, and Record adds the action and records into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html)) | partial | `ui.action.new`, `ui.action.play`; `panels/actions.rs` tests. A function key plays its action, even when a command has the same shortcut, and the command keeps it. Button Mode shows the color | unknown | +| Actions panel: Delete Selection (bottom bar) deletes the selected set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.actionSet.delete`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: deleting a set asks first (a selected action is still deleted at once), Shift-click on a set's name selects a range of sets, ≡ › Delete does the same as the button, and Default Actions and the last set can be deleted. Undo does not restore a deleted set, and recorded commands cannot be selected or deleted | unknown | +| Actions panel: ≡ › Duplicate copies the selected action or set ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.actionSet.duplicate`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected, and a copied set holds copies of all its actions. Undo does not remove the copy, and recorded commands cannot be duplicated | unknown | +| Asset Export tile context menus | done | Export / Remove selected assets, Rename inline, Select Artwork on Canvas, and collect selected artwork as one/multiple assets; right-click selection and multi-selection preservation; `panels::tests_asset_export` | unknown | +| Properties panel per context (every selection type's Quick Actions) | partial | Ungroup when any selected object is a group, Isolate Group only for that one group, and Unite only for selections of at least two objects, each a non-guide path or a compound path (`panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`); one clip group: Edit Clipping Path and Edit Contents, at the top of the panel rather than in Quick Actions (G1); the overview's additional controls ([Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html)): Blend Options (one blend selected, with any tool, #4817), Repeat Options (one radial, grid or mirror repeat selected: Object › Repeat › Options, #5181; the overview does not list it) and Merge Live Paint (a Live Paint group with more) in Quick Actions, text Quick Actions (live type selected: Create Outlines, Retype, Find and Replace…; `panels::properties::tests::type_quick_actions_show_text_commands_and_create_outlines`), the Width Profile list (Width tool or a variable-width stroke) and an applied effect's Delete icon in Appearance, Corner and Corner Radius for corners selected with Direct Selection; Variable Font was already there; Edit Artboards: a Transform section (reference point, X, Y, W, H, preset, orientation) above the Artboards section (#5219) | unknown | +| Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs; a Shift-click on a highlighted match leaves it out | partial | #3521, `select.globalEdit` / `select.globalEditOptions` / `select.globalEditExclude`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); a group holding type or an image is not taken, as Global Edit does not take images or text; Shift-click to leave a match out ([public source](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)); the Control bar's Global Edit Options dropdown opens the same options; the matches are highlighted before the start (`selecting_one_object_highlights_the_similar_objects_before_global_edit_starts`); rotated copies are matched and take an edit turned by their angle ([public source](https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html); `start_global_edit_takes_rotated_copies_and_an_edit_reaches_each_turned_by_its_angle`); reflected copies are not matched (VectorCraft's own rule) | unknown | +| Contextual task bar | done | | unknown | +| Control bar with Transform and Stroke popovers | done | | unknown | +| Control bar and Properties panel: Corners link and pop-up for the picked corners (part of #1232) | done | the link opens the corner kind, the radius (blank while the picked corners differ) and the Relative or Absolute rounding; each change sets the picked corners of every selected path in one `object.setLiveShape {items}`, one undo step | unknown | +| Control bar: numeric Corner Radius for eligible selected ordinary and live corners (part of #7238, request 3 only) | done | Anchor Points visibility group; common/mixed values, general document units and multi-object edits through `object.setLiveShape`, one Undo. A partial selection containing no eligible corners contributes no target. Corner kind and relative mode are retained; existing corner-widget selection, widget visibility and maximum-radius behavior are unchanged. Requests 1/2 remain open. | unknown | +| Stroke panel: custom arrowheads after the built-in ones in both arrowhead menus, from the arrowheads file that the panel menu's Edit Arrowheads… opens; saving the file reloads the menus, and a stroke keeps a copy of its custom head's art | done | [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html) (Customize arrowheads); the file's layout (one symbol per head, pointing right, tip at the registration point, height drawn as wide as the built-in heads) is VectorCraft's own; `stroke.arrowheads.edit`, `stroke.arrowheads.list`, `stroke.arrowheads.reload`, `stroke.set` `{custom: name}`; engine `tests::arrowheads`, `stroke::tests_arrows::custom_heads_draw_their_own_art_at_the_tip` | unknown | +| Control bar: Paragraph: link and Align left/center/right while type is selected (#5372) | done | After the Character controls, as the public documentation has the Control panel format paragraphs ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html), [Align text](https://helpx.adobe.com/illustrator/using/align-text.html)); the link opens the Paragraph panel in a popover, as Character: does with the Character panel. The bar trims from its right end: X/Y/W/H, Distribute, Align, area type vertical alignment, then these buttons, then the link. The three-button set is our choice for room; all seven alignments are in the popover. `panels/paragraph/tests.rs` headless tests (`the_control_bar_shows_the_paragraph_alignment_of_the_selected_type`, `the_control_bar_trims_its_paragraph_section_after_the_controls_to_its_right`) | unknown | +| Pathfinder shape results keep their source names and SVG IDs | done | #1293; Minus Front keeps the back name, Minus Back the front name; Unite/Intersect/Exclude use the backmost named input; compound output carries it once; geometry and paint unchanged | unknown | +| Attributes fill-rule controls with a compound member selected | done | Edits the compound's rule; direction still edits only the member; rendered-hole and Undo/Redo regression tests (#1197) | unknown | +| Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves, the Gradient tool draws a vector or a Pen drag pulls out an anchor's handle; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | unknown | +| Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | unknown | +| Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | unknown | +| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Decorative, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; fifteen built-in libraries (original, generated in code) | unknown | +| Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | unknown | +| Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | unknown | +| Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | unknown | +| Pathfinder Trim, Merge and Crop remove strokes; Merge joins same-fill objects whatever their strokes | done | #1570 (#1572) | unknown | +| Pathfinder panel on one group selected alone; a greyed-out button says what it needs | partial | #1450; the group's members are combined; one plain path selected alone stays disabled (the public documentation doesn't say what the operations do to a single path) | unknown | +| Pathfinder Divide: an open cutting line splits a filled path | done | #1307; straight, crossed, bent and curved cutters, holes and frontmost appearance regression-tested; native automation: independent piece movement, one Undo/Redo, saved-document round trip and window capture; existing bounded-map fallback remains | unknown | +| Pathfinder panel › Pathfinder Options…: Precision, Remove Redundant Points, Divide and Outline Will Remove Unpainted Artwork | done | #3426; `object.pathfinder.options`, kept in the preferences; defaults (0.01 pt, both off) keep the earlier results; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | unknown | +| Cmd/Ctrl+4 repeats the last successful Shape Mode or Pathfinder operation on the selection | done | Panel operations, direct `object.pathfinder.*` commands and `command.batch` steps (Actions playback) set history; `action.batch`, Trap, compound-shape edits and live effects do not. Repeat uses current Pathfinder Options; [key spec](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [menu spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | unknown | +| Pathfinder panel: compound shapes (Make, Release and Expand Compound Shape in the panel menu, Alt-click a Shape Mode, a Shape Mode for selected members, the Expand button) | partial | #4522; `object.compoundShape.make`/`setMode`/`release`/`expand`; members stay editable, the area draws, exports and saves; the button of the members' shared mode is lit, and members in different modes put a question mark on each Shape Mode button; blends, envelopes and warped objects are members as they draw; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html); missing: hit-testing by the area | unknown | +| Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). A selection with a visible stroke to outline (a path, compound path or group holding one; not type) adds Outline Stroke (`object.path.outlineStroke`, the Object › Path item, no shortcut), after the path operations (#5267). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | unknown | +| Layers panel row context menu | done | Right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export; right-clicking a ruler guide row shows Hide/Show, Lock/Unlock, Release Guides, Delete and Locate Object; right-clicking a blend spine row shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object (#8592). | unknown | +| Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. | unknown | +| History panel row context menu (G12) | done | New Document from State, Step to This State, and Clear History; current-row stepping and empty-history clearing are disabled. Snapshot identity is checked after pending tool edits, and jumps settle typing before counting undo/redo. A state discarded while an edit settles reports that it is unavailable. Shift+F10 opens the focused row menu; Escape returns focus to the row. Switching documents dismisses the menu. Headless tests: `panels::history::tests`. | unknown | +| Links panel row context menu (G12) | done | Right-clicking a link row presents an item context menu offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, and Embed Image / Unembed…; right-clicking an unselected row selects it first, preserving selection if already part of a multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. | unknown | +| Appearance panel row context menu (G12) | done | Right-clicking a stroke or fill row offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide/Show Stroke / Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide/Show Effect; root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets it first before opening the context menu. Tests: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance`. | unknown | +| SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | unknown | +| Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). Installed fonts not loaded yet are compared too, read in the background with Cancel (`retype.cancelSearch`). Opening it from the Type menu, the context menu, and the Properties panel for outlined shapes (the Properties panel Quick Action opens it for text selections only), filtering by font source and favorites, near matches and text in images are missing (#4934) | unknown | +| Comments, Version History panels | missing | cloud features (out of scope) | unknown | +| Blend panel (30.7) | partial | Window › Blend provides Type (Ease In, Ease Out, Ease In Out, Ease Out In), Ramp 0–100% and independent color Shift, alongside the existing blend controls. Easing is disabled without a spine. Original polynomial distributions approximate the publicly documented behavior. On-canvas Appearance and Easing widgets set Shift and Ramp; a blend without a spine shows the Appearance widget alone. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) | unknown | +| Gradient panel: Dither (30.0) | done | Dither box under the stops (`paint.editGradient` `dither`); dimmed behind the Stroke proxy, fills only; `panels::gradient` test | unknown | +| Gradient panel: Method, Classic or Perceptual (30.0) | done | Method menu under the Stroke buttons for linear and radial gradients (`paint.editGradient` `method`); [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/control-perceptual-interpolation-in-gradients.html); `panels::gradient` test | unknown | +| Gradient panel: Presets (30.0) | done | Presets menu by library (theme) plus Saved: applies a preset to the gradient behind the active proxy, keeping its placement, one undo step; panel menu Save Gradient Preset…, Delete Gradient Preset, Hide/Show Presets (`gradient.presets.*`); `panels::gradient` tests | unknown | +| Gradient panel: delete a stop | done | Delete Stop at the right end of the ramp deletes the selected stop, and a stop dragged down off the ramp is deleted on release, never below two stops, one undo step each; [Gradient panel options](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/gradient-tool-and-panel.html); `panels::gradient` test | unknown | +| Gradient stop editor: Color mode menu | done | Compact current-mode menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion; a choice keeps the editor open, Escape closes the menu first, and clicking outside both dismisses the editor (#7918); `crates/ui-egui/tests/gradient_stop_color_mode_menu.rs` | unknown | +| Gradient tool: the annotator's end handle changes the length; Alt-drag changes the length and angle together | done | A plain drag keeps the end on the bar's line, at least 10 px from the start (VectorCraft's own minimum); Alt-drag moves it freely, Shift with Alt at 45° steps; [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html); `xform::gradient` tests | unknown | +| Workspaces (save, reset, switch); each remembers the layout changes made in it across switches and restarts until Reset | done | `UiState::workspace_changes` | unknown | +| Opening a file: after 0.4 s a progress window with the file name, a moving bar (reading counts no steps), how many more files wait, Cancel (Esc: the file doesn't open) and Continue in Background; never over another dialog or progress window | done | #5930; `opening::show`, `file.cancelOpen`, `file.openInBackground`. A save that runs in the background shows the same window, with how many more saves wait; its Cancel (`file.cancelSave`) stops the save before it replaces the file, which stays as it was. A save whose file is already being replaced finishes and is reported as saved, and a save of several files (EPS with Use Artboards) whose first file is in place writes the rest. Its Continue in Background is `file.saveInBackground` (the help page lists each background save's progress with a Cancel button: https://helpx.adobe.com/illustrator/using/saving-artwork.html). A place that takes longer than 0.4 s shows the progress window with Cancel (`placing::show`, `file.cancelPlace`); Close still shows only the status bar's spinner (Close is immediate) | unknown | +| Window › Help Bar shows or hides the tool-help strip apart from the status bar; kept with the preferences and in saved workspaces; Presentation Mode hides both bars | done | `window.helpBar`; `help_bar_toggle_is_independent_and_saved_in_workspaces`, `help_bar_and_status_bar_render_independently`, `legacy_help_bar_visibility_follows_each_layouts_status_bar` | unknown | +| Status bar: a click on the info field opens a Show menu that chooses its readout: Artboard Name, Current Tool (the default), Date and Time, Number of Undos (undo and redo counts) or Document Color Profile; kept with the UI state | done | `view.statusBarShow`; [public behavior reference](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html); `the_status_bar_info_field_shows_the_chosen_readout`, `a_click_on_the_info_field_opens_the_show_menu`, `the_status_bar_show_choice_is_checked_and_saved`. The menu labels are VectorCraft's own | unknown | +| Background Export: a progress dialog with the file name, the artboard count and a bar (busy for one artboard and for formats made in one go), Cancel (Esc) and Continue in Background; it opens after 0.4 s and never over another dialog. A cancelled export writes no file | done | #2564; on the shared `vectorcraft_doc::cancel` token (#2546), so a cancelled render keeps no half-drawn pattern tile or effect raster. The bar moves between artboards, not within one. Save As, Export for Screens and Export Selection don't show it yet | unknown | +| Swatch, graphic style and symbol library panels: each library opens in a panel of its own, several at once, that floats, groups, docks and closes like any panel; opening an open library brings its panel forward; Previous / Next Library change the library in place; the panel menu's Persistent reopens the panel at startup with its view and find field (a library loaded from a file is read again; when its file is missing the panel reopens showing the file's path with Locate Library…, and the status bar names the file) | done | #2603; panel ids `library::`, `ui.libraryPanel {panel, library?, view?, showFind?, persistent?}`, `ui.libraryPanel.locate {panel, path?}`; the library panels have no sort option, as before | unknown | +| Raster export dialogs retain supplied values for their controls and apply defaults only to omitted values | done | #8324; `tests_raster_supplied_options` checks PNG resolution, background, anti-aliasing and interlacing through `file.export.png`, JPEG quality, omitted defaults, and invalid resolution rejection | unknown | +| DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500) | unknown | +| macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | unknown | +| Preferences: every option acts | partial | 2 stored but unused (#394, audited 2026-10-30): Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | unknown | +| Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, ); flares and Pen paths are not turned | unknown | +| Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | unknown | +| Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | unknown | +| Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | unknown | +| Overprint Preview draws a white canvas around the artboards, with no artboard shadows | done | VectorCraft's own rule, in Overprint Preview and in Separations Preview, which turns it on: while the artboards show, the canvas outside the artboards is white in every interface brightness and Canvas Color, and the artboards keep their paper and edges and draw no shadows. With a display profile, translucent art around the artboards is blended with the white canvas. Turning the preview off brings back the pasteboard color and the shadows. Tests `overprint_preview_draws_a_white_canvas_without_shadows`, `translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas`, `translucent_pixels_around_the_artboards_are_blended_with_the_white_canvas` | unknown | +| Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` | unknown | +| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Preview mode and output draw them as before. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | unknown | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | unknown | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `_YYYY-MM-DD_HH-MM.` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | unknown | +| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | unknown | +| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › New Symbols from Layers makes a symbol of each layer's art named after the layer (the highlighted layers when two or more are, else all); Convert Layers to Symbols also replaces each layer's art with an instance in place; empty layers skipped, one undo step | done | #4927; `addon.document.symbolsFromLayers`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool (also in the Pen tool's group in both shipped toolbars, after the Quick Pen; the All Tools drawer lists it under Draw; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its nine tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool, Tangent Circle Tool, Trim at Crossings Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped (except Trim at Crossings, which both shipped toolbars and the drawer show in the Scissors tool's group), opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush, Extend Path or Tangent Circle tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Corner and Shared Edge Merge options restore canceled edits | done | Canceling a control gesture restores its opening draft values. Confirmed changes remain available to the tool. | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none (its options show or hide the center cross and the radii, set their color, and set how near a segment is picked with Smart Guides on or off); Add Points to Existing Paths (in its options; Alt at the release turns it the other way, a dot beside the pointer while it is in effect) also adds an anchor point where the circle touches each segment; one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… draw a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, from a dialog with Offset, One per Object (a shape around each object instead of one around the whole selection) and Preview; one undo step | done | `addon.pathtools.boundingRectangle` and `addon.pathtools.boundingCircle` (in `crates/engine/src/cmd/addons/pathtools/bounding.rs`, the circle in `crates/geom/src/shapes.rs`, `enclosing_circle`; the dialog is the command dialog, `crates/ui-egui/src/dialogs/command.rs`) and their tests, with the menu items' test `add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests, with the menu item's test `add_inscribed_circle_draws_its_circles_without_a_dialog` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool (also in the Pen tool's group in both shipped toolbars, after the Quick Pen; the All Tools drawer lists it under Draw; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point); an Alt-drag away from paths selects the points inside a marquee | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its three tools (Anchor Eraser Brush, Extend Path, Measure & Inspect), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and runs Add Points at / Split at Crossings; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Artwork Cleanup add-on (VectorCraft addition): Object › Plug-ins › Artwork Cleanup opens its panel, which checks the selection or the document for 16 kinds of issue, lists them with counts, and shows or fixes the picked rows or all of them, each fix one undo step; Simplify Anchors (Keep Shape), Rejoin Path Pieces and Deep Ungroup open their options first | done | `addon.cleanup.*`, `crates/ui-egui/src/addons/cleanup.rs` and its tests; not a feature of the reference app, so it is not scored | unknown | +| Artwork Cleanup add-on text tools (VectorCraft addition): the panel's Text row, which the panel can hide, and Object › Plug-ins › Artwork Cleanup set the alignment of point type keeping its place, break type into lines (Shift-click: paragraphs), words or glyphs, split type at the cursor, reset a text transform (Alt-click: and its horizontal scale), combine point type, remove line or paragraph breaks and replace missing fonts, each one undo step | done | `addon.cleanup.*` text commands, `crates/ui-egui/src/addons/cleanup.rs` and its tests; a VectorCraft addition, so it is not scored | unknown | +| Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step; Select by Color Kind selects the objects that use spot colours, carry colour effects, or are RGB, CMYK or grayscale images; Vector Halftone draws an object as halftone dots live (the dots Object › Vector Halftone makes), which Expand Appearance and the exporters write as paths; Duotone prints each colour's tone with one to four inks (a tint of a spot tone's swatch, or the CMYK mix of several), live or as a filter, its dialog a row per tone and the picked tone's curve; Print Ink Fixes (a CMYK document's ink limit, white overprint removed, black overprint set) opens its options from the submenu and the panel's Inks | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not a feature of the reference app, so it is not scored | unknown | +| Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Find Nearest Swatch… picks a Library (Document Swatches, a built-in library, or a library or colour book the user saved or loaded) and Fill and Stroke, lists each colour of the selection with its three closest swatches (chip, name, ΔE 2000), and Apply gives each colour its nearest swatch (global and spot swatches linked; a library's swatches added to the document first), one undo step | done | #4923; `addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, `crates/engine/src/cmd/addons/color/nearest.rs`, `crates/ui-egui/src/addons/color/nearest.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | +| Selection Tools add-on (VectorCraft addition): Object › Plug-ins › Selection Tools › Select by Artboards… lists every artboard (number, name, width × height in the document's units), filters them by name, chooses several (click, Shift-click for a range, Cmd/Ctrl-click to toggle; Select All / None act on the rows shown; a count of those chosen), fits a row's artboard in the window on double-click and makes it active, and on OK selects the objects overlapping, fully inside or fully outside the chosen artboards (Overlapping is All on Active Artboard's test) | done | #5525, #5548, #5549; `addon.select.byArtboards`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select.rs` and their tests; not a feature of the reference app | unknown | +| Selection Tools add-on (VectorCraft addition): Select Linked, Select Embedded, Select Missing and Select Modified in Object › Plug-ins › Selection Tools and the Links panel menu (off when no image has that status; Shift adds to the selection) select the images and placed documents with that link status, leaving out hidden, locked, template-layer and outside-isolation ones, which the status bar counts (e.g. "Selected 9 missing images; 3 more are hidden or locked"); Select by Link Status… lists them with name, status and format, searches by name, filters by status, picks with checkboxes and All / None, and selects with Zoom to Selection on by default | done | #5526; `addon.select.byLinkStatus`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select/link_status.rs` and their tests; not a feature of the reference app | unknown | +| Style panels: a double-click on a user character style's row opens its Character Style Options, and on a paragraph style's row opens the same Paragraph Style Options as the panel menu, with General, Basic Paragraph Formats, Tabs, Composition, Hyphenation, Justification and East Asian Composition Settings; the Character Style Options dialog keeps a fixed width, its sections scrolling when the window is shorter so OK and Cancel stay on screen | done | `ui.charStyleOptions`, `ui.paraStyleOptions` (`paraStyle.edit`); `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`, `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`, `dialogs::para_style_options::tests::every_section_draws_its_fields`, `dialogs::para_style_options::tests::tabs_section_edits_the_style_stops` | unknown | ## Look and feel From f17ec731907e90dd79ef3b60179c3a9218208763 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:37:53 -0800 Subject: [PATCH 14/50] JavaScript: a with binding gone since its lookup reads as undefined GetBindingValue of an object environment asks HasProperty again before [[Get]] (ES2015 8.1.1.2.6). When the binding is gone, typeof x and a plain read of x give undefined in sloppy code without calling get, and strict code throws a ReferenceError. --- crates/js/src/interp.rs | 12 +++++++++++- crates/js/src/proxy_tests.rs | 16 +++++++++++++--- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index bada62b44e..4b151220c7 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1306,8 +1306,18 @@ impl Interp { Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)), Resolved::Decl(e) => Ok((self.binding_value(e, name)?, Value::Undefined)), Resolved::Obj { object, with_this } => { + // GetBindingValue of an object environment asks HasProperty again (ES2015 + // 8.1.1.2.6): a binding gone since the lookup reads as undefined, or throws in + // strict code, without a [[Get]]. + let this = if with_this { Value::Object(object) } else { Value::Undefined }; + if !self.scope_has(object, name)? { + if self.strict() { + return Err(self.not_defined(name)); + } + return Ok((Value::Undefined, this)); + } let v = self.get_value(&Value::Object(object), name)?; - Ok((v, if with_this { Value::Object(object) } else { Value::Undefined })) + Ok((v, this)) } Resolved::Unresolved => Err(self.not_defined(name)), } diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index aed9fa3f90..e7b12c4e3e 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -409,13 +409,23 @@ fn a_proxy_works_as_a_prototype_and_a_with_scope() { #[test] fn typeof_reads_the_binding_a_with_scope_reported_once() { + // GetBindingValue asks `has` again, and a binding gone by then reads as undefined without `get`. truth( - "var asked = 0; + "var asked = 0, got = 0; var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; }, - get: function (t, k) { return k === 'x' ? function () {} : undefined; } }); + get: function (t, k) { got++; return k === 'x' ? function () {} : undefined; } }); var r; with (p) { r = typeof x; } - r === 'function' && asked === 1", + r === 'undefined' && asked === 2 && got === 0", + ); + // A plain read of the same binding takes the same path. + truth( + "var asked = 0, got = 0; + var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; }, + get: function (t, k) { got++; return 1; } }); + var r; + with (p) { r = x; } + r === undefined && asked === 2 && got === 0", ); } From cfd6aed392eb842f55cd03401d99b96326047df6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:18:51 -0800 Subject: [PATCH 15/50] JavaScript: proxies keep their traps after the merge with main Function.prototype.bind reads a proxy's prototype through its trap, Object.prototype.toString reads a proxy's Symbol.toStringTag from its target, Reflect.set writes a typed array's elements, a super assignment runs the set trap of a proxy on the home object's chain, and 'in' asks a proxy's has trap once. The name a trap is given is counted against the heap and fuel limits, and Proxy and Reflect stay reachable while their functions are installed. --- crates/js/src/builtins.rs | 34 ++++++++-- crates/js/src/builtins/binary.rs | 5 ++ crates/js/src/builtins/reflect.rs | 13 +++- crates/js/src/class_ops.rs | 23 ++++--- crates/js/src/host_classes.rs | 12 ++-- crates/js/src/interp.rs | 25 +++---- crates/js/src/proxy.rs | 63 +++++++++++++----- crates/js/src/proxy_tests.rs | 105 ++++++++++++++++++++++++++++++ crates/js/src/xml.rs | 6 +- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 11 files changed, 233 insertions(+), 58 deletions(-) diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index f90112f93a..197e5be3c1 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -537,11 +537,14 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J // A proxy reads as an array when its target is one, and a revoked proxy is a // `TypeError` (ECMA-262 2020 section 19.1.3.6). Value::Object(o) if interp.is_proxy(*o) => { - if interp.is_array(&this)? { - "Array" - } else { - interp.heap.object(*o).map_or("Object", |o| o.class.name()) + let array = interp.is_array(&this)?; + // `Symbol.toStringTag` is read through the proxy to its target. + let o = *o; + if let Some(tag) = interp.rooted(std::slice::from_ref(&this), |i| i.string_tag_of(o))? { + let roots = [Value::String(tag.clone())]; + return interp.rooted(&roots, |i| i.wrap_str("[object ", Some(&tag), "]")); } + if array { "Array" } else { interp.heap.object(o).map_or("Object", |o| o.class.name()) } } _ => { let o = interp.to_object(&this)?; @@ -740,13 +743,30 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into(); // With ECMAScript 2015 the bound function inherits from the target's prototype, read before // `length` and `name` (ECMA-262 2020 section 9.4.1.3 step 2), so a bound generator function - // inherits from %GeneratorFunction.prototype%. - let target_proto = interp.heap.object(target).and_then(|o| o.proto); + // inherits from %GeneratorFunction.prototype%. A proxy's prototype comes from its + // `getPrototypeOf` trap, and it stays reachable while `length` and `name` are read. + let target_proto = if interp.options.es2015 { interp.get_prototype_of(target)? } else { interp.heap.object(target).and_then(|o| o.proto) }; + let mark = interp.temp_roots.len(); + interp.temp_roots.extend(target_proto.map(Value::Object)); + let r = bind_from(interp, &this, target, target_proto, bound_this, bound_args); + interp.temp_roots.truncate(mark); + r +} + +/// The steps of `Function.prototype.bind` after the target's prototype is read. +fn bind_from( + interp: &mut Interp, + this: &Value, + target: ObjId, + target_proto: Option, + bound_this: Value, + bound_args: Rc<[Value]>, +) -> JsResult { // A host function's `length` is an ordinary property a script can set, so it is converted // to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is // read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run. let has_length = !interp.options.es2015 || interp.get_own_property(target, &key("length"))?.is_some(); - let length_value = if has_length { interp.get_from(target, &key("length"), &this)? } else { Value::Undefined }; + let length_value = if has_length { interp.get_from(target, &key("length"), this)? } else { Value::Undefined }; let target_length = match length_value { Value::Number(n) if n.is_nan() => 0.0, Value::Number(n) => n.trunc(), diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index 3ec93edc07..b18a0cda67 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -342,6 +342,11 @@ pub(crate) fn set_element(interp: &mut Interp, id: ObjId, n: f64, v: &Value) -> Ok(()) } +/// Does the numeric name `n` name an element of the typed array `id` (IsValidIntegerIndex)? +pub(crate) fn is_element(interp: &Interp, id: ObjId, n: f64) -> bool { + view_of(interp, id).is_some_and(|view| valid_index(n, view.length).is_some()) +} + /// `[[DefineOwnProperty]]` of a numeric name of a typed array (section 9.4.5.3, with the /// configurable elements of later editions). pub(crate) fn define_element(interp: &mut Interp, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult { diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index 5e25784b59..2b5158624e 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -19,7 +19,9 @@ pub(super) fn install(interp: &mut Interp, keep: bool) -> JsResult<()> { let global = interp.global; if !(keep && interp.get_own_property(global, &key("Proxy"))?.is_some()) { let proxy = native(interp, "Proxy", proxy_ctor, 2, NativeKind::Plain, true)?; - method(interp, proxy, "revocable", revocable, 2)?; + // Naming a new method can collect, and the constructor is reachable from nowhere else + // until it is published. + interp.rooted(&[Value::Object(proxy)], |interp| method(interp, proxy, "revocable", revocable, 2))?; data(interp, global, "Proxy", Value::Object(proxy), HIDDEN)?; } if !(keep && interp.get_own_property(global, &key("Reflect"))?.is_some()) { @@ -34,6 +36,12 @@ fn install_reflect(interp: &mut Interp) -> JsResult<()> { let global = interp.global; let object_proto = interp.intrinsics.object_proto; let reflect = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + interp.rooted(&[Value::Object(reflect)], |interp| reflect_methods(interp, reflect))?; + data(interp, global, "Reflect", Value::Object(reflect), HIDDEN) +} + +/// Defines `Reflect`'s functions on `reflect`, which the caller keeps reachable. +fn reflect_methods(interp: &mut Interp, reflect: ObjId) -> JsResult<()> { method(interp, reflect, "apply", apply, 3)?; method(interp, reflect, "construct", construct, 2)?; method(interp, reflect, "defineProperty", define_property, 3)?; @@ -46,8 +54,7 @@ fn install_reflect(interp: &mut Interp) -> JsResult<()> { method(interp, reflect, "ownKeys", own_keys, 1)?; method(interp, reflect, "preventExtensions", prevent_extensions, 1)?; method(interp, reflect, "set", set, 3)?; - method(interp, reflect, "setPrototypeOf", set_prototype_of, 2)?; - data(interp, global, "Reflect", Value::Object(reflect), HIDDEN) + method(interp, reflect, "setPrototypeOf", set_prototype_of, 2) } // ---- Proxy ---- diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 99a52146cf..73a8f4d0f8 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -557,14 +557,6 @@ impl Interp { } } - /// The property `k` of `start` or an object it inherits from. - fn find_pk(&mut self, start: ObjId, k: &PropKey) -> JsResult> { - match k { - PropKey::Str(name) => self.find_property(start, name), - PropKey::Sym(s) => self.find_sym(start, s), - } - } - /// [[Get]] of `k` from `start` with `receiver` as `this`. fn get_pk_from(&mut self, start: ObjId, k: &PropKey, receiver: &Value) -> JsResult { match k { @@ -605,7 +597,20 @@ impl Interp { /// 6.2.3.2). fn super_put(&mut self, proto: ObjId, k: PropKey, v: Value, receiver: &Value) -> JsResult<()> { let throw = self.strict_writes(); - let why = match self.find_pk(proto, &k)? { + let inherited = match &k { + PropKey::Str(name) => match self.lookup(proto, name)? { + crate::interp::Lookup::Proxy(p) => { + if !self.set_with_receiver(p, name.clone(), v, receiver)? { + return self.super_reject(throw, &k, "the proxy did not set it"); + } + return Ok(()); + } + crate::interp::Lookup::Found(prop) => Some(prop), + crate::interp::Lookup::Missing => None, + }, + PropKey::Sym(s) => self.find_sym(proto, s)?, + }; + let why = match inherited { Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), receiver, &[v]).map(drop), Some(Prop::Accessor { set: None, .. }) => Some("it has only a getter"), Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => Some("it is read-only"), diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index d8b81fdcec..e5db3cb582 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -393,14 +393,18 @@ impl Interp { /// [[HasProperty]] of `k` on `id`: for an object of a host class with an indexer, an array index, /// or a name that the object and its prototypes lack, is there when the indexer gives a value other /// than `undefined` for it. - pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &[u16]) -> JsResult { - let index = crate::value::array_index(k).is_some(); - if (index || !self.has_property(id, k)?) + pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &Key) -> JsResult { + // The lookup runs once, so a proxy's `has` trap is asked once. + let found = if crate::value::array_index(k).is_some() { None } else { Some(self.has_property(id, k)?) }; + if found != Some(true) && let Some(f) = self.host_indexer(id)? { return Ok(!matches!(self.host_index(&f, id, Self::indexer_key(k), true)?, Value::Undefined)); } - self.has_property(id, k) + match found { + Some(found) => Ok(found), + None => self.has_property(id, k), + } } /// `d` as a JavaScript value, the objects of host classes in it made from their [`host_ref`]. diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index c177f6578c..c9cfe69b61 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1458,7 +1458,7 @@ impl Interp { // ---- variables ---- - fn resolve(&mut self, name: &[u16]) -> JsResult { + fn resolve(&mut self, name: &Key) -> JsResult { let mut cur = Some(self.frame()?.env); while let Some(e) = cur { match self.heap.env(e) { @@ -1685,7 +1685,7 @@ impl Interp { } /// [[GetOwnProperty]] (section 8.12.1), through a proxy's trap when `id` is a proxy. - pub(crate) fn get_own_property(&mut self, id: ObjId, k: &[u16]) -> JsResult> { + pub(crate) fn get_own_property(&mut self, id: ObjId, k: &Key) -> JsResult> { if self.is_proxy(id) { return self.proxy_get_own_property(id, k); } @@ -1783,7 +1783,7 @@ impl Interp { /// [[GetProperty]]: the property found on the object or its prototype chain, through the /// `getOwnPropertyDescriptor` and `getPrototypeOf` traps of the proxies on it. - pub(crate) fn find_property(&mut self, id: ObjId, k: &[u16]) -> JsResult> { + pub(crate) fn find_property(&mut self, id: ObjId, k: &Key) -> JsResult> { // One root slot holds the prototype the walk has reached; each hop replaces it. let mark = self.temp_roots.len(); self.temp_roots.push(Value::Undefined); @@ -1821,7 +1821,7 @@ impl Interp { } /// [[HasProperty]], through the `has` trap of a proxy on the prototype chain. - pub(crate) fn has_property(&mut self, id: ObjId, k: &[u16]) -> JsResult { + pub(crate) fn has_property(&mut self, id: ObjId, k: &Key) -> JsResult { match self.lookup(id, k)? { Lookup::Found(_) => Ok(true), Lookup::Missing => Ok(false), @@ -1831,7 +1831,7 @@ impl Interp { /// [[Get]] starting at `start`, with `receiver` as `this` for a getter, through the `get` trap /// of a proxy on the prototype chain. - pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + pub(crate) fn get_from(&mut self, start: ObjId, k: &Key, receiver: &Value) -> JsResult { // An array index of an object of a host class with an indexer is the indexer's answer. if let Some(i) = array_index(k) && let Some(f) = self.host_indexer(start)? @@ -1854,7 +1854,7 @@ impl Interp { /// [[Get]] of a name that is not an array index, without the indexer of an object of a host /// class: a name the object and its prototypes lack is `undefined`. For names the engine looks /// up itself, such as `toJSON`, which a collection's indexer would answer with an error. - pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + pub(crate) fn get_property_only(&mut self, start: ObjId, k: &Key, receiver: &Value) -> JsResult { match self.lookup(start, k)? { Lookup::Missing | Lookup::Found(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Lookup::Found(Prop::Data { value, .. }) => Ok(value), @@ -1880,7 +1880,7 @@ impl Interp { } /// `base[k]` for any value (GetValue, section 8.7.1). - pub(crate) fn get_value(&mut self, base: &Value, k: &[u16]) -> JsResult { + pub(crate) fn get_value(&mut self, base: &Value, k: &Key) -> JsResult { if self.options.e4x && self.is_xml(base) { return self.xml_get(base, &Value::String(Str::from_units(k.to_vec()))); } @@ -2253,7 +2253,7 @@ impl Interp { } /// [[Delete]] (section 8.12.7). - pub(crate) fn delete(&mut self, id: ObjId, k: &[u16], throw: bool) -> JsResult { + pub(crate) fn delete(&mut self, id: ObjId, k: &Key, throw: bool) -> JsResult { if self.is_proxy(id) { let deleted = self.proxy_delete(id, k)?; if !deleted && throw { @@ -3136,7 +3136,7 @@ impl Interp { /// the objects that follow it are searched. A name deleted or made non-enumerable after the /// names were listed is skipped, on an ordinary object as on a proxy. A proxy's `has` trap is /// not asked. Each proxy on the chain takes a unit of fuel. - fn for_in_still_has(&mut self, o: ObjId, k: &[u16]) -> JsResult { + fn for_in_still_has(&mut self, o: ObjId, k: &Key) -> JsResult { // One root slot holds the prototype the walk has reached; each hop replaces it. let mark = self.temp_roots.len(); self.temp_roots.push(Value::Undefined); @@ -3145,7 +3145,7 @@ impl Interp { r } - fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &[u16], slot: usize) -> JsResult { + fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &Key, slot: usize) -> JsResult { loop { let p = match self.lookup(cur, k)? { Lookup::Found(prop) => return Ok(prop.enumerable()), @@ -4421,8 +4421,9 @@ impl Interp { return self.xml_has(b, a).map(Value::Bool); } let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) }; - let k = self.to_prop_key(a)?; - self.has_pk_indexed(*o, &k).map(Value::Bool) + // The key stays rooted while a proxy's trap is given a copy of it. + let o = *o; + self.with_prop_key(a, |i, k| i.has_pk_indexed(o, &k)).map(Value::Bool) } } } diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index bb35ea100a..01afb8ab00 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -109,8 +109,15 @@ impl Interp { Ok(v) } - fn key_value(k: &[u16]) -> Value { - Value::String(Str::from_units(k.to_vec())) + /// The property name a trap is given, a copy of `k` counted against the heap limit, its code + /// units charged as fuel. + fn key_value(&mut self, k: &Key) -> JsResult { + let bytes = string_bytes(k.len()); + self.reserve_heap(bytes)?; + crate::string_builtins::charge_units(self, k.len())?; + let copy = Value::String(Str::from_units(k.to_vec())); + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + Ok(copy) } fn invariant(&mut self, trap: &str, why: &str) -> Abrupt { @@ -220,10 +227,11 @@ impl Interp { // ---- properties ---- /// [[GetOwnProperty]] of a proxy (section 9.5.5). - pub(crate) fn proxy_get_own_property(&mut self, p: ObjId, k: &[u16]) -> JsResult> { - self.proxy_op(p, "read a property of", &[], |i, target, handler| { + pub(crate) fn proxy_get_own_property(&mut self, p: ObjId, k: &Key) -> JsResult> { + self.proxy_op(p, "read a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "getOwnPropertyDescriptor")? else { return i.get_own_property(target, k) }; - let result = i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k)])?; + let name = i.key_value(k)?; + let result = i.call_trap(&trap, handler, &[Value::Object(target), name])?; if !matches!(result, Value::Object(_) | Value::Undefined) { return Err(i.invariant("getOwnPropertyDescriptor", "returned a value that is neither an object nor undefined")); } @@ -267,12 +275,14 @@ impl Interp { /// [[DefineOwnProperty]] of a proxy (section 9.5.6): whether the trap defined the property. pub(crate) fn proxy_define_own_property(&mut self, p: ObjId, k: &Key, desc: &Desc) -> JsResult { - let roots = desc_values(desc); + let mut roots = desc_values(desc); + roots.push(Value::String(Str::from_rc(k.clone()))); self.proxy_op(p, "define a property of", &roots, |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "defineProperty")? else { return i.define_own_property(target, k.clone(), desc, false) }; let desc_obj = from_desc(i, desc)?; i.temp_roots.push(desc_obj.clone()); - if !i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k), desc_obj])?.truthy() { + let name = i.rooted(std::slice::from_ref(&desc_obj), |i| i.key_value(k))?; + if !i.call_trap(&trap, handler, &[Value::Object(target), name, desc_obj])?.truthy() { return Ok(false); } let target_prop = i.get_own_property(target, k)?; @@ -305,10 +315,11 @@ impl Interp { } /// [[HasProperty]] of a proxy (section 9.5.7). - pub(crate) fn proxy_has(&mut self, p: ObjId, k: &[u16]) -> JsResult { - self.proxy_op(p, "test a property of", &[], |i, target, handler| { + pub(crate) fn proxy_has(&mut self, p: ObjId, k: &Key) -> JsResult { + self.proxy_op(p, "test a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "has")? else { return i.has_property(target, k) }; - let found = i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k)])?.truthy(); + let name = i.key_value(k)?; + let found = i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy(); if !found && let Some(current) = i.get_own_property(target, k)? { if !current.configurable() { return Err(i.invariant("has", "hid a non-configurable property of its target")); @@ -322,10 +333,11 @@ impl Interp { } /// [[Get]] of a proxy (section 9.5.8). - pub(crate) fn proxy_get(&mut self, p: ObjId, k: &[u16], receiver: &Value) -> JsResult { - self.proxy_op(p, "read a property of", std::slice::from_ref(receiver), |i, target, handler| { + pub(crate) fn proxy_get(&mut self, p: ObjId, k: &Key, receiver: &Value) -> JsResult { + self.proxy_op(p, "read a property of", &[receiver.clone(), Value::String(Str::from_rc(k.clone()))], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "get")? else { return i.get_from(target, k, receiver) }; - let v = i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k), receiver.clone()])?; + let name = i.key_value(k)?; + let v = i.call_trap(&trap, handler, &[Value::Object(target), name, receiver.clone()])?; match i.get_own_property(target, k)? { Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(&v, &value) => { Err(i.invariant("get", "gave a value other than its target's non-configurable, read-only property")) @@ -340,9 +352,10 @@ impl Interp { /// [[Set]] of a proxy (section 9.5.9): whether the trap set the property. fn proxy_set(&mut self, p: ObjId, k: &Key, v: &Value, receiver: &Value) -> JsResult { - self.proxy_op(p, "set a property of", &[v.clone(), receiver.clone()], |i, target, handler| { + self.proxy_op(p, "set a property of", &[v.clone(), receiver.clone(), Value::String(Str::from_rc(k.clone()))], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "set")? else { return i.set_with_receiver(target, k.clone(), v.clone(), receiver) }; - if !i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k), v.clone(), receiver.clone()])?.truthy() { + let name = i.key_value(k)?; + if !i.call_trap(&trap, handler, &[Value::Object(target), name, v.clone(), receiver.clone()])?.truthy() { return Ok(false); } match i.get_own_property(target, k)? { @@ -358,10 +371,11 @@ impl Interp { } /// [[Delete]] of a proxy (section 9.5.10): whether the trap deleted the property. - pub(crate) fn proxy_delete(&mut self, p: ObjId, k: &[u16]) -> JsResult { - self.proxy_op(p, "delete a property of", &[], |i, target, handler| { + pub(crate) fn proxy_delete(&mut self, p: ObjId, k: &Key) -> JsResult { + self.proxy_op(p, "delete a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "deleteProperty")? else { return i.delete(target, k, false) }; - if !i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k)])?.truthy() { + let name = i.key_value(k)?; + if !i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy() { return Ok(false); } let Some(current) = i.get_own_property(target, k)? else { return Ok(true) }; @@ -468,6 +482,19 @@ impl Interp { } fn ordinary_set(&mut self, o: ObjId, k: Key, v: Value, receiver: &Value) -> JsResult { + // A typed array set on itself writes a numeric key as its element, converting the value + // and ignoring a key outside the view; with another receiver a key outside the view is + // ignored and an element is set on the receiver as usual, as the typed arrays' other + // writes follow the later editions (https://tc39.es/ecma262/#sec-typedarray-set). + if let Some(n) = crate::builtins::binary::typed_key(self, o, &k) { + if receiver.as_object() == Some(o) { + crate::builtins::binary::set_element(self, o, n, &v)?; + return Ok(true); + } + if !crate::builtins::binary::is_element(self, o, n) { + return Ok(true); + } + } let own = match self.lookup(o, &k)? { Lookup::Proxy(p) => return self.proxy_set(p, &k, &v, receiver), Lookup::Found(prop) => prop, diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index f1294b20d6..78f7785dea 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -42,6 +42,33 @@ fn limit(src: &str, limits: Limits) -> LimitKind { } } +#[test] +fn the_name_a_trap_is_given_counts_against_the_heap_limit() { + // The same key fits for an ordinary object, but its copy for the trap does not fit in what + // is left. + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let make = "var k = 'x'; while (k.length < 1048576) k += k;"; + assert_eq!(Realm::with_options(es_options(), limits.clone()).run(&format!("{make} k in {{}}")), Ok(JsValue::Bool(false))); + let src = format!("{make} var p = new Proxy({{}}, {{ has: function () {{ return false; }} }}); k in p"); + assert_eq!(limit(&src, limits.clone()), LimitKind::Heap); + // A key made fresh by converting an object stays counted while its copy is reserved. + let fresh = "var o = { toString: function () { var k = 'x'; while (k.length < 1048576) k += k; return k; } };"; + assert_eq!(Realm::with_options(es_options(), limits.clone()).run(&format!("{fresh} o in {{}}")), Ok(JsValue::Bool(false))); + let src = format!("{fresh} var p = new Proxy({{}}, {{ has: function () {{ return false; }} }}); o in p"); + assert_eq!(limit(&src, limits.clone()), LimitKind::Heap); + assert_eq!(Realm::with_options(es_options(), limits.clone()).run(&format!("{fresh} var t = {{}}; delete t[o]")), Ok(JsValue::Bool(true))); + let src = format!("{fresh} var p = new Proxy({{}}, {{ deleteProperty: function () {{ return true; }} }}); delete p[o]"); + assert_eq!(limit(&src, limits.clone()), LimitKind::Heap); + assert_eq!( + Realm::with_options(es_options(), limits.clone()).run(&format!("{fresh} Object.getOwnPropertyDescriptor({{}}, o) === undefined")), + Ok(JsValue::Bool(true)) + ); + let src = format!( + "{fresh} var p = new Proxy({{}}, {{ getOwnPropertyDescriptor: function () {{ return undefined; }} }}); Object.getOwnPropertyDescriptor(p, o)" + ); + assert_eq!(limit(&src, limits), LimitKind::Heap); +} + // ---- the realm gate ---- #[test] @@ -67,6 +94,24 @@ fn only_a_realm_that_ran_es2015_code_has_proxy_and_reflect() { assert_eq!(taken.run("Proxy + Reflect"), Ok(JsValue::Number(3.0))); } +#[test] +fn late_proxy_and_reflect_installation_keeps_their_methods_reachable() { + let mut realm = Realm::new(); + assert_eq!(realm.run("typeof Proxy + ' ' + typeof Reflect"), Ok(JsValue::String("undefined undefined".into()))); + realm.set_es2015(true); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let r = realm.run( + "var pair = Proxy.revocable({ a: 7 }, {}); + var keys = Reflect.ownKeys(pair.proxy); + var value = pair.proxy.a; + pair.revoke(); + value === 7 && keys.length === 1 && keys[0] === 'a'", + ); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert_eq!(r, Ok(JsValue::Bool(true))); + assert!(realm.interp().heap.collections > 0); +} + // ---- Proxy ---- #[test] @@ -624,3 +669,63 @@ fn a_host_function_refuses_a_proxy_and_names_the_argument() { let r = realm.run("var ran = false; try { host.take(new Proxy({}, { ownKeys: function () { ran = true; return []; } })); } catch (e) {} ran"); assert_eq!(r, Ok(JsValue::Bool(false))); } + +#[test] +fn a_bound_proxy_inherits_from_the_prototype_its_trap_gives() { + truth( + "var p = new Proxy(function () { return 7; }, {}); + var b = p.bind(null); + Object.getPrototypeOf(b) === Function.prototype && typeof b.call === 'function' && b() === 7", + ); + // A prototype the trap makes stays the bound function's while `length` and `name` are read. + truth_collecting( + "var target = function () {}, reads = []; + Object.defineProperty(target, 'length', { get: function () { reads.push({ key: 'length' }); return 2; } }); + Object.defineProperty(target, 'name', { get: function () { reads.push({ key: 'name' }); return 'target'; } }); + var q = new Proxy(target, { getPrototypeOf: function () { return { tag: 'made' }; } }); + var c = q.bind(null); + Object.getPrototypeOf(c).tag === 'made' && c.length === 2 && c.name === 'bound target' + && reads.length === 2 && reads[0].key === 'length' && reads[1].key === 'name'", + ); +} + +#[test] +fn in_asks_a_proxy_s_has_trap_once() { + truth( + "var n = 0, p = new Proxy({}, { has: function () { n++; return false; } }); + !('a' in p) && n === 1 && !(0 in p) && n === 2", + ); +} + +#[test] +fn to_string_reads_the_tag_of_a_proxy_s_target() { + truth( + "var t = {}; t[Symbol.toStringTag] = 'Thing'; + Object.prototype.toString.call(new Proxy(t, {})) === '[object Thing]' + && Object.prototype.toString.call(new Proxy([], {})) === '[object Array]'", + ); +} + +#[test] +fn reflect_set_writes_a_typed_array_element_and_ignores_a_key_outside_the_view() { + truth( + "var a = new Uint8Array(1); + var converted = false, big = { valueOf: function () { converted = true; return 5; } }; + Reflect.set(a, '0', 300) && a[0] === 44 && Reflect.set(a, '3', big) && converted && a.length === 1 + && !a.hasOwnProperty('3') + && (function () { var r = {}; return Reflect.set(a, '0', 7, r) && a[0] === 44 && r[0] === 7; })() + && (function () { var r = {}; return Reflect.set(a, '5', 7, r) && !r.hasOwnProperty('5'); })()", + ); +} + +#[test] +fn a_super_assignment_runs_the_set_trap_of_a_proxy_on_the_chain() { + truth( + "var seen = []; + var base = new Proxy({}, { set: function (t, k, v, r) { seen.push(k); return true; } }); + var o = { m() { super.x = 1; } }; + Reflect.setPrototypeOf(o, base); + o.m(); + seen.join() === 'x' && !o.hasOwnProperty('x')", + ); +} diff --git a/crates/js/src/xml.rs b/crates/js/src/xml.rs index bb311cf1a8..a764f7e343 100644 --- a/crates/js/src/xml.rs +++ b/crates/js/src/xml.rs @@ -749,7 +749,7 @@ impl Interp { } /// Whether a scope object has the variable `name`. - pub(crate) fn scope_has(&mut self, object: ObjId, name: &[u16]) -> JsResult { + pub(crate) fn scope_has(&mut self, object: ObjId, name: &Key) -> JsResult { if self.options.e4x && self.is_xml(&Value::Object(object)) { let k = Value::String(Str::from_units(name.to_vec())); return self.xml_has(&Value::Object(object), &k); @@ -871,7 +871,7 @@ impl Interp { /// The function a call `base.name(...)` runs and its `this` (ECMA-357 section 11.2.2.1). A /// call looks the name up among the methods, never among the children. - pub(crate) fn xml_method(&mut self, base: &Value, name: &[u16]) -> JsResult<(Value, Value)> { + pub(crate) fn xml_method(&mut self, base: &Value, name: &Key) -> JsResult<(Value, Value)> { let mut base = base.clone(); loop { let Value::Object(o) = base else { return Err(self.not_xml()) }; @@ -896,7 +896,7 @@ impl Interp { } /// A method found through an XML value in scope, for a call of a bare name in a filter. - pub(crate) fn xml_scope_method(&mut self, name: &[u16]) -> JsResult> { + pub(crate) fn xml_scope_method(&mut self, name: &Key) -> JsResult> { let mut cur = Some(self.frame()?.env); while let Some(e) = cur { match self.heap.env(e) { diff --git a/docs/mcp.md b/docs/mcp.md index 358b636c56..7a3deef8a0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2810,7 +2810,8 @@ counts against the call depth. A generator function called in an engine that `#t throws a `TypeError`, since that engine was made without the ECMAScript 2015 built-ins. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and an engine that `#targetengine` keeps reads each run the way that run's script does. A `.js` script also has the globals `Proxy`, with `Proxy.revocable`, and `Reflect` (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 -and 26.2), with string property names. A trap is a script call: it takes fuel and counts against the limit on nested calls, and +and 26.2), with string property names. A trap is a script call: it takes fuel and counts against the limit on nested calls, +the copy of the property name it is given counts against the heap limit, and a trap result that breaks one of the proxy invariants, or any operation on a revoked proxy, throws a `TypeError`. A proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets `Proxy` and `Reflect` at its first `.js` run and keeps them for later `.jsx` runs. A diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1c1152b00c..e53059cef0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1189,7 +1189,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The collector retains tagged-template cache entries only while the site's code is reachable. - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. - `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`. - - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file both globals; a `.jsx` file and a `source` string have neither in a new engine or in an engine that has not run a `.js` file. An engine that `#targetengine` keeps gets both globals at its first `.js` run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and the first `.js` run does not replace it. `cargo xtask test262` runs the suite's `Proxy` and `Reflect` tests whose features are present: 573 of 663 runs pass with the option (0 without it). Of the 90 failing runs, 4 do not parse because the tests use method definitions, and 86 expect function `name` properties and a configurable function `length`, `Object.setPrototypeOf`, and integer keys listed before other keys, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file both globals; a `.jsx` file and a `source` string have neither in a new engine or in an engine that has not run a `.js` file. An engine that `#targetengine` keeps gets both globals at its first `.js` run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and the first `.js` run does not replace it. `cargo xtask test262` runs the suite's `Proxy` and `Reflect` tests whose features are present: 573 of 663 runs pass with the option (0 without it). Of the 90 failing runs, 4 do not parse because the tests use method definitions, and 86 expect function `name` properties and a configurable function `length`, `Object.setPrototypeOf`, and integer keys listed before other keys, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.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`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. From af9709b16fbe1880c748ab70728f6e4621a34b63 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:46:06 -0800 Subject: [PATCH 16/50] JavaScript: proxies follow module namespaces, for-in key accounting and built-in construction A proxy's descriptor and write paths honor a module namespace's uninitialized exports and read-only writes, for-in through proxies counts the keys it keeps against the heap limit, new through an empty-handler proxy of a built-in constructs it, and revoke has its standard name and length. Object.freeze, seal, isFrozen and isSealed throw a TypeError for a proxy whose target chain has Symbol properties. --- crates/js/src/builtins/object.rs | 27 +++++- crates/js/src/builtins/reflect.rs | 7 +- crates/js/src/class_ops.rs | 2 +- crates/js/src/interp.rs | 69 +++++++++++---- crates/js/src/proxy.rs | 15 +++- crates/js/src/proxy_tests.rs | 134 +++++++++++++++++++++++++++++- docs/mcp.md | 12 ++- docs/target-app-parity.md | 2 +- 8 files changed, 237 insertions(+), 31 deletions(-) diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 8818ae3f6b..a598dd5f6a 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -258,11 +258,14 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { /// 15.2.3.8 and 15.2.3.9). A proxy that does not become non-extensible is a `TypeError`. fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { let Value::Object(o) = v else { return Ok(v) }; + check_integrity_symbols(interp, o)?; if !interp.prevent_extensions(o)? { let what = if freeze { "frozen" } else { "sealed" }; return Err(interp.type_error(&format!("the object cannot be {what}: it did not stop being extensible"))); } - for k in own_prop_keys(interp, o)? { + let keys = own_prop_keys(interp, o)?; + check_integrity_symbols(interp, o)?; + for k in keys { interp.use_fuel()?; let desc = if freeze { let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; @@ -275,6 +278,7 @@ fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { }; interp.define_own_pk(o, k, &desc, true)?; } + check_integrity_symbols(interp, o)?; Ok(Value::Object(o)) } @@ -303,16 +307,20 @@ fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let Value::Object(o) = v else { return Ok(Value::Bool(true)) }; let o = *o; + check_integrity_symbols(interp, o)?; if interp.is_extensible(o)? { return Ok(Value::Bool(false)); } - for k in own_prop_keys(interp, o)? { + let keys = own_prop_keys(interp, o)?; + check_integrity_symbols(interp, o)?; + for k in keys { interp.use_fuel()?; let Some(prop) = interp.own_pk(o, &k)? else { continue }; if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) { return Ok(Value::Bool(false)); } } + check_integrity_symbols(interp, o)?; Ok(Value::Bool(true)) } @@ -320,6 +328,21 @@ fn is_sealed(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult locked(interp, &arg(args, 0), false) } +fn check_integrity_symbols(interp: &mut Interp, o: ObjId) -> JsResult<()> { + if !interp.is_proxy(o) { + return Ok(()); + } + let mut current = o; + loop { + if interp.object(current)?.syms.as_ref().is_some_and(|m| m.len() != 0) { + return Err(interp.type_error("proxy integrity operations with symbol properties are not supported")); + } + let Some(target) = interp.symbol_lookup_target(current)? else { return Ok(()) }; + interp.use_fuel()?; + current = target; + } +} + fn is_frozen(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { locked(interp, &arg(args, 0), true) } diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index 2b5158624e..89af0e1a20 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -6,7 +6,7 @@ use std::rc::Rc; use super::object::{from_prop, names_array, to_desc}; use super::{arg, data, method, native}; -use crate::heap::{Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key}; +use crate::heap::{CONFIGURABLE, Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key}; use crate::interp::{Desc, Interp, JsResult}; use crate::proxy::desc_values; use crate::value::Value; @@ -78,7 +78,8 @@ fn revocable(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult let proto = interp.intrinsics.function_proto; let class = Class::Function(Func::Bound { target: inner, this: Value::Object(p), args: Rc::from(Vec::new()) }); let f = interp.heap.alloc_object(Object::new(class, Some(proto))); - interp.define(f, key("length"), Prop::Data { value: Value::Number(0.0), flags: 0 })?; + interp.define(f, key("length"), Prop::Data { value: Value::Number(0.0), flags: CONFIGURABLE })?; + interp.define(f, key("name"), Prop::Data { value: Value::String(crate::value::Str::from("")), flags: CONFIGURABLE })?; let result = interp.new_object(); interp.define(result, key("proxy"), Prop::Data { value: Value::Object(p), flags: OPEN })?; interp.define(result, key("revoke"), Prop::Data { value: Value::Object(f), flags: OPEN })?; @@ -174,7 +175,7 @@ fn get(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let o = target(interp, args, "getOwnPropertyDescriptor")?; - interp.with_key(&arg(args, 1), |interp, k| match interp.get_own_property(o, &k)? { + interp.with_key(&arg(args, 1), |interp, k| match interp.own_property(o, &k)? { Some(p) => from_prop(interp, &p), None => Ok(Value::Undefined), }) diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 73a8f4d0f8..529226671c 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -304,7 +304,7 @@ impl Interp { Some(Func::Native { f: native, constructor: true, name, .. }) => { // `Proxy` does not read `new.target` (section 26.2.1.1). let subclass = nt != callee && name != "Proxy"; - if subclass && !self.subclassable(callee)? { + if subclass && self.unwrapped_proxy_target(nt)? != callee && !self.subclassable(callee)? { return Err(self.type_error("this built-in cannot be subclassed")); } let intrinsic = match self.get_own_property(callee, &key("prototype"))? { diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 93476206d5..30eb8b40cf 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1824,6 +1824,31 @@ impl Interp { Ok(self.lookup_on(id, k)?.1) } + pub(crate) fn lookup_for_set(&self, id: ObjId, k: &[u16]) -> JsResult> { + let mut cur = Some(id); + let mut steps = 0usize; + while let Some(o) = cur { + if self.is_proxy(o) { + return Ok(Some(Lookup::Proxy(o))); + } + if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) { + return Ok(None); + } + if let Some(p) = self.ordinary_own_property(o, k)? { + return Ok(Some(Lookup::Found(p))); + } + if crate::builtins::binary::typed_key(self, o, k).is_some() { + break; + } + cur = self.object(o)?.proto; + steps += 1; + if steps > 1_000_000 { + return internal("prototype chain too long"); + } + } + Ok(Some(Lookup::Missing)) + } + /// [`Self::lookup`], with the object the search stopped at: the one that has the property, or /// the proxy. fn lookup_on(&self, id: ObjId, k: &[u16]) -> JsResult<(ObjId, Lookup)> { @@ -2300,22 +2325,15 @@ impl Interp { Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), None => {} } - // A write that reaches a module namespace object on the prototype chain, before any proxy, - // is refused there too: its [[Set]] returns false for every key. let proto = self.object(id)?.proto; - let mut cur = proto; - let mut steps = 0usize; - while let Some(o) = cur.filter(|&o| !self.is_proxy(o)) { - if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) { - return self.reject(throw, &k, "a module namespace object is read-only"); - } - cur = self.object(o)?.proto; - steps += 1; - if steps > 1_000_000 { - return internal("prototype chain too long"); - } - } - let inherited = match proto.map(|p| self.lookup(p, &k)).transpose()? { + let lookup = match proto { + Some(p) => match self.lookup_for_set(p, &k)? { + Some(found) => Some(found), + None => return self.reject(throw, &k, "a module namespace object is read-only"), + }, + None => None, + }; + let inherited = match lookup { Some(Lookup::Proxy(p)) => { if !self.set_with_receiver(p, k.clone(), v, &Value::Object(id))? { return self.reject(throw, &k, "the proxy did not set it"); @@ -3179,16 +3197,21 @@ impl Interp { /// whose descriptor trap gives `undefined` does not hide the same name further up the chain. fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult> { let mut seen = std::collections::HashSet::new(); + let mut held = HeldBytes::new(self); let mut out = Vec::new(); let mut cur = Some(id); while let Some(o) = cur { if self.is_proxy(o) { - for k in self.own_keys(o)? { + let keys = self.own_keys(o)?; + let mut listed = HeldBytes::new(self); + listed.add(self, keys.iter().fold(0usize, |bytes, k| bytes.saturating_add(string_bytes(k.len()) + KEY_ENTRY_BYTES)))?; + for k in keys { self.use_fuel()?; if seen.contains(&k) { continue; } let Some(p) = self.get_own_property(o, &k)? else { continue }; + held.add(self, string_bytes(k.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; seen.insert(k.clone()); if p.enumerable() { out.push(k); @@ -3212,17 +3235,27 @@ impl Interp { for i in 0..len { self.use_fuel()?; let k = index_key(u32::try_from(i).unwrap_or(u32::MAX)); - if seen.insert(k.clone()) { + if !seen.contains(&k) { + held.add(self, string_bytes(k.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; + seen.insert(k.clone()); out.push(k); } } } - if is_array { + if is_array && !seen.contains(&key("length")) { + held.add(self, string_bytes(6) + KEY_ENTRY_BYTES)?; seen.insert(key("length")); } for _ in 0..self.object(o)?.props.len() { self.use_fuel()?; } + let retained = self + .object(o)? + .props + .iter() + .filter(|(k, _)| !seen.contains(*k)) + .fold(0usize, |bytes, (k, _)| bytes.saturating_add(string_bytes(k.len()) + 2 * KEY_ENTRY_BYTES)); + held.add(self, retained)?; let obj = self.object(o)?; for (k, p) in obj.props.iter() { if seen.insert(k.clone()) && p.enumerable() { diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index 01afb8ab00..65eb8e079a 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -41,6 +41,14 @@ impl Interp { } } + pub(crate) fn unwrapped_proxy_target(&mut self, mut id: ObjId) -> JsResult { + while let Some(target) = self.symbol_lookup_target(id)? { + self.use_fuel()?; + id = target; + } + Ok(id) + } + fn proxy_data(&self, id: ObjId) -> Option { match self.heap.object(id).map(|o| &o.class) { Some(Class::Proxy(p)) => Some(**p), @@ -229,13 +237,13 @@ impl Interp { /// [[GetOwnProperty]] of a proxy (section 9.5.5). pub(crate) fn proxy_get_own_property(&mut self, p: ObjId, k: &Key) -> JsResult> { self.proxy_op(p, "read a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "getOwnPropertyDescriptor")? else { return i.get_own_property(target, k) }; + let Some(trap) = i.proxy_trap(handler, "getOwnPropertyDescriptor")? else { return i.own_property(target, k) }; let name = i.key_value(k)?; let result = i.call_trap(&trap, handler, &[Value::Object(target), name])?; if !matches!(result, Value::Object(_) | Value::Undefined) { return Err(i.invariant("getOwnPropertyDescriptor", "returned a value that is neither an object nor undefined")); } - let target_prop = i.get_own_property(target, k)?; + let target_prop = i.own_property(target, k)?; if matches!(result, Value::Undefined) { let Some(current) = target_prop else { return Ok(None) }; if !current.configurable() { @@ -495,7 +503,8 @@ impl Interp { return Ok(true); } } - let own = match self.lookup(o, &k)? { + let Some(found) = self.lookup_for_set(o, &k)? else { return Ok(false) }; + let own = match found { Lookup::Proxy(p) => return self.proxy_set(p, &k, &v, receiver), Lookup::Found(prop) => prop, Lookup::Missing => Prop::Data { value: Value::Undefined, flags: OPEN }, diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 78f7785dea..d3facca9c5 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -190,6 +190,10 @@ fn a_revoked_proxy_refuses_every_operation() { truth( "var r = Proxy.revocable(function () {}, {}); var p = r.proxy; + var name = Object.getOwnPropertyDescriptor(r.revoke, 'name'); + var length = Object.getOwnPropertyDescriptor(r.revoke, 'length'); + var descriptors = name.value === '' && !name.writable && !name.enumerable && name.configurable && + length.value === 0 && !length.writable && !length.enumerable && length.configurable; r.revoke(); r.revoke(); var ops = [ @@ -202,7 +206,7 @@ fn a_revoked_proxy_refuses_every_operation() { ]; var all = true; for (var i = 0; i < ops.length; i++) all = all && type_error(ops[i]); - all && typeof p === 'function' && r.revoke.length === 0 && r.revoke() === undefined", + all && descriptors && typeof p === 'function' && r.revoke.length === 0 && r.revoke() === undefined", ); // A trap that revokes its own proxy still has its target for the checks that follow. truth( @@ -559,6 +563,134 @@ fn walk_limits() -> Limits { Limits { heap_bytes: 4 << 20, ..Limits::default() } } +#[test] +fn non_enumerable_names_retained_from_proxy_prototypes_count_against_the_heap_limit() { + let setup = "var hops = 0; + var handler = { + ownKeys: function () { var k = 'x'; while (k.length < 65536) k += k; return [k + hops]; }, + getOwnPropertyDescriptor: function () { return { value: 1, enumerable: false, configurable: true }; }, + getPrototypeOf: function () { hops++; return hops < 80 ? new Proxy({}, handler) : null; } + };"; + let control = + format!("{setup} var p = new Proxy({{}}, handler); while (p !== null) {{ Reflect.ownKeys(p); p = Reflect.getPrototypeOf(p); }} hops === 80"); + assert_eq!(Realm::with_options(es_options(), walk_limits()).run(&control), Ok(JsValue::Bool(true))); + let src = format!("{setup} for (var k in new Proxy({{}}, handler)) {{}} hops"); + assert_eq!(limit(&src, walk_limits()), LimitKind::Heap); +} + +#[test] +fn transparent_builtin_constructors_read_the_proxy_new_target_prototype() { + truth( + "var M = new Proxy(Map, {}), U = new Proxy(Uint8Array, {}); + var m = new M(), u = new U(3); + m.set('x', 7); u[1] = 9; + var reads = 0; + var P = new Proxy(M, { get: function (t, k) { if (k === 'prototype') reads++; return t[k]; } }); + var other = new P(); other.set('y', 8); + m.get('x') === 7 && u.length === 3 && u[1] === 9 && + Object.getPrototypeOf(m) === Map.prototype && Object.getPrototypeOf(u) === Uint8Array.prototype && + Object.getPrototypeOf(other) === Map.prototype && other.get('y') === 8 && reads === 1", + ); +} + +#[test] +fn proxy_integrity_operations_reject_symbol_properties() { + truth( + "var s = Symbol('x'), t = {}; t[s] = 1; + var p = new Proxy(new Proxy(t, {}), {}); + var freeze = type_error(function () { Object.freeze(p); }); + var seal = type_error(function () { Object.seal(p); }); + var extensible = Object.isExtensible(t); + Object.preventExtensions(t); + freeze && seal && extensible && type_error(function () { Object.isFrozen(p); }) && + type_error(function () { Object.isSealed(p); }) && Object.getOwnPropertyDescriptor(t, s).writable", + ); + truth( + "var p = new Proxy({}, {}); p[Symbol('x')] = 1; + type_error(function () { Object.freeze(p); }) && type_error(function () { Object.isFrozen(p); })", + ); + truth( + "var p = new Proxy({}, { ownKeys: function () { p[Symbol('x')] = 1; return []; } }); + type_error(function () { Object.freeze(p); })", + ); +} + +fn namespace_script(source: &str) -> Realm { + let mut realm = es(); + assert!(realm.run("var out = false;").is_ok()); + let mut load = |_: &str, _: &str| -> Result { + Ok(crate::LoadedModule { key: "exports.mjs".into(), source: Some("export let x = 1;".into()) }) + }; + assert_eq!(realm.run_module("main.mjs", source, crate::ModuleLimits::default(), &mut load), Ok(JsValue::Undefined)); + realm +} + +#[test] +fn assignment_stops_at_a_descriptor_before_a_namespace_prototype() { + let mut realm = namespace_script( + "import * as ns from './exports.mjs'; + var middle = Object.create(ns), o = Object.create(middle), receiver; + Object.defineProperty(middle, 'x', { value: 2, writable: true }); + Object.defineProperty(middle, 'saved', { value: 0, writable: true }); + Object.defineProperty(middle, 'y', { set: function (v) { receiver = this; this.saved = v; } }); + o.x = 3; o.y = 4; + var direct = o.x === 3 && ns.x === 1 && receiver === o && o.saved === 4; + var r = Object.create(middle); + out = direct && Reflect.set(middle, 'x', 5, r) && Reflect.set(middle, 'y', 6, r) && + r.x === 5 && receiver === r && r.saved === 6;", + ); + assert_eq!(realm.run("out"), Ok(JsValue::Bool(true))); +} + +#[test] +fn reflected_and_forwarded_namespace_writes_always_fail() { + let mut realm = es(); + assert!(realm.run("var out = false;").is_ok()); + let mut load = |_: &str, _: &str| -> Result { + Ok(crate::LoadedModule { key: "exports.mjs".into(), source: Some("export let x = 1;".into()) }) + }; + let source = "import * as ns from './exports.mjs'; + var targets = [ns, new Proxy(ns, {}), Object.create(ns)], r = {}, ok = true; + targets.forEach(function (t) { + ok = ok && !Reflect.set(t, 'x', 1) && !Reflect.set(t, 'missing', 2) && + !Reflect.set(t, 'x', 1, r) && !Reflect.set(t, 'missing', 2, r); + }); + out = ok && !('x' in r) && !('missing' in r) && ns.x === 1;"; + assert_eq!(realm.run_module("main.mjs", source, crate::ModuleLimits::default(), &mut load), Ok(JsValue::Undefined)); + assert_eq!(realm.run("out"), Ok(JsValue::Bool(true))); +} + +#[test] +fn reflected_and_forwarded_namespace_descriptors_preserve_the_temporal_dead_zone() { + let mut realm = es(); + assert!(realm.run("var out = [];").is_ok()); + let mut load = |_: &str, specifier: &str| -> Result { + let (key, source) = if specifier == "main" { + ("main.mjs", None) + } else { + ( + "cycle.mjs", + Some( + "import * as ns from 'main'; + var p = new Proxy(ns, {}); + [function () { Reflect.getOwnPropertyDescriptor(ns, 'x'); }, + function () { Reflect.getOwnPropertyDescriptor(p, 'x'); }, + function () { Object.getOwnPropertyDescriptor(p, 'x'); }].forEach(function (f) { + try { f(); out.push(false); } catch (e) { out.push(e instanceof ReferenceError); } + });" + .into(), + ), + ) + }; + Ok(crate::LoadedModule { key: key.into(), source }) + }; + assert_eq!( + realm.run_module("main.mjs", "import './cycle.mjs'; export let x = 1;", crate::ModuleLimits::default(), &mut load), + Ok(JsValue::Undefined) + ); + assert_eq!(realm.run("out.join()"), Ok(JsValue::String("true,true,true".into()))); +} + #[test] fn a_prototype_walk_keeps_only_the_prototype_it_has_reached() { // Declaring a function without the option reads the global object's inherited property. diff --git a/docs/mcp.md b/docs/mcp.md index 974a3dd3b7..ea987f0db5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2835,10 +2835,18 @@ throws a `TypeError`, since that engine was made without the ECMAScript 2015 bui an engine that `#targetengine` keeps reads each run the way that run's script does. A `.js` script also has the globals `Proxy`, with `Proxy.revocable`, and `Reflect` (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. A trap is a script call: it takes fuel and counts against the limit on nested calls, -the copy of the property name it is given counts against the heap limit, and +the copy of the property name it is given and the names retained during a `for-in` prototype walk count against the heap limit, and a trap result that breaks one of the proxy invariants, or any operation on a revoked proxy, throws a `TypeError`. A proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets -`Proxy` and `Reflect` at its first `.js` run and keeps them for later `.jsx` runs. A +`Proxy` and `Reflect` at its first `.js` run and keeps them for later `.jsx` runs. +An empty-handler proxy forwards construction of built-ins, including `Map` and typed arrays, and reads +the proxy's `prototype` for the constructed object. `Object.freeze`, `Object.seal`, `Object.isFrozen` +and `Object.isSealed` throw `TypeError` for a proxy when it or any of its proxy targets has symbol properties. +`Reflect.set` and a write a proxy forwards return false when the lookup reaches a module namespace +object before it finds the property. `Reflect.getOwnPropertyDescriptor` +and forwarded proxy descriptors throw `ReferenceError` for an uninitialized namespace export. +The function returned as `Proxy.revocable(...).revoke` has an own empty-string `name` and a `length` of zero; +both properties are nonwritable, nonenumerable and configurable. A `.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there `yield` is a name like any other. A `.js` file `.jsx` file and a `source` string read ES5.1 when run as scripts. With `module: true`, they run as modules and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fab1a56ca6..50fd2f27cd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1193,7 +1193,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The collector retains tagged-template cache entries only while the site's code is reachable. - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. - `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`. - - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file both globals; a `.jsx` file and a `source` string have neither in a new engine or in an engine that has not run a `.js` file. An engine that `#targetengine` keeps gets both globals at its first `.js` run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and the first `.js` run does not replace it. `cargo xtask test262` runs the suite's `Proxy` and `Reflect` tests whose features are present: 573 of 663 runs pass with the option (0 without it). Of the 90 failing runs, 4 do not parse because the tests use method definitions, and 86 expect function `name` properties and a configurable function `length`, `Object.setPrototypeOf`, and integer keys listed before other keys, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file both globals; a `.jsx` file and a `source` string have neither in a new engine or in an engine that has not run a `.js` file. An engine that `#targetengine` keeps gets both globals at its first `.js` run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and the first `.js` run does not replace it. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.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`. From 457661418b2b9c4e5e5b6667a35e50cf91d2d97f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:56:29 -0800 Subject: [PATCH 17/50] JavaScript: Reflect.ownKeys lists index keys first and proxy writes skip typed-array gaps Reflect.ownKeys and a proxy without an ownKeys trap list integer-index keys in ascending order first. Reflect.construct takes another newTarget for Map, Set and typed arrays, for-in reads each proxy key's descriptor once, deleting a with binding runs only the deleteProperty trap, a write past a typed array's view on the prototype chain is ignored, and a target's descriptor stays reachable while a trap runs. The crate documentation states that traps take string keys only. --- crates/js/src/builtins/reflect.rs | 2 +- crates/js/src/class_ops.rs | 2 +- crates/js/src/interp.rs | 59 ++++++++++------ crates/js/src/lib.rs | 4 +- crates/js/src/proxy.rs | 17 +++-- crates/js/src/proxy_tests.rs | 114 ++++++++++++++++++++++++++++++ docs/mcp.md | 11 ++- 7 files changed, 177 insertions(+), 32 deletions(-) diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index 89af0e1a20..ad1bdbabc7 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -202,7 +202,7 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe /// `Reflect.ownKeys(target)` (section 26.1.10): every own property name, enumerable or not. fn own_keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "ownKeys")?; - let names = interp.own_keys(o)?; + let names = interp.ecma_own_keys(o)?; names_array(interp, names) } diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 529226671c..8e9b9a1f53 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -304,7 +304,7 @@ impl Interp { Some(Func::Native { f: native, constructor: true, name, .. }) => { // `Proxy` does not read `new.target` (section 26.2.1.1). let subclass = nt != callee && name != "Proxy"; - if subclass && self.unwrapped_proxy_target(nt)? != callee && !self.subclassable(callee)? { + if !boundary && subclass && self.unwrapped_proxy_target(nt)? != callee && !self.subclassable(callee)? { return Err(self.type_error("this built-in cannot be subclassed")); } let intrinsic = match self.get_own_property(callee, &key("prototype"))? { diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 30eb8b40cf..deb59fe3bd 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1671,7 +1671,7 @@ impl Interp { _ => return internal("not a declarative environment"), }, Resolved::Obj { object, with_this } => { - let own = self.get_own_property(object, &name)?.is_some(); + let own = !with_this && object == self.global && self.get_own_property(object, &name)?.is_some(); let deleted = self.delete(object, &name, false)?; // A global variable whose own property is deleted through the global environment // no longer stops a `let` or `const` of its name (ECMA-262 2015 section 8.1.1.4.7). @@ -1824,21 +1824,21 @@ impl Interp { Ok(self.lookup_on(id, k)?.1) } - pub(crate) fn lookup_for_set(&self, id: ObjId, k: &[u16]) -> JsResult> { + pub(crate) fn lookup_for_set(&self, id: ObjId, k: &[u16]) -> JsResult { let mut cur = Some(id); let mut steps = 0usize; while let Some(o) = cur { if self.is_proxy(o) { - return Ok(Some(Lookup::Proxy(o))); + return Ok(SetLookup::Proxy(o)); } if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) { - return Ok(None); + return Ok(SetLookup::ReadOnly); } if let Some(p) = self.ordinary_own_property(o, k)? { - return Ok(Some(Lookup::Found(p))); + return Ok(SetLookup::Found(p)); } if crate::builtins::binary::typed_key(self, o, k).is_some() { - break; + return Ok(SetLookup::Ignored); } cur = self.object(o)?.proto; steps += 1; @@ -1846,7 +1846,7 @@ impl Interp { return internal("prototype chain too long"); } } - Ok(Some(Lookup::Missing)) + Ok(SetLookup::Missing) } /// [`Self::lookup`], with the object the search stopped at: the one that has the property, or @@ -2281,6 +2281,18 @@ impl Interp { Ok(out) } + pub(crate) fn ecma_own_keys(&mut self, id: ObjId) -> JsResult> { + let mut keys = self.own_keys(id)?; + if !self.is_proxy(id) { + if matches!(self.object(id)?.class, Class::Array { .. }) { + let length = keys.pop().ok_or_else(|| Abrupt::Internal("array has no length key".into()))?; + keys.insert(0, length); + } + keys.sort_by_key(|k| array_index(k).map_or((1, 0), |n| (0, n))); + } + Ok(keys) + } + /// Runs `f` with `values` kept reachable for any collection it starts. pub(crate) fn rooted(&mut self, values: &[Value], f: impl FnOnce(&mut Self) -> JsResult) -> JsResult { let mark = self.temp_roots.len(); @@ -2327,21 +2339,20 @@ impl Interp { } let proto = self.object(id)?.proto; let lookup = match proto { - Some(p) => match self.lookup_for_set(p, &k)? { - Some(found) => Some(found), - None => return self.reject(throw, &k, "a module namespace object is read-only"), - }, - None => None, + Some(p) => self.lookup_for_set(p, &k)?, + None => SetLookup::Missing, }; let inherited = match lookup { - Some(Lookup::Proxy(p)) => { + SetLookup::ReadOnly => return self.reject(throw, &k, "a module namespace object is read-only"), + SetLookup::Ignored => return Ok(()), + SetLookup::Proxy(p) => { if !self.set_with_receiver(p, k.clone(), v, &Value::Object(id))? { return self.reject(throw, &k, "the proxy did not set it"); } return Ok(()); } - Some(Lookup::Found(prop)) => Some(prop), - Some(Lookup::Missing) | None => None, + SetLookup::Found(prop) => Some(prop), + SetLookup::Missing => None, }; match inherited { Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), @@ -3192,9 +3203,8 @@ impl Interp { } /// [`Self::enumerable_keys`] after the XML case. A proxy on the chain gives its names with its - /// `ownKeys` trap, whether each is enumerable with its `getOwnPropertyDescriptor` trap and the - /// next object with its `getPrototypeOf` trap, which `temp_roots[slot]` keeps reachable. A name - /// whose descriptor trap gives `undefined` does not hide the same name further up the chain. + /// `ownKeys` trap and the next object with its `getPrototypeOf` trap, which + /// `temp_roots[slot]` keeps reachable. Descriptors are checked when iteration reaches each name. fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult> { let mut seen = std::collections::HashSet::new(); let mut held = HeldBytes::new(self); @@ -3210,12 +3220,9 @@ impl Interp { if seen.contains(&k) { continue; } - let Some(p) = self.get_own_property(o, &k)? else { continue }; held.add(self, string_bytes(k.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; seen.insert(k.clone()); - if p.enumerable() { - out.push(k); - } + out.push(k); } cur = self.get_prototype_of(o)?; if let Some(root) = self.temp_roots.get_mut(slot) { @@ -4981,6 +4988,14 @@ pub(crate) enum Lookup { Missing, } +pub(crate) enum SetLookup { + Found(Prop), + Proxy(ObjId), + Missing, + ReadOnly, + Ignored, +} + /// What a proxy's [[Call]] or [[Construct]] did. pub(crate) enum ProxyCall { /// The proxy has no trap for it: the target is called or constructed instead. diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 9a70abf4d4..f812193c13 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -124,7 +124,9 @@ //! //! With [`Options::es2015`], the realm also has `Proxy`, with `Proxy.revocable`, and `Reflect`, as //! ECMAScript 2020 defines them (sections 26.1 and 26.2 and 9.5, -//! ). PROXYKEYS +//! ), with string property names: a trap is given only +//! string keys, `Reflect.ownKeys` lists only string keys, and a Symbol key read through a proxy +//! goes to its target without a trap. #![forbid(unsafe_code)] pub mod ast; diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index 65eb8e079a..354aa391e5 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -19,7 +19,7 @@ use crate::builtins::object::{from_desc, to_desc}; use crate::heap::{ CONFIGURABLE, Class, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, PROXY_BYTES, Prop, ProxyData, WRITABLE, key, string_bytes, }; -use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, Interp, JsResult, KEY_ENTRY_BYTES, Lookup, ProxyCall, merge_desc, same_value}; +use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, Interp, JsResult, KEY_ENTRY_BYTES, ProxyCall, SetLookup, merge_desc, same_value}; use crate::value::{Str, Value, index_key}; /// The most names an `ownKeys` trap may give. @@ -244,6 +244,9 @@ impl Interp { return Err(i.invariant("getOwnPropertyDescriptor", "returned a value that is neither an object nor undefined")); } let target_prop = i.own_property(target, k)?; + if let Some(prop) = &target_prop { + i.temp_roots.extend(desc_values(&prop_desc(prop))); + } if matches!(result, Value::Undefined) { let Some(current) = target_prop else { return Ok(None) }; if !current.configurable() { @@ -403,7 +406,7 @@ impl Interp { /// unit of fuel and counts against the heap limit while the list is built. pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult> { self.proxy_op(p, "list the properties of", &[], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.own_keys(target) }; + let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.ecma_own_keys(target) }; let result = i.call_trap(&trap, handler, &[Value::Object(target)])?; let mut held = HeldBytes::new(i); let keys = i.trap_key_list(&result, &mut held)?; @@ -503,11 +506,13 @@ impl Interp { return Ok(true); } } - let Some(found) = self.lookup_for_set(o, &k)? else { return Ok(false) }; + let found = self.lookup_for_set(o, &k)?; let own = match found { - Lookup::Proxy(p) => return self.proxy_set(p, &k, &v, receiver), - Lookup::Found(prop) => prop, - Lookup::Missing => Prop::Data { value: Value::Undefined, flags: OPEN }, + SetLookup::ReadOnly => return Ok(false), + SetLookup::Ignored => return Ok(true), + SetLookup::Proxy(p) => return self.proxy_set(p, &k, &v, receiver), + SetLookup::Found(prop) => prop, + SetLookup::Missing => Prop::Data { value: Value::Undefined, flags: OPEN }, }; match own { Prop::Accessor { set: Some(s), .. } => { diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index d3facca9c5..eac8c9c645 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -861,3 +861,117 @@ fn a_super_assignment_runs_the_set_trap_of_a_proxy_on_the_chain() { seen.join() === 'x' && !o.hasOwnProperty('x')", ); } + +#[test] +fn reflect_construct_allows_distinct_new_targets_for_collections_and_typed_arrays() { + truth( + "function Custom() {} Custom.prototype = { custom: true }; + var m = Reflect.construct(Map, [], Custom), s = Reflect.construct(Set, [], Custom); + Map.prototype.set.call(m, 'x', 7); Set.prototype.add.call(s, 8); + var u = Reflect.construct(Uint8Array, [2], Custom); u[1] = 9; + var proxied = Reflect.construct(new Proxy(Map, {}), [], Custom); + Object.getPrototypeOf(m) === Custom.prototype && Map.prototype.get.call(m, 'x') === 7 && + Object.getPrototypeOf(s) === Custom.prototype && Set.prototype.has.call(s, 8) && + Object.getPrototypeOf(u) === Custom.prototype && u[1] === 9 && + Object.getPrototypeOf(proxied) === Custom.prototype && + type_error(function () { class M extends Map {} new M(); }) && + type_error(function () { class U extends Uint8Array {} new U(1); })", + ); +} + +#[test] +fn for_in_checks_proxy_descriptors_only_when_each_candidate_is_reached() { + truth( + "var calls = [], seen = [], first = true; + var p = new Proxy({}, { + ownKeys: function () { return ['x', 'y']; }, + getOwnPropertyDescriptor: function (t, k) { + calls.push(k); + if (!first) return undefined; + first = false; + return { value: 1, enumerable: true, configurable: true }; + } + }); + for (var k in p) { seen.push(k); calls.push('body'); } + seen.join() === 'x' && calls.join() === 'x,body,y'", + ); +} + +#[test] +fn reflect_own_keys_orders_indices_and_preserves_proxy_trap_order() { + truth( + "var a = []; a[2] = 2; a[1] = 1; a.label = 'a'; + var o = {}; o.z = 0; o[10] = 10; o[2] = 2; o['01'] = 1; o['4294967295'] = 3; o.a = 4; + var p = new Proxy(a, { ownKeys: function () { return ['label', '2', 'length', '1']; } }); + Reflect.ownKeys(a).join() === '1,2,length,label' && + Reflect.ownKeys(o).join() === '2,10,z,01,4294967295,a' && + Reflect.ownKeys(new Proxy(a, {})).join() === '1,2,length,label' && + Reflect.ownKeys(p).join() === 'label,2,length,1' && + Reflect.ownKeys(new Proxy(p, {})).join() === 'label,2,length,1'", + ); +} + +#[test] +fn deleting_a_with_binding_does_not_read_its_descriptor() { + truth( + "var deleted = false, result = false; + var p = new Proxy({}, { + has: function (t, k) { return k === 'x'; }, + getOwnPropertyDescriptor: function () { throw new Error('descriptor'); }, + deleteProperty: function (t, k) { deleted = k === 'x'; return true; } + }); + with (p) { result = delete x; } + result && deleted", + ); +} + +#[test] +fn target_descriptor_values_stay_reachable_after_a_nested_proxy_is_revoked() { + use crate::builtins::native; + use crate::heap::{HIDDEN, NativeKind, Prop, key}; + use crate::value::Value; + + fn descriptor_alive(interp: &mut crate::interp::Interp, _: Value, _: &[Value], _: bool) -> crate::interp::JsResult { + let marker = key("savedDescriptorMarker"); + Ok(Value::Bool(interp.heap.object_ids().iter().any(|&id| interp.heap.object(id).is_some_and(|o| o.props.get(&marker).is_some())))) + } + + for field in ["value", "get", "set"] { + let mut realm = es(); + let interp = realm.interp(); + let probe = native(interp, "descriptorAlive", descriptor_alive, 0, NativeKind::Plain, false).unwrap(); + interp.define(interp.global, key("descriptorAlive"), Prop::Data { value: Value::Object(probe), flags: HIDDEN }).unwrap(); + let src = format!( + "var pair, alive = false; + (function () {{ + var saved = function () {{}}; saved.savedDescriptorMarker = true; + var t = {{}}; Object.defineProperty(t, 'x', {{ {field}: saved, configurable: true }}); + pair = Proxy.revocable(t, {{ isExtensible: function () {{ pair.revoke(); return true; }} }}); + }})(); + var p = new Proxy(pair.proxy, {{ getOwnPropertyDescriptor: function () {{ return {{ + get enumerable() {{ var junk = [{{}}, {{}}]; alive = descriptorAlive(); return false; }}, configurable: true + }}; }} }}); + Reflect.getOwnPropertyDescriptor(p, 'x'); alive" + ); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let result = realm.run(&src); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert_eq!(result, Ok(JsValue::Bool(true)), "{field}"); + assert!(realm.interp().heap.collections > 0); + } +} + +#[test] +fn typed_array_prototypes_ignore_invalid_numeric_indices_during_assignment() { + truth( + "var a = new Uint8Array(1), o = Object.create(a), r = {}, converted = false; + var value = { valueOf: function () { converted = true; return 9; } }; + var ok = Reflect.set(o, '2', value) && Reflect.set(o, '-0', 9) && Reflect.set(o, 'NaN', 9) && + Reflect.set(o, 'Infinity', 9) && Reflect.set(o, '0.5', 9) && Reflect.set(o, '2', 9, r); + o[3] = 9; + ok && !converted && !o.hasOwnProperty('2') && !o.hasOwnProperty('-0') && !o.hasOwnProperty('NaN') && + !o.hasOwnProperty('Infinity') && !o.hasOwnProperty('0.5') && !o.hasOwnProperty('3') && !r.hasOwnProperty('2') && + Reflect.set(o, '0', 7) && o.hasOwnProperty('0') && o[0] === 7 && a[0] === 0 && + Reflect.set(o, 'label', 8) && o.label === 8", + ); +} diff --git a/docs/mcp.md b/docs/mcp.md index ea987f0db5..8a368ddcdf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2840,7 +2840,16 @@ a trap result that breaks one of the proxy invariants, or any operation on a rev proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets `Proxy` and `Reflect` at its first `.js` run and keeps them for later `.jsx` runs. An empty-handler proxy forwards construction of built-ins, including `Map` and typed arrays, and reads -the proxy's `prototype` for the constructed object. `Object.freeze`, `Object.seal`, `Object.isFrozen` +the proxy's `prototype` for the constructed object. `Reflect.construct` also accepts a distinct constructor +as `newTarget` for `Map`, `Set` and typed arrays and uses its `prototype` for the new object. +`Reflect.ownKeys` returns string keys only. Ordinary targets list array-index keys in ascending order, +then other strings in insertion order; an array's `length` precedes its other non-index strings. +A proxy's `ownKeys` trap determines its key order. A `for-in` loop checks each proxy candidate's descriptor +when iteration reaches that name. Deleting a binding in a `with` scope calls the proxy's `deleteProperty` +trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay +reachable during proxy callbacks, including callbacks that revoke a nested target proxy. +`Reflect.set` and ordinary assignment ignore invalid numeric indices found on a typed-array prototype +without creating a property on the receiver. `Object.freeze`, `Object.seal`, `Object.isFrozen` and `Object.isSealed` throw `TypeError` for a proxy when it or any of its proxy targets has symbol properties. `Reflect.set` and a write a proxy forwards return false when the lookup reaches a module namespace object before it finds the property. `Reflect.getOwnPropertyDescriptor` From f3b3cbfe67d6641d2aed904a7ce9a63bdd0c607d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 22:16:56 -0800 Subject: [PATCH 18/50] JavaScript: proxies keep revocation, namespace and collection rules, and key lists stay counted A revoked proxy no longer gives its own Symbol properties, the reflect extension reads proxies without running traps, key lists a proxy gives stay counted against the heap while callers use them, has through a proxy of a host collection asks the collection, a proxy's invariant checks keep a namespace's uninitialized-export errors, and a binary constructor checks its arguments before it reads newTarget's prototype. Trap arguments stay rooted while a trap runs. --- crates/js/src/builtins/binary.rs | 54 +++++++++- crates/js/src/builtins/json.rs | 8 +- crates/js/src/builtins/object.rs | 20 ++-- crates/js/src/builtins/reflect.rs | 2 +- crates/js/src/class_ops.rs | 10 +- crates/js/src/interp.rs | 52 +++++++-- crates/js/src/proxy.rs | 34 +++--- crates/js/src/proxy_tests.rs | 169 ++++++++++++++++++++++++++++++ crates/js/src/reflect.rs | 3 + crates/js/src/symbol.rs | 5 +- docs/mcp.md | 17 ++- 11 files changed, 330 insertions(+), 44 deletions(-) diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index b18a0cda67..5a48799007 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -429,8 +429,48 @@ fn array_buffer_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing if !constructing { return Err(interp.type_error("ArrayBuffer must be called with new")); } + array_buffer_with_target(interp, args, None) +} + +fn array_buffer_with_target(interp: &mut Interp, args: &[Value], new_target: Option) -> JsResult { let len = to_index(interp, &arg(args, 0), "the length")?; - new_buffer(interp, len, 0).map(Value::Object) + let fallback = interp.intrinsics.es2015.array_buffer_proto; + let proto = match new_target { + Some(nt) => interp.prototype_from(nt, fallback)?, + None => fallback, + }; + interp.rooted(&[Value::Object(proto)], |i| { + let buffer = new_buffer(i, len, 0)?; + i.object_mut(buffer)?.proto = Some(proto); + Ok(Value::Object(buffer)) + }) +} + +pub(crate) fn defers_prototype(interp: &Interp, intrinsic: Option, args: &[Value]) -> bool { + let i = &interp.intrinsics.es2015; + intrinsic.is_some_and(|p| { + p == i.array_buffer_proto || p == i.data_view_proto || (i.typed_protos.contains(&p) && !matches!(arg(args, 0), Value::Object(_))) + }) +} + +pub(crate) fn construct_with_target(interp: &mut Interp, intrinsic: Option, args: &[Value], new_target: ObjId) -> JsResult { + let i = &interp.intrinsics.es2015; + if intrinsic == Some(i.array_buffer_proto) { + return array_buffer_with_target(interp, args, Some(new_target)); + } + if intrinsic == Some(i.data_view_proto) { + return data_view_with_target(interp, args, Some(new_target)); + } + let elem = Elem::ALL.into_iter().find(|e| intrinsic == Some(typed_proto(interp, *e))); + let Some(elem) = elem else { return Err(Abrupt::Internal("not a binary constructor".into())) }; + let len = to_index(interp, &arg(args, 0), "the length")?; + let fallback = typed_proto(interp, elem); + let proto = interp.prototype_from(new_target, fallback)?; + interp.rooted(&[Value::Object(proto)], |i| { + let view = new_typed(i, elem, len)?; + i.object_mut(view)?.proto = Some(proto); + Ok(Value::Object(view)) + }) } /// `ArrayBuffer.isView` (section 24.1.3.1). @@ -516,6 +556,10 @@ fn data_view_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: b if !constructing { return Err(interp.type_error("DataView must be called with new")); } + data_view_with_target(interp, args, None) +} + +fn data_view_with_target(interp: &mut Interp, args: &[Value], new_target: Option) -> JsResult { let buffer = match arg(args, 0).as_object() { Some(o) if bytes(interp, o).is_some() => o, _ => return Err(interp.type_error("the first argument of DataView must be an ArrayBuffer")), @@ -532,8 +576,12 @@ fn data_view_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: b if offset.saturating_add(view_len) > len { return Err(interp.throw(ErrorType::Range, "the view does not fit in the buffer")); } - interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; - let proto = interp.intrinsics.es2015.data_view_proto; + let fallback = interp.intrinsics.es2015.data_view_proto; + let proto = match new_target { + Some(nt) => interp.prototype_from(nt, fallback)?, + None => fallback, + }; + interp.rooted(&[Value::Object(buffer), Value::Object(proto)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(view_len).unwrap_or(0), elem: Elem::Uint8 }; Ok(Value::Object(new_view(interp, Class::DataView(Box::new(view)), proto))) } diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index f0b5daf9e3..8e4d027574 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -415,6 +415,7 @@ enum Item { struct Writing { obj: ObjId, keys: Vec, + _held_keys: Option, array: bool, next: usize, count: usize, @@ -630,6 +631,7 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J } // A proxy whose target is an array is written as one (ECMA-262 2020 section 24.5.2.1). let array = interp.is_array(&Value::Object(o))?; + let mut held_keys = None; let keys = if array { let len = length_of(interp, o)?; // Every element is written as at least `null` and a comma, so a length that cannot fit @@ -647,8 +649,10 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J } else if let Some(list) = &settings.properties { list.clone() } else { + let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?; + held_keys = Some(held); let mut keys = Vec::new(); - for k in interp.own_keys(o)? { + for k in names { if interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) { keys.push(k); } @@ -659,7 +663,7 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J let stepback = w.indent.len(); w.indent.extend_from_slice(&settings.gap); w.out.push_str(interp, if array { "[" } else { "{" })?; - w.stack.push(Writing { obj: o, keys, array, next: 0, count: 0, stepback }); + w.stack.push(Writing { obj: o, keys, _held_keys: held_keys, array, next: 0, count: 0, stepback }); Ok(()) } diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index a598dd5f6a..599519c0e0 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -135,7 +135,7 @@ fn descriptor_object(interp: &mut Interp, prop: &Prop) -> JsResult { } /// An array of the names, kept reachable while it is filled. -pub(crate) fn names_array(interp: &mut Interp, names: Vec) -> JsResult { +pub(crate) fn names_array(interp: &mut Interp, names: impl IntoIterator) -> JsResult { let a = new_array(interp, 0)?; interp.rooted(&[Value::Object(a)], |interp| { for (i, k) in names.into_iter().enumerate() { @@ -148,10 +148,11 @@ pub(crate) fn names_array(interp: &mut Interp, names: Vec) -> JsResult JsResult> { - let mut keys: Vec = interp.own_keys(o)?.into_iter().map(PropKey::Str).collect(); +fn own_prop_keys(interp: &mut Interp, o: ObjId) -> JsResult<(Vec, crate::interp::HeldBytes)> { + let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?; + let mut keys: Vec = names.into_iter().map(PropKey::Str).collect(); keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym)); - Ok(keys) + Ok((keys, held)) } /// `Object.getPrototypeOf` (section 15.2.3.2). @@ -224,7 +225,7 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { interp.temp_roots.push(Value::Object(p)); let r = (|| { let mut descs = Vec::new(); - let keys = own_prop_keys(interp, p)?; + let (keys, _held) = own_prop_keys(interp, p)?; // A getter can delete a Symbol-keyed property already read, so the Symbols stay rooted // until they are defined on `o`. for k in &keys { @@ -263,7 +264,7 @@ fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { let what = if freeze { "frozen" } else { "sealed" }; return Err(interp.type_error(&format!("the object cannot be {what}: it did not stop being extensible"))); } - let keys = own_prop_keys(interp, o)?; + let (keys, _held) = own_prop_keys(interp, o)?; check_integrity_symbols(interp, o)?; for k in keys { interp.use_fuel()?; @@ -311,7 +312,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { if interp.is_extensible(o)? { return Ok(Value::Bool(false)); } - let keys = own_prop_keys(interp, o)?; + let (keys, _held) = own_prop_keys(interp, o)?; check_integrity_symbols(interp, o)?; for k in keys { interp.use_fuel()?; @@ -357,13 +358,14 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { + let crate::interp::HeldKeys { keys, held } = interp.own_keys(o)?; let mut names = Vec::new(); - for k in interp.own_keys(o)? { + for k in keys { interp.use_fuel()?; if interp.own_property(o, &k)?.is_some_and(|p| p.enumerable()) { names.push(k); } } - names_array(interp, names) + names_array(interp, crate::interp::HeldKeys { keys: names, held }) }) } diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index ad1bdbabc7..3f649a3673 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -190,7 +190,7 @@ fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J /// `Reflect.has(target, propertyKey)` (section 26.1.8). fn has(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "has")?; - interp.with_key(&arg(args, 1), |interp, k| interp.has_property(o, &k)).map(Value::Bool) + interp.with_key(&arg(args, 1), |interp, k| interp.has_property_indexed(o, &k)).map(Value::Bool) } /// `Reflect.isExtensible(target)` (section 26.1.9). diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 8e9b9a1f53..c691db98bd 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -176,7 +176,7 @@ impl Interp { } /// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14). - fn prototype_from(&mut self, new_target: ObjId, fallback: ObjId) -> JsResult { + pub(crate) fn prototype_from(&mut self, new_target: ObjId, fallback: ObjId) -> JsResult { match self.get_from(new_target, &key("prototype"), &Value::Object(new_target))? { Value::Object(p) => Ok(p), _ => Ok(fallback), @@ -317,11 +317,15 @@ impl Interp { let fallback = self.intrinsics.object_proto; let proto = self.prototype_from(nt, fallback)?; Value::Object(self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)))) + } else if subclass && crate::builtins::binary::defers_prototype(self, intrinsic, &args) { + let held = self.held_bytes; + let r = crate::builtins::binary::construct_with_target(self, intrinsic, &args, nt); + self.held_bytes = held; + r? } else { // `Number`, `String`, `Date` and `Function` convert their arguments before // `prototype` is read (sections 20.1.1.1, 21.1.1.1, 20.4.2 and 19.2.1.1.1), so - // a conversion that throws reads nothing from `new.target`; the others read it - // first. + // a conversion that throws reads nothing from `new.target`. let converts_first = { let i = &self.intrinsics; intrinsic.is_some_and(|p| [i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p)) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index deb59fe3bd..24daab16cc 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -483,6 +483,47 @@ impl Drop for HeldBytes { } } +pub(crate) struct HeldKeys { + pub(crate) keys: Vec, + pub(crate) held: HeldBytes, +} + +impl std::ops::Deref for HeldKeys { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.keys + } +} + +impl std::ops::DerefMut for HeldKeys { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.keys + } +} + +pub(crate) struct HeldKeyIter { + keys: std::vec::IntoIter, + _held: HeldBytes, +} + +impl Iterator for HeldKeyIter { + type Item = Key; + + fn next(&mut self) -> Option { + self.keys.next() + } +} + +impl IntoIterator for HeldKeys { + type Item = Key; + type IntoIter = HeldKeyIter; + + fn into_iter(self) -> Self::IntoIter { + HeldKeyIter { keys: self.keys.into_iter(), _held: self.held } + } +} + /// The least heap size a collection waits for. const MIN_GC_BYTES: usize = 1 << 20; @@ -2248,7 +2289,7 @@ impl Interp { /// `length` first, then the rest in the order they were added, which is the order `for-in` /// visits them, then an array's `length`. Each name takes a unit of fuel, and the heap for the /// list is checked first. A proxy's names come from its `ownKeys` trap. - pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult> { + pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult { if self.is_proxy(id) { return self.proxy_own_keys(id); } @@ -2262,7 +2303,8 @@ impl Interp { let is_string = matches!(o.class, Class::String(_)); let is_array = matches!(o.class, Class::Array { .. }); let count = o.props.len().saturating_add(string_len).saturating_add(usize::from(is_string || is_array)); - self.reserve_heap(index_keys_bytes(string_len).saturating_add(count.saturating_mul(KEY_ENTRY_BYTES)))?; + let mut held = HeldBytes::new(self); + held.add(self, index_keys_bytes(string_len).saturating_add(count.saturating_mul(KEY_ENTRY_BYTES)))?; let mut out = Vec::with_capacity(count); for i in 0..string_len { self.use_fuel()?; @@ -2278,10 +2320,10 @@ impl Interp { if is_array { out.push(key("length")); } - Ok(out) + Ok(HeldKeys { keys: out, held }) } - pub(crate) fn ecma_own_keys(&mut self, id: ObjId) -> JsResult> { + pub(crate) fn ecma_own_keys(&mut self, id: ObjId) -> JsResult { let mut keys = self.own_keys(id)?; if !self.is_proxy(id) { if matches!(self.object(id)?.class, Class::Array { .. }) { @@ -3213,8 +3255,6 @@ impl Interp { while let Some(o) = cur { if self.is_proxy(o) { let keys = self.own_keys(o)?; - let mut listed = HeldBytes::new(self); - listed.add(self, keys.iter().fold(0usize, |bytes, k| bytes.saturating_add(string_bytes(k.len()) + KEY_ENTRY_BYTES)))?; for k in keys { self.use_fuel()?; if seen.contains(&k) { diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index 354aa391e5..bbde3c6933 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -19,7 +19,7 @@ use crate::builtins::object::{from_desc, to_desc}; use crate::heap::{ CONFIGURABLE, Class, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, PROXY_BYTES, Prop, ProxyData, WRITABLE, key, string_bytes, }; -use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, Interp, JsResult, KEY_ENTRY_BYTES, ProxyCall, SetLookup, merge_desc, same_value}; +use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, HeldKeys, Interp, JsResult, KEY_ENTRY_BYTES, ProxyCall, SetLookup, merge_desc, same_value}; use crate::value::{Str, Value, index_key}; /// The most names an `ownKeys` trap may give. @@ -112,7 +112,11 @@ impl Interp { /// Calls the trap with the handler as `this`, keeping its result rooted. fn call_trap(&mut self, trap: &Value, handler: ObjId, args: &[Value]) -> JsResult { - let v = self.call(trap, &Value::Object(handler), args)?; + let mark = self.temp_roots.len(); + self.temp_roots.extend(args.iter().cloned()); + let result = self.call(trap, &Value::Object(handler), args); + self.temp_roots.truncate(mark); + let v = result?; self.temp_roots.push(v.clone()); Ok(v) } @@ -296,7 +300,7 @@ impl Interp { if !i.call_trap(&trap, handler, &[Value::Object(target), name, desc_obj])?.truthy() { return Ok(false); } - let target_prop = i.get_own_property(target, k)?; + let target_prop = i.own_property(target, k)?; let extensible = i.is_extensible(target)?; let setting_config_false = desc.configurable == Some(false); let Some(current) = target_prop else { @@ -328,10 +332,10 @@ impl Interp { /// [[HasProperty]] of a proxy (section 9.5.7). pub(crate) fn proxy_has(&mut self, p: ObjId, k: &Key) -> JsResult { self.proxy_op(p, "test a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "has")? else { return i.has_property(target, k) }; + let Some(trap) = i.proxy_trap(handler, "has")? else { return i.has_property_indexed(target, k) }; let name = i.key_value(k)?; let found = i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy(); - if !found && let Some(current) = i.get_own_property(target, k)? { + if !found && let Some(current) = i.own_property(target, k)? { if !current.configurable() { return Err(i.invariant("has", "hid a non-configurable property of its target")); } @@ -349,7 +353,7 @@ impl Interp { let Some(trap) = i.proxy_trap(handler, "get")? else { return i.get_from(target, k, receiver) }; let name = i.key_value(k)?; let v = i.call_trap(&trap, handler, &[Value::Object(target), name, receiver.clone()])?; - match i.get_own_property(target, k)? { + match i.own_property(target, k)? { Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(&v, &value) => { Err(i.invariant("get", "gave a value other than its target's non-configurable, read-only property")) } @@ -369,7 +373,7 @@ impl Interp { if !i.call_trap(&trap, handler, &[Value::Object(target), name, v.clone(), receiver.clone()])?.truthy() { return Ok(false); } - match i.get_own_property(target, k)? { + match i.own_property(target, k)? { Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(v, &value) => { Err(i.invariant("set", "set a value other than its target's non-configurable, read-only property")) } @@ -389,7 +393,7 @@ impl Interp { if !i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy() { return Ok(false); } - let Some(current) = i.get_own_property(target, k)? else { return Ok(true) }; + let Some(current) = i.own_property(target, k)? else { return Ok(true) }; if !current.configurable() { return Err(i.invariant("deleteProperty", "deleted a non-configurable property of its target")); } @@ -403,15 +407,15 @@ impl Interp { /// [[OwnPropertyKeys]] of a proxy (section 9.5.11). The trap must give an array-like object /// of distinct strings, at most [`MAX_OWN_KEYS`] of them, that holds every non-configurable /// name of the target, and of a non-extensible target exactly its names. Each name takes a - /// unit of fuel and counts against the heap limit while the list is built. - pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult> { + /// unit of fuel and counts against the heap limit until the caller drops the list. + pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult { self.proxy_op(p, "list the properties of", &[], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.ecma_own_keys(target) }; let result = i.call_trap(&trap, handler, &[Value::Object(target)])?; let mut held = HeldBytes::new(i); let keys = i.trap_key_list(&result, &mut held)?; i.check_own_keys(target, &keys)?; - Ok(keys) + Ok(HeldKeys { keys, held }) }) } @@ -449,12 +453,12 @@ impl Interp { let target_keys = self.own_keys(target)?; let mut fixed = Vec::new(); let mut configurable = Vec::new(); - for k in target_keys { + for k in target_keys.iter() { self.use_fuel()?; - if self.get_own_property(target, &k)?.is_some_and(|p| !p.configurable()) { - fixed.push(k); + if self.own_property(target, k)?.is_some_and(|p| !p.configurable()) { + fixed.push(k.clone()); } else { - configurable.push(k); + configurable.push(k.clone()); } } if extensible && fixed.is_empty() { diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index eac8c9c645..dac40b6c6b 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -975,3 +975,172 @@ fn typed_array_prototypes_ignore_invalid_numeric_indices_during_assignment() { Reflect.set(o, 'label', 8) && o.label === 8", ); } + +#[test] +fn proxy_key_lists_stay_charged_during_nested_descriptor_callbacks() { + use crate::builtins::native; + use crate::heap::{HIDDEN, NativeKind, Prop, key}; + use crate::value::Value; + + fn live_bytes(interp: &mut crate::interp::Interp, _: Value, _: &[Value], _: bool) -> crate::interp::JsResult { + interp.collect_garbage(); + Ok(Value::Number(f64::from(u32::try_from(interp.heap.bytes).unwrap()))) + } + + for operation in ["Object.keys(p)", "JSON.stringify(p)"] { + let mut realm = es(); + let interp = realm.interp(); + let probe = native(interp, "liveBytes", live_bytes, 0, NativeKind::Plain, false).unwrap(); + interp.define(interp.global, key("liveBytes"), Prop::Data { value: Value::Object(probe), flags: HIDDEN }).unwrap(); + let src = format!( + "var name = 'x'; while (name.length < 65536) name += name; + var names = [name], depth = 0, retained = 0; + var inner = new Proxy({{}}, {{ + ownKeys: function () {{ return names; }}, + getOwnPropertyDescriptor: function () {{ + depth++; + if (depth < 3) {{ {operation}; }} else {{ retained = liveBytes(); }} + depth--; + return {{ configurable: true, enumerable: false }}; + }} + }}); + var p = new Proxy(inner, {{}}), baseline = liveBytes(); + {operation}; + retained - baseline > 5 * name.length * 2" + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true)), "{operation}"); + } +} + +#[test] +fn legacy_reflection_rejects_proxy_receivers_without_enumerating_them() { + let mut realm = es(); + realm.add_script_extensions().unwrap(); + let src = format!( + "{PRELUDE} + var calls = 0; + var p = new Proxy({{}}, {{ + ownKeys: function () {{ calls++; return {{ length: 10001 }}; }}, + getOwnPropertyDescriptor: function () {{ calls++; throw 1; }} + }}); + var getter = Object.getOwnPropertyDescriptor(Object.prototype, 'reflect').get; + type_error(function () {{ p.reflect; }}) && type_error(function () {{ getter.call(p); }}) && calls === 0" + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); +} + +#[test] +fn transparent_proxy_and_reflect_membership_use_host_indexers() { + let index: HostFunction = Rc::new(|args| { + assert_eq!(args.get(2), Some(&Data::Bool(true))); + Ok(match args.get(1) { + Some(Data::Number(n)) if *n == 0.0 => Data::Bool(true), + Some(Data::String(s)) if s == "named" => Data::Bool(true), + _ => Data::Undefined, + }) + }); + let class = crate::HostClass { name: "Indexed".into(), parent: None, members: vec![], info: vec![], index: Some(index), construct: None }; + let mut realm = es(); + realm.define_host_classes(vec![class], vec![("indexed".into(), crate::host_ref("Indexed", &[1.0]))]).unwrap(); + assert_eq!( + realm.run( + "var p = new Proxy(new Proxy(indexed, {}), {}); + var ok = [indexed, p].every(function (t) { + return 0 in t && 'named' in t && !(1 in t) && !('missing' in t) && + Reflect.has(t, 0) && Reflect.has(t, 'named') && !Reflect.has(t, 1) && !Reflect.has(t, 'missing'); + }); + var calls = 0; + var trapped = new Proxy(indexed, { has: function () { calls++; return false; } }); + ok && !Reflect.has(trapped, 0) && calls === 1", + ), + Ok(JsValue::Bool(true)) + ); +} + +#[test] +fn binary_constructors_validate_arguments_before_reading_new_target_prototype() { + truth( + "var reads = 0, proto = {}; + var nt = new Proxy(function () {}, { get: function () { reads++; return proto; } }); + var constructors = [ArrayBuffer, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, + Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; + var ok = constructors.every(function (C) { + try { Reflect.construct(C, [-1], nt); } catch (e) { return e instanceof RangeError && reads === 0; } + return false; + }); + var buffer = new ArrayBuffer(4); + ok = ok && [function () { Reflect.construct(DataView, [{}], nt); }, + function () { Reflect.construct(DataView, [buffer, -1], nt); }, + function () { Reflect.construct(DataView, [buffer, 5], nt); }, + function () { Reflect.construct(DataView, [buffer, 0, 5], nt); }].every(function (f) { + try { f(); } catch (e) { return (e instanceof RangeError || e instanceof TypeError) && reads === 0; } + return false; + }); + var a = Reflect.construct(ArrayBuffer, [2], nt), u = Reflect.construct(Uint8Array, ['2'], nt); + var d = Reflect.construct(DataView, [buffer, 1, 2], nt); + ok && reads === 3 && Object.getPrototypeOf(a) === proto && Object.getPrototypeOf(u) === proto && + Object.getPrototypeOf(d) === proto && Uint8Array.prototype.join.call(u) === '0,0'", + ); + truth( + "var log = [], proto = {}; + var nt = new Proxy(function () {}, { get: function () { log.push('prototype'); return proto; } }); + var length = { valueOf: function () { log.push('length'); return 2; } }; + var offset = { valueOf: function () { log.push('offset'); return 1; } }; + Reflect.construct(ArrayBuffer, [length], nt); + Reflect.construct(DataView, [new ArrayBuffer(4), offset, length], nt); + log.join() === 'length,prototype,offset,length,prototype'", + ); +} + +#[test] +fn proxy_invariants_preserve_namespace_initialization_errors() { + let mut realm = es(); + assert!(realm.run("var out = [];").is_ok()); + let mut load = |_: &str, specifier: &str| -> Result { + let (key, source) = if specifier == "main" { + ("main.mjs", None) + } else { + ( + "cycle.mjs", + Some( + "import * as ns from 'main'; + var p = new Proxy(ns, { + get: function () { return 9; }, set: function () { return true; }, + has: function () { return false; }, deleteProperty: function () { return true; }, + defineProperty: function () { return true; }, ownKeys: function () { return ['x']; } + }); + [function () { p.x; }, function () { p.x = 9; }, function () { 'x' in p; }, + function () { delete p.x; }, function () { Reflect.defineProperty(p, 'x', { value: 9 }); }, + function () { Reflect.ownKeys(p); }].forEach(function (f) { + try { f(); out.push(false); } catch (e) { out.push(e instanceof ReferenceError); } + });" + .into(), + ), + ) + }; + Ok(crate::LoadedModule { key: key.into(), source }) + }; + assert_eq!( + realm.run_module("main.mjs", "import './cycle.mjs'; export let x = 1;", crate::ModuleLimits::default(), &mut load), + Ok(JsValue::Undefined) + ); + assert_eq!(realm.run("out.join()"), Ok(JsValue::String("true,true,true,true,true,true".into()))); +} + +#[test] +fn revoked_proxies_reject_symbol_operations_on_their_own_properties() { + truth( + "var s = Symbol('saved'), missing = Symbol('missing'), pair = Proxy.revocable({}, {}), p = pair.proxy; + p[s] = 7; + var child = Object.create(p); + var ok = p[s] === 7 && s in p && Object.getOwnPropertyDescriptor(p, s).value === 7; + pair.revoke(); + ok && [function () { p[s]; }, function () { p[missing]; }, function () { child[s]; }, + function () { s in p; }, function () { p[s] = 8; }, function () { p[missing] = 8; }, + function () { delete p[s]; }, function () { delete p[missing]; }, + function () { Object.getOwnPropertyDescriptor(p, s); }, + function () { Object.defineProperty(p, s, { value: 8 }); }, + function () { Object.defineProperty(p, missing, { value: 8 }); }, + function () { Object.getOwnPropertySymbols(p); }].every(type_error)", + ); +} diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs index 79cac25cc0..62c63c6bb0 100644 --- a/crates/js/src/reflect.rs +++ b/crates/js/src/reflect.rs @@ -100,6 +100,9 @@ fn reflect(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult (interp.symbols.objects.map_or(interp.intrinsics.object_proto, |o| o.symbol_proto), Some("Symbol")), Value::Object(o) => (*o, None), }; + if interp.is_proxy(id) { + return Err(interp.type_error("reflect does not support proxy objects")); + } let (name, properties, methods) = match interp.host_class_members(id)? { Some((name, members)) if primitive.is_none() => { let (properties, methods) = host_infos(interp, &members)?; diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index bbac60d461..e90652ec00 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -315,7 +315,8 @@ impl Interp { self.reject(true, &name, why) } - pub(crate) fn get_own_sym(&self, id: ObjId, k: &Sym) -> JsResult> { + pub(crate) fn get_own_sym(&mut self, id: ObjId, k: &Sym) -> JsResult> { + self.symbol_lookup_target(id)?; Ok(self.object(id)?.syms.as_ref().and_then(|m| m.get(k)).cloned()) } @@ -364,6 +365,7 @@ impl Interp { /// Adds or replaces an own property directly, keeping the heap estimate. pub(crate) fn define_sym(&mut self, id: ObjId, k: Sym, prop: Prop) -> JsResult<()> { + self.symbol_lookup_target(id)?; let o = self.object_mut(id)?; if o.syms.get_or_insert_with(Box::default).insert(k, prop) { self.heap.bytes = self.heap.bytes.saturating_add(PROP_BYTES); @@ -488,6 +490,7 @@ impl Interp { /// An object's own Symbol keys in the order they were added. Each takes a unit of fuel, and /// the heap for the list is checked first. pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { + self.symbol_lookup_target(id)?; let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); self.reserve_heap(count.saturating_mul(16))?; for _ in 0..count { diff --git a/docs/mcp.md b/docs/mcp.md index bb5f85d641..1aba1d1294 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2853,14 +2853,22 @@ counts against the call depth. A generator function called in an engine that `#t throws a `TypeError`, since that engine was made without the ECMAScript 2015 built-ins. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and an engine that `#targetengine` keeps reads each run the way that run's script does. A `.js` script also has the globals `Proxy`, with `Proxy.revocable`, and `Reflect` (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 -and 26.2), with string property names. A trap is a script call: it takes fuel and counts against the limit on nested calls, -the copy of the property name it is given and the names retained during a `for-in` prototype walk count against the heap limit, and -a trap result that breaks one of the proxy invariants, or any operation on a revoked proxy, throws a `TypeError`. A +and 26.2), with string property names. A trap is a script call: it takes fuel and counts against the limit on nested calls. +The copy of the property name it is given, key lists retained by enumeration callers, and the names retained during +a `for-in` prototype walk count against the heap limit. A trap result that breaks one of the proxy invariants, +or any operation on a revoked proxy, throws a `TypeError`. A proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets `Proxy` and `Reflect` at its first `.js` run and keeps them for later `.jsx` runs. An empty-handler proxy forwards construction of built-ins, including `Map` and typed arrays, and reads the proxy's `prototype` for the constructed object. `Reflect.construct` also accepts a distinct constructor as `newTarget` for `Map`, `Set` and typed arrays and uses its `prototype` for the new object. +`ArrayBuffer` and typed arrays constructed from primitive lengths convert the length before reading +`newTarget.prototype`. `DataView` validates its buffer, byte offset and byte length before reading that prototype. +A failure during conversion or validation throws before the prototype getter runs. `Reflect.has` and an empty-handler proxy's +membership checks use host collection indexers, including numeric indices and named items. +The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating +its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations +and symbol enumeration on a revoked proxy also throw `TypeError`. `Reflect.ownKeys` returns string keys only. Ordinary targets list array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes its other non-index strings. A proxy's `ownKeys` trap determines its key order. A `for-in` loop checks each proxy candidate's descriptor @@ -2872,7 +2880,8 @@ without creating a property on the receiver. `Object.freeze`, `Object.seal`, `Ob and `Object.isSealed` throw `TypeError` for a proxy when it or any of its proxy targets has symbol properties. `Reflect.set` and a write a proxy forwards return false when the lookup reaches a module namespace object before it finds the property. `Reflect.getOwnPropertyDescriptor` -and forwarded proxy descriptors throw `ReferenceError` for an uninitialized namespace export. +and forwarded proxy descriptors throw `ReferenceError` for an uninitialized namespace export. Proxy invariant +checks that read a target descriptor also throw `ReferenceError` for an uninitialized namespace export. The function returned as `Proxy.revocable(...).revoke` has an own empty-string `name` and a `length` of zero; both properties are nonwritable, nonenumerable and configurable. A `.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there From 8c7c3d9eadc9cab41cc67f465b4109666ab689cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 22:25:57 -0800 Subject: [PATCH 19/50] JavaScript: Map and Set built for another newTarget use its adder, and Reflect has its tag Reflect.construct of Map, Set, WeakMap and WeakSet with another newTarget fills the collection through the new prototype's adder, new through an empty-handler proxy of a host class constructs the class, Reflect has Symbol.toStringTag, and an ownKeys result is read in full before a duplicate is refused. --- crates/js/src/builtins/collections.rs | 17 +++- crates/js/src/builtins/reflect.rs | 6 +- crates/js/src/class_ops.rs | 10 ++- crates/js/src/proxy.rs | 10 ++- crates/js/src/proxy_tests.rs | 107 ++++++++++++++++++++++++++ docs/mcp.md | 12 ++- 6 files changed, 154 insertions(+), 8 deletions(-) diff --git a/crates/js/src/builtins/collections.rs b/crates/js/src/builtins/collections.rs index 2d9f6176d3..2e921aaa10 100644 --- a/crates/js/src/builtins/collections.rs +++ b/crates/js/src/builtins/collections.rs @@ -250,7 +250,7 @@ fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bo } /// A new collection object of `class` with `proto`, filled from `args[0]`. -fn construct(interp: &mut Interp, args: &[Value], constructing: bool, name: &str, class: Class, proto: ObjId) -> JsResult { +pub(crate) fn construct(interp: &mut Interp, args: &[Value], constructing: bool, name: &str, class: Class, proto: ObjId) -> JsResult { if !constructing { return Err(interp.type_error(&format!("{name} must be called with new"))); } @@ -264,6 +264,21 @@ fn construct(interp: &mut Interp, args: &[Value], constructing: bool, name: &str Ok(Value::Object(o)) } +pub(crate) fn constructor_class(interp: &Interp, proto: ObjId) -> Option<(&'static str, Class)> { + let i = &interp.intrinsics.es2015; + if proto == i.map_proto { + Some(("Map", Class::Map(Box::default()))) + } else if proto == i.set_proto { + Some(("Set", Class::Set(Box::default()))) + } else if proto == i.weak_map_proto { + Some(("WeakMap", Class::WeakMap(Box::default()))) + } else if proto == i.weak_set_proto { + Some(("WeakSet", Class::WeakSet(Box::default()))) + } else { + None + } +} + fn map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { let proto = interp.intrinsics.es2015.map_proto; construct(interp, args, constructing, "Map", Class::Map(Box::default()), proto) diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index 3f649a3673..8524edabbb 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -54,7 +54,11 @@ fn reflect_methods(interp: &mut Interp, reflect: ObjId) -> JsResult<()> { method(interp, reflect, "ownKeys", own_keys, 1)?; method(interp, reflect, "preventExtensions", prevent_extensions, 1)?; method(interp, reflect, "set", set, 3)?; - method(interp, reflect, "setPrototypeOf", set_prototype_of, 2) + method(interp, reflect, "setPrototypeOf", set_prototype_of, 2)?; + if let Some(tag) = interp.well_known(|w| &w.to_string_tag) { + interp.define_sym(reflect, tag, Prop::Data { value: Value::str("Reflect"), flags: CONFIGURABLE })?; + } + Ok(()) } // ---- Proxy ---- diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index c691db98bd..66b20a1834 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -317,6 +317,14 @@ impl Interp { let fallback = self.intrinsics.object_proto; let proto = self.prototype_from(nt, fallback)?; Value::Object(self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)))) + } else if let Some((name, class)) = + intrinsic.filter(|_| subclass).and_then(|p| crate::builtins::collections::constructor_class(self, p)) + { + let proto = self.prototype_from(nt, intrinsic.unwrap_or(self.intrinsics.object_proto))?; + let held = self.held_bytes; + let r = self.rooted(&[Value::Object(proto)], |i| crate::builtins::collections::construct(i, &args, true, name, class, proto)); + self.held_bytes = held; + r? } else if subclass && crate::builtins::binary::defers_prototype(self, intrinsic, &args) { let held = self.held_bytes; let r = crate::builtins::binary::construct_with_target(self, intrinsic, &args, nt); @@ -361,7 +369,7 @@ impl Interp { // object it gives inherits from the class's prototype. The class's other functions are // not constructors. A constructor called with `new` cannot wait for its result. Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted }) if self.is_host_constructor(callee) => { - if nt != callee { + if nt != callee && self.unwrapped_proxy_target(nt)? != callee { return Err(self.type_error("this built-in cannot be subclassed")); } let was = std::mem::replace(&mut self.constructing, true); diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index bbde3c6933..c7872eb9fc 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -432,18 +432,22 @@ impl Interp { } let mut keys = Vec::new(); let mut seen: HashSet = HashSet::new(); + let mut duplicate = None; for index in 0..n as u32 { self.use_fuel()?; let v = self.get_from(*list, &index_key(index), result)?; let Value::String(s) = v else { return Err(self.invariant("ownKeys", "returned a name that is not a string")) }; held.add(self, string_bytes(s.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; let k = s.flat(); - if !seen.insert(k.clone()) { - let name = String::from_utf16_lossy(&k); - return Err(self.invariant("ownKeys", &format!("returned the name '{name}' twice"))); + if !seen.insert(k.clone()) && duplicate.is_none() { + duplicate = Some(k.clone()); } keys.push(k); } + if let Some(k) = duplicate { + let name = String::from_utf16_lossy(&k); + return Err(self.invariant("ownKeys", &format!("returned the name '{name}' twice"))); + } Ok(keys) } diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index dac40b6c6b..4dfdb7ca67 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -274,6 +274,113 @@ fn an_own_keys_result_is_checked_against_the_target() { assert!(e.message.starts_with("RangeError"), "{e:?}"); } +#[test] +fn own_keys_reads_and_validates_the_list_before_rejecting_duplicates() { + truth( + "var reads = 0, marker = {}, result = { length: 3, 0: 'x', 1: 'x' }; + var p = new Proxy({}, { ownKeys: function () { return result; } }); + Object.defineProperty(result, '2', { configurable: true, get: function () { reads++; return 'y'; } }); + var duplicate = type_error(function () { Reflect.ownKeys(p); }); + Object.defineProperty(result, '2', { configurable: true, get: function () { reads++; throw marker; } }); + var caught = false; + try { Reflect.ownKeys(p); } catch (e) { caught = e === marker; } + Object.defineProperty(result, '2', { get: function () { reads++; return 1; } }); + var invalid = false; + try { Reflect.ownKeys(p); } catch (e) { invalid = e instanceof TypeError && e.message.indexOf('not a string') >= 0; } + duplicate && caught && invalid && reads === 3", + ); +} + +#[test] +fn reflect_has_the_standard_symbol_tag_descriptor() { + truth( + "var d = Object.getOwnPropertyDescriptor(Reflect, Symbol.toStringTag); + var ok = Object.prototype.toString.call(Reflect) === '[object Reflect]' && + d.value === 'Reflect' && !d.writable && !d.enumerable && d.configurable; + Reflect[Symbol.toStringTag] = 'Other'; + ok = ok && Reflect[Symbol.toStringTag] === 'Reflect'; + ok && delete Reflect[Symbol.toStringTag] && Object.prototype.toString.call(Reflect) === '[object Object]'", + ); +} + +#[test] +fn transparent_host_constructor_proxies_forward_construction() { + let calls = Rc::new(RefCell::new(0)); + let count = calls.clone(); + let make: HostFunction = Rc::new(move |_| { + *count.borrow_mut() += 1; + Ok(Data::Object(Vec::new())) + }); + let class = crate::HostClass { name: "Preset".into(), parent: None, members: vec![], info: vec![], index: None, construct: Some(make) }; + let mut realm = es(); + realm.define_host_classes(vec![class], vec![]).unwrap(); + assert_eq!( + realm.run(&format!( + "{PRELUDE}var P = new Proxy(Preset, {{}}), Q = new Proxy(P, {{}}); + var a = new P(), b = new Q(), c = Reflect.construct(Q, []); + function Other() {{}} + a instanceof Preset && b instanceof Preset && c instanceof Preset && + Object.getPrototypeOf(a) === Preset.prototype && + type_error(function () {{ Reflect.construct(P, [], Other); }}) && + type_error(function () {{ class Child extends P {{}} new Child(); }})" + )), + Ok(JsValue::Bool(true)) + ); + assert_eq!(*calls.borrow(), 3); +} + +#[test] +fn reflect_construct_initializes_collections_with_the_new_target_adder() { + truth( + "[Map, Set, WeakMap, WeakSet].every(function (C) { + var pairs = C === Map || C === WeakMap, name = pairs ? 'set' : 'add'; + var key = {}, calls = 0, receiver, reads = 0; + function Custom() {} Custom.prototype = {}; + Object.defineProperty(Custom.prototype, name, { get: function () { + reads++; + return function (k, v) { calls++; receiver = this; return C.prototype[name].call(this, k, v); }; + } }); + var nt = new Proxy(Custom, { get: function (t, k) { return t[k]; } }); + var made = Reflect.construct(new Proxy(C, {}), [pairs ? [[key, 7]] : [key]], nt); + return calls === 1 && reads === 1 && receiver === made && Object.getPrototypeOf(made) === Custom.prototype && + (pairs ? C.prototype.get.call(made, key) === 7 : C.prototype.has.call(made, key)); + })", + ); +} + +#[test] +fn reflect_construct_rejects_missing_collection_adders_before_reading_the_iterable() { + truth( + "[Map, Set, WeakMap, WeakSet].every(function (C) { + function Custom() {} Custom.prototype = {}; + var reads = 0, list = {}; + Object.defineProperty(list, Symbol.iterator, { get: function () { reads++; throw 'iterator'; } }); + var missing = type_error(function () { Reflect.construct(C, [list], Custom); }); + Custom.prototype.set = 1; Custom.prototype.add = 1; + var invalid = type_error(function () { Reflect.construct(C, [[]], Custom); }); + return missing && invalid && reads === 0 && + Object.getPrototypeOf(Reflect.construct(C, [null], Custom)) === Custom.prototype; + })", + ); +} + +#[test] +fn reflect_construct_closes_the_iterator_when_the_custom_collection_adder_throws() { + truth( + "[Map, Set, WeakMap, WeakSet].every(function (C) { + function Custom() {} var marker = {}, closed = 0, calls = 0; + Custom.prototype = { set: function () { throw marker; }, add: function () { throw marker; } }; + var list = {}; + list[Symbol.iterator] = function () { return { + next: function () { calls++; return { done: false, value: [{}, 7] }; }, + return: function () { closed++; return {}; } + }; }; + try { Reflect.construct(C, [list], Custom); } catch (e) { return e === marker && closed === 1 && calls === 1; } + return false; + })", + ); +} + // ---- limits ---- #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 1aba1d1294..8016d929e8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2861,7 +2861,13 @@ proxy in a command's params throws a `TypeError` without running its traps. An e `Proxy` and `Reflect` at its first `.js` run and keeps them for later `.jsx` runs. An empty-handler proxy forwards construction of built-ins, including `Map` and typed arrays, and reads the proxy's `prototype` for the constructed object. `Reflect.construct` also accepts a distinct constructor -as `newTarget` for `Map`, `Set` and typed arrays and uses its `prototype` for the new object. +as `newTarget` for `Map`, `Set`, `WeakMap`, `WeakSet` and typed arrays and uses its `prototype` for the new object. +`Map`, `Set`, `WeakMap` and `WeakSet` initialize iterable arguments through the requested prototype's +`set` or `add` method. A missing or noncallable adder throws `TypeError` before the iterable is read; +an omitted or nullish iterable does not require an adder. An adder that throws closes the iterator. +An empty-handler proxy also forwards construction of host classes. A distinct host subclass remains unsupported +and throws `TypeError`. In a realm with `Symbol.toStringTag`, `Reflect` has the tag `Reflect`; +its symbol property is nonwritable, nonenumerable and configurable. `ArrayBuffer` and typed arrays constructed from primitive lengths convert the length before reading `newTarget.prototype`. `DataView` validates its buffer, byte offset and byte length before reading that prototype. A failure during conversion or validation throws before the prototype getter runs. `Reflect.has` and an empty-handler proxy's @@ -2872,7 +2878,9 @@ and symbol enumeration on a revoked proxy also throw `TypeError`. `Reflect.ownKeys` returns string keys only. Ordinary targets list array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes its other non-index strings. A proxy's `ownKeys` trap determines its key order. A `for-in` loop checks each proxy candidate's descriptor -when iteration reaches that name. Deleting a binding in a `with` scope calls the proxy's `deleteProperty` +when iteration reaches that name. An `ownKeys` result is read and its elements are validated before duplicate +names are rejected; a later getter's exception takes precedence over the duplicate-name error. +Deleting a binding in a `with` scope calls the proxy's `deleteProperty` trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay reachable during proxy callbacks, including callbacks that revoke a nested target proxy. `Reflect.set` and ordinary assignment ignore invalid numeric indices found on a typed-array prototype From 0248f7eb74d3a962ea164455ef163c501ab8fe7e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 23:11:43 -0800 Subject: [PATCH 20/50] JavaScript: for-in keeps a detached proxy reachable, Promise checks its executor first, and late Proxy and Reflect respect a sealed global --- crates/js/src/builtins/reflect.rs | 6 +-- crates/js/src/class_ops.rs | 3 ++ crates/js/src/interp.rs | 8 +++- crates/js/src/proxy_tests.rs | 77 +++++++++++++++++++++++++++++++ docs/mcp.md | 11 ++++- 5 files changed, 98 insertions(+), 7 deletions(-) diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index 8524edabbb..ae85c85a40 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -5,7 +5,7 @@ use std::rc::Rc; use super::object::{from_prop, names_array, to_desc}; -use super::{arg, data, method, native}; +use super::{arg, method, native}; use crate::heap::{CONFIGURABLE, Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key}; use crate::interp::{Desc, Interp, JsResult}; use crate::proxy::desc_values; @@ -22,7 +22,7 @@ pub(super) fn install(interp: &mut Interp, keep: bool) -> JsResult<()> { // Naming a new method can collect, and the constructor is reachable from nowhere else // until it is published. interp.rooted(&[Value::Object(proxy)], |interp| method(interp, proxy, "revocable", revocable, 2))?; - data(interp, global, "Proxy", Value::Object(proxy), HIDDEN)?; + interp.define_own_property(global, key("Proxy"), &Desc::data(Value::Object(proxy), HIDDEN), true)?; } if !(keep && interp.get_own_property(global, &key("Reflect"))?.is_some()) { install_reflect(interp)?; @@ -37,7 +37,7 @@ fn install_reflect(interp: &mut Interp) -> JsResult<()> { let object_proto = interp.intrinsics.object_proto; let reflect = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); interp.rooted(&[Value::Object(reflect)], |interp| reflect_methods(interp, reflect))?; - data(interp, global, "Reflect", Value::Object(reflect), HIDDEN) + interp.define_own_property(global, key("Reflect"), &Desc::data(Value::Object(reflect), HIDDEN), true).map(|_| ()) } /// Defines `Reflect`'s functions on `reflect`, which the caller keeps reachable. diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 66b20a1834..9ddd1732bc 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -331,6 +331,9 @@ impl Interp { self.held_bytes = held; r? } else { + if subclass && name == "Promise" && !args.first().is_some_and(|v| self.is_callable(v)) { + return Err(self.type_error("the Promise executor is not a function")); + } // `Number`, `String`, `Date` and `Function` convert their arguments before // `prototype` is read (sections 20.1.1.1, 21.1.1.1, 20.4.2 and 19.2.1.1.1), so // a conversion that throws reads nothing from `new.target`. diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24daab16cc..4b7506c062 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -3245,8 +3245,9 @@ impl Interp { } /// [`Self::enumerable_keys`] after the XML case. A proxy on the chain gives its names with its - /// `ownKeys` trap and the next object with its `getPrototypeOf` trap, which - /// `temp_roots[slot]` keeps reachable. Descriptors are checked when iteration reaches each name. + /// `ownKeys` trap and the next object with its `getPrototypeOf` trap. + /// `temp_roots[slot]` roots the current proxy through that lookup, then the returned prototype. + /// Descriptors are checked when iteration reaches each name. fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult> { let mut seen = std::collections::HashSet::new(); let mut held = HeldBytes::new(self); @@ -3254,6 +3255,9 @@ impl Interp { let mut cur = Some(id); while let Some(o) = cur { if self.is_proxy(o) { + if let Some(root) = self.temp_roots.get_mut(slot) { + *root = Value::Object(o); + } let keys = self.own_keys(o)?; for k in keys { self.use_fuel()?; diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 4dfdb7ca67..91357b2c2a 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -112,6 +112,38 @@ fn late_proxy_and_reflect_installation_keeps_their_methods_reachable() { assert!(realm.interp().heap.collections > 0); } +#[test] +fn late_proxy_and_reflect_installation_respects_global_extensibility() { + for operation in ["preventExtensions", "seal", "freeze"] { + for (setup, has_proxy, has_reflect) in + [("", false, false), ("var Proxy = 7;", true, false), ("var Reflect = 8;", false, true), ("var Proxy = 7, Reflect = 8;", true, true)] + { + let mut realm = Realm::new(); + assert_eq!(realm.run(&format!("{setup} var runs = 0; Object.{operation}(this); 0")), Ok(JsValue::Number(0.0))); + realm.set_es2015(true); + if has_proxy && has_reflect { + assert_eq!(realm.run("Proxy + Reflect"), Ok(JsValue::Number(15.0))); + } else { + for _ in 0..2 { + let err = realm.run("runs++").unwrap_err(); + assert_eq!(err.kind, RunErrorKind::Internal); + assert!(err.message.contains("Proxy and Reflect could not be installed"), "{err:?}"); + assert!(err.message.contains("the object is not extensible"), "{err:?}"); + let missing = if has_proxy { "Reflect" } else { "Proxy" }; + assert!(err.message.contains(missing), "{err:?}"); + } + } + realm.set_es2015(false); + let check = format!( + "runs === 0 && !Object.isExtensible(this) && this.hasOwnProperty('Proxy') === {has_proxy} + && this.hasOwnProperty('Reflect') === {has_reflect} + && (typeof Proxy === 'undefined' || Proxy === 7) && (typeof Reflect === 'undefined' || Reflect === 8)" + ); + assert_eq!(realm.run(&check), Ok(JsValue::Bool(true)), "{operation}: {setup}"); + } + } +} + // ---- Proxy ---- #[test] @@ -986,6 +1018,51 @@ fn reflect_construct_allows_distinct_new_targets_for_collections_and_typed_array ); } +#[test] +fn for_in_keeps_a_proxy_reachable_after_its_own_keys_trap_detaches_it() { + truth_collecting( + "var o, reads = 0; + o = Object.create(new Proxy({ first: 1, second: 2 }, { + ownKeys: function () { Reflect.setPrototypeOf(o, null); return ['first', 'second']; }, + getPrototypeOf: function () { reads++; return null; } + })); + var seen = []; + for (var k in o) seen.push(k); + reads === 1 && seen.length === 0 && Object.getPrototypeOf(o) === null", + ); +} + +#[test] +fn reflect_construct_validates_promise_executors_before_reading_the_prototype() { + for trap in ["return t[k];", "throw 'prototype read';"] { + truth(&format!( + "var reads = 0; + var nt = new Proxy(function () {{}}, {{ get: function (t, k) {{ + if (k === 'prototype') {{ reads++; {trap} }} return t[k]; + }} }}); + var invalid = [undefined, null, false, 1, 'executor', {{}}, new Proxy({{}}, {{}})], rejected = 0; + for (var i = 0; i < invalid.length; i++) {{ + if (type_error(function () {{ Reflect.construct(Promise, [invalid[i]], nt); }})) rejected++; + }} + rejected === invalid.length && type_error(function () {{ Reflect.construct(Promise, [], nt); }}) && reads === 0" + )); + } + truth_collecting( + "var log = [], proto = {}; + var nt = new Proxy(function () {}, { get: function (t, k) { + if (k === 'prototype') { log.push('prototype'); return proto; } return t[k]; + } }); + var p = Reflect.construct(Promise, [function (resolve) { log.push('executor'); resolve(7); }], nt); + log.join() === 'prototype,executor' && Object.getPrototypeOf(p) === proto", + ); + truth( + "var ran = false, marker = {}, caught = false; + var nt = new Proxy(function () {}, { get: function (t, k) { if (k === 'prototype') throw marker; return t[k]; } }); + try { Reflect.construct(Promise, [function () { ran = true; }], nt); } catch (e) { caught = e === marker; } + caught && !ran", + ); +} + #[test] fn for_in_checks_proxy_descriptors_only_when_each_candidate_is_reached() { truth( diff --git a/docs/mcp.md b/docs/mcp.md index 8016d929e8..c9f9c63559 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2859,6 +2859,8 @@ a `for-in` prototype walk count against the heap limit. A trap result that break or any operation on a revoked proxy, throws a `TypeError`. A proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets `Proxy` and `Reflect` at its first `.js` run and keeps them for later `.jsx` runs. +Existing globals with either name are preserved. If a missing global cannot be added because the global object +is nonextensible, sealed or frozen, the run fails with an installation error before the script executes. An empty-handler proxy forwards construction of built-ins, including `Map` and typed arrays, and reads the proxy's `prototype` for the constructed object. `Reflect.construct` also accepts a distinct constructor as `newTarget` for `Map`, `Set`, `WeakMap`, `WeakSet` and typed arrays and uses its `prototype` for the new object. @@ -2870,14 +2872,19 @@ and throws `TypeError`. In a realm with `Symbol.toStringTag`, `Reflect` has the its symbol property is nonwritable, nonenumerable and configurable. `ArrayBuffer` and typed arrays constructed from primitive lengths convert the length before reading `newTarget.prototype`. `DataView` validates its buffer, byte offset and byte length before reading that prototype. -A failure during conversion or validation throws before the prototype getter runs. `Reflect.has` and an empty-handler proxy's +A failure during conversion or validation throws before the prototype getter runs. `Reflect.construct(Promise, args, newTarget)` +rejects a missing or noncallable executor with `TypeError` before reading `newTarget.prototype`. +For a callable executor, it reads that prototype before calling the executor; a throwing prototype getter prevents the call. +`Reflect.has` and an empty-handler proxy's membership checks use host collection indexers, including numeric indices and named items. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations and symbol enumeration on a revoked proxy also throw `TypeError`. `Reflect.ownKeys` returns string keys only. Ordinary targets list array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes its other non-index strings. -A proxy's `ownKeys` trap determines its key order. A `for-in` loop checks each proxy candidate's descriptor +A proxy's `ownKeys` trap determines its key order. A `for-in` prototype walk keeps the current proxy reachable +through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from the receiver's prototype chain. +A `for-in` loop checks each proxy candidate's descriptor when iteration reaches that name. An `ownKeys` result is read and its elements are validated before duplicate names are rejected; a later getter's exception takes precedence over the duplicate-name error. Deleting a binding in a `with` scope calls the proxy's `deleteProperty` From 94cbceb676e3282a5dbc976bf28eebd34340e65b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 23:24:50 -0800 Subject: [PATCH 21/50] JavaScript: JSON reads proxy array lengths with ToLength and skips host indexers through transparent proxies, and proxies construct bound built-ins --- crates/js/src/builtins/json.rs | 17 +++-- crates/js/src/class_ops.rs | 17 +++-- crates/js/src/interp.rs | 4 +- crates/js/src/proxy.rs | 6 +- crates/js/src/proxy_tests.rs | 117 +++++++++++++++++++++++++++++++++ docs/mcp.md | 9 ++- 6 files changed, 155 insertions(+), 15 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 8e4d027574..7db63c71be 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -483,12 +483,16 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult JsResult> { - let len = length_of(interp, r)?; + let len = super::collections::length_of(interp, r)?; + if len > interp.fuel { + return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel)); + } + interp.reserve_heap(usize::try_from(len).unwrap_or(usize::MAX).saturating_mul(ELEMENT_BYTES))?; let mut list: Vec = Vec::new(); let mut seen = HashSet::new(); for i in 0..len { interp.use_fuel()?; - let v = interp.get_from(r, &key_of(f64::from(i)), &Value::Object(r))?; + let v = interp.get_from(r, &key_of(i as f64), &Value::Object(r))?; let item = match &v { Value::String(s) => Some(s.clone()), Value::Number(_) => Some(interp.primitive_to_str(&v)), @@ -633,17 +637,20 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J let array = interp.is_array(&Value::Object(o))?; let mut held_keys = None; let keys = if array { - let len = length_of(interp, o)?; + let len = super::collections::length_of(interp, o)?; // Every element is written as at least `null` and a comma, so a length that cannot fit // is refused before anything is listed. - if u64::from(len).saturating_mul(5) > (interp.limits.heap_bytes / 4) as u64 { + if len.saturating_mul(5) > (interp.limits.heap_bytes / 4) as u64 { return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Heap)); } + if len > interp.fuel { + return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel)); + } interp.reserve_heap((len as usize).saturating_mul(crate::heap::PROP_BYTES))?; let mut keys = Vec::with_capacity(len as usize); for i in 0..len { interp.use_fuel()?; - keys.push(key_of(f64::from(i))); + keys.push(key_of(i as f64)); } keys } else if let Some(list) = &settings.properties { diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 9ddd1732bc..b0cecf8d63 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -237,6 +237,7 @@ impl Interp { /// boundary when `boundary` is set. A proxy runs its `construct` trap, or without one /// constructs its target with the same `new.target` (section 9.5.13). fn construct_at(&mut self, start: usize, f: Value, mut args: Vec, new_target: Option, boundary: bool) -> JsResult<()> { + let forwarding = new_target.is_none() || new_target == f.as_object(); let mut f = f; let mut new_target = new_target; // A bound function constructs its target with its arguments first, and a `new.target` @@ -261,7 +262,7 @@ impl Interp { } } let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) else { - break self.construct_function(start, f, args, new_target, boundary); + break self.construct_function(start, f, args, new_target, boundary, forwarding); }; if let Err(e) = self.use_fuel() { break Err(e); @@ -283,7 +284,15 @@ impl Interp { } /// The steps of [`Interp::construct_at`] for `f` once it is neither a proxy nor bound. - fn construct_function(&mut self, start: usize, f: Value, args: Vec, new_target: Option, boundary: bool) -> JsResult<()> { + fn construct_function( + &mut self, + start: usize, + f: Value, + args: Vec, + new_target: Option, + boundary: bool, + forwarding: bool, + ) -> JsResult<()> { let Some(callee) = f.as_object() else { return Err(self.type_error("the value is not a constructor")) }; let nt = new_target.unwrap_or(callee); match self.func_of(&f) { @@ -304,7 +313,7 @@ impl Interp { Some(Func::Native { f: native, constructor: true, name, .. }) => { // `Proxy` does not read `new.target` (section 26.2.1.1). let subclass = nt != callee && name != "Proxy"; - if !boundary && subclass && self.unwrapped_proxy_target(nt)? != callee && !self.subclassable(callee)? { + if !boundary && subclass && !forwarding && self.unwrapped_proxy_target(nt)? != callee && !self.subclassable(callee)? { return Err(self.type_error("this built-in cannot be subclassed")); } let intrinsic = match self.get_own_property(callee, &key("prototype"))? { @@ -372,7 +381,7 @@ impl Interp { // object it gives inherits from the class's prototype. The class's other functions are // not constructors. A constructor called with `new` cannot wait for its result. Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted }) if self.is_host_constructor(callee) => { - if nt != callee && self.unwrapped_proxy_target(nt)? != callee { + if nt != callee && !forwarding && self.unwrapped_proxy_target(nt)? != callee { return Err(self.type_error("this built-in cannot be subclassed")); } let was = std::mem::replace(&mut self.constructing, true); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 4b7506c062..54b4dea4a0 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2017,7 +2017,7 @@ impl Interp { Lookup::Found(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Lookup::Found(Prop::Data { value, .. }) => Ok(value), Lookup::Found(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), - Lookup::Proxy(p) => self.proxy_get(p, k, receiver), + Lookup::Proxy(p) => self.proxy_get(p, k, receiver, true), } } @@ -2033,7 +2033,7 @@ impl Interp { Lookup::Missing | Lookup::Found(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Lookup::Found(Prop::Data { value, .. }) => Ok(value), Lookup::Found(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), - Lookup::Proxy(p) => self.proxy_get(p, k, receiver), + Lookup::Proxy(p) => self.proxy_get(p, k, receiver, false), } } diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index c7872eb9fc..7a53949a83 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -348,9 +348,11 @@ impl Interp { } /// [[Get]] of a proxy (section 9.5.8). - pub(crate) fn proxy_get(&mut self, p: ObjId, k: &Key, receiver: &Value) -> JsResult { + pub(crate) fn proxy_get(&mut self, p: ObjId, k: &Key, receiver: &Value, indexed: bool) -> JsResult { self.proxy_op(p, "read a property of", &[receiver.clone(), Value::String(Str::from_rc(k.clone()))], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "get")? else { return i.get_from(target, k, receiver) }; + let Some(trap) = i.proxy_trap(handler, "get")? else { + return if indexed { i.get_from(target, k, receiver) } else { i.get_property_only(target, k, receiver) }; + }; let name = i.key_value(k)?; let v = i.call_trap(&trap, handler, &[Value::Object(target), name, receiver.clone()])?; match i.own_property(target, k)? { diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 91357b2c2a..41e1ae4a75 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -1328,3 +1328,120 @@ fn revoked_proxies_reject_symbol_operations_on_their_own_properties() { function () { Object.getOwnPropertySymbols(p); }].every(type_error)", ); } + +#[test] +fn json_proxy_array_lengths_use_to_length() { + truth( + "var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0; + var empty = lengths.every(function (length) { + var p = new Proxy([7], { get: function (t, k) { + if (k === 'length') return length; + if (k === '0') reads++; + return t[k]; + } }); + return JSON.stringify(new Proxy(p, {})) === '[]'; + }); + var p = new Proxy([7, 8], { get: function (t, k) { return k === 'length' ? '1.9' : t[k]; } }); + empty && reads === 0 && JSON.stringify(p) === '[7]'", + ); +} + +#[test] +fn json_proxy_replacer_lengths_use_to_length() { + truth( + "var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0; + var empty = lengths.every(function (length) { + var p = new Proxy(['a'], { get: function (t, k) { + if (k === 'length') return length; + if (k === '0') reads++; + return t[k]; + } }); + return JSON.stringify({ a: 7 }, new Proxy(p, {})) === '{}'; + }); + var p = new Proxy(['a', 'b'], { get: function (t, k) { return k === 'length' ? '1.9' : t[k]; } }); + empty && reads === 0 && JSON.stringify({ a: 7, b: 8 }, p) === '{\"a\":7}'", + ); +} + +#[test] +fn json_proxy_lengths_check_limits_before_reading_elements() { + for length in ["4294967296", "Infinity"] { + let setup = format!( + "var p = new Proxy([], {{ get: function (t, k) {{ + if (k === 'length') return {length}; + if (k === 'toJSON') return undefined; + throw new Error('element read'); + }} }});" + ); + assert_eq!(limit(&format!("{setup} JSON.stringify(p)"), Limits::default()), LimitKind::Heap); + assert_eq!(limit(&format!("{setup} JSON.stringify({{}}, p)"), Limits::default()), LimitKind::Fuel); + } + let limits = Limits { fuel: 200_000, ..Limits::default() }; + assert_eq!( + limit( + "var p = new Proxy([], { get: function (t, k) { + if (k === 'length') return 300000; + if (k === 'toJSON') return undefined; + throw new Error('element read'); + } }); JSON.stringify(p)", + limits, + ), + LimitKind::Fuel + ); + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + assert_eq!( + limit( + "var p = new Proxy([], { get: function (t, k) { + if (k === 'length') return 1000000; + throw new Error('element read'); + } }); JSON.stringify({}, p)", + limits, + ), + LimitKind::Heap + ); +} + +#[test] +fn transparent_proxies_construct_bound_builtins_without_allowing_subclasses() { + truth( + "var B = Map.bind(null, [[1, 7]]), P = new Proxy(B, {}), Q = new Proxy(P, {}); + var a = new P(), b = new Q(), c = Reflect.construct(Q, []); + var R = new Proxy(Q.bind(null), {}), d = new R(); + var U = new Proxy(Uint8Array.bind(null, [7, 8]), {}), u = new U(); + Object.defineProperty(B, 'prototype', { value: Map.prototype }); + a.get(1) === 7 && b.get(1) === 7 && c.get(1) === 7 && d.get(1) === 7 && + Object.getPrototypeOf(a) === Map.prototype && u.length === 2 && u[1] === 8 && + type_error(function () { class Child extends P {} new Child(); })", + ); +} + +#[test] +fn json_transparent_host_proxies_skip_indexers_but_call_get_traps() { + let calls = Rc::new(RefCell::new(0)); + let count = calls.clone(); + let index: HostFunction = Rc::new(move |_| { + *count.borrow_mut() += 1; + Err(crate::HostError::Error("unknown item".into())) + }); + let class = crate::HostClass { name: "Indexed".into(), parent: None, members: vec![], info: vec![], index: Some(index), construct: None }; + let mut realm = es(); + realm.define_host_classes(vec![class], vec![("indexed".into(), crate::host_ref("Indexed", &[1.0]))]).unwrap(); + assert_eq!( + realm.run( + "var p = new Proxy(new Proxy(indexed, {}), {}); + var plain = JSON.stringify(indexed); + var ok = JSON.stringify(p) === plain; + var receiver, reads = 0; + var trapped = new Proxy(indexed, { get: function (t, k, r) { + if (k === 'toJSON') { reads++; receiver = r; return function () { return this === outer ? 7 : 0; }; } + return Reflect.get(t, k, r); + } }); + var outer = new Proxy(trapped, {}); + ok && JSON.stringify(outer) === '7' && reads === 1 && receiver === outer", + ), + Ok(JsValue::Bool(true)) + ); + assert_eq!(*calls.borrow(), 0); + assert_eq!(realm.run("var caught = false; try { p.missing; } catch (e) { caught = true; } caught"), Ok(JsValue::Bool(true))); + assert_eq!(*calls.borrow(), 1); +} diff --git a/docs/mcp.md b/docs/mcp.md index c9f9c63559..159ed458dc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2861,8 +2861,9 @@ proxy in a command's params throws a `TypeError` without running its traps. An e `Proxy` and `Reflect` at its first `.js` run and keeps them for later `.jsx` runs. Existing globals with either name are preserved. If a missing global cannot be added because the global object is nonextensible, sealed or frozen, the run fails with an installation error before the script executes. -An empty-handler proxy forwards construction of built-ins, including `Map` and typed arrays, and reads -the proxy's `prototype` for the constructed object. `Reflect.construct` also accepts a distinct constructor +An empty-handler proxy forwards construction of built-ins, including bound built-ins such as `Map.bind(null)` +and bound typed-array constructors, and reads the proxy's `prototype` for the constructed object. +`Reflect.construct` also accepts a distinct constructor as `newTarget` for `Map`, `Set`, `WeakMap`, `WeakSet` and typed arrays and uses its `prototype` for the new object. `Map`, `Set`, `WeakMap` and `WeakSet` initialize iterable arguments through the requested prototype's `set` or `add` method. A missing or noncallable adder throws `TypeError` before the iterable is read; @@ -2877,6 +2878,10 @@ rejects a missing or noncallable executor with `TypeError` before reading `newTa For a callable executor, it reads that prototype before calling the executor; a throwing prototype getter prevents the call. `Reflect.has` and an empty-handler proxy's membership checks use host collection indexers, including numeric indices and named items. +`JSON.stringify` uses `ToLength` for proxy array lengths and proxy replacer-array lengths, so negative lengths +become zero and fractional lengths are truncated. It checks run limits before allocating array traversal keys +or iterating either list. Its `toJSON` lookup skips host collection indexers through empty-handler proxies +and calls an explicit `get` trap when present. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations and symbol enumeration on a revoked proxy also throw `TypeError`. From be9ce43ce2589c8ba636c9641b0c68e691f89604 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 23:46:42 -0800 Subject: [PATCH 22/50] JavaScript: concat and JSON revivers read proxy array lengths with ToLength, reviver key lists stay charged, and E4X bare calls walk the scope once --- crates/js/src/builtins/array.rs | 11 ++- crates/js/src/builtins/json.rs | 25 +++++-- crates/js/src/interp.rs | 39 +++++++--- crates/js/src/proxy_tests.rs | 129 ++++++++++++++++++++++++++++++++ crates/js/src/xml.rs | 30 -------- docs/mcp.md | 11 ++- docs/target-app-parity.md | 2 +- 7 files changed, 198 insertions(+), 49 deletions(-) diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index 81e77efab1..3e18d4d137 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -392,11 +392,20 @@ fn concat(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult // A proxy whose target is an array is spread too (ECMA-262 2020 section 22.1.3.1.1). let spread = if interp.is_array(&e)? { e.as_object() } else { None }; let Some(e) = spread else { + if n >= 9_007_199_254_740_991 { + return Err(interp.type_error("concat exceeds the maximum safe length")); + } create_at(interp, a, n as f64, e)?; n += 1; continue; }; - let len = u64::from(length_of(interp, e)?); + let len = super::collections::length_of(interp, e)?; + if len > 9_007_199_254_740_991 - n { + return Err(interp.type_error("concat exceeds the maximum safe length")); + } + if len > interp.fuel && chain(interp, e).is_none() { + return Err(Abrupt::Limit(crate::LimitKind::Fuel)); + } let mut it = Indices::up(interp, e, 0, len)?; while let Some(k) = it.next(interp)? { if let Some(v) = element(interp, e, k)? { diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 7db63c71be..e8aada1b9a 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -10,7 +10,7 @@ use std::collections::HashSet; -use super::{Builder, ELEMENT_BYTES, arg, data, key_of, length_of, method, new_array, new_string, to_integer}; +use super::{Builder, ELEMENT_BYTES, arg, data, key_of, method, new_array, new_string, to_integer}; use crate::heap::{Class, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key, string_bytes}; use crate::interp::{Desc, ErrorType, Hint, Interp, JsResult}; use crate::string_builtins::flat_charged; @@ -326,6 +326,7 @@ struct Walk { name: Key, val: Value, keys: Vec, + _held_keys: Option, next: usize, } @@ -335,23 +336,35 @@ fn enter(interp: &mut Interp, holder: ObjId, name: Key) -> JsResult { let val = interp.get_from(holder, &name, &Value::Object(holder))?; interp.temp_roots.push(val.clone()); let mut keys = Vec::new(); + let mut held_keys = None; if let Value::Object(o) = val { if interp.is_array(&val)? { - let len = length_of(interp, o)?; - interp.reserve_heap((len as usize).saturating_mul(crate::heap::PROP_BYTES))?; + let len = super::collections::length_of(interp, o)?; + if len > (interp.limits.heap_bytes / crate::heap::PROP_BYTES) as u64 { + return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Heap)); + } + if len > interp.fuel { + return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel)); + } + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, (len as usize).saturating_mul(crate::heap::PROP_BYTES))?; + held_keys = Some(held); + keys = Vec::with_capacity(len as usize); for i in 0..len { interp.use_fuel()?; - keys.push(key_of(f64::from(i))); + keys.push(key_of(i as f64)); } } else { - for k in interp.own_keys(o)? { + let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?; + held_keys = Some(held); + for k in names { if interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) { keys.push(k); } } } } - Ok(Walk { holder, name, val, keys, next: 0 }) + Ok(Walk { holder, name, val, keys, _held_keys: held_keys, next: 0 }) } /// Walks the parsed value bottom-up, calling the reviver for each property and replacing or diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 54b4dea4a0..235e8f8d43 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1584,7 +1584,35 @@ impl Interp { self.throw(ErrorType::Reference, &format!("{ident} is used before it is initialized")) } - fn get_var(&mut self, name: &Key) -> JsResult<(Value, Value)> { + fn get_var(&mut self, name: &Key, xml_method: bool) -> JsResult<(Value, Value)> { + if xml_method { + let mut cur = Some(self.frame()?.env); + while let Some(e) = cur { + match self.heap.env(e) { + Some(Env::Decl { bindings, outer }) => { + if bindings.contains(name) { + return self.get_resolved(Resolved::Decl(e), name); + } + cur = *outer; + } + Some(&Env::Obj { object, with_this, outer }) => { + if self.scope_has(object, name)? { + return self.get_resolved(Resolved::Obj { object, with_this }, name); + } + let this = Value::Object(object); + if self.is_xml(&this) { + let f = self.get_from(object, name, &this)?; + if self.is_callable(&f) { + return Ok((f, this)); + } + } + cur = outer; + } + None => return internal("environment out of range"), + } + } + return self.get_resolved(Resolved::Unresolved, name); + } let r = self.resolve(name)?; self.get_resolved(r, name) } @@ -1668,14 +1696,7 @@ impl Interp { fn op_get_var(&mut self, n: u32, with_this: bool) -> JsResult<()> { let name = self.name(n)?; - if with_this - && self.options.e4x - && let Some((f, this)) = self.xml_scope_method(&name)? - { - self.push(f)?; - return self.push(this); - } - let (v, this) = self.get_var(&name)?; + let (v, this) = self.get_var(&name, with_this && self.options.e4x)?; self.push(v)?; if with_this { self.push(this) } else { Ok(()) } } diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 41e1ae4a75..ef4a6fdda2 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -617,6 +617,89 @@ fn typeof_reads_the_binding_a_with_scope_reported_once() { ); } +#[test] +fn e4x_bare_calls_resolve_proxy_scopes_once() { + for present in ["asked++ < 2", "asked++ === 0", "false"] { + let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default()); + let src = format!( + "var asked = 0, got = 0, outer = 0, receiver; + function method() {{ outer++; return 'outer'; }} + var p = new Proxy({{}}, {{ + has: function (t, k) {{ return k === 'method' && ({present}); }}, + get: function () {{ got++; return function () {{ receiver = this; return 'proxy'; }}; }} + }}); + var result, caught = false; + try {{ with (p) {{ result = method(); }} }} catch (e) {{ caught = e instanceof TypeError; }} + {expected}", + expected = match present { + "asked++ < 2" => "result === 'proxy' && receiver === p && asked === 2 && got === 1 && outer === 0 && !caught", + "asked++ === 0" => "caught && asked === 2 && got === 0 && outer === 0", + _ => "result === 'outer' && got === 0 && outer === 1 && !caught", + } + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true)), "{present}"); + } + let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default()); + assert_eq!(realm.run("var result; with (text) { result = toString(); } result === 'text'"), Ok(JsValue::Bool(true))); +} + +#[test] +fn concat_proxy_array_lengths_use_to_length() { + truth( + "var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0; + var empty = lengths.every(function (length) { + var p = new Proxy([7], { + get: function (t, k) { if (k === 'length') return length; reads++; return t[k]; }, + has: function () { reads++; return true; } + }); + return [3].concat(new Proxy(p, {}), 9).join() === '3,9'; + }); + var p = new Proxy([7, 8], { get: function (t, k) { return k === 'length' ? '1.9' : t[k]; } }); + empty && reads === 0 && [].concat(p).join() === '7' && Array.prototype.concat.call(p, 9).join() === '7,9'", + ); +} + +#[test] +fn reviver_proxy_array_lengths_use_to_length() { + truth( + "var lengths = [-1, -Infinity, NaN, -0, 0.9, '1.9']; + lengths.every(function (length) { + var reads = 0, seen = []; + var p = new Proxy([7, 8], { get: function (t, k) { + if (k === 'length') return length; + reads++; return t[k]; + } }); + var result = JSON.parse('{\"first\":0,\"next\":null}', function (k, v) { + if (k === 'first') this.next = new Proxy(p, {}); + seen.push(k); return v; + }); + return result.next !== null && (length === '1.9' + ? reads === 1 && seen.join() === 'first,0,next,' + : reads === 0 && seen.join() === 'first,next,'); + })", + ); +} + +#[test] +fn concat_and_reviver_proxy_lengths_check_limits_before_reading_elements() { + for length in ["4294967296", "Infinity"] { + let setup = format!( + "var p = new Proxy([], {{ + get: function (t, k) {{ if (k === 'length') return {length}; throw new Error('element read'); }}, + has: function () {{ throw new Error('element checked'); }} + }});" + ); + assert_eq!(limit(&format!("{setup} [].concat(p)"), Limits::default()), LimitKind::Fuel); + let src = format!("{setup} JSON.parse('{{\"first\":0,\"next\":null}}', function (k, v) {{ if (k === 'first') this.next = p; return v; }})"); + assert_eq!(limit(&src, Limits::default()), LimitKind::Heap); + } + let src = "var p = new Proxy([], { get: function (t, k) { + if (k === 'length') return 300000; throw new Error('element read'); + } }); JSON.parse('{\"first\":0,\"next\":null}', function (k, v) { if (k === 'first') this.next = p; return v; })"; + assert_eq!(limit(src, Limits { fuel: 200_000, ..Limits::default() }), LimitKind::Fuel); + type_errors(&["var p = new Proxy([], { get: function () { return Infinity; } }); [0].concat(p)"]); +} + #[test] fn arrays_json_for_in_and_keys_read_a_proxy_through_its_traps() { truth( @@ -1196,6 +1279,52 @@ fn proxy_key_lists_stay_charged_during_nested_descriptor_callbacks() { } } +#[test] +fn reviver_traversal_keys_stay_charged_until_the_frame_is_dropped() { + use crate::builtins::native; + use crate::heap::{HIDDEN, NativeKind, PROP_BYTES, Prop, key}; + use crate::value::Value; + + fn live_bytes(interp: &mut crate::interp::Interp, _: Value, _: &[Value], _: bool) -> crate::interp::JsResult { + interp.collect_garbage(); + Ok(Value::Number(f64::from(u32::try_from(interp.heap.bytes).unwrap()))) + } + + for array in [false, true] { + let mut realm = es(); + let interp = realm.interp(); + let probe = native(interp, "liveBytes", live_bytes, 0, NativeKind::Plain, false).unwrap(); + interp.define(interp.global, key("liveBytes"), Prop::Data { value: Value::Object(probe), flags: HIDDEN }).unwrap(); + let src = format!( + "var name = 'x'; while (name.length < 65536) name += name; + var names = [name], hops = 0, retained = 0; + var handler = {{ + ownKeys: function () {{ return names; }}, + getOwnPropertyDescriptor: function () {{ return {{ configurable: true, enumerable: true }}; }}, + get: function (t, k) {{ + if (k === 'length') return 4096; + if (k !== {first}) return null; + hops++; return hops < 4 ? new Proxy({target}, handler) : null; + }} + }}; + var p = new Proxy({target}, handler), baseline = liveBytes(); + JSON.parse('{{\"first\":0,\"next\":null}}', function (k, v) {{ + if (k === 'first') this.next = p; + if (hops === 4 && retained === 0) retained = liveBytes(); + if (k !== 'first' && k !== 'next' && k !== '' && k !== {first}) return undefined; + return v; + }}); + p = null; + var released = liveBytes(); + retained - baseline > {minimum} && released - baseline < {minimum}", + first = if array { "'0'" } else { "name" }, + target = if array { "[]" } else { "{}" }, + minimum = if array { 3 * 4096 * PROP_BYTES } else { 3 * 65536 * 2 }, + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true)), "array: {array}"); + } +} + #[test] fn legacy_reflection_rejects_proxy_receivers_without_enumerating_them() { let mut realm = es(); diff --git a/crates/js/src/xml.rs b/crates/js/src/xml.rs index a764f7e343..877351d4be 100644 --- a/crates/js/src/xml.rs +++ b/crates/js/src/xml.rs @@ -895,36 +895,6 @@ impl Interp { } } - /// A method found through an XML value in scope, for a call of a bare name in a filter. - pub(crate) fn xml_scope_method(&mut self, name: &Key) -> JsResult> { - let mut cur = Some(self.frame()?.env); - while let Some(e) = cur { - match self.heap.env(e) { - Some(Env::Decl { bindings, outer }) => { - if bindings.contains(name) { - return Ok(None); - } - cur = *outer; - } - Some(&Env::Obj { object, outer, .. }) => { - if self.scope_has(object, name)? { - return Ok(None); - } - let this = Value::Object(object); - if self.is_xml(&this) { - let f = self.get_from(object, name, &this)?; - if self.is_callable(&f) { - return Ok(Some((f, this))); - } - } - cur = outer; - } - None => return Err(Abrupt::Internal("environment out of range".into())), - } - } - Ok(None) - } - pub(crate) fn xml_enumerate(&mut self, id: ObjId) -> JsResult> { let len = match self.classify(&Value::Object(id)) { Xv::List(l) => self.list_len(l)?, diff --git a/docs/mcp.md b/docs/mcp.md index 159ed458dc..55ea16abca 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2851,14 +2851,16 @@ generator object whose `next`, `return` and `throw` run its body to the next `yi `finally` blocks, and resuming a generator while its body runs throws a `TypeError`. Each resumption takes fuel and counts against the call depth. A generator function called in an engine that `#targetengine` kept from a `.jsx` run throws a `TypeError`, since that engine was made without the ECMAScript 2015 built-ins. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and -an engine that `#targetengine` keeps reads each run the way that run's script does. A `.js` script also has the +an engine that `#targetengine` keeps reads each run the way that run's script does. A `.js` script, a `.mjs` file, +and a run with `module: true` also have the globals `Proxy`, with `Proxy.revocable`, and `Reflect` (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. A trap is a script call: it takes fuel and counts against the limit on nested calls. The copy of the property name it is given, key lists retained by enumeration callers, and the names retained during a `for-in` prototype walk count against the heap limit. A trap result that breaks one of the proxy invariants, or any operation on a revoked proxy, throws a `TypeError`. A proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets -`Proxy` and `Reflect` at its first `.js` run and keeps them for later `.jsx` runs. +`Proxy` and `Reflect` at its first ECMAScript 2015 run and keeps them for later `.jsx` runs. +A `.jsx` script or a `source` string run as a script has neither global in a fresh engine. Existing globals with either name are preserved. If a missing global cannot be added because the global object is nonextensible, sealed or frozen, the run fails with an installation error before the script executes. An empty-handler proxy forwards construction of built-ins, including bound built-ins such as `Map.bind(null)` @@ -2882,6 +2884,11 @@ membership checks use host collection indexers, including numeric indices and na become zero and fractional lengths are truncated. It checks run limits before allocating array traversal keys or iterating either list. Its `toJSON` lookup skips host collection indexers through empty-handler proxies and calls an explicit `get` trap when present. +`concat` and `JSON.parse` reviver traversal also use `ToLength` for proxy arrays. They check lengths before +walking indices or allocating traversal keys. `concat` throws `TypeError` if the combined length exceeds +the maximum safe integer. Reviver traversal keys count against the heap limit until their traversal frame is dropped. +In E4X mode, a bare call resolves each scope once. An object binding still checks property membership again +when reading its value; a binding removed between those checks does not select an outer function. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations and symbol enumeration on a revoked proxy also throw `TypeError`. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index dbdb4307e8..1cd85f5b1b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1195,7 +1195,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The collector retains tagged-template cache entries only while the site's code is reachable. - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. - `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`. - - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file both globals; a `.jsx` file and a `source` string have neither in a new engine or in an engine that has not run a `.js` file. An engine that `#targetengine` keeps gets both globals at its first `.js` run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and the first `.js` run does not replace it. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.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`. From 793d0f0832c9404987b245cf3aa8148d4df4f6b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:02:31 -0800 Subject: [PATCH 23/50] JavaScript: stringify keeps array key lists charged, revokers drop their proxy, host constructors refuse distinct new targets, and GeneratorFunction parses before reading the prototype --- crates/js/src/builtins/json.rs | 4 +- crates/js/src/builtins/reflect.rs | 17 ++-- crates/js/src/class_ops.rs | 13 +-- crates/js/src/proxy_tests.rs | 133 ++++++++++++++++++++++++++++++ docs/mcp.md | 11 ++- 5 files changed, 163 insertions(+), 15 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index e8aada1b9a..4d9c87a4d9 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -659,7 +659,9 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J if len > interp.fuel { return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel)); } - interp.reserve_heap((len as usize).saturating_mul(crate::heap::PROP_BYTES))?; + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, (len as usize).saturating_mul(crate::heap::PROP_BYTES))?; + held_keys = Some(held); let mut keys = Vec::with_capacity(len as usize); for i in 0..len { interp.use_fuel()?; diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index ae85c85a40..0b0f60cacf 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -72,15 +72,17 @@ fn proxy_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) } /// `Proxy.revocable(target, handler)` (section 26.2.2.1): an object whose `proxy` is a new proxy -/// and whose `revoke` function revokes it. The function holds the proxy as the `this` of a bound -/// call to [`revoke`], and calling it again does nothing. +/// and whose `revoke` function revokes it. The function's bound `this` holds a private slot +/// whose proxy reference is cleared by the first call. fn revocable(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let p = interp.proxy_create(&arg(args, 0), &arg(args, 1))?; interp.rooted(&[Value::Object(p)], |interp| { - interp.reserve_heap(3 * OBJECT_BYTES)?; + interp.reserve_heap(4 * OBJECT_BYTES + crate::interp::binding_bytes("proxy".len()))?; let inner = native(interp, "", revoke, 0, NativeKind::Plain, false)?; + let slot = interp.heap.alloc_object(Object::new(Class::Ordinary, None)); + interp.define(slot, key("proxy"), Prop::Data { value: Value::Object(p), flags: 0 })?; let proto = interp.intrinsics.function_proto; - let class = Class::Function(Func::Bound { target: inner, this: Value::Object(p), args: Rc::from(Vec::new()) }); + let class = Class::Function(Func::Bound { target: inner, this: Value::Object(slot), args: Rc::from(Vec::new()) }); let f = interp.heap.alloc_object(Object::new(class, Some(proto))); interp.define(f, key("length"), Prop::Data { value: Value::Number(0.0), flags: CONFIGURABLE })?; interp.define(f, key("name"), Prop::Data { value: Value::String(crate::value::Str::from("")), flags: CONFIGURABLE })?; @@ -91,9 +93,12 @@ fn revocable(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult }) } -/// A revocation function's call (section 26.2.2.1.1): `this` is the proxy it revokes. +/// A revocation function's call (section 26.2.2.1.1): `this` contains its private revocation slot. fn revoke(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - if let Value::Object(p) = this { + if let Value::Object(slot) = this + && let Some(Prop::Data { value, .. }) = interp.object_mut(slot)?.props.get_mut(&key("proxy")) + && let Value::Object(p) = std::mem::replace(value, Value::Undefined) + { interp.proxy_revoke(p); } Ok(Value::Undefined) diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index b0cecf8d63..ced17a3507 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -343,12 +343,15 @@ impl Interp { if subclass && name == "Promise" && !args.first().is_some_and(|v| self.is_callable(v)) { return Err(self.type_error("the Promise executor is not a function")); } - // `Number`, `String`, `Date` and `Function` convert their arguments before - // `prototype` is read (sections 20.1.1.1, 21.1.1.1, 20.4.2 and 19.2.1.1.1), so - // a conversion that throws reads nothing from `new.target`. + // `Number`, `String` and `Date` convert arguments before reading `prototype` + // (sections 20.1.1.1, 21.1.1.1 and 20.4.2). `Function` and `GeneratorFunction` + // convert and parse source first (sections 19.2.1.1.1 and 25.2.1.1). let converts_first = { let i = &self.intrinsics; - intrinsic.is_some_and(|p| [i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p)) + intrinsic.is_some_and(|p| { + [i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p) + || self.symbols.objects.is_some_and(|o| p == o.generator_function_proto) + }) }; let fallback = intrinsic.unwrap_or(self.intrinsics.object_proto); let mark = self.temp_roots.len(); @@ -381,7 +384,7 @@ impl Interp { // object it gives inherits from the class's prototype. The class's other functions are // not constructors. A constructor called with `new` cannot wait for its result. Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted }) if self.is_host_constructor(callee) => { - if nt != callee && !forwarding && self.unwrapped_proxy_target(nt)? != callee { + if nt != callee && !forwarding { return Err(self.type_error("this built-in cannot be subclassed")); } let was = std::mem::replace(&mut self.constructing, true); diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index ef4a6fdda2..a3ed321311 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -361,6 +361,139 @@ fn transparent_host_constructor_proxies_forward_construction() { assert_eq!(*calls.borrow(), 3); } +#[test] +fn host_constructors_reject_distinct_proxy_new_targets_before_calling_the_host() { + let calls = Rc::new(RefCell::new(0)); + let count = calls.clone(); + let make: HostFunction = Rc::new(move |_| { + *count.borrow_mut() += 1; + Ok(Data::Object(Vec::new())) + }); + let class = crate::HostClass { name: "Preset".into(), parent: None, members: vec![], info: vec![], index: None, construct: Some(make) }; + let mut realm = es(); + realm.define_host_classes(vec![class], vec![]).unwrap(); + assert_eq!( + realm.run(&format!( + "{PRELUDE}var reads = 0, proto = {{}}; + var P = new Proxy(Preset, {{ get: function (t, k) {{ + if (k === 'prototype') {{ reads++; return proto; }} return t[k]; + }} }}), Q = new Proxy(P, {{}}); + var rejected = type_error(function () {{ Reflect.construct(Preset, [], P); }}) && + type_error(function () {{ Reflect.construct(Preset, [], Q); }}) && + type_error(function () {{ Reflect.construct(P, [], Q); }}); + var a = new P(), b = Reflect.construct(Q, []), c = Reflect.construct(P, [], P); + rejected && reads === 0 && Object.getPrototypeOf(a) === Preset.prototype && + Object.getPrototypeOf(b) === Preset.prototype && Object.getPrototypeOf(c) === Preset.prototype" + )), + Ok(JsValue::Bool(true)) + ); + assert_eq!(*calls.borrow(), 3); +} + +#[test] +fn dynamic_function_constructors_validate_source_before_reading_new_target_prototype() { + truth( + "var G = (function* () {}).constructor; + [Function, G].every(function (C) { + var reads = 0, log = [], proto = {}; + var nt = new Proxy(function () {}, { get: function (t, k) { + if (k === 'prototype') { reads++; log.push('prototype'); throw 17; } return t[k]; + } }); + var syntax = false; + try { Reflect.construct(C, ['}'], nt); } catch (e) { syntax = e instanceof SyntaxError; } + var conversion = false; + try { Reflect.construct(C, [{ toString: function () { throw 23; } }], nt); } + catch (e) { conversion = e === 23; } + if (!syntax || !conversion || reads !== 0) return false; + var thrown = false; + try { Reflect.construct(C, ['return 1;'], nt); } catch (e) { thrown = e === 17; } + if (!thrown || reads !== 1) return false; + log = []; + nt = new Proxy(function () {}, { get: function (t, k) { + if (k === 'prototype') { log.push('prototype'); return proto; } return t[k]; + } }); + var f = Reflect.construct(C, [{ toString: function () { log.push('source'); return 'return 1;'; } }], nt); + var result = C === Function ? f() : f().next().value; + return log.join() === 'source,prototype' && Object.getPrototypeOf(f) === proto && result === 1; + })", + ); +} + +#[test] +fn retained_revokers_release_the_proxy_after_the_first_call() { + fn marker_alive(realm: &mut Realm) -> bool { + realm.collect_garbage(); + let interp = realm.interp(); + let marker = crate::heap::key("revokerRetentionMarker"); + interp.heap.object_ids().iter().any(|&id| interp.heap.object(id).is_some_and(|o| o.props.get(&marker).is_some())) + } + + let mut realm = es(); + assert_eq!( + realm.run( + "var retainedRevoke; + (function () { + var pair = Proxy.revocable({}, {}); + pair.proxy[Symbol('saved')] = { revokerRetentionMarker: true }; + retainedRevoke = pair.revoke; + })(); true", + ), + Ok(JsValue::Bool(true)) + ); + assert!(marker_alive(&mut realm)); + assert_eq!(realm.run("retainedRevoke.call({}) === undefined"), Ok(JsValue::Bool(true))); + assert!(!marker_alive(&mut realm)); + assert_eq!(realm.run("retainedRevoke() === undefined && retainedRevoke.bind(null)() === undefined"), Ok(JsValue::Bool(true))); + assert!(!marker_alive(&mut realm)); +} + +#[test] +fn stringify_array_traversal_keys_stay_charged_until_the_frame_is_dropped() { + use crate::builtins::native; + use crate::heap::{HIDDEN, NativeKind, PROP_BYTES, Prop, key}; + use crate::value::Value; + + fn live_bytes(interp: &mut crate::interp::Interp, _: Value, _: &[Value], _: bool) -> crate::interp::JsResult { + interp.collect_garbage(); + Ok(Value::Number(f64::from(u32::try_from(interp.heap.bytes).unwrap()))) + } + + let mut realm = es(); + let interp = realm.interp(); + let probe = native(interp, "liveBytes", live_bytes, 0, NativeKind::Plain, false).unwrap(); + interp.define(interp.global, key("liveBytes"), Prop::Data { value: Value::Object(probe), flags: HIDDEN }).unwrap(); + let src = format!( + "var hops = 0, retained = 0; + var handler = {{ get: function (t, k) {{ + if (k === 'length') return 4096; + if (k !== '0') return null; + hops++; + if (hops < 4) return new Proxy([], handler); + retained = liveBytes(); return null; + }} }}; + var p = new Proxy([], handler), baseline = liveBytes(); + JSON.stringify(p); + var released = liveBytes(); + hops === 4 && retained - baseline > {minimum} && released - baseline < {minimum}", + minimum = 3 * 4096 * PROP_BYTES, + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); + assert_eq!( + limit( + "var hops = 0; + var handler = { get: function (t, k) { + if (k === 'length') return 4096; + if (k !== '0') return null; + if (++hops === 40) throw 17; + return new Proxy([], handler); + } }; + JSON.stringify(new Proxy([], handler));", + walk_limits(), + ), + LimitKind::Heap + ); +} + #[test] fn reflect_construct_initializes_collections_with_the_new_target_adder() { truth( diff --git a/docs/mcp.md b/docs/mcp.md index 55ea16abca..55d59eb251 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2871,18 +2871,22 @@ as `newTarget` for `Map`, `Set`, `WeakMap`, `WeakSet` and typed arrays and uses `set` or `add` method. A missing or noncallable adder throws `TypeError` before the iterable is read; an omitted or nullish iterable does not require an adder. An adder that throws closes the iterator. An empty-handler proxy also forwards construction of host classes. A distinct host subclass remains unsupported -and throws `TypeError`. In a realm with `Symbol.toStringTag`, `Reflect` has the tag `Reflect`; +and throws `TypeError`. For a host constructor, an explicit distinct `newTarget`, including a proxy wrapping that constructor, +throws `TypeError` before the host constructor runs. In a realm with `Symbol.toStringTag`, `Reflect` has the tag `Reflect`; its symbol property is nonwritable, nonenumerable and configurable. `ArrayBuffer` and typed arrays constructed from primitive lengths convert the length before reading `newTarget.prototype`. `DataView` validates its buffer, byte offset and byte length before reading that prototype. A failure during conversion or validation throws before the prototype getter runs. `Reflect.construct(Promise, args, newTarget)` rejects a missing or noncallable executor with `TypeError` before reading `newTarget.prototype`. For a callable executor, it reads that prototype before calling the executor; a throwing prototype getter prevents the call. +`Function` and `GeneratorFunction` convert and parse their source arguments before reading `newTarget.prototype`. +A conversion or syntax error throws before that prototype getter runs. `Reflect.has` and an empty-handler proxy's membership checks use host collection indexers, including numeric indices and named items. `JSON.stringify` uses `ToLength` for proxy array lengths and proxy replacer-array lengths, so negative lengths become zero and fractional lengths are truncated. It checks run limits before allocating array traversal keys -or iterating either list. Its `toJSON` lookup skips host collection indexers through empty-handler proxies +or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped. +Its `toJSON` lookup skips host collection indexers through empty-handler proxies and calls an explicit `get` trap when present. `concat` and `JSON.parse` reviver traversal also use `ToLength` for proxy arrays. They check lengths before walking indices or allocating traversal keys. `concat` throws `TypeError` if the combined length exceeds @@ -2910,7 +2914,8 @@ object before it finds the property. `Reflect.getOwnPropertyDescriptor` and forwarded proxy descriptors throw `ReferenceError` for an uninitialized namespace export. Proxy invariant checks that read a target descriptor also throw `ReferenceError` for an uninitialized namespace export. The function returned as `Proxy.revocable(...).revoke` has an own empty-string `name` and a `length` of zero; -both properties are nonwritable, nonenumerable and configurable. A +both properties are nonwritable, nonenumerable and configurable. Its first call clears the revoker's reference +to the proxy. Later calls return `undefined` without revoking another object. A `.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there `yield` is a name like any other. A `.js` file `.jsx` file and a `source` string read ES5.1 when run as scripts. With `module: true`, they run as modules and From 3ce03dbf6e9e70389d759df2d44f49300cf32b1b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:59:03 -0800 Subject: [PATCH 24/50] Scripts: ES2015 realms have Object.setPrototypeOf A realm made with Options::es2015 had no Object.setPrototypeOf, so a call threw "the value is not a function". It now follows ECMA-262 2015 section 19.1.2.18: undefined or null for the object, or a prototype that is neither an object nor null, is a TypeError; any other primitive is returned unchanged; an object whose [[SetPrototypeOf]] gives false is a TypeError. It calls the same [[SetPrototypeOf]] as Reflect.setPrototypeOf (Interp::set_prototype_of in crates/js/src/proxy.rs). A non-extensible object given a different prototype, Object.prototype given any other prototype than null, and a prototype whose chain leads back to the object give false. For a proxy it calls the handler's setPrototypeOf trap, or sets the target's prototype when there is no trap; a false result, a revoked proxy and a trap that breaks the section 9.5.2 invariant are TypeErrors. Each prototype the cycle check passes takes fuel, and a sparse array walk that is running sees indices the new prototype brings. The function has length 2 and the name setPrototypeOf, and a realm made without the option does not have it. --- crates/js/src/builtins/object.rs | 28 +++++- crates/js/src/es2015_object_tests.rs | 123 ++++++++++++++++++++++++++- docs/target-app-parity.md | 1 + 3 files changed, 149 insertions(+), 3 deletions(-) diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 599519c0e0..23228fae42 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -24,7 +24,11 @@ pub(super) fn install(interp: &mut Interp, object: ObjId) -> JsResult<()> { method(interp, object, "isSealed", is_sealed, 1)?; method(interp, object, "isFrozen", is_frozen, 1)?; method(interp, object, "isExtensible", is_extensible, 1)?; - method(interp, object, "keys", keys, 1) + method(interp, object, "keys", keys, 1)?; + if interp.options.es2015 { + method(interp, object, "setPrototypeOf", set_prototype_of, 2)?; + } + Ok(()) } fn require_object(interp: &mut Interp, v: &Value, function: &str) -> JsResult { @@ -199,6 +203,28 @@ fn create(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { + let o = arg(args, 0); + if matches!(o, Value::Undefined | Value::Null) { + return Err(interp.type_error("Object.setPrototypeOf was given undefined or null")); + } + let proto = match arg(args, 1) { + Value::Object(p) => Some(p), + Value::Null => None, + _ => return Err(interp.type_error("Object.setPrototypeOf's prototype must be an object or null")), + }; + let Value::Object(id) = o else { return Ok(o) }; + if !interp.set_prototype_of(id, proto)? { + return Err(interp.type_error("Object.setPrototypeOf could not set the prototype")); + } + Ok(o) +} + /// `Object.defineProperty` (section 15.2.3.6). fn define_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = require_object(interp, &arg(args, 0), "defineProperty")?; diff --git a/crates/js/src/es2015_object_tests.rs b/crates/js/src/es2015_object_tests.rs index fbac524860..9e27b1f6b1 100644 --- a/crates/js/src/es2015_object_tests.rs +++ b/crates/js/src/es2015_object_tests.rs @@ -1,5 +1,5 @@ -//! Object literals with computed names, shorthand properties and methods, and the `name` and -//! `length` of functions, with [`Options::es2015`]. +//! Object literals with computed names, shorthand properties and methods, the `name` and +//! `length` of functions, and `Object.setPrototypeOf`, proxies included, with [`Options::es2015`]. use proptest::prelude::*; @@ -504,6 +504,125 @@ fn function_lengths_can_be_redefined() { truth("delete Math.max.length && Math.max.hasOwnProperty('length') === false"); } +// ---- Object.setPrototypeOf ---- + +#[test] +fn set_prototype_of_sets_the_prototype_and_returns_the_object() { + truth("var p = { x: 1 }; var o = {}; Object.setPrototypeOf(o, p) === o && Object.getPrototypeOf(o) === p && o.x === 1"); + truth("var o = {}; Object.setPrototypeOf(o, null) === o && Object.getPrototypeOf(o) === null && !('toString' in o)"); + truth("var a = [1, 2]; Object.setPrototypeOf(a, Object.prototype); a.length === 2 && a.push === undefined"); + truth("var a = []; a.length = 3; Object.setPrototypeOf(a, { 1: 'p' }); a[1] === 'p' && Array.prototype.indexOf.call(a, 'p') === 1"); + truth("function F() {} var o = Object.setPrototypeOf({}, F.prototype); o instanceof F"); + // The prototype it already has is set again even when the object is not extensible. + truth("var p = {}; var o = Object.preventExtensions(Object.create(p)); Object.setPrototypeOf(o, p) === o"); +} + +#[test] +fn set_prototype_of_returns_a_primitive_unchanged() { + truth("Object.setPrototypeOf(1, null) === 1 && Object.setPrototypeOf('s', {}) === 's' && Object.setPrototypeOf(true, null) === true"); + truth("var s = Symbol(); Object.setPrototypeOf(s, null) === s"); + truth("Object.getPrototypeOf(Object.setPrototypeOf(2, null)) === Number.prototype"); +} + +/// `Object.setPrototypeOf` throws a `TypeError` of its own for the script. +fn refused(src: &str) { + throws(src, "TypeError: Object.setPrototypeOf"); +} + +#[test] +fn set_prototype_of_throws_for_undefined_null_and_a_bad_prototype() { + refused("Object.setPrototypeOf(undefined, {})"); + refused("Object.setPrototypeOf(null, null)"); + refused("Object.setPrototypeOf()"); + refused("Object.setPrototypeOf({})"); + refused("Object.setPrototypeOf({}, 1)"); + refused("Object.setPrototypeOf(1, 'p')"); + refused("Object.setPrototypeOf(undefined, 1)"); +} + +#[test] +fn set_prototype_of_throws_when_the_prototype_cannot_change() { + refused("Object.setPrototypeOf(Object.preventExtensions({}), {})"); + refused("Object.setPrototypeOf(Object.freeze({}), null)"); + refused("var a = {}; var b = Object.create(a); Object.setPrototypeOf(a, b)"); + refused("var o = {}; Object.setPrototypeOf(o, o)"); + refused("Object.setPrototypeOf(Object.prototype, {})"); + refused("Object.setPrototypeOf(Object.prototype, Object.create(null))"); + truth("Object.setPrototypeOf(Object.prototype, null) === Object.prototype"); + // A refused change leaves the prototype as it was. + truth( + "var p = {}; var o = Object.preventExtensions(Object.create(p)); try { Object.setPrototypeOf(o, {}); } catch (e) {} Object.getPrototypeOf(o) === p", + ); +} + +#[test] +fn set_prototype_of_lets_a_later_forward_walk_see_the_new_prototype_indices() { + truth( + "var p = { 500000: 'p' }; var a = []; a.length = 1000000; a[0] = 0; var seen = ''; \ + a.forEach(function (v, i) { seen += i + ';'; if (i === 0) Object.setPrototypeOf(a, p); }); seen === '0;500000;'", + ); +} + +#[test] +fn set_prototype_of_calls_a_proxy_trap() { + truth( + "var t = {}; var p = {}; var log = []; \ + var x = new Proxy(t, { setPrototypeOf: function (target, proto) { log.push(target === t, proto === p); return Reflect.setPrototypeOf(target, proto); } }); \ + Object.setPrototypeOf(x, p) === x && Object.getPrototypeOf(t) === p && log.join() === 'true,true'", + ); + // Without a trap the target's prototype is set. + truth("var t = {}; var p = {}; var x = new Proxy(t, {}); Object.setPrototypeOf(x, p) === x && Object.getPrototypeOf(t) === p"); + // A proxy in the new prototype's chain ends the cycle check. + truth("var o = {}; var x = new Proxy(o, {}); Object.setPrototypeOf(o, x) === o && Object.getPrototypeOf(o) === x"); + refused("Object.setPrototypeOf(new Proxy({}, { setPrototypeOf: function () { return false; } }), {})"); + refused("Object.setPrototypeOf(new Proxy({}, { setPrototypeOf: function () { return 0; } }), null)"); + truth( + "var t = {}; var x = new Proxy(t, { setPrototypeOf: function () { return false; } }); \ + try { Object.setPrototypeOf(x, null); } catch (e) {} Object.getPrototypeOf(t) === Object.prototype", + ); + // A trap that reports success for a non-extensible target it did not change breaks an invariant. + throws( + "var t = Object.preventExtensions({}); Object.setPrototypeOf(new Proxy(t, { setPrototypeOf: function () { return true; } }), null)", + "TypeError: the proxy's setPrototypeOf trap", + ); +} + +#[test] +fn set_prototype_of_throws_for_a_revoked_proxy() { + throws( + "var r = Proxy.revocable({}, {}); r.revoke(); Object.setPrototypeOf(r.proxy, {})", + "TypeError: cannot set the prototype of a revoked proxy", + ); + // The prototype check comes before the proxy is read. + refused("var r = Proxy.revocable({}, {}); r.revoke(); Object.setPrototypeOf(r.proxy, 1)"); +} + +#[test] +fn set_prototype_of_has_the_length_and_name_of_a_built_in() { + truth(&name_is("Object.setPrototypeOf", "setPrototypeOf")); + truth( + "var d = Object.getOwnPropertyDescriptor(Object, 'setPrototypeOf'); \ + d.writable && !d.enumerable && d.configurable && Object.setPrototypeOf.length === 2", + ); +} + +#[test] +fn set_prototype_of_charges_fuel_along_a_long_chain() { + let mut realm = es(); + assert_eq!(realm.run("var p = {}; for (var i = 0; i < 5000; i++) p = Object.create(p); true"), Ok(JsValue::Bool(true))); + realm.set_limits(Limits { fuel: 1_000, ..Limits::default() }); + let e = realm.run("Object.setPrototypeOf({}, p); true").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{e:?}"); +} + +#[test] +fn without_the_option_there_is_no_set_prototype_of() { + for options in [Options::default(), Options { e4x: true, ..Options::default() }] { + let mut realm = Realm::with_options(options, Limits::default()); + assert_eq!(realm.run("typeof Object.setPrototypeOf"), Ok(JsValue::String("undefined".into()))); + } +} + // ---- the language mode ---- #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1cd85f5b1b..8a14a790f7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1205,6 +1205,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Object.setPrototypeOf(o, proto)` (ECMA-262 2015 section 19.1.2.18, https://262.ecma-international.org/6.0/#sec-object.setprototypeof), which returns `o` with `proto` as its prototype. `undefined` or `null` for `o`, a `proto` that is neither an object nor `null`, a non-extensible object given a different prototype, and a prototype whose chain leads back to the object are `TypeError`s; any other primitive `o` is returned unchanged. `Object.prototype` keeps its `null` prototype, as later editions give it (https://262.ecma-international.org/11.0/#sec-immutable-prototype-exotic-objects). For a proxy it calls the handler's `setPrototypeOf` trap, or sets the target's prototype when the handler has none, and a `false` result, a revoked proxy and a trap that breaks the invariant of section 9.5.2 are `TypeError`s. It uses the same [[SetPrototypeOf]] as `Reflect.setPrototypeOf`, so the cycle check stops at a proxy in the chain and each prototype it passes takes fuel. A realm made without the option has no `Object.setPrototypeOf`. Tests: `crates/js/src/es2015_object_tests.rs`. - With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals (with a computed name too), `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function, a generator method included, has a `prototype` and is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 1,285 of 1,289 runs of 669 tests pass. The 4 others expect the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. From fd50e7dba103d145fb235216d8b3bca024e051ee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 22:20:58 -0800 Subject: [PATCH 25/50] Scripts: proxies take Symbol keys through their traps A Symbol key on a proxy read, wrote, tested, deleted and described the proxy's own Symbol table, so the target never saw it and no trap ran. Every Symbol path now resolves a proxy the way a string key does: the get, set, has, deleteProperty, defineProperty and getOwnPropertyDescriptor traps receive the Symbol, and without a trap the operation reaches the target with its writable and accessor checks. A super write and a write on a primitive that reach a proxy go through its [[Set]]. - ownKeys traps may return Symbols; a duplicate Symbol (by identity) or any other value is a TypeError, and the result is checked against the target's non-configurable and, for a non-extensible target, all keys of both kinds, in the target's own key order. - Reflect.ownKeys lists Symbols, in the trap's order for a proxy, and Reflect's other functions take Symbol keys. Object.freeze, seal, isFrozen and isSealed include a proxy's Symbols instead of throwing. - Symbol key lists stay rooted and charged to the heap until released. - new Proxy and Proxy.revocable reject a revoked target or handler. - A typed array reached on the prototype chain as the receiver converts the value for an index it lacks. - The eval redeclaration test asserts the runtime SyntaxError. --- crates/js/src/builtins/json.rs | 4 +- crates/js/src/builtins/object.rs | 88 ++++---- crates/js/src/builtins/reflect.rs | 51 +++-- crates/js/src/builtins/symbol.rs | 28 ++- crates/js/src/class_ops.rs | 13 +- crates/js/src/es2015_tests.rs | 2 +- crates/js/src/interp.rs | 39 +++- crates/js/src/lib.rs | 5 +- crates/js/src/proxy.rs | 338 ++++++++++++++++++++++-------- crates/js/src/proxy_tests.rs | 252 ++++++++++++++++++++-- crates/js/src/symbol.rs | 100 +++++++-- docs/mcp.md | 19 +- docs/target-app-parity.md | 2 +- 13 files changed, 724 insertions(+), 217 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 4d9c87a4d9..a6d8babc9e 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -355,7 +355,7 @@ fn enter(interp: &mut Interp, holder: ObjId, name: Key) -> JsResult { keys.push(key_of(i as f64)); } } else { - let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?; + let crate::interp::HeldKeys { keys: names, held, .. } = interp.own_keys(o)?; held_keys = Some(held); for k in names { if interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) { @@ -671,7 +671,7 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J } else if let Some(list) = &settings.properties { list.clone() } else { - let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?; + let crate::interp::HeldKeys { keys: names, held, .. } = interp.own_keys(o)?; held_keys = Some(held); let mut keys = Vec::new(); for k in names { diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 23228fae42..21b0b5e0c3 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -153,10 +153,17 @@ pub(crate) fn names_array(interp: &mut Interp, names: impl IntoIterator JsResult<(Vec, crate::interp::HeldBytes)> { - let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?; - let mut keys: Vec = names.into_iter().map(PropKey::Str).collect(); - keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym)); - Ok((keys, held)) + Ok(interp.own_keys_and_symbols(o)?.into_prop_keys()) +} + +/// Returns the Symbol roots for a property-key list. +fn prop_key_roots(keys: &[PropKey]) -> Vec { + keys.iter() + .filter_map(|k| match k { + PropKey::Sym(s) => Some(Value::Symbol(s.clone())), + PropKey::Str(_) => None, + }) + .collect() } /// `Object.getPrototypeOf` (section 15.2.3.2). @@ -285,28 +292,28 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { /// 15.2.3.8 and 15.2.3.9). A proxy that does not become non-extensible is a `TypeError`. fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { let Value::Object(o) = v else { return Ok(v) }; - check_integrity_symbols(interp, o)?; if !interp.prevent_extensions(o)? { let what = if freeze { "frozen" } else { "sealed" }; return Err(interp.type_error(&format!("the object cannot be {what}: it did not stop being extensible"))); } let (keys, _held) = own_prop_keys(interp, o)?; - check_integrity_symbols(interp, o)?; - for k in keys { - interp.use_fuel()?; - let desc = if freeze { - let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; - match prop { - Prop::Data { .. } => Desc { configurable: Some(false), writable: Some(false), ..Desc::default() }, - Prop::Accessor { .. } => Desc { configurable: Some(false), ..Desc::default() }, - } - } else { - Desc { configurable: Some(false), ..Desc::default() } - }; - interp.define_own_pk(o, k, &desc, true)?; - } - check_integrity_symbols(interp, o)?; - Ok(Value::Object(o)) + let roots = prop_key_roots(&keys); + interp.rooted(&roots, |interp| { + for k in keys { + interp.use_fuel()?; + let desc = if freeze { + let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; + match prop { + Prop::Data { .. } => Desc { configurable: Some(false), writable: Some(false), ..Desc::default() }, + Prop::Accessor { .. } => Desc { configurable: Some(false), ..Desc::default() }, + } + } else { + Desc { configurable: Some(false), ..Desc::default() } + }; + interp.define_own_pk(o, k, &desc, true)?; + } + Ok(Value::Object(o)) + }) } fn seal(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { @@ -334,42 +341,27 @@ fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let Value::Object(o) = v else { return Ok(Value::Bool(true)) }; let o = *o; - check_integrity_symbols(interp, o)?; if interp.is_extensible(o)? { return Ok(Value::Bool(false)); } let (keys, _held) = own_prop_keys(interp, o)?; - check_integrity_symbols(interp, o)?; - for k in keys { - interp.use_fuel()?; - let Some(prop) = interp.own_pk(o, &k)? else { continue }; - if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) { - return Ok(Value::Bool(false)); + let roots = prop_key_roots(&keys); + interp.rooted(&roots, |interp| { + for k in keys { + interp.use_fuel()?; + let Some(prop) = interp.own_pk(o, &k)? else { continue }; + if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) { + return Ok(Value::Bool(false)); + } } - } - check_integrity_symbols(interp, o)?; - Ok(Value::Bool(true)) + Ok(Value::Bool(true)) + }) } fn is_sealed(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { locked(interp, &arg(args, 0), false) } -fn check_integrity_symbols(interp: &mut Interp, o: ObjId) -> JsResult<()> { - if !interp.is_proxy(o) { - return Ok(()); - } - let mut current = o; - loop { - if interp.object(current)?.syms.as_ref().is_some_and(|m| m.len() != 0) { - return Err(interp.type_error("proxy integrity operations with symbol properties are not supported")); - } - let Some(target) = interp.symbol_lookup_target(current)? else { return Ok(()) }; - interp.use_fuel()?; - current = target; - } -} - fn is_frozen(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { locked(interp, &arg(args, 0), true) } @@ -384,7 +376,7 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { - let crate::interp::HeldKeys { keys, held } = interp.own_keys(o)?; + let crate::interp::HeldKeys { keys, held, .. } = interp.own_keys(o)?; let mut names = Vec::new(); for k in keys { interp.use_fuel()?; @@ -392,6 +384,6 @@ fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult /// property was defined. fn define_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "defineProperty")?; - interp.with_key(&arg(args, 1), |interp, k| { + interp.with_prop_key(&arg(args, 1), |interp, k| { let desc: Desc = to_desc(interp, &arg(args, 2))?; let roots = desc_values(&desc); - interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, false)).map(Value::Bool) + interp.rooted(&roots, |interp| interp.define_own_pk(o, k, &desc, false)).map(Value::Bool) }) } /// `Reflect.deleteProperty(target, propertyKey)` (section 26.1.4): whether the property is gone. fn delete_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "deleteProperty")?; - interp.with_key(&arg(args, 1), |interp, k| interp.delete(o, &k, false)).map(Value::Bool) + interp.with_prop_key(&arg(args, 1), |interp, k| interp.delete_pk(o, &k, false)).map(Value::Bool) } /// `Reflect.get(target, propertyKey[, receiver])` (section 26.1.5). fn get(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "get")?; let receiver = if args.len() > 2 { arg(args, 2) } else { Value::Object(o) }; - interp.with_key(&arg(args, 1), |interp, k| interp.get_from(o, &k, &receiver)) + interp.with_prop_key(&arg(args, 1), |interp, k| match k { + PropKey::Str(name) => interp.get_from(o, &name, &receiver), + PropKey::Sym(s) => interp.get_sym_from(o, &s, &receiver), + }) } /// `Reflect.getOwnPropertyDescriptor(target, propertyKey)` (section 26.1.6). fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "getOwnPropertyDescriptor")?; - interp.with_key(&arg(args, 1), |interp, k| match interp.own_property(o, &k)? { + interp.with_prop_key(&arg(args, 1), |interp, k| match interp.own_pk(o, &k)? { Some(p) => from_prop(interp, &p), None => Ok(Value::Undefined), }) @@ -199,7 +203,7 @@ fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J /// `Reflect.has(target, propertyKey)` (section 26.1.8). fn has(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "has")?; - interp.with_key(&arg(args, 1), |interp, k| interp.has_property_indexed(o, &k)).map(Value::Bool) + interp.with_prop_key(&arg(args, 1), |interp, k| interp.has_pk_indexed(o, &k)).map(Value::Bool) } /// `Reflect.isExtensible(target)` (section 26.1.9). @@ -208,11 +212,32 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe interp.is_extensible(o).map(Value::Bool) } -/// `Reflect.ownKeys(target)` (section 26.1.10): every own property name, enumerable or not. +/// `Reflect.ownKeys(target)` (section 26.1.10): every own property key, enumerable or not: the +/// names, then the Symbols. fn own_keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "ownKeys")?; - let names = interp.ecma_own_keys(o)?; - names_array(interp, names) + // A proxy's list holds its Symbols already, in its trap's order, from the one `ownKeys` call. + let mut keys = interp.ecma_own_keys(o)?; + if !interp.is_proxy(o) { + keys.syms = interp.own_symbols(o)?; + keys.held.add(interp, keys.syms.len().saturating_mul(crate::interp::KEY_ENTRY_BYTES))?; + } + let roots: Vec = keys.syms.iter().cloned().map(Value::Symbol).collect(); + let (keys, _held) = keys.into_prop_keys(); + interp.rooted(&roots, |interp| { + let a = new_array(interp, 0)?; + interp.rooted(&[Value::Object(a)], |interp| { + for (i, k) in keys.into_iter().enumerate() { + interp.use_fuel()?; + let v = match k { + PropKey::Str(name) => Value::String(Str::from_rc(name)), + PropKey::Sym(s) => Value::Symbol(s), + }; + create_at(interp, a, i as f64, v)?; + } + Ok(Value::Object(a)) + }) + }) } /// `Reflect.preventExtensions(target)` (section 26.1.11): whether the object is now not @@ -228,7 +253,7 @@ fn set(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult 3 { arg(args, 3) } else { Value::Object(o) }; let v = arg(args, 2); - interp.with_key(&arg(args, 1), |interp, k| interp.set_with_receiver(o, k, v, &receiver)).map(Value::Bool) + interp.with_prop_key(&arg(args, 1), |interp, k| interp.set_pk_with_receiver(o, k, v, &receiver)).map(Value::Bool) } /// `Reflect.setPrototypeOf(target, proto)` (section 26.1.13): whether the prototype was set. A diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index beec94c6a5..0bbccebb1c 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -169,14 +169,26 @@ fn date_to_primitive(interp: &mut Interp, this: Value, args: &[Value], _: bool) fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { - let syms = interp.own_symbols(o)?; - let a = new_array(interp, 0)?; - interp.rooted(&[Value::Object(a)], |interp| { - for (i, s) in syms.into_iter().enumerate() { - interp.use_fuel()?; - create_at(interp, a, i as f64, Value::Symbol(s))?; - } - Ok(Value::Object(a)) + // A proxy's list stays counted against the heap until the array holds its Symbols. + let (syms, _held) = if interp.is_proxy(o) { + let keys = interp.proxy_own_keys(o)?; + (keys.syms, keys.held) + } else { + let syms = interp.own_symbols(o)?; + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, syms.len().saturating_mul(crate::interp::KEY_ENTRY_BYTES))?; + (syms, held) + }; + let roots: Vec = syms.iter().cloned().map(Value::Symbol).collect(); + interp.rooted(&roots, |interp| { + let a = new_array(interp, 0)?; + interp.rooted(&[Value::Object(a)], |interp| { + for (i, s) in syms.into_iter().enumerate() { + interp.use_fuel()?; + create_at(interp, a, i as f64, Value::Symbol(s))?; + } + Ok(Value::Object(a)) + }) }) }) } diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index ced17a3507..8f69f066df 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -577,7 +577,7 @@ impl Interp { } /// The key as text for a message. - fn pk_name(&mut self, k: &PropKey) -> JsResult { + pub(crate) fn pk_name(&mut self, k: &PropKey) -> JsResult { match k { PropKey::Str(name) => Ok(String::from_utf16_lossy(name)), PropKey::Sym(s) => self.sym_name(s), @@ -635,7 +635,16 @@ impl Interp { crate::interp::Lookup::Found(prop) => Some(prop), crate::interp::Lookup::Missing => None, }, - PropKey::Sym(s) => self.find_sym(proto, s)?, + PropKey::Sym(s) => match self.sym_holder(proto, s)? { + Some((p, None)) => { + if !self.set_sym_with_receiver(p, s.clone(), v, receiver)? { + return self.super_reject(throw, &k, "the proxy did not set it"); + } + return Ok(()); + } + Some((_, prop)) => prop, + None => None, + }, }; let why = match inherited { Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), receiver, &[v]).map(drop), diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 1b6233bbd1..e2d9f9cd25 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -311,7 +311,7 @@ fn eval_without_the_option_cannot_redeclare_an_earlier_runs_let() { realm.set_es2015(false); for src in ["eval('var x = 2')", "eval('function x() {}')", "(0, eval)('var x = 2')"] { let r = realm.run(src); - assert!(matches!(&r, Err(RunError { message, .. }) if message.starts_with("SyntaxError")), "{src}: {r:?}"); + assert!(is_thrown(&r, "SyntaxError"), "{src}: {r:?}"); } assert_eq!(realm.run("x === 1 && !this.hasOwnProperty('x')"), Ok(JsValue::Bool(true))); // A name no `let` holds is still declared. diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 235e8f8d43..8db5ccd6e3 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -485,9 +485,24 @@ impl Drop for HeldBytes { pub(crate) struct HeldKeys { pub(crate) keys: Vec, + /// The Symbols, when the list was asked for with them: empty otherwise. + pub(crate) syms: Vec, + /// Both kinds of key in the order a proxy's `ownKeys` trap gave them; `None` for a list + /// whose names come before its Symbols. + pub(crate) ordered: Option>, pub(crate) held: HeldBytes, } +impl HeldKeys { + /// Every key of both kinds, in the trap's order or with the names first, and what keeps them + /// counted. + pub(crate) fn into_prop_keys(self) -> (Vec, HeldBytes) { + let HeldKeys { keys, syms, ordered, held } = self; + let all = ordered.unwrap_or_else(|| keys.into_iter().map(PropKey::Str).chain(syms.into_iter().map(PropKey::Sym)).collect()); + (all, held) + } +} + impl std::ops::Deref for HeldKeys { type Target = Vec; @@ -1804,7 +1819,7 @@ impl Interp { /// [[GetOwnProperty]] (section 8.12.1), through a proxy's trap when `id` is a proxy. pub(crate) fn get_own_property(&mut self, id: ObjId, k: &Key) -> JsResult> { if self.is_proxy(id) { - return self.proxy_get_own_property(id, k); + return self.proxy_get_own_property(id, &PropKey::Str(k.clone())); } self.ordinary_own_property(id, k) } @@ -1899,8 +1914,8 @@ impl Interp { if let Some(p) = self.ordinary_own_property(o, k)? { return Ok(SetLookup::Found(p)); } - if crate::builtins::binary::typed_key(self, o, k).is_some() { - return Ok(SetLookup::Ignored); + if let Some(n) = crate::builtins::binary::typed_key(self, o, k) { + return Ok(SetLookup::TypedArray(o, n)); } cur = self.object(o)?.proto; steps += 1; @@ -2009,7 +2024,7 @@ impl Interp { match self.lookup(id, k)? { Lookup::Found(_) => Ok(true), Lookup::Missing => Ok(false), - Lookup::Proxy(p) => self.proxy_has(p, k), + Lookup::Proxy(p) => self.proxy_has(p, &PropKey::Str(k.clone())), } } @@ -2038,7 +2053,7 @@ impl Interp { Lookup::Found(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Lookup::Found(Prop::Data { value, .. }) => Ok(value), Lookup::Found(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), - Lookup::Proxy(p) => self.proxy_get(p, k, receiver, true), + Lookup::Proxy(p) => self.proxy_get(p, &PropKey::Str(k.clone()), receiver, true), } } @@ -2054,7 +2069,7 @@ impl Interp { Lookup::Missing | Lookup::Found(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Lookup::Found(Prop::Data { value, .. }) => Ok(value), Lookup::Found(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), - Lookup::Proxy(p) => self.proxy_get(p, k, receiver, false), + Lookup::Proxy(p) => self.proxy_get(p, &PropKey::Str(k.clone()), receiver, false), } } @@ -2121,7 +2136,7 @@ impl Interp { /// `throw` a rejection throws a `TypeError` instead. pub(crate) fn define_own_property(&mut self, id: ObjId, k: Key, desc: &Desc, throw: bool) -> JsResult { if self.is_proxy(id) { - let defined = self.proxy_define_own_property(id, &k, desc)?; + let defined = self.proxy_define_own_property(id, &PropKey::Str(k.clone()), desc)?; if !defined { return self.reject_bool(throw, &k, "the proxy's defineProperty trap returned false"); } @@ -2341,7 +2356,7 @@ impl Interp { if is_array { out.push(key("length")); } - Ok(HeldKeys { keys: out, held }) + Ok(HeldKeys { keys: out, syms: Vec::new(), ordered: None, held }) } pub(crate) fn ecma_own_keys(&mut self, id: ObjId) -> JsResult { @@ -2407,7 +2422,7 @@ impl Interp { }; let inherited = match lookup { SetLookup::ReadOnly => return self.reject(throw, &k, "a module namespace object is read-only"), - SetLookup::Ignored => return Ok(()), + SetLookup::TypedArray(..) => return Ok(()), SetLookup::Proxy(p) => { if !self.set_with_receiver(p, k.clone(), v, &Value::Object(id))? { return self.reject(throw, &k, "the proxy did not set it"); @@ -2489,7 +2504,7 @@ impl Interp { /// [[Delete]] (section 8.12.7). pub(crate) fn delete(&mut self, id: ObjId, k: &Key, throw: bool) -> JsResult { if self.is_proxy(id) { - let deleted = self.proxy_delete(id, k)?; + let deleted = self.proxy_delete(id, &PropKey::Str(k.clone()))?; if !deleted && throw { let key = String::from_utf16_lossy(k); return Err(self.type_error(&format!("cannot delete property '{key}': the proxy's deleteProperty trap returned false"))); @@ -5058,7 +5073,9 @@ pub(crate) enum SetLookup { Proxy(ObjId), Missing, ReadOnly, - Ignored, + /// A typed array on the chain with a numeric name it has no element for: the write is + /// ignored, after converting the value when the typed array is the receiver. + TypedArray(ObjId, f64), } /// What a proxy's [[Call]] or [[Construct]] did. diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index f812193c13..ed4ae49268 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -124,9 +124,8 @@ //! //! With [`Options::es2015`], the realm also has `Proxy`, with `Proxy.revocable`, and `Reflect`, as //! ECMAScript 2020 defines them (sections 26.1 and 26.2 and 9.5, -//! ), with string property names: a trap is given only -//! string keys, `Reflect.ownKeys` lists only string keys, and a Symbol key read through a proxy -//! goes to its target without a trap. +//! ), with string and Symbol property keys: a trap is +//! given either kind of key, an `ownKeys` trap may return both, and `Reflect.ownKeys` lists both. #![forbid(unsafe_code)] pub mod ast; diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index 7a53949a83..650cc3a97b 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -20,6 +20,7 @@ use crate::heap::{ CONFIGURABLE, Class, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, PROXY_BYTES, Prop, ProxyData, WRITABLE, key, string_bytes, }; use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, HeldKeys, Interp, JsResult, KEY_ENTRY_BYTES, ProxyCall, SetLookup, merge_desc, same_value}; +use crate::symbol::{PropKey, Sym}; use crate::value::{Str, Value, index_key}; /// The most names an `ownKeys` trap may give. @@ -30,8 +31,7 @@ impl Interp { matches!(self.heap.object(id).map(|o| &o.class), Some(Class::Proxy(_))) } - /// The target that a lookup of a Symbol key on the proxy `id` goes on to, since traps take - /// string property names only; `None` when `id` is not a proxy. A revoked proxy is a + /// The target of the proxy `id`, `None` when `id` is not a proxy. A revoked proxy is a /// `TypeError`. pub(crate) fn symbol_lookup_target(&mut self, id: ObjId) -> JsResult> { let Some(ProxyData { target, handler, .. }) = self.proxy_data(id) else { return Ok(None) }; @@ -60,6 +60,12 @@ impl Interp { pub(crate) fn proxy_create(&mut self, target: &Value, handler: &Value) -> JsResult { let Value::Object(t) = target else { return Err(self.type_error("a proxy's target must be an object")) }; let Value::Object(h) = handler else { return Err(self.type_error("a proxy's handler must be an object")) }; + // A revoked proxy is neither a target nor a handler (section 9.5.14, steps 2 and 4). + for (o, what) in [(*t, "target"), (*h, "handler")] { + if matches!(self.proxy_data(o), Some(ProxyData { handler: None, .. })) { + return Err(self.type_error(&format!("a proxy's {what} cannot be a revoked proxy"))); + } + } let data = ProxyData { target: Some(*t), handler: Some(*h), callable: self.is_callable(target), constructor: self.is_constructor(target) }; self.rooted(&[target.clone(), handler.clone()], |i| i.reserve_heap(OBJECT_BYTES + PROXY_BYTES))?; self.heap.bytes = self.heap.bytes.saturating_add(PROXY_BYTES); @@ -239,15 +245,15 @@ impl Interp { // ---- properties ---- /// [[GetOwnProperty]] of a proxy (section 9.5.5). - pub(crate) fn proxy_get_own_property(&mut self, p: ObjId, k: &Key) -> JsResult> { - self.proxy_op(p, "read a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "getOwnPropertyDescriptor")? else { return i.own_property(target, k) }; - let name = i.key_value(k)?; + pub(crate) fn proxy_get_own_property(&mut self, p: ObjId, k: &PropKey) -> JsResult> { + self.proxy_op(p, "read a property of", &[pk_root(k)], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "getOwnPropertyDescriptor")? else { return i.own_pk(target, k) }; + let name = i.pk_value(k)?; let result = i.call_trap(&trap, handler, &[Value::Object(target), name])?; if !matches!(result, Value::Object(_) | Value::Undefined) { return Err(i.invariant("getOwnPropertyDescriptor", "returned a value that is neither an object nor undefined")); } - let target_prop = i.own_property(target, k)?; + let target_prop = i.own_pk(target, k)?; if let Some(prop) = &target_prop { i.temp_roots.extend(desc_values(&prop_desc(prop))); } @@ -289,18 +295,18 @@ impl Interp { } /// [[DefineOwnProperty]] of a proxy (section 9.5.6): whether the trap defined the property. - pub(crate) fn proxy_define_own_property(&mut self, p: ObjId, k: &Key, desc: &Desc) -> JsResult { + pub(crate) fn proxy_define_own_property(&mut self, p: ObjId, k: &PropKey, desc: &Desc) -> JsResult { let mut roots = desc_values(desc); - roots.push(Value::String(Str::from_rc(k.clone()))); + roots.push(pk_root(k)); self.proxy_op(p, "define a property of", &roots, |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "defineProperty")? else { return i.define_own_property(target, k.clone(), desc, false) }; + let Some(trap) = i.proxy_trap(handler, "defineProperty")? else { return i.define_own_pk(target, k.clone(), desc, false) }; let desc_obj = from_desc(i, desc)?; i.temp_roots.push(desc_obj.clone()); - let name = i.rooted(std::slice::from_ref(&desc_obj), |i| i.key_value(k))?; + let name = i.rooted(std::slice::from_ref(&desc_obj), |i| i.pk_value(k))?; if !i.call_trap(&trap, handler, &[Value::Object(target), name, desc_obj])?.truthy() { return Ok(false); } - let target_prop = i.own_property(target, k)?; + let target_prop = i.own_pk(target, k)?; let extensible = i.is_extensible(target)?; let setting_config_false = desc.configurable == Some(false); let Some(current) = target_prop else { @@ -330,12 +336,12 @@ impl Interp { } /// [[HasProperty]] of a proxy (section 9.5.7). - pub(crate) fn proxy_has(&mut self, p: ObjId, k: &Key) -> JsResult { - self.proxy_op(p, "test a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "has")? else { return i.has_property_indexed(target, k) }; - let name = i.key_value(k)?; + pub(crate) fn proxy_has(&mut self, p: ObjId, k: &PropKey) -> JsResult { + self.proxy_op(p, "test a property of", &[pk_root(k)], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "has")? else { return i.has_pk_indexed(target, k) }; + let name = i.pk_value(k)?; let found = i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy(); - if !found && let Some(current) = i.own_property(target, k)? { + if !found && let Some(current) = i.own_pk(target, k)? { if !current.configurable() { return Err(i.invariant("has", "hid a non-configurable property of its target")); } @@ -348,14 +354,18 @@ impl Interp { } /// [[Get]] of a proxy (section 9.5.8). - pub(crate) fn proxy_get(&mut self, p: ObjId, k: &Key, receiver: &Value, indexed: bool) -> JsResult { - self.proxy_op(p, "read a property of", &[receiver.clone(), Value::String(Str::from_rc(k.clone()))], |i, target, handler| { + pub(crate) fn proxy_get(&mut self, p: ObjId, k: &PropKey, receiver: &Value, indexed: bool) -> JsResult { + self.proxy_op(p, "read a property of", &[receiver.clone(), pk_root(k)], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "get")? else { - return if indexed { i.get_from(target, k, receiver) } else { i.get_property_only(target, k, receiver) }; + return match k { + PropKey::Str(name) if indexed => i.get_from(target, name, receiver), + PropKey::Str(name) => i.get_property_only(target, name, receiver), + PropKey::Sym(s) => i.get_sym_from(target, s, receiver), + }; }; - let name = i.key_value(k)?; + let name = i.pk_value(k)?; let v = i.call_trap(&trap, handler, &[Value::Object(target), name, receiver.clone()])?; - match i.own_property(target, k)? { + match i.own_pk(target, k)? { Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(&v, &value) => { Err(i.invariant("get", "gave a value other than its target's non-configurable, read-only property")) } @@ -368,14 +378,14 @@ impl Interp { } /// [[Set]] of a proxy (section 9.5.9): whether the trap set the property. - fn proxy_set(&mut self, p: ObjId, k: &Key, v: &Value, receiver: &Value) -> JsResult { - self.proxy_op(p, "set a property of", &[v.clone(), receiver.clone(), Value::String(Str::from_rc(k.clone()))], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "set")? else { return i.set_with_receiver(target, k.clone(), v.clone(), receiver) }; - let name = i.key_value(k)?; + pub(crate) fn proxy_set(&mut self, p: ObjId, k: &PropKey, v: &Value, receiver: &Value) -> JsResult { + self.proxy_op(p, "set a property of", &[v.clone(), receiver.clone(), pk_root(k)], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "set")? else { return i.set_pk_with_receiver(target, k.clone(), v.clone(), receiver) }; + let name = i.pk_value(k)?; if !i.call_trap(&trap, handler, &[Value::Object(target), name, v.clone(), receiver.clone()])?.truthy() { return Ok(false); } - match i.own_property(target, k)? { + match i.own_pk(target, k)? { Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(v, &value) => { Err(i.invariant("set", "set a value other than its target's non-configurable, read-only property")) } @@ -388,14 +398,14 @@ impl Interp { } /// [[Delete]] of a proxy (section 9.5.10): whether the trap deleted the property. - pub(crate) fn proxy_delete(&mut self, p: ObjId, k: &Key) -> JsResult { - self.proxy_op(p, "delete a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "deleteProperty")? else { return i.delete(target, k, false) }; - let name = i.key_value(k)?; + pub(crate) fn proxy_delete(&mut self, p: ObjId, k: &PropKey) -> JsResult { + self.proxy_op(p, "delete a property of", &[pk_root(k)], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "deleteProperty")? else { return i.delete_pk(target, k, false) }; + let name = i.pk_value(k)?; if !i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy() { return Ok(false); } - let Some(current) = i.own_property(target, k)? else { return Ok(true) }; + let Some(current) = i.own_pk(target, k)? else { return Ok(true) }; if !current.configurable() { return Err(i.invariant("deleteProperty", "deleted a non-configurable property of its target")); } @@ -407,23 +417,45 @@ impl Interp { } /// [[OwnPropertyKeys]] of a proxy (section 9.5.11). The trap must give an array-like object - /// of distinct strings, at most [`MAX_OWN_KEYS`] of them, that holds every non-configurable - /// name of the target, and of a non-extensible target exactly its names. Each name takes a - /// unit of fuel and counts against the heap limit until the caller drops the list. + /// of distinct strings and Symbols, at most [`MAX_OWN_KEYS`] of them, that holds every + /// non-configurable key of the target, and of a non-extensible target exactly its keys. Each + /// key takes a unit of fuel and counts against the heap limit until the caller drops the list, + /// which keeps the trap's order in [`HeldKeys::ordered`]. pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult { self.proxy_op(p, "list the properties of", &[], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.ecma_own_keys(target) }; + let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { + // A target that is a proxy gives its Symbols with its names. + let mut keys = i.ecma_own_keys(target)?; + if !i.is_proxy(target) { + keys.syms = i.own_symbols(target)?; + keys.held.add(i, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?; + } + return Ok(keys); + }; let result = i.call_trap(&trap, handler, &[Value::Object(target)])?; let mut held = HeldBytes::new(i); - let keys = i.trap_key_list(&result, &mut held)?; - i.check_own_keys(target, &keys)?; - Ok(HeldKeys { keys, held }) + let TrapKeys { keys, syms, ordered } = i.trap_key_list(&result, &mut held)?; + i.check_own_keys(target, &keys, &syms)?; + Ok(HeldKeys { keys, syms, ordered: Some(ordered), held }) }) } - /// CreateListFromArrayLike (section 7.3.17) of an `ownKeys` trap's result, refusing a value - /// that is not a string and a name given twice. - fn trap_key_list(&mut self, result: &Value, held: &mut HeldBytes) -> JsResult> { + /// The object's own names and its own Symbols together, from a single [[OwnPropertyKeys]]: + /// one `ownKeys` trap call for a proxy. + pub(crate) fn own_keys_and_symbols(&mut self, id: ObjId) -> JsResult { + if self.is_proxy(id) { + return self.proxy_own_keys(id); + } + let mut keys = self.own_keys(id)?; + keys.syms = self.own_symbols(id)?; + keys.held.add(self, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?; + Ok(keys) + } + + /// CreateListFromArrayLike (section 7.3.17) of an `ownKeys` trap's result: its names and its + /// Symbols in the order given, refusing a value that is neither and a key given twice. Two + /// Symbols are the same key only when they are the same Symbol. + fn trap_key_list(&mut self, result: &Value, held: &mut HeldBytes) -> JsResult { let Value::Object(list) = result else { return Err(self.invariant("ownKeys", "returned a value that is not an object")) }; let length = self.get_from(*list, &key("length"), result)?; let n = self.to_number(&length)?; @@ -433,63 +465,167 @@ impl Interp { return Err(self.throw(ErrorType::Range, "the proxy's ownKeys trap returned too many names")); } let mut keys = Vec::new(); + let mut syms = Vec::new(); + let mut ordered = Vec::new(); let mut seen: HashSet = HashSet::new(); + // Symbols by identity: their addresses. + let mut seen_syms: HashSet = HashSet::new(); let mut duplicate = None; for index in 0..n as u32 { self.use_fuel()?; let v = self.get_from(*list, &index_key(index), result)?; - let Value::String(s) = v else { return Err(self.invariant("ownKeys", "returned a name that is not a string")) }; - held.add(self, string_bytes(s.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; - let k = s.flat(); - if !seen.insert(k.clone()) && duplicate.is_none() { - duplicate = Some(k.clone()); + match v { + Value::String(s) => { + held.add(self, string_bytes(s.len()).saturating_add(3 * KEY_ENTRY_BYTES))?; + let k = s.flat(); + if !seen.insert(k.clone()) && duplicate.is_none() { + duplicate = Some(PropKey::Str(k.clone())); + } + ordered.push(PropKey::Str(k.clone())); + keys.push(k); + } + Value::Symbol(s) => { + // A Symbol read from the list stays reachable while later entries are read. + self.temp_roots.push(Value::Symbol(s.clone())); + held.add(self, 3 * KEY_ENTRY_BYTES)?; + if !seen_syms.insert(s.addr()) && duplicate.is_none() { + duplicate = Some(PropKey::Sym(s.clone())); + } + ordered.push(PropKey::Sym(s.clone())); + syms.push(s); + } + _ => return Err(self.invariant("ownKeys", "returned a key that is neither a string nor a Symbol")), } - keys.push(k); } if let Some(k) = duplicate { - let name = String::from_utf16_lossy(&k); - return Err(self.invariant("ownKeys", &format!("returned the name '{name}' twice"))); + let name = self.pk_name(&k)?; + return Err(self.invariant("ownKeys", &format!("returned the key '{name}' twice"))); } - Ok(keys) + Ok(TrapKeys { keys, syms, ordered }) } - /// Steps 16 to 23 of section 9.5.11: the names `keys` the trap gave against the target's. - fn check_own_keys(&mut self, target: ObjId, keys: &[Key]) -> JsResult<()> { + /// Steps 16 to 23 of section 9.5.11: the names `keys` and the Symbols `syms` the trap gave + /// against the target's own keys of both kinds. + fn check_own_keys(&mut self, target: ObjId, keys: &[Key], syms: &[Sym]) -> JsResult<()> { let extensible = self.is_extensible(target)?; - let target_keys = self.own_keys(target)?; - let mut fixed = Vec::new(); - let mut configurable = Vec::new(); - for k in target_keys.iter() { - self.use_fuel()?; - if self.own_property(target, k)?.is_some_and(|p| !p.configurable()) { - fixed.push(k.clone()); - } else { - configurable.push(k.clone()); + // The target's keys in its own order (a proxy target's trap order), counted until the + // check ends. + let (target_keys, _held) = self.own_keys_and_symbols(target)?.into_prop_keys(); + let mark = self.temp_roots.len(); + self.temp_roots.extend(target_keys.iter().filter_map(|k| match k { + PropKey::Sym(s) => Some(Value::Symbol(s.clone())), + PropKey::Str(_) => None, + })); + let r = (|| { + let mut fixed = Vec::new(); + let mut configurable = Vec::new(); + for k in target_keys.iter().cloned() { + self.use_fuel()?; + if self.own_pk(target, &k)?.is_some_and(|p| !p.configurable()) { + fixed.push(k); + } else { + configurable.push(k); + } + } + if extensible && fixed.is_empty() { + return Ok(()); + } + let mut unchecked: HashSet<&[u16]> = keys.iter().map(|k| &**k).collect(); + let mut unchecked_syms: HashSet = syms.iter().map(Sym::addr).collect(); + for k in &fixed { + if !take(&mut unchecked, &mut unchecked_syms, k) { + let name = self.pk_name(k)?; + return Err(self.invariant("ownKeys", &format!("left out the non-configurable property '{name}' of its target"))); + } + } + if extensible { + return Ok(()); + } + for k in &configurable { + if !take(&mut unchecked, &mut unchecked_syms, k) { + let name = self.pk_name(k)?; + return Err(self.invariant("ownKeys", &format!("left out the property '{name}' of its non-extensible target"))); + } + } + if !unchecked.is_empty() || !unchecked_syms.is_empty() { + return Err(self.invariant("ownKeys", "gave a key its non-extensible target does not have")); + } + Ok(()) + })(); + self.temp_roots.truncate(mark); + r + } + + /// The value a trap is given for the key `k`: a copy of a name, or the Symbol itself. + fn pk_value(&mut self, k: &PropKey) -> JsResult { + match k { + PropKey::Str(name) => self.key_value(name), + PropKey::Sym(s) => Ok(Value::Symbol(s.clone())), + } + } + + /// [[Set]] of `k` on `o` with `receiver`, for a name or a Symbol: whether the value was set. + pub(crate) fn set_pk_with_receiver(&mut self, o: ObjId, k: PropKey, v: Value, receiver: &Value) -> JsResult { + match k { + PropKey::Str(name) => self.set_with_receiver(o, name, v, receiver), + PropKey::Sym(s) => self.set_sym_with_receiver(o, s, v, receiver), + } + } + + /// [[Set]] (sections 9.1.9 and 9.5.9) of the Symbol `k` on `o` with `receiver`: a proxy's + /// `set` trap, a setter found on the chain, or a data property defined on the receiver + /// through its own [[DefineOwnProperty]]. Whether the value was set. + pub(crate) fn set_sym_with_receiver(&mut self, o: ObjId, k: Sym, v: Value, receiver: &Value) -> JsResult { + let mark = self.temp_roots.len(); + self.temp_roots.extend([Value::Object(o), Value::Symbol(k.clone()), v.clone(), receiver.clone()]); + let r = self.ordinary_set_sym(o, k, v, receiver); + self.temp_roots.truncate(mark); + r + } + + fn ordinary_set_sym(&mut self, o: ObjId, k: Sym, v: Value, receiver: &Value) -> JsResult { + let mut cur = o; + let mut steps = 0usize; + let own = loop { + if self.is_proxy(cur) { + return self.proxy_set(cur, &PropKey::Sym(k), &v, receiver); + } + if matches!(self.object(cur)?.class, Class::ModuleNamespace(_)) { + return Ok(false); + } + if let Some(p) = self.get_own_sym(cur, &k)? { + break p; + } + match self.object(cur)?.proto { + Some(next) => { + self.use_fuel()?; + cur = next; + } + None => break Prop::Data { value: Value::Undefined, flags: OPEN }, + } + steps += 1; + if steps > 1_000_000 { + return Err(Abrupt::Internal("prototype chain too long".into())); + } + }; + match own { + Prop::Accessor { set: Some(s), .. } => { + self.call(&Value::Object(s), receiver, &[v])?; + Ok(true) + } + Prop::Accessor { set: None, .. } => Ok(false), + Prop::Data { flags, .. } if flags & WRITABLE == 0 => Ok(false), + Prop::Data { .. } => { + let Value::Object(r) = receiver else { return Ok(false) }; + let r = *r; + match self.get_own_sym(r, &k)? { + Some(Prop::Accessor { .. }) => Ok(false), + Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => Ok(false), + Some(Prop::Data { .. }) => self.define_own_sym(r, k, &Desc { value: Some(v), ..Desc::default() }, false), + None => self.define_own_sym(r, k, &Desc::data(v, OPEN), false), + } } } - if extensible && fixed.is_empty() { - return Ok(()); - } - let mut unchecked: HashSet<&[u16]> = keys.iter().map(|k| &**k).collect(); - for k in &fixed { - if !unchecked.remove(&**k) { - let name = String::from_utf16_lossy(k); - return Err(self.invariant("ownKeys", &format!("left out the non-configurable property '{name}' of its target"))); - } - } - if extensible { - return Ok(()); - } - for k in &configurable { - if !unchecked.remove(&**k) { - let name = String::from_utf16_lossy(k); - return Err(self.invariant("ownKeys", &format!("left out the property '{name}' of its non-extensible target"))); - } - } - if !unchecked.is_empty() { - return Err(self.invariant("ownKeys", "gave a name its non-extensible target does not have")); - } - Ok(()) } /// [[Set]] (section 9.1.9) of `k` on `o` with `receiver`: a proxy's `set` trap, a setter found @@ -519,8 +655,13 @@ impl Interp { let found = self.lookup_for_set(o, &k)?; let own = match found { SetLookup::ReadOnly => return Ok(false), - SetLookup::Ignored => return Ok(true), - SetLookup::Proxy(p) => return self.proxy_set(p, &k, &v, receiver), + SetLookup::TypedArray(t, n) => { + if receiver.as_object() == Some(t) { + crate::builtins::binary::set_element(self, t, n, &v)?; + } + return Ok(true); + } + SetLookup::Proxy(p) => return self.proxy_set(p, &PropKey::Str(k), &v, receiver), SetLookup::Found(prop) => prop, SetLookup::Missing => Prop::Data { value: Value::Undefined, flags: OPEN }, }; @@ -612,6 +753,29 @@ impl Interp { } } +/// The keys an `ownKeys` trap gave: the names, the Symbols, and both in the trap's order. +struct TrapKeys { + keys: Vec, + syms: Vec, + ordered: Vec, +} + +/// The key `k` as a value, to keep it reachable while a trap runs. +fn pk_root(k: &PropKey) -> Value { + match k { + PropKey::Str(name) => Value::String(Str::from_rc(name.clone())), + PropKey::Sym(s) => Value::Symbol(s.clone()), + } +} + +/// Removes `k` from the keys a trap gave that are not yet matched: whether it was there. +fn take(names: &mut HashSet<&[u16]>, syms: &mut HashSet, k: &PropKey) -> bool { + match k { + PropKey::Str(name) => names.remove(&**name), + PropKey::Sym(s) => syms.remove(&s.addr()), + } +} + /// The values a descriptor holds, to keep them reachable while more script runs. pub(crate) fn desc_values(desc: &Desc) -> Vec { let mut out: Vec = desc.value.iter().cloned().collect(); diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index a3ed321311..55887b2c67 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -318,7 +318,7 @@ fn own_keys_reads_and_validates_the_list_before_rejecting_duplicates() { try { Reflect.ownKeys(p); } catch (e) { caught = e === marker; } Object.defineProperty(result, '2', { get: function () { reads++; return 1; } }); var invalid = false; - try { Reflect.ownKeys(p); } catch (e) { invalid = e instanceof TypeError && e.message.indexOf('not a string') >= 0; } + try { Reflect.ownKeys(p); } catch (e) { invalid = e instanceof TypeError && e.message.indexOf('neither a string nor a Symbol') >= 0; } duplicate && caught && invalid && reads === 3", ); } @@ -949,24 +949,183 @@ fn transparent_builtin_constructors_read_the_proxy_new_target_prototype() { } #[test] -fn proxy_integrity_operations_reject_symbol_properties() { +fn proxy_integrity_operations_reach_the_targets_symbol_properties() { truth( "var s = Symbol('x'), t = {}; t[s] = 1; var p = new Proxy(new Proxy(t, {}), {}); - var freeze = type_error(function () { Object.freeze(p); }); - var seal = type_error(function () { Object.seal(p); }); - var extensible = Object.isExtensible(t); - Object.preventExtensions(t); - freeze && seal && extensible && type_error(function () { Object.isFrozen(p); }) && - type_error(function () { Object.isSealed(p); }) && Object.getOwnPropertyDescriptor(t, s).writable", + var before = Object.isSealed(p); + Object.freeze(p); + var d = Object.getOwnPropertyDescriptor(t, s); + !before && Object.isFrozen(p) && Object.isSealed(p) && !d.writable && !d.configurable && t[s] === 1", ); truth( - "var p = new Proxy({}, {}); p[Symbol('x')] = 1; - type_error(function () { Object.freeze(p); }) && type_error(function () { Object.isFrozen(p); })", + "var s = Symbol('x'), p = new Proxy({}, {}); p[s] = 1; + Object.seal(p); + var d = Object.getOwnPropertyDescriptor(p, s); + Object.isSealed(p) && !Object.isFrozen(p) && d.writable && !d.configurable", ); +} + +#[test] +fn symbol_keys_on_a_proxy_reach_its_target_without_traps() { truth( - "var p = new Proxy({}, { ownKeys: function () { p[Symbol('x')] = 1; return []; } }); - type_error(function () { Object.freeze(p); })", + "var s = Symbol('s'), t = {}; t[s] = 1; + var p = new Proxy(t, {}); + var syms = Object.getOwnPropertySymbols(p), d = Reflect.getOwnPropertyDescriptor(p, s); + p[s] = 2; + var other = Symbol('other'); p[other] = 3; + Object.defineProperty(p, Symbol.iterator, { value: 4, configurable: true }); + var deleted = delete p[other]; + syms.length === 1 && syms[0] === s && d.value === 1 && t[s] === 2 && p[s] === 2 && s in p && + deleted && !(other in t) && t[Symbol.iterator] === 4 && + Object.getOwnPropertySymbols(p).length === 2 && Reflect.ownKeys(p)[1] === Symbol.iterator", + ); + // A write through a proxy keeps the target's read-only and getter-only properties. + truth( + "var s = Symbol('s'), g = Symbol('g'), t = {}; + Object.defineProperty(t, s, { value: 1, writable: false, configurable: true }); + Object.defineProperty(t, g, { get: function () { return 5; }, configurable: true }); + var p = new Proxy(t, {}); p[s] = 2; p[g] = 6; + t[s] === 1 && t[g] === 5 && !Reflect.set(p, s, 2) && !Reflect.set(p, g, 6) && + type_error(function () { 'use strict'; p[s] = 2; })", + ); + // An object that inherits from a proxy sets its own property through the proxy's [[Set]]. + truth( + "var s = Symbol('s'), t = {}, child = Object.create(new Proxy(t, {})); + child[s] = 1; + Object.getOwnPropertySymbols(child).length === 1 && !(s in t) && child[s] === 1", + ); +} + +#[test] +fn symbol_keys_on_a_proxy_run_its_traps() { + truth( + "var s = Symbol('s'), log = []; + var p = new Proxy({}, { + get: function (t, k, r) { log.push('get'); return k === s ? 'from trap' : undefined; }, + has: function (t, k) { log.push('has'); return k === s; }, + set: function (t, k, v) { log.push('set'); return k === s; }, + deleteProperty: function (t, k) { log.push('delete'); return k === s; }, + defineProperty: function (t, k, d) { log.push('define'); return k === s; }, + getOwnPropertyDescriptor: function (t, k) { log.push('gopd'); return undefined; } + }); + var child = Object.create(p); + var read = p[s] === 'from trap' && child[s] === 'from trap' && s in p && s in child; + p[s] = 1; + var set = Reflect.set(p, s, 1) && !Reflect.set(p, Symbol('x'), 1); + var del = delete p[s] && Reflect.deleteProperty(p, s); + var def = Reflect.defineProperty(p, s, { value: 1, configurable: true }); + var gopd = Reflect.getOwnPropertyDescriptor(p, s) === undefined; + read && set && del && def && gopd && + log.join() === 'get,get,has,has,set,set,set,delete,delete,define,gopd'", + ); + // A `super` write with a Symbol key that reaches a proxy is its [[Set]], with `this` as the + // receiver; the descriptor trap does not run. + truth( + "var s = Symbol('s'), seen = null; + var proto = new Proxy({}, { + set: function (t, k, v, r) { seen = [k, v, r]; return true; }, + getOwnPropertyDescriptor: function () { throw 'descriptor'; } + }); + class C { write() { super[s] = 3; } } + Object.setPrototypeOf(C.prototype, proto); + var o = new C(); + o.write(); + seen[0] === s && seen[1] === 3 && seen[2] === o", + ); + // A Symbol write on a primitive whose prototype chain reaches a proxy is the proxy's [[Set]], + // with the primitive as the receiver. + truth( + "var s = Symbol('s'), seen = null; + Object.setPrototypeOf(Number.prototype, new Proxy({}, { + set: function (t, k, v, r) { seen = [k, v, r]; return true; }, + getOwnPropertyDescriptor: function () { throw 'descriptor'; } + })); + (1)[s] = 2; + seen[0] === s && seen[1] === 2 && seen[2] === 1", + ); + // An outer proxy checks its trap's keys against an inner proxy target's keys in that + // target's trap order. + truth( + "var s = Symbol('s'), order = []; + var inner = new Proxy({}, { + ownKeys: function () { return [s, 'x']; }, + getOwnPropertyDescriptor: function (t, k) { order.push(k); return undefined; } + }); + var outer = new Proxy(inner, { ownKeys: function () { return []; } }); + Reflect.ownKeys(outer); + order.length === 2 && order[0] === s && order[1] === 'x'", + ); + // A trap that breaks an invariant for a Symbol key is a TypeError. + type_errors(&[ + "var s = Symbol('s'), t = {}; Object.defineProperty(t, s, { value: 1 }); + var p = new Proxy(t, { get: function () { return 2; } }); p[s];", + "var s = Symbol('s'), t = {}; Object.defineProperty(t, s, { value: 1 }); + var p = new Proxy(t, { has: function () { return false; } }); s in p;", + ]); +} + +#[test] +fn own_keys_traps_give_symbols_and_are_checked_against_the_targets_symbols() { + truth( + "var s = Symbol('s'), u = Symbol('s'); + var p = new Proxy({}, { ownKeys: function () { return [s, 'a', u]; } }); + var keys = Reflect.ownKeys(p), syms = Object.getOwnPropertySymbols(p); + keys.length === 3 && keys[0] === s && keys[1] === 'a' && keys[2] === u && + syms.length === 2 && syms[0] === s && Object.getOwnPropertyNames(p).length === 1", + ); + // `Object.defineProperties` reads the descriptors in the trap's order. + truth( + "var s = Symbol('s'), order = []; + var source = new Proxy({ a: {}, [s]: {} }, { + ownKeys: function () { return [s, 'a']; }, + getOwnPropertyDescriptor: function (t, k) { order.push(k); return Reflect.getOwnPropertyDescriptor(t, k); } + }); + Object.defineProperties({}, source); + order.length === 2 && order[0] === s && order[1] === 'a'", + ); + type_errors(&[ + // The same Symbol twice. + "var s = Symbol('s'); var p = new Proxy({}, { ownKeys: function () { return [s, s]; } }); Reflect.ownKeys(p);", + // A value that is neither a string nor a Symbol. + "var p = new Proxy({}, { ownKeys: function () { return [1]; } }); Reflect.ownKeys(p);", + // A non-configurable Symbol of the target left out. + "var s = Symbol('s'), t = {}; Object.defineProperty(t, s, { value: 1 }); + var p = new Proxy(t, { ownKeys: function () { return []; } }); Reflect.ownKeys(p);", + // A Symbol of a non-extensible target left out. + "var s = Symbol('s'), t = {}; t[s] = 1; Object.preventExtensions(t); + var p = new Proxy(t, { ownKeys: function () { return []; } }); Reflect.ownKeys(p);", + // A Symbol a non-extensible target does not have. + "var t = Object.preventExtensions({}); + var p = new Proxy(t, { ownKeys: function () { return [Symbol('s')]; } }); Reflect.ownKeys(p);", + ]); + // The target's non-configurable Symbol, given back, passes. + truth( + "var s = Symbol('s'), t = {}; Object.defineProperty(t, s, { value: 1 }); + var p = new Proxy(t, { ownKeys: function () { return [s]; } }); + Reflect.ownKeys(p)[0] === s", + ); +} + +#[test] +fn a_revoked_proxy_is_neither_a_target_nor_a_handler() { + type_errors(&[ + "var r = Proxy.revocable({}, {}); r.revoke(); new Proxy(r.proxy, {});", + "var r = Proxy.revocable({}, {}); r.revoke(); new Proxy({}, r.proxy);", + "var r = Proxy.revocable({}, {}); r.revoke(); Proxy.revocable(r.proxy, {});", + "var r = Proxy.revocable({}, {}); r.revoke(); Proxy.revocable({}, r.proxy);", + ]); + // A proxy that is not revoked is still a valid target and handler. + truth("var p = new Proxy({ x: 1 }, {}); new Proxy(p, new Proxy({}, {})).x === 1"); +} + +#[test] +fn a_typed_array_receiver_converts_the_value_for_an_index_it_lacks() { + truth( + "var a = new Uint8Array(1), reads = 0, v = { valueOf: function () { reads++; return 1; } }; + var set = Reflect.set(Object.create(a), '2', v, a); + var other = {}, ignored = Reflect.set(Object.create(a), '2', v, other); + set && reads === 1 && ignored && reads === 1 && !('2' in other) && a.length === 1", ); } @@ -1412,6 +1571,75 @@ fn proxy_key_lists_stay_charged_during_nested_descriptor_callbacks() { } } +#[test] +fn symbol_keys_stay_counted_when_descriptor_traps_delete_the_target_properties() { + use crate::builtins::native; + use crate::heap::{HIDDEN, NativeKind, Prop, key}; + use crate::value::Value; + + fn live_bytes(interp: &mut crate::interp::Interp, _: Value, _: &[Value], _: bool) -> crate::interp::JsResult { + interp.collect_garbage(); + Ok(Value::Number(f64::from(u32::try_from(interp.heap.bytes).unwrap()))) + } + + for operation in ["Object.freeze(p)", "Object.isFrozen(p)", "Object.isSealed(p)"] { + let mut realm = es(); + realm.define_function("makeSymbol", |_| Ok(JsValue::Symbol(Some("x".repeat(65536))))); + let interp = realm.interp(); + let probe = native(interp, "liveBytes", live_bytes, 0, NativeKind::Plain, false).unwrap(); + interp.define(interp.global, key("liveBytes"), Prop::Data { value: Value::Object(probe), flags: HIDDEN }).unwrap(); + let src = format!( + "var t = {{}}, retained = 0, cleared = false; + t[makeSymbol()] = 1; t[makeSymbol()] = 2; + Object.preventExtensions(t); + function clear() {{ Object.getOwnPropertySymbols(t).forEach(function (s) {{ delete t[s]; }}); }} + var p = new Proxy(t, {{ getOwnPropertyDescriptor: function () {{ + if (!cleared) {{ clear(); cleared = true; }} + retained = liveBytes(); return undefined; + }} }}); + var baseline = liveBytes(); + {operation}; + cleared && retained > baseline - 65536 && liveBytes() < retained - 65536" + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true)), "{operation}"); + } +} + +#[test] +fn forwarded_symbol_key_lists_stay_charged_until_released() { + use crate::builtins::native; + use crate::heap::{HIDDEN, NativeKind, Prop, key}; + use crate::interp::KEY_ENTRY_BYTES; + use crate::value::Value; + + fn check_list(interp: &mut crate::interp::Interp, _: Value, args: &[Value], _: bool) -> crate::interp::JsResult { + let Value::Object(o) = args[0] else { panic!("expected an object") }; + interp.collect_garbage(); + let before = interp.heap.bytes; + let keys = interp.own_keys_and_symbols(o)?; + assert!(!keys.syms.is_empty()); + interp.collect_garbage(); + let retained = interp.heap.bytes; + assert!(retained >= before + keys.syms.len() * KEY_ENTRY_BYTES); + drop(keys); + interp.collect_garbage(); + assert!(interp.heap.bytes < retained); + Ok(Value::Bool(true)) + } + + let mut realm = es(); + let interp = realm.interp(); + let probe = native(interp, "checkList", check_list, 1, NativeKind::Plain, false).unwrap(); + interp.define(interp.global, key("checkList"), Prop::Data { value: Value::Object(probe), flags: HIDDEN }).unwrap(); + assert_eq!( + realm.run( + "var t = {}; t[Symbol('a')] = 1; t[Symbol('b')] = 2; + checkList(t) && checkList(new Proxy(t, {})) && checkList(new Proxy(new Proxy(t, {}), {}))" + ), + Ok(JsValue::Bool(true)) + ); +} + #[test] fn reviver_traversal_keys_stay_charged_until_the_frame_is_dropped() { use crate::builtins::native; diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index e90652ec00..7ebcacbbc2 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -143,6 +143,7 @@ impl SymProps { } /// A property key (section 6.1.7): a name or a Symbol. +#[derive(Clone)] pub(crate) enum PropKey { Str(crate::heap::Key), Sym(Sym), @@ -315,24 +316,29 @@ impl Interp { self.reject(true, &name, why) } + /// [[GetOwnProperty]] for a Symbol key, through a proxy's `getOwnPropertyDescriptor` trap + /// when `id` is a proxy. pub(crate) fn get_own_sym(&mut self, id: ObjId, k: &Sym) -> JsResult> { - self.symbol_lookup_target(id)?; + if self.is_proxy(id) { + return self.proxy_get_own_property(id, &PropKey::Sym(k.clone())); + } Ok(self.object(id)?.syms.as_ref().and_then(|m| m.get(k)).cloned()) } - /// The property `k` found on the object or its prototype chain. Each step to a prototype takes - /// a unit of fuel. A proxy on the way is passed through to its target. - pub(crate) fn find_sym(&mut self, id: ObjId, k: &Sym) -> JsResult> { + /// The object on the chain from `id` that holds `k` with the property, or the first proxy on + /// the way, whose traps answer the rest; `None` when no object on the chain has `k`. Each step + /// to a prototype takes a unit of fuel. + pub(crate) fn sym_holder(&mut self, id: ObjId, k: &Sym) -> JsResult)>> { let mut cur = Some(id); let mut steps = 0usize; while let Some(o) = cur { - if let Some(p) = self.get_own_sym(o, k)? { - return Ok(Some(p)); + if self.is_proxy(o) { + return Ok(Some((o, None))); } - cur = match self.symbol_lookup_target(o)? { - Some(target) => Some(target), - None => self.object(o)?.proto, - }; + if let Some(p) = self.object(o)?.syms.as_ref().and_then(|m| m.get(k)).cloned() { + return Ok(Some((o, Some(p)))); + } + cur = self.object(o)?.proto; if cur.is_some() { self.use_fuel()?; } @@ -344,12 +350,23 @@ impl Interp { Ok(None) } - /// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter. + /// [[HasProperty]] of `k`, through the `has` trap of a proxy on the prototype chain. + pub(crate) fn has_sym(&mut self, id: ObjId, k: &Sym) -> JsResult { + match self.sym_holder(id, k)? { + None => Ok(false), + Some((_, Some(_))) => Ok(true), + Some((p, None)) => self.proxy_has(p, &PropKey::Sym(k.clone())), + } + } + + /// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter, through the + /// `get` trap of a proxy on the prototype chain. pub(crate) fn get_sym_from(&mut self, start: ObjId, k: &Sym, receiver: &Value) -> JsResult { - match self.find_sym(start, k)? { - None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), - Some(Prop::Data { value, .. }) => Ok(value), - Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), + match self.sym_holder(start, k)? { + None | Some((_, Some(Prop::Accessor { get: None, .. }))) => Ok(Value::Undefined), + Some((_, Some(Prop::Data { value, .. }))) => Ok(value), + Some((_, Some(Prop::Accessor { get: Some(g), .. }))) => self.call(&Value::Object(g), receiver, &[]), + Some((p, None)) => self.proxy_get(p, &PropKey::Sym(k.clone()), receiver, true), } } @@ -363,9 +380,9 @@ impl Interp { self.get_sym_from(start, k, base) } - /// Adds or replaces an own property directly, keeping the heap estimate. + /// Adds or replaces an own property directly, keeping the heap estimate. For objects the + /// engine made, which are never proxies. pub(crate) fn define_sym(&mut self, id: ObjId, k: Sym, prop: Prop) -> JsResult<()> { - self.symbol_lookup_target(id)?; let o = self.object_mut(id)?; if o.syms.get_or_insert_with(Box::default).insert(k, prop) { self.heap.bytes = self.heap.bytes.saturating_add(PROP_BYTES); @@ -375,6 +392,12 @@ impl Interp { /// The default [[DefineOwnProperty]] (section 9.1.6) for a Symbol key. pub(crate) fn define_own_sym(&mut self, id: ObjId, k: Sym, desc: &Desc, throw: bool) -> JsResult { + if self.is_proxy(id) { + if !self.proxy_define_own_property(id, &PropKey::Sym(k.clone()), desc)? { + return self.reject_sym_bool(throw, &k, "the proxy's defineProperty trap returned false"); + } + return Ok(true); + } let Some(current) = self.get_own_sym(id, &k)? else { if !self.object(id)?.extensible { return self.reject_sym_bool(throw, &k, "the object is not extensible"); @@ -399,6 +422,12 @@ impl Interp { /// [[Set]] (section 9.1.9) of an ordinary object for a Symbol key. pub(crate) fn put_sym(&mut self, id: ObjId, k: Sym, v: Value, throw: bool) -> JsResult<()> { + if self.is_proxy(id) { + if !self.set_sym_with_receiver(id, k.clone(), v, &Value::Object(id))? { + return self.reject_sym(throw, &k, "the proxy did not set it"); + } + return Ok(()); + } match self.get_own_sym(id, &k)? { Some(Prop::Data { flags, .. }) => { if flags & WRITABLE == 0 { @@ -420,6 +449,13 @@ impl Interp { if matches!(self.object(object)?.class, crate::heap::Class::ModuleNamespace(_)) { return self.reject_sym(throw, &k, "a module namespace object is read-only"); } + // Past a proxy the rest is its [[Set]], with the object as the receiver. + if self.is_proxy(object) { + if !self.set_sym_with_receiver(object, k.clone(), v, &Value::Object(id))? { + return self.reject_sym(throw, &k, "the proxy did not set it"); + } + return Ok(()); + } if let Some(property) = self.get_own_sym(object, &k)? { inherited = Some(property); break; @@ -460,10 +496,18 @@ impl Interp { } _ => { let proto = self.primitive_proto(base, &[])?; - if let Some(Prop::Accessor { set: Some(s), .. }) = self.find_sym(proto, &k)? { - return self.call(&Value::Object(s), base, &[v]).map(drop); - } let strict = self.strict(); + match self.sym_holder(proto, &k)? { + Some((_, Some(Prop::Accessor { set: Some(s), .. }))) => return self.call(&Value::Object(s), base, &[v]).map(drop), + // Past a proxy the rest is its [[Set]], with the primitive as the receiver. + Some((p, None)) => { + if !self.set_sym_with_receiver(p, k.clone(), v, base)? { + return self.reject_sym(strict, &k, "the proxy did not set it"); + } + return Ok(()); + } + _ => {} + } self.reject_sym(strict, &k, "the value is a primitive") } } @@ -471,6 +515,14 @@ impl Interp { /// [[Delete]] (section 9.1.10) for a Symbol key. pub(crate) fn delete_sym(&mut self, id: ObjId, k: &Sym, throw: bool) -> JsResult { + if self.is_proxy(id) { + let deleted = self.proxy_delete(id, &PropKey::Sym(k.clone()))?; + if !deleted && throw { + let key = self.sym_name(k)?; + return Err(self.type_error(&format!("cannot delete property '{key}': the proxy's deleteProperty trap returned false"))); + } + return Ok(deleted); + } match self.get_own_sym(id, k)? { None => Ok(true), Some(p) if p.configurable() => { @@ -488,9 +540,11 @@ impl Interp { } /// An object's own Symbol keys in the order they were added. Each takes a unit of fuel, and - /// the heap for the list is checked first. + /// the heap for the list is checked first. A proxy's Symbols come from its `ownKeys` trap. pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { - self.symbol_lookup_target(id)?; + if self.is_proxy(id) { + return Ok(self.proxy_own_keys(id)?.syms); + } let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); self.reserve_heap(count.saturating_mul(16))?; for _ in 0..count { @@ -511,7 +565,7 @@ impl Interp { pub(crate) fn has_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult { match k { PropKey::Str(name) => self.has_property(id, name), - PropKey::Sym(s) => Ok(self.find_sym(id, s)?.is_some()), + PropKey::Sym(s) => self.has_sym(id, s), } } diff --git a/docs/mcp.md b/docs/mcp.md index 55d59eb251..53ae667e35 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2854,7 +2854,7 @@ throws a `TypeError`, since that engine was made without the ECMAScript 2015 bui an engine that `#targetengine` keeps reads each run the way that run's script does. A `.js` script, a `.mjs` file, and a run with `module: true` also have the globals `Proxy`, with `Proxy.revocable`, and `Reflect` (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 -and 26.2), with string property names. A trap is a script call: it takes fuel and counts against the limit on nested calls. +and 26.2), with string and Symbol property keys. A trap is a script call: it takes fuel and counts against the limit on nested calls. The copy of the property name it is given, key lists retained by enumeration callers, and the names retained during a `for-in` prototype walk count against the heap limit. A trap result that breaks one of the proxy invariants, or any operation on a revoked proxy, throws a `TypeError`. A @@ -2896,9 +2896,15 @@ when reading its value; a binding removed between those checks does not select a The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations and symbol enumeration on a revoked proxy also throw `TypeError`. -`Reflect.ownKeys` returns string keys only. Ordinary targets list array-index keys in ascending order, -then other strings in insertion order; an array's `length` precedes its other non-index strings. -A proxy's `ownKeys` trap determines its key order. A `for-in` prototype walk keeps the current proxy reachable +A Symbol key on a proxy goes through the same traps as a string key (`get`, `set`, `has`, `deleteProperty`, +`defineProperty` and `getOwnPropertyDescriptor`), which receive the Symbol itself; without a trap the operation +reaches the target. `Reflect`'s functions take Symbol keys too. +For an ordinary object, `Reflect.ownKeys` returns the string keys, then the Symbols in insertion order. Ordinary +targets list array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes +its other non-index strings. A proxy's `ownKeys` trap determines its key order, with strings and Symbols mixed as the +trap gives them. The trap may return strings and Symbols; any other value, or +the same key twice (two Symbols are the same key only when they are the same Symbol), throws `TypeError`, and the +result is checked against the target's non-configurable keys of both kinds. A `for-in` prototype walk keeps the current proxy reachable through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from the receiver's prototype chain. A `for-in` loop checks each proxy candidate's descriptor when iteration reaches that name. An `ownKeys` result is read and its elements are validated before duplicate @@ -2907,8 +2913,9 @@ Deleting a binding in a `with` scope calls the proxy's `deleteProperty` trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay reachable during proxy callbacks, including callbacks that revoke a nested target proxy. `Reflect.set` and ordinary assignment ignore invalid numeric indices found on a typed-array prototype -without creating a property on the receiver. `Object.freeze`, `Object.seal`, `Object.isFrozen` -and `Object.isSealed` throw `TypeError` for a proxy when it or any of its proxy targets has symbol properties. +without creating a property on the receiver; when that typed array is the receiver, the value is converted to a +number first. `Object.freeze`, `Object.seal`, `Object.isFrozen` and `Object.isSealed` include a proxy's Symbol +keys. `new Proxy` and `Proxy.revocable` throw `TypeError` when the target or the handler is a revoked proxy. `Reflect.set` and a write a proxy forwards return false when the lookup reaches a module namespace object before it finds the property. `Reflect.getOwnPropertyDescriptor` and forwarded proxy descriptors throw `ReferenceError` for an uninitialized namespace export. Proxy invariant diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8a14a790f7..410b9cf84a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1195,7 +1195,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The collector retains tagged-template cache entries only while the site's code is reachable. - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. - `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`. - - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string and Symbol property keys. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate key or a value that is neither a string nor a Symbol), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.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`. From 5b0fbec41677dc5af9701e68de03272348546b84 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 02:55:01 -0800 Subject: [PATCH 26/50] Retype: glyphs drawn alike in several fonts count as one outline in near matching Near matching compared a shape with the 256 glyphs closest to it in proportion, over every indexed face. Faces that draw the same glyphs (Noto families sharing their Latin dots, copies of a font under other names) each took places among the 256, and when glyphs tied, which of them kept a place depended on an unstable selection. A simplified period, turned with its line, ranks near the 240th place among the faces craft-fonts supplies, so each face loaded after them pushed some fonts' periods out: with four copies of Source Sans 3 loaded, Source Sans 3's period was no longer compared and Retype left the period of "no." an outline. In a full vectorcraft-engine test run the test fonts that other tests load into the shared font database did this to turned_near_matched_round_glyphs_keep_the_line_turn. Each indexed glyph now carries a hash of its outline. Ranking groups the glyphs drawn alike into one outline, keeps the 256 closest outlines with every glyph of each, and breaks ties by index order. A group is fitted once and its poses go to each of its glyphs, so the comparisons spent do not grow with the number of faces that draw the outline. docs/mcp.md describes the limit as 256 outlines. --- crates/text/src/retype.rs | 168 ++++++++++++++++++++++++++++++-------- docs/mcp.md | 4 +- 2 files changed, 138 insertions(+), 34 deletions(-) diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index deeebbd519..b020a3827f 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -79,7 +79,8 @@ pub const MAX_NEAR_KEYS: usize = 1024; const NEAR_WORK: u64 = 2_000_000_000; /// Point comparisons near matching makes for one shape, at most. const NEAR_SHAPE_WORK: u64 = 50_000_000; -/// Glyphs one shape is near matched against, at most: those closest to it in proportion. +/// Outlines one shape is near matched against, at most: those closest to it in proportion, each +/// with every glyph drawn as it is. const NEAR_FITS: usize = 256; /// Contours [`clusters`] reads, at most: past it, none. const MAX_CLUSTER_CONTOURS: usize = 1024; @@ -173,6 +174,8 @@ struct Entry { sig: Signature, /// The glyph's outline in font units, for the whole-outline check. outline: BezPath, + /// [`outline_hash`] of `outline`: glyphs drawn alike hash alike. + drawn: u64, /// Whether the glyph was indexed for its exact key: only these take part in exact matching, /// and the ones indexed only for near matching ([`RetypeIndex::near_matches`]) do not. exact: bool, @@ -285,7 +288,7 @@ impl RetypeIndex { if keys.contains(&key) { let outline = drawn.unwrap_or_else(|| db.outline_uncached(face, gid)); if let Some(sig) = signatures(&outline, false).into_iter().next() { - entries.push(Entry { face: fi, gid, ch, sig, outline, exact: true }); + entries.push(Entry { face: fi, gid, ch, sig, drawn: outline_hash(&outline), outline, exact: true }); } continue; } @@ -308,7 +311,7 @@ impl RetypeIndex { break 'faces; } if let Some(sig) = signatures(&outline, false).into_iter().next() { - entries.push(Entry { face: fi, gid, ch, sig, outline, exact: false }); + entries.push(Entry { face: fi, gid, ch, sig, drawn: outline_hash(&outline), outline, exact: false }); } } } @@ -496,11 +499,12 @@ impl RetypeIndex { /// shape need not be built as the glyph is. Upright ones first, then the closest; the other /// turns a glyph fits in (at most 7) are kept in [`GlyphMatch::alts`]; at most /// [`MAX_CANDIDATES`] for each face. Empty for a tolerance of 0 or less, and for shapes of more - /// than 8 contours. A shape is compared with at most the 256 glyphs closest to it in proportion - /// (the spread-to-length ratio, and the share of the length each contour has), closest first, - /// in at most 50 million point comparisons, and the index's calls make at most 2 billion in - /// all (ranking a glyph by proportion counts as one per contour and one more); once they are - /// spent, the glyphs not yet ranked or compared are left out. + /// than 8 contours. A shape is compared with the glyphs of at most the 256 outlines closest to + /// it in proportion (the spread-to-length ratio, and the share of the length each contour has), + /// closest first; glyphs drawn alike, in several faces or in one, are one outline and are fitted + /// once. A shape takes at most 50 million point comparisons, and the index's calls make at most + /// 2 billion in all (ranking a glyph by proportion counts as one per contour and one more); once + /// they are spent, the glyphs not yet ranked or compared are left out. pub fn near_matches(&self, shape: &BezPath, tolerance: f64) -> Vec { // NaN too. if tolerance.is_nan() || tolerance <= 0.0 { @@ -529,20 +533,33 @@ impl RetypeIndex { } }; let near = self.ranked_near(&s, &mut work); + // The glyph fitted last and its poses: the glyphs drawn alike after it take them. + let mut last: Option<(&Entry, Option)> = None; for (_, e) in near { - if work == 0 { - break; - } let Some(face) = self.faces.get(e.face) else { continue }; - let fits = near_fit(&e.sig, &s, tolerance, &mut work); - let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol)); - let Some(flat) = flat.as_ref() else { break }; - // Every turn the glyph fits the shape at, nearest upright first: the first is its - // pose, the others its alternatives (a glyph that looks alike turned). - let mut poses = - fits.into_iter().filter(|f| f.1 <= tolerance).filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r))).take(MAX_NEAR_POSES); - let Some((pose, residual)) = poses.next() else { continue }; - let rest: Vec<(Pose, f64)> = poses.collect(); + let alike = last.as_ref().filter(|(l, _)| drawn_alike(l, e)).map(|(_, p)| p.clone()); + let posed = match alike { + Some(p) => p, + None => { + if work == 0 { + break; + } + let fits = near_fit(&e.sig, &s, tolerance, &mut work); + let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol)); + let Some(flat) = flat.as_ref() else { break }; + // Every turn the glyph fits the shape at, nearest upright first: the first is its + // pose, the others its alternatives (a glyph that looks alike turned). + let mut poses = fits + .into_iter() + .filter(|f| f.1 <= tolerance) + .filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r))) + .take(MAX_NEAR_POSES); + let p = poses.next().map(|(pose, residual)| (pose, residual, poses.collect())); + last = Some((e, p.clone())); + p + } + }; + let Some((pose, residual, rest)) = posed else { continue }; let m = GlyphMatch { face: face.clone(), gid: e.gid, @@ -568,11 +585,13 @@ impl RetypeIndex { out.into_iter().map(|(_, m)| m).collect() } - /// The glyphs of as many contours as near-matching shape `s` that are closest to it in - /// proportion, at most [`NEAR_FITS`], closest first: their spread-to-length ratio, and the - /// share of the length each contour has, longest first. Ranking a glyph takes one comparison - /// per contour, and one more, from `work`; once it is spent, the glyphs not yet ranked are - /// left out. + /// The glyphs of as many contours as near-matching shape `s` whose outlines are among the + /// [`NEAR_FITS`] outlines closest to it in proportion, closest first: their spread-to-length + /// ratio, and the share of the length each contour has, longest first. Glyphs drawn alike (one + /// outline in several faces, or in several glyphs of one face) are one outline and come + /// together, in index order, so copies of a font do not crowd out the glyphs of the faces they + /// copy; outlines as close come in index order. Ranking a glyph takes one comparison per + /// contour, and one more, from `work`; once it is spent, the glyphs not yet ranked are left out. fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> { let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); @@ -595,24 +614,40 @@ impl RetypeIndex { if d.is_finite() { d } else { f64::INFINITY } }; let cost = s.contours as u64 + 1; - let mut near: Vec<(f64, &Entry)> = vec![]; - for e in list.iter().skip(start).filter_map(|i| self.entries.get(*i)).take_while(|e| e.sig.invariant <= hi) { + // Each outline with its distance and its glyphs, in the order they are ranked; the list + // is sorted by invariant and then by index, so each outline's first glyph is its lowest. + let mut outlines: Vec<(f64, Vec<(usize, &Entry)>)> = vec![]; + let mut by_drawn: HashMap> = HashMap::new(); + for (i, e) in list.iter().skip(start).filter_map(|i| Some((*i, self.entries.get(*i)?))).take_while(|(_, e)| e.sig.invariant <= hi) { let Some(left) = work.checked_sub(cost) else { break }; *work = left; - near.push((apart(e), e)); + let same = by_drawn.entry(e.drawn).or_default(); + let found = same.iter().copied().find(|k| outlines.get(*k).and_then(|o| o.1.first()).is_some_and(|(_, f)| drawn_alike(f, e))); + match found.and_then(|k| outlines.get_mut(k)) { + Some(o) => o.1.push((i, e)), + None => { + same.push(outlines.len()); + outlines.push((apart(e), vec![(i, e)])); + } + } } - if near.len() > NEAR_FITS { - near.select_nth_unstable_by(NEAR_FITS, |a, b| a.0.total_cmp(&b.0)); - near.truncate(NEAR_FITS); + let first = |o: &(f64, Vec<(usize, &Entry)>)| o.1.first().map_or(usize::MAX, |(i, _)| *i); + let order = |a: &(f64, Vec<(usize, &Entry)>), b: &(f64, Vec<(usize, &Entry)>)| a.0.total_cmp(&b.0).then(first(a).cmp(&first(b))); + if outlines.len() > NEAR_FITS { + outlines.select_nth_unstable_by(NEAR_FITS, order); + outlines.truncate(NEAR_FITS); } - near.sort_by(|a, b| a.0.total_cmp(&b.0)); - near + outlines.sort_by(order); + outlines.into_iter().flat_map(|(d, glyphs)| glyphs.into_iter().map(move |(_, e)| (d, e))).collect() } } /// Turns of one glyph [`RetypeIndex::near_matches`] keeps, at most: its pose and its alternatives. const MAX_NEAR_POSES: usize = 8; +/// A near-matched glyph's pose and leftover distance, and its other poses, each with its own. +type NearPoses = (Pose, f64, Vec<(Pose, f64)>); + /// `out` (each match with its face's index) without the matches past the first /// [`MAX_CANDIDATES`] of each face, so faces drawn alike (copies of one font under other names) /// do not crowd out the glyphs of the faces after them. @@ -625,6 +660,38 @@ fn keep_per_face(out: &mut Vec<(usize, GlyphMatch)>) { }); } +/// Whether glyphs `a` and `b` are drawn alike: the same outline in font units. +fn drawn_alike(a: &Entry, b: &Entry) -> bool { + a.drawn == b.drawn && a.outline == b.outline +} + +/// A hash of `outline`'s elements and points: outlines drawn alike hash alike. +fn outline_hash(outline: &BezPath) -> u64 { + // FNV-1a, as `key_and_count`; a rare clash only compares two outlines in full. + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + let mut add = |v: u64| { + for b in v.to_le_bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + }; + for el in outline.elements() { + let (tag, pts) = match *el { + PathEl::MoveTo(p) => (0, [p, p, p]), + PathEl::LineTo(p) => (1, [p, p, p]), + PathEl::QuadTo(a, b) => (2, [a, b, b]), + PathEl::CurveTo(a, b, c) => (3, [a, b, c]), + PathEl::ClosePath => (4, [Point::ZERO; 3]), + }; + add(tag); + for p in pts { + add(p.x.to_bits()); + add(p.y.to_bits()); + } + } + h +} + /// Entry `e`'s pose on near-matching shape `s` at scaled turn `z`, when its whole outline, so /// placed, lies within `tol` of the shape's (`flat`). fn near_pose(e: &Entry, s: &Signature, z: (f64, f64), flat: &Flat, tol: f64) -> Option { @@ -2106,6 +2173,41 @@ mod tests { assert!(found.len() > MAX_CANDIDATES && has_every_period(&found), "near: {} matches", found.len()); } + #[test] + fn glyphs_drawn_alike_in_many_faces_are_all_near_matched() { + // Source Sans 3 Regular first, then 40 copies of it under other names: each face has nine + // glyphs close to a period in proportion, 369 in all, more than the 256 near matching + // compares a shape with, but nine outlines. + let db = FontDb::with_font_dirs(vec![]); + let source = db.face("Source Sans 3", "Regular").unwrap(); + let mut faces = vec![source.clone()]; + for i in 0..40 { + let family = format!("Alike {i} Sans"); + db.add_font(crate::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("Alike{i}Sans-Regular"))).unwrap()); + faces.push(db.face(&family, "Regular").unwrap()); + } + let gid = source.mapped_chars().iter().find(|(c, _)| *c == '.').map(|(_, g)| *g).unwrap(); + // Turned a half turn, as a line of type set upside down. + let period = + Affine::translate((300.0, 200.0)) * Affine::rotate(std::f64::consts::PI) * Affine::scale(0.04) * db.outline_uncached(&source, gid); + let simple = simplified(&period, 0.05); + let index = RetypeIndex::build_near(&db, faces.clone(), &BTreeSet::new(), &[near_key(&simple).unwrap()]); + let found = index.near_matches(&simple, 0.02); + for f in &faces { + assert!(found.iter().any(|m| m.ch == '.' && m.face.id() == f.id()), "{}: no period among {} matches", f.family, found.len()); + } + // Each outline is fitted once, however many faces draw it: past ranking the copies' glyphs + // (two comparisons each, for one contour), the comparisons spent are those of Source Sans 3 + // alone. + let alone = RetypeIndex::build_near(&db, [source], &BTreeSet::new(), &[near_key(&simple).unwrap()]); + let alone_found = alone.near_matches(&simple, 0.02); + assert_eq!(found.len(), alone_found.len() * faces.len()); + let mut all = u64::MAX; + let ranked = alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).len() as u64; + let spent = |ix: &RetypeIndex| NEAR_WORK - ix.near_work.load(Ordering::Acquire); + assert_eq!(spent(&index), spent(&alone) + 40 * ranked * 2); + } + #[test] fn a_face_past_its_near_share_keeps_the_glyphs_closest_to_the_shapes() { // One glyph of the face is indexed for near matching: the one closest to a simplified o, diff --git a/docs/mcp.md b/docs/mcp.md index a9e9d9649a..fdf4720f1c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13420,7 +13420,9 @@ glyphs may become separate objects that paint the overlap twice. When the split shortest runs is checked, then the other complete splits in order, up to 32 splits per shape for exact matches and 32 for near matches; when none passes, the shape stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups, 512 contours or 65,536 path elements is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are -matched whole only. Near matching compares a shape with at most the 256 glyphs closest to it in proportion, in at +matched whole only. Near matching compares a shape with the glyphs of at most the 256 outlines closest to it in +proportion; glyphs drawn alike (copies of one font under other names, or one outline under several characters) are one +outline and are fitted once. It takes at most 50 million point comparisons per shape and 2 billion per command, ranking a glyph by proportion counting as one comparison per contour and one more; past them, the glyphs not yet ranked or compared are left out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in selection order, then the runs of groups of the compound paths. Glyphs close only to the shapes and runs past that From 3e0a3f6cc71937c307863fb14b6c04b067ea11ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 04:14:24 -0800 Subject: [PATCH 27/50] Retype: outline comparisons in near matching count toward its work limit Near matching groups the glyphs drawn alike by a hash of their outline and compares each glyph's outline with the outlines in its hash bucket. Those comparisons were not counted toward the work limit, and the hash is not collision-resistant: a font with many glyphs whose outlines hash alike made each new glyph compare with every outline before it, so the work grew with the square of the glyph count. Each comparison now takes one unit per element of the glyph's outline from the work limit, and a glyph is compared with at most 4 outlines of one hash; past them, it is an outline of its own. docs/mcp.md describes the new count. The engine test helper lines_in_family took the line's face from RetypeIndex::matches, which keeps the first 16 matches over every face. When other tests had loaded more than 16 copies of Source Sans 3 that draw the i alike, the family the test asked for could fall past them, and the helper would use another face, without its kerning, so a_word_space_after_a_glyph_kerned_toward_it_is_kept_past_the_glyphs_measured could fail in a full engine run with craft-fonts. The helper now reads all_matches, as Retype does. --- crates/engine/src/cmd/retype_tests.rs | 5 +- crates/text/src/retype.rs | 85 +++++++++++++++++++++++---- docs/mcp.md | 3 +- 3 files changed, 78 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 5f89bc1284..f5deb6b600 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1926,11 +1926,12 @@ fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec = vec![]; for pc in &pieces { - let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect(); + let cands: Vec<_> = index.all_matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect(); if !lines.last_mut().is_some_and(|l| super::join(l, pc, &cands)) { lines.extend(super::new_line(pc, &cands, 0.0)); } diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index b020a3827f..c000cce127 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -82,6 +82,9 @@ const NEAR_SHAPE_WORK: u64 = 50_000_000; /// Outlines one shape is near matched against, at most: those closest to it in proportion, each /// with every glyph drawn as it is. const NEAR_FITS: usize = 256; +/// Outlines with one [`outline_hash`] that near matching compares a glyph's outline with, at most: +/// past them, a glyph whose outline hashes alike is an outline of its own. +const MAX_HASH_CLASHES: usize = 4; /// Contours [`clusters`] reads, at most: past it, none. const MAX_CLUSTER_CONTOURS: usize = 1024; @@ -503,8 +506,9 @@ impl RetypeIndex { /// it in proportion (the spread-to-length ratio, and the share of the length each contour has), /// closest first; glyphs drawn alike, in several faces or in one, are one outline and are fitted /// once. A shape takes at most 50 million point comparisons, and the index's calls make at most - /// 2 billion in all (ranking a glyph by proportion counts as one per contour and one more); once - /// they are spent, the glyphs not yet ranked or compared are left out. + /// 2 billion in all (ranking a glyph by proportion counts as one per contour and one more, and + /// comparing its outline with one of at most 4 others with the same hash as one per element of + /// its outline); once they are spent, the glyphs not yet ranked or compared are left out. pub fn near_matches(&self, shape: &BezPath, tolerance: f64) -> Vec { // NaN too. if tolerance.is_nan() || tolerance <= 0.0 { @@ -591,7 +595,9 @@ impl RetypeIndex { /// outline in several faces, or in several glyphs of one face) are one outline and come /// together, in index order, so copies of a font do not crowd out the glyphs of the faces they /// copy; outlines as close come in index order. Ranking a glyph takes one comparison per - /// contour, and one more, from `work`; once it is spent, the glyphs not yet ranked are left out. + /// contour, and one more, from `work`, and comparing its outline with one that hashes alike (at + /// most [`MAX_HASH_CLASHES`] of them) one per element of its outline; once it is spent, the + /// glyphs not yet ranked are left out. fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> { let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); @@ -622,11 +628,32 @@ impl RetypeIndex { let Some(left) = work.checked_sub(cost) else { break }; *work = left; let same = by_drawn.entry(e.drawn).or_default(); - let found = same.iter().copied().find(|k| outlines.get(*k).and_then(|o| o.1.first()).is_some_and(|(_, f)| drawn_alike(f, e))); + // Each outline that hashes alike is compared with this one in full, one comparison per + // element of its outline. + let compare = e.outline.elements().len() as u64; + let (mut found, mut spent) = (None, false); + for k in same.iter().copied() { + let Some(left) = work.checked_sub(compare) else { + spent = true; + break; + }; + *work = left; + if outlines.get(k).and_then(|o| o.1.first()).is_some_and(|(_, f)| drawn_alike(f, e)) { + found = Some(k); + break; + } + } + if spent { + break; + } match found.and_then(|k| outlines.get_mut(k)) { Some(o) => o.1.push((i, e)), None => { - same.push(outlines.len()); + // Past MAX_HASH_CLASHES outlines that hash alike, the others are not compared: + // each is an outline of its own. + if same.len() < MAX_HASH_CLASHES { + same.push(outlines.len()); + } outlines.push((apart(e), vec![(i, e)])); } } @@ -2197,15 +2224,46 @@ mod tests { assert!(found.iter().any(|m| m.ch == '.' && m.face.id() == f.id()), "{}: no period among {} matches", f.family, found.len()); } // Each outline is fitted once, however many faces draw it: past ranking the copies' glyphs - // (two comparisons each, for one contour), the comparisons spent are those of Source Sans 3 - // alone. + // (two comparisons each, for one contour, and one per element of the outline for comparing + // it with Source Sans 3's), the comparisons spent are those of Source Sans 3 alone. let alone = RetypeIndex::build_near(&db, [source], &BTreeSet::new(), &[near_key(&simple).unwrap()]); let alone_found = alone.near_matches(&simple, 0.02); assert_eq!(found.len(), alone_found.len() * faces.len()); let mut all = u64::MAX; - let ranked = alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).len() as u64; + let ranked: u64 = + alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).iter().map(|(_, e)| 2 + e.outline.elements().len() as u64).sum(); let spent = |ix: &RetypeIndex| NEAR_WORK - ix.near_work.load(Ordering::Acquire); - assert_eq!(spent(&index), spent(&alone) + 40 * ranked * 2); + assert_eq!(spent(&index), spent(&alone) + 40 * ranked); + } + + #[test] + fn outlines_whose_hashes_clash_are_compared_within_the_work_budget() { + // 5,000 glyphs of one square each, moved apart, all given the same outline hash: each is + // compared with at most MAX_HASH_CLASHES of the others, and each comparison is charged. + let square = |i: usize| Affine::translate((i as f64, 0.0)) * kurbo::Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1); + let n = 5_000; + let entries: Vec = (0..n) + .map(|i| Entry { face: 0, gid: i as u32, ch: 'a', sig: signature(&square(i)).unwrap(), outline: square(i), drawn: 7, exact: false }) + .collect(); + let elements = square(0).elements().len() as u64; + let s = signature(&square(0)).unwrap(); + let cost = s.contours as u64 + 1; + let mut buckets = HashMap::new(); + buckets.insert(s.contours, (0..n).collect::>()); + let index = RetypeIndex { faces: vec![], entries, buckets, by_glyph: HashMap::new(), near_work: AtomicU64::new(NEAR_WORK) }; + let mut work = u64::MAX; + let ranked = index.ranked_near(&s, &mut work); + assert_eq!(ranked.len(), NEAR_FITS, "each square is an outline of its own"); + let compared: u64 = (0..n as u64).map(|i| i.min(MAX_HASH_CLASHES as u64)).sum(); + assert_eq!(u64::MAX - work, n as u64 * cost + compared * elements); + // With too little work left for the comparisons, ranking stops where it runs out. + let mut work = n as u64 * cost / 4; + let short = index.ranked_near(&s, &mut work); + assert!(short.len() < NEAR_FITS, "{} ranked", short.len()); + assert!(work < cost + elements, "{work} left"); + // Near matching the shape spends at most one shape's allowance and returns. + index.near_matches(&square(0), 0.02); + assert!(NEAR_WORK - index.near_work.load(Ordering::Acquire) <= NEAR_SHAPE_WORK); } #[test] @@ -2479,9 +2537,12 @@ mod tests { let index = RetypeIndex::build_near(db, [face], &BTreeSet::new(), &[near_key(&shape).unwrap()]); let s = near_signature(&shape).unwrap(); let mut all = u64::MAX; - let ranked = index.ranked_near(&s, &mut all).len(); - assert!(ranked >= 1, "the o is ranked"); - assert_eq!(u64::MAX - all, ranked as u64 * 3, "each glyph of two contours takes three"); + let ranked = index.ranked_near(&s, &mut all); + assert!(!ranked.is_empty(), "the o is ranked"); + // The Greek omicron is drawn as the o: it is also compared with the o's outline. + let compared = |i: usize, e: &Entry| if ranked[..i].iter().any(|(_, f)| f.drawn == e.drawn) { e.outline.elements().len() as u64 } else { 0 }; + let spent: u64 = ranked.iter().enumerate().map(|(i, (_, e))| 3 + compared(i, e)).sum(); + assert_eq!(u64::MAX - all, spent, "each glyph of two contours takes three, and one per element for each comparison"); // Enough to rank one glyph of two contours and nothing more. let mut work = 4; assert_eq!(index.ranked_near(&s, &mut work).len(), 1); diff --git a/docs/mcp.md b/docs/mcp.md index fdf4720f1c..93c53b4eeb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13424,7 +13424,8 @@ matched whole only. Near matching compares a shape with the glyphs of at most th proportion; glyphs drawn alike (copies of one font under other names, or one outline under several characters) are one outline and are fitted once. It takes at most 50 million point comparisons per shape and 2 billion per command, ranking a glyph by proportion counting as one -comparison per contour and one more; past them, the glyphs not yet ranked or compared are left out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in +comparison per contour and one more, and comparing its outline with one of at most 4 others that hash alike counting +as one per element of its outline; past them, the glyphs not yet ranked or compared are left out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in selection order, then the runs of groups of the compound paths. Glyphs close only to the shapes and runs past that limit are not looked up. At most 262,144 glyphs are drawn to check whether they could near match, and at most 32,768 are indexed for it, each face taking an equal share of both; of a face's glyphs, those closest to the selected shapes From bf562e37170495327dfbc34d57b7cba92e2b0409 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:27:38 -0800 Subject: [PATCH 28/50] Retype: near matching reuses poses by outline group without comparing again ranked_near now returns each glyph's outline group with it, and near_matches reuses the last fitted poses when the group matches instead of comparing the two outlines again. The outline comparisons all happen in ranked_near, where each one is charged to the shape's allowance, so the 50 million and 2 billion limits cover them. A new test counts the outline comparisons near_matches makes beyond ranking. --- crates/text/src/retype.rs | 57 +++++++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 11 deletions(-) diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index c000cce127..f27fc5e561 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -537,11 +537,12 @@ impl RetypeIndex { } }; let near = self.ranked_near(&s, &mut work); - // The glyph fitted last and its poses: the glyphs drawn alike after it take them. - let mut last: Option<(&Entry, Option)> = None; - for (_, e) in near { + // The outline fitted last and its poses: the glyphs drawn alike after it take them, with no + // second comparison of their outlines. + let mut last: Option<(usize, Option)> = None; + for (_, outline, e) in near { let Some(face) = self.faces.get(e.face) else { continue }; - let alike = last.as_ref().filter(|(l, _)| drawn_alike(l, e)).map(|(_, p)| p.clone()); + let alike = last.as_ref().filter(|(l, _)| *l == outline).map(|(_, p)| p.clone()); let posed = match alike { Some(p) => p, None => { @@ -559,7 +560,7 @@ impl RetypeIndex { .filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r))) .take(MAX_NEAR_POSES); let p = poses.next().map(|(pose, residual)| (pose, residual, poses.collect())); - last = Some((e, p.clone())); + last = Some((outline, p.clone())); p } }; @@ -597,8 +598,9 @@ impl RetypeIndex { /// copy; outlines as close come in index order. Ranking a glyph takes one comparison per /// contour, and one more, from `work`, and comparing its outline with one that hashes alike (at /// most [`MAX_HASH_CLASHES`] of them) one per element of its outline; once it is spent, the - /// glyphs not yet ranked are left out. - fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> { + /// glyphs not yet ranked are left out. Each glyph comes with its distance and the number of + /// its outline in the list, the same for every glyph drawn alike. + fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, usize, &Entry)> { let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); let hi = s.invariant * (1.0 + NEAR_INVARIANT_SLACK); @@ -665,7 +667,7 @@ impl RetypeIndex { outlines.truncate(NEAR_FITS); } outlines.sort_by(order); - outlines.into_iter().flat_map(|(d, glyphs)| glyphs.into_iter().map(move |(_, e)| (d, e))).collect() + outlines.into_iter().enumerate().flat_map(|(k, (d, glyphs))| glyphs.into_iter().map(move |(_, e)| (d, k, e))).collect() } } @@ -689,6 +691,8 @@ fn keep_per_face(out: &mut Vec<(usize, GlyphMatch)>) { /// Whether glyphs `a` and `b` are drawn alike: the same outline in font units. fn drawn_alike(a: &Entry, b: &Entry) -> bool { + #[cfg(test)] + OUTLINES_COMPARED.set(OUTLINES_COMPARED.get() + 1); a.drawn == b.drawn && a.outline == b.outline } @@ -1818,6 +1822,8 @@ fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize] thread_local! { /// How many readings [`signatures`] tried on this thread, kept or not. static READINGS_TRIED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many outline comparisons [`drawn_alike`] made on this thread. + static OUTLINES_COMPARED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The first reading of `path` (for tests). @@ -2231,11 +2237,39 @@ mod tests { assert_eq!(found.len(), alone_found.len() * faces.len()); let mut all = u64::MAX; let ranked: u64 = - alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).iter().map(|(_, e)| 2 + e.outline.elements().len() as u64).sum(); + alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).iter().map(|(_, _, e)| 2 + e.outline.elements().len() as u64).sum(); let spent = |ix: &RetypeIndex| NEAR_WORK - ix.near_work.load(Ordering::Acquire); assert_eq!(spent(&index), spent(&alone) + 40 * ranked); } + #[test] + fn glyphs_drawn_alike_are_not_compared_again_after_ranking() { + // Source Sans 3 Regular and 30 copies of it: ranking compares each copy's outlines with + // the first face's and charges every comparison; fitting reuses the poses by outline and + // compares no outline again. + let db = FontDb::with_font_dirs(vec![]); + let source = db.face("Source Sans 3", "Regular").unwrap(); + let mut faces = vec![source.clone()]; + for i in 0..30 { + let family = format!("Again {i} Sans"); + db.add_font(crate::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("Again{i}Sans-Regular"))).unwrap()); + faces.push(db.face(&family, "Regular").unwrap()); + } + let gid = source.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap(); + let shape = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * db.outline_uncached(&source, gid); + let simple = simplified(&shape, 0.05); + let index = RetypeIndex::build_near(&db, faces.clone(), &BTreeSet::new(), &[near_key(&simple).unwrap()]); + OUTLINES_COMPARED.set(0); + let mut all = u64::MAX; + let ranked = index.ranked_near(&near_signature(&simple).unwrap(), &mut all); + let in_ranking = OUTLINES_COMPARED.get(); + assert!(ranked.len() > faces.len(), "{} ranked", ranked.len()); + OUTLINES_COMPARED.set(0); + let found = index.near_matches(&simple, 0.02); + assert!(found.iter().any(|m| m.ch == 'o'), "no o among {} matches", found.len()); + assert_eq!(OUTLINES_COMPARED.get(), in_ranking, "outlines compared outside the charged ranking"); + } + #[test] fn outlines_whose_hashes_clash_are_compared_within_the_work_budget() { // 5,000 glyphs of one square each, moved apart, all given the same outline hash: each is @@ -2540,8 +2574,9 @@ mod tests { let ranked = index.ranked_near(&s, &mut all); assert!(!ranked.is_empty(), "the o is ranked"); // The Greek omicron is drawn as the o: it is also compared with the o's outline. - let compared = |i: usize, e: &Entry| if ranked[..i].iter().any(|(_, f)| f.drawn == e.drawn) { e.outline.elements().len() as u64 } else { 0 }; - let spent: u64 = ranked.iter().enumerate().map(|(i, (_, e))| 3 + compared(i, e)).sum(); + let compared = + |i: usize, e: &Entry| if ranked[..i].iter().any(|(_, _, f)| f.drawn == e.drawn) { e.outline.elements().len() as u64 } else { 0 }; + let spent: u64 = ranked.iter().enumerate().map(|(i, (_, _, e))| 3 + compared(i, e)).sum(); assert_eq!(u64::MAX - all, spent, "each glyph of two contours takes three, and one per element for each comparison"); // Enough to rank one glyph of two contours and nothing more. let mut work = 4; From 454e134152662bcf0ecb0f47babff2da161750ee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:11:36 -0800 Subject: [PATCH 29/50] xtask: test-lint follows each loading path, keeps || table checks and skips name-only suffix checks - never-run: follow every file that loads a module up to its crate root and combine the gates along each path; a module that no root loads any more is treated as compiled out. Deleted parents and base `#[path]` loaders now select unchanged children, and the base comparison matches tests by line so same-named tests in other inline modules stay apart. - cfgs_over: skip sibling attributes such as `#[test_case(1; "one")]` before looking for the item body. - census: a helper behind `&&` on the left of `||` no longer hides the whole-table check on the right. - reads-source: an `ends_with(".rs")` check counts only when it selects from a listing or the file's test code reads a file. - docs: unchanged-line hits fail the command when a changed parent takes away a test's last CI route. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 593 ++++++++++++++++++++++++++++++++++++----- 2 files changed, 525 insertions(+), 70 deletions(-) diff --git a/docs/development.md b/docs/development.md index c833a400e8..278aa77454 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` keeps out of every CI test build (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, and an environment variable that no CI leg sets. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` keeps out of every CI test build (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, and an environment variable that no CI leg sets. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it, except a `never-run` test in an unchanged file whose last CI route a changed `mod` declaration or `cfg` in a file that loads it takes away. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 5384b51e4c..52186558be 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -79,7 +79,7 @@ //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the //! workspace by crate and rule, and does not fail. -use std::cell::OnceCell; +use std::cell::{OnceCell, RefCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::Path; use std::process::Command; @@ -295,31 +295,55 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let crates: BTreeSet = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); let helper_files: Vec = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); - // Files under the module of a changed file: a `cfg` added to their `mod` declaration can turn - // their tests off without a change to them. + // Deleted files do not appear in `changed`, but a deleted root or parent may have been the + // last file that loaded a child. `--no-renames` lists the old path of a moved file as deleted. + let deleted: BTreeSet = + git(root, &["-c", "core.quotepath=off", "diff", "--no-renames", "--name-only", "-z", "--diff-filter=D", &base, "--", "*.rs"])? + .split('\0') + .filter(|p| !p.is_empty() && is_scanned(p)) + .map(str::to_owned) + .collect(); + // Files under the module of a changed or deleted file: a `cfg` added to their `mod` + // declaration can turn their tests off without a change to them. let module_dirs: Vec = present .iter() + .chain(&deleted) .map(|p| { let (dir, file) = p.rsplit_once('/').unwrap_or(("", p)); if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) } }) .collect(); - let below: Vec = - files.iter().filter(|p| !changed.contains_key(*p) && module_dirs.iter().any(|d| p.starts_with(d.as_str()))).cloned().collect(); + // The gates the parent declarations gave at the base: a parent edit counts against a child's + // test only when the test ran in CI before it. Each parent is read from the base once, hit or + // miss. + let base_reads: RefCell>> = RefCell::default(); + let read_base = |p: &str| { + if let Some(s) = base_reads.borrow().get(p) { + return s.clone(); + } + let s = git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE); + base_reads.borrow_mut().insert(p.to_owned(), s.clone()); + s + }; + let loaders = base_path_loads(&present.iter().chain(&deleted).cloned().collect::>(), &read_base); + let below = unchanged_children(&files, &changed, &module_dirs, &loaders); let gated: Vec = present.iter().chain(&below).cloned().collect(); let gates = module_gates(&gated, &|p| read_small(root, p)); - let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); + let base_gates = module_gates_from(&gated, &read_base, &loaders); + // A changed or deleted file that loaded a child at the base may have stopped loading it, which + // the head's gates do not show; the base comparison below still drops a test that was already + // off. + let base_parent_changed = + |p: &str| base_gates.get(p).is_some_and(|g| g.sources.iter().any(|(parent, _)| changed.contains_key(parent) || deleted.contains(parent))); + let path_index = OnceCell::new(); + let module_cfgs = head_cfgs(&gated, &gates, &base_gates, &|p| path_names(&path_index, &files, &|f| read_small(root, f), p)); let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; - // The gates the parent declarations gave at the base: a parent edit counts against a child's - // test only when the test ran in CI before it. - let read_base = |p: &str| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE); - let base_cfgs = module_gates(&gated, &read_base).into_iter().map(|(p, g)| (p, g.preds)).collect(); + let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - let newly_off = - |path: &str, src: &str, hit: &Hit| !lint_file(path, src, &base_ctx).iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test); + let newly_off = |path: &str, src: &str, hit: &Hit| off_since(&lint_file(path, src, &base_ctx), hit); let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { - let parent_changed = gate_changed(gates.get(&path), &changed); + let parent_changed = gate_changed(gates.get(&path), &changed) || base_parent_changed(&path); for hit in lint_file(&path, &src, &ctx) { if touches(&hit, changed.get(&path).and_then(Option::as_ref)) || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) @@ -330,13 +354,101 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } } } - for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { + for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed) || base_parent_changed(p)) { let Some(src) = read_small(root, path) else { continue }; counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); } finish(&counted, older, present.len(), &base) } +/// The head's `cfg` predicates for each of `paths`. A module file that reached a crate root at the +/// base and reaches none now ([`Gates::dead`]) is compiled into no target, so it gets the +/// predicate `any()`, which never holds, unless `elsewhere` says a `#[path]` attribute in some +/// other file may still load it. +fn head_cfgs( + paths: &[String], + head: &HashMap, + base: &HashMap, + elsewhere: &dyn Fn(&str) -> bool, +) -> HashMap> { + paths + .iter() + .filter_map(|p| { + let was_live = base.get(p).is_some_and(|b| !b.dead && !b.sources.is_empty()); + let now_dead = head.get(p).is_none_or(|g| g.dead) && module_parent(p).is_some(); + if was_live && now_dead && !elsewhere(p) { + Some((p.clone(), vec!["any()".to_owned()])) + } else { + head.get(p).map(|g| (p.clone(), g.preds.clone())) + } + }) + .collect() +} + +/// Whether any of `files`, read through `read`, has a `#[path]` declaration that resolves to `p`. +fn path_names(index: &OnceCell>>, files: &[String], read: &dyn Fn(&str) -> Option, p: &str) -> bool { + index + .get_or_init(|| { + let mut names: HashMap> = HashMap::new(); + for f in files { + if let Some(s) = read(f) { + for load in path_loads(&s, f) { + names.entry(load.path).or_default().insert(f.clone()); + } + } + } + names + }) + .get(p) + .is_some_and(|parents| parents.iter().any(|f| f != p)) +} + +/// The `#[path]` declarations reachable from `paths` at the base, through at most 16 levels. +/// Each file is read at most once through `read`. +fn base_path_loads(paths: &[String], read: &dyn Fn(&str) -> Option) -> Vec { + let mut pending = paths.to_vec(); + let mut seen = HashSet::new(); + let mut loaders = vec![]; + for _ in 0..16 { + if pending.is_empty() { + break; + } + for p in std::mem::take(&mut pending) { + if !seen.insert(p.clone()) { + continue; + } + if let Some(s) = read(&p) { + let loads = path_loads(&s, &p); + pending.extend(loads.iter().map(|l| l.path.clone())); + loaders.extend(loads); + } + } + } + loaders +} + +/// The unchanged files whose tests a changed or deleted file can turn off: those under one of +/// `module_dirs`, and those a `#[path]` declaration in `loaders` loaded at the base. +fn unchanged_children( + files: &[String], + changed: &BTreeMap>>, + module_dirs: &[String], + loaders: &[PathLoad], +) -> Vec { + files + .iter() + .filter(|p| !changed.contains_key(*p) && (module_dirs.iter().any(|d| p.starts_with(d.as_str())) || loaders.iter().any(|l| l.path == **p))) + .cloned() + .collect() +} + +/// Whether `hit` is a `never-run` test that `base`, the hits of the same source under the base's +/// gates, does not report. Both lints read the same source, so the test's line tells same-named +/// tests in different inline modules apart. +fn off_since(base: &[Hit], hit: &Hit) -> bool { + !base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) +} + /// The command line: `--all`, `--base `. #[derive(Debug, Default, PartialEq)] struct Options { @@ -1465,7 +1577,7 @@ fn census(v: &View, helpers: &HashSet) -> Vec { /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions /// nested deeper than 64 operators are not judged. An operand that calls one of `helpers` (asserting /// helpers called in the condition) is not a presence check, and a weak right side of an `||` does -/// not count when the left side calls one, since the left side always runs. +/// not count when the left side always calls one ([`always_calls`]). fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool) { let or = top_level_at(cond, "||").first().copied(); if depth > 64 || !cond.contains(".all(") { @@ -1477,7 +1589,7 @@ fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool if s.contains(".all(") { census_condition(s, depth + 1, helpers) } else { (weak_predicate(s) && !calls_any(s, helpers), false) } }; let (l, r) = (side(&cond[..at]), side(&cond[at + 2..])); - let r = if or.is_some() && calls_any(&cond[..at], helpers) { (false, false) } else { r }; + let r = if or.is_some() && always_calls(&cond[..at], helpers, depth) { (false, false) } else { r }; if or.is_none() { (l.0 && r.0, l.1 || r.1) } else if l == (true, true) || r == (true, true) { @@ -1491,6 +1603,21 @@ fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool } } +/// Whether evaluating the (whitespace-free) condition `s` always calls one of `helpers`: a call +/// behind a top-level `&&` or `||` runs only on one outcome of the operand before it, so only the +/// first operand of either counts. +fn always_calls(s: &str, helpers: &[String], depth: usize) -> bool { + if depth > 64 { + false + } else if s.starts_with('(') && matching(s.as_bytes(), 0) == Some(s.len() - 1) { + always_calls(&s[1..s.len() - 1], helpers, depth + 1) + } else if let Some(at) = top_level_at(s, "||").first().copied().or_else(|| top_level_at(s, "&&").first().copied()) { + always_calls(&s[..at], helpers, depth + 1) + } else { + calls_any(s, helpers) + } +} + /// Whether `s` calls a function or method named in `names`, with or without a turbofish. fn calls_any(s: &str, names: &[String]) -> bool { names.iter().any(|n| { @@ -2988,7 +3115,9 @@ fn reads_source_hits(file: &File) -> Vec { let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); let rs = match word { - b"ends_with" => literal == "\".rs\"", + // A suffix check alone may test a generated name; it counts when it selects files + // from a listing or the file's test code also reads a file. + b"ends_with" => literal == "\".rs\"" && (selects(m, at) || reads_files(file)), // The last path literal in the argument names the file read: `root.join("src/lib.rs")`, // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), @@ -3005,6 +3134,36 @@ fn reads_source_hits(file: &File) -> Vec { out } +/// Whether the call at `at` sits in the closure of a `filter`, `filter_map`, `find`, `any`, +/// `all`, `position` or `retain` call, which picks entries out of a listing. +fn selects(m: &[u8], at: usize) -> bool { + const PICKS: &[&[u8]] = &[b"filter", b"filter_map", b"find", b"find_map", b"any", b"all", b"position", b"retain"]; + m[..at].iter().enumerate().rev().filter(|&(_, &c)| c == b'(').find(|&(open, _)| matching(m, open).is_none_or(|close| close > at)).is_some_and( + |(open, _)| { + let head = m[..open].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + PICKS.contains(&&head[head.len() - name..]) + }, + ) +} + +/// Whether the test code of the file (the tests, and the test modules and helpers around them) +/// reads a file or lists a directory: a helper elsewhere in it may read what a test selects. +fn reads_files(file: &File) -> bool { + file.regions.iter().any(|&(from, to)| { + [&b"read_to_string"[..], b"read_to_end", b"read_dir", b"include_str", b"read", b"open"].iter().any(|w| { + words(&file.m, w, from, to).into_iter().any(|p| { + if *w == b"open" && !norm(&file.m[..p]).ends_with("File::") { + return false; + } + let next = skip_ws(&file.m, p + w.len()); + let next = if file.m.get(next) == Some(&b'!') { skip_ws(&file.m, next + 1) } else { next }; + file.m.get(next) == Some(&b'(') + }) + }) + }) +} + /// The last string literal in a (whitespace-free) expression, quotes included. fn last_literal(arg: &str) -> Option<&str> { let close = arg.rfind('"')?; @@ -3425,7 +3584,20 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { let enclosing = m[..at].iter().rposition(|&c| c == b'{'); enclosing.and_then(|o| matching(m, o).map(|c| (o, c))).unwrap_or((0, m.len())) } else { - let after = end + 1; + // Sibling attributes such as `#[test_case(1; "one")]` come before the item and may hold + // a `;`, so the scan for the body starts after them. + let mut after = end + 1; + loop { + let hash = skip_ws(m, after); + let open = skip_ws(m, hash + 1); + match (m.get(hash), m.get(open)) { + (Some(b'#'), Some(b'[')) => match matching(m, open) { + Some(close) => after = close + 1, + None => break, + }, + _ => break, + } + } let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; match (m[open], matching(m, open)) { (b'{', Some(close)) => (at, close), @@ -3462,6 +3634,48 @@ struct Loaded<'a> { chain: &'a [String], } +/// A `#[path]` declaration: the file `path` it loads, the file `parent` that declares it, and the +/// inline modules `chain` (outermost first) around the declaration. +struct PathLoad { + path: String, + parent: String, + chain: Vec, +} + +/// The `#[path]` declarations in `src`, the file `parent`. +fn path_loads(src: &str, parent: &str) -> Vec { + let m = mask(src); + words(&m, b"mod", 0, m.len()) + .into_iter() + .filter_map(|at| { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') { + return None; + } + let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let rel = path_attr(&m, src.as_bytes(), item, at)?; + let chain = inline_mods(&m, at); + Some(PathLoad { path: module_path(parent, &chain, &rel), parent: parent.to_owned(), chain }) + }) + .collect() +} + +/// The file a `#[path = "rel"]` declaration in `parent` loads: relative to the file's directory +/// outside inline modules, and inside them to the inline modules' directory under the file's +/// module. +fn module_path(parent: &str, chain: &[String], rel: &str) -> String { + let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); + let mut base = dir.to_owned(); + if !chain.is_empty() && !["mod.rs", "lib.rs", "main.rs"].contains(&file) { + base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); + } + for seg in chain { + base = join_path(&base, seg); + } + join_path(&base, rel) +} + /// The `cfg` predicates under which `src`, the file `parent`, loads `want`: those on the /// `mod ;` declarations that load it (by name, or through a `#[path]` override) and on the /// items, inline modules and file around them, with the 1-based lines of those declarations and @@ -3470,8 +3684,6 @@ struct Loaded<'a> { fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, Vec)> { let m = mask(src); let lines = Lines::new(src); - let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); - let mod_rs = ["mod.rs", "lib.rs", "main.rs"].contains(&file); let (mut each, mut at_lines) = (vec![], vec![]); for at in words(&m, b"mod", 0, m.len()) { let start = skip_ws(&m, at + 3); @@ -3484,14 +3696,7 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, Some(rel) => { // A `#[path]` outside inline modules is relative to the file's directory; inside them, // to the inline modules' directory under the file's module. - let mut base = dir.to_owned(); - if !want.chain.is_empty() && !mod_rs { - base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); - } - for seg in want.chain { - base = join_path(&base, seg); - } - join_path(&base, &rel) == want.path + module_path(parent, want.chain, &rel) == want.path } None => &m[start..end] == want.name.as_bytes(), }; @@ -3566,7 +3771,7 @@ fn inline_mods(m: &[u8], at: usize) -> Vec { /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the /// modules above it, read through `read`. fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { - module_gates(paths, read).into_iter().map(|(p, g)| (p, g.preds)).collect() + module_gates(paths, read).into_iter().filter(|(_, g)| !g.preds.is_empty()).map(|(p, g)| (p, g.preds)).collect() } /// The `cfg` predicates a module file inherits ([`module_cfgs`]) and, for each file that declares @@ -3575,59 +3780,94 @@ fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashM struct Gates { preds: Vec, sources: Vec<(String, Vec)>, + /// No path from the file reaches a crate root: the file, or a file on every path above it, + /// is a module file that nothing found loads. + dead: bool, } /// [`Gates`] for each of `paths` that inherits a predicate. A file is looked up in the files that -/// may declare its module and, when none does, in the files above them through inline modules +/// may declare its module and in the files above them through inline modules /// (`mod platform { mod child; }` loads `platform/child.rs`). fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap { + module_gates_from(paths, read, &[]) +} + +/// [`module_gates`], with the `#[path]` declarations in `loaders` as further ways in. +fn module_gates_from(paths: &[String], read: &dyn Fn(&str) -> Option, loaders: &[PathLoad]) -> HashMap { let mut out = HashMap::new(); for path in paths { - let (mut gates, mut at) = (Gates::default(), path.clone()); - 'up: for _ in 0..16 { - let Some((name, mut candidates)) = module_parent(&at) else { break }; - let name = name.to_owned(); - let file = at.rsplit_once('/').map_or(at.as_str(), |(_, f)| f); - let Some(mut module_dir) = (if file == "mod.rs" { - at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) - } else { - at.rsplit_once('/').map(|(d, _)| d.to_owned()) - }) else { - break; - }; - let mut chain: Vec = vec![]; - for _ in 0..4 { - let want = Loaded { path: &at, name: &name, chain: &chain }; - // Every file that loads the module is another way in (a library and a binary root - // can both load it): its tests are off only when every one of them leaves them out. - let found: Vec<_> = - candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); - if let Some(parent) = found.first().map(|(p, _)| p.clone()) { - if let [(_, (preds, _))] = found.as_slice() { - gates.preds.extend(preds.iter().cloned()); - } else { - let each: Vec = found.iter().map(|(_, (p, _))| format!("all({})", p.join(","))).collect(); - gates.preds.push(format!("any({})", each.join(","))); - } - gates.sources.extend(found.into_iter().map(|(p, (_, lines))| (p, lines))); - at = parent; - continue 'up; - } - let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break 'up }; - let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break 'up }; - chain.insert(0, seg); - candidates = next; - module_dir = up; - } - break; - } - if !gates.preds.is_empty() { + let gates = gates_of(path, read, loaders, 0); + // A file with sources and no predicate is still listed: a change to a file that loads it + // can take that route away. + if !gates.preds.is_empty() || !gates.sources.is_empty() || gates.dead { out.insert(path.clone(), gates); } } out } +/// [`Gates`] for the file `at`. Every file that loads the module is another way in (a library and +/// a binary root can both load it), and each is followed up to its crate root: the gates along one +/// path all apply, and the tests are off only when every path leaves them out. +fn gates_of(at: &str, read: &dyn Fn(&str) -> Option, loaders: &[PathLoad], depth: usize) -> Gates { + let none = Gates::default(); + if depth >= 16 { + return none; + } + let Some((name, mut candidates)) = module_parent(at) else { return none }; + let file = at.rsplit_once('/').map_or(at, |(_, f)| f); + let Some(mut module_dir) = (if file == "mod.rs" { + at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) + } else { + at.rsplit_once('/').map(|(d, _)| d.to_owned()) + }) else { + return none; + }; + let mut chain: Vec = vec![]; + let mut found = vec![]; + for loader in loaders.iter().filter(|l| l.path == at) { + let want = Loaded { path: at, name, chain: &loader.chain }; + if let Some(f) = read(&loader.parent).and_then(|s| declared_cfgs(&s, &loader.parent, &want)) { + found.push((loader.parent.clone(), f)); + } + } + for _ in 0..4 { + let want = Loaded { path: at, name, chain: &chain }; + found.extend(candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f)))); + let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break }; + let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break }; + chain.insert(0, seg); + candidates = next; + module_dir = up; + } + found.sort(); + found.dedup(); + let mut gates = Gates { dead: true, ..Gates::default() }; + let mut each: Vec> = vec![]; + let mut dead_each = vec![]; + for (parent, (mut preds, lines)) in found { + let up = gates_of(&parent, read, loaders, depth + 1); + gates.dead &= up.dead; + preds.extend(up.preds); + if up.dead { + dead_each.push(preds); + } else { + each.push(preds); + } + gates.sources.push((parent, lines)); + gates.sources.extend(up.sources); + } + if gates.dead { + each = dead_each; + } + gates.preds = match each.len() { + 0 => vec![], + 1 => each.pop().unwrap_or_default(), + _ => vec![format!("any({})", each.iter().map(|p| format!("all({})", p.join(","))).collect::>().join(","))], + }; + gates +} + /// A test that a `cfg` compiles out on every target CI runs tests on. fn never_run(v: &View, ctx: &Ctx) -> Option { let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); @@ -3870,6 +4110,8 @@ mod tests { assert_eq!(census_in(inner, &ctx()), [(2, "census")], "a helper inside the predicate behind an || can be skipped"); let outer = "#[test]\nfn t() {\n assert!(verify_entry() || COLORS.iter().all(|c| c.is_some()));\n}\n"; assert_eq!(census_in(outer, &ctx()), [], "a helper on the left of an outer || always runs"); + let guarded = "#[test]\nfn t() {\n assert!((ready && verify_entry()) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(guarded, &ctx()), [(2, "census")], "a helper behind an && on the left is skipped when ready is false"); let in_message = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some(), \"{:?}\", verify_entry(c));\n }\n}\n"; assert_eq!(census_in(in_message, &ctx()), [(2, "census")], "a helper in a failure message runs only after a failure"); let first = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| verify_entry(c) || c.is_some()));\n}\n"; @@ -4940,6 +5182,32 @@ mod tests { assert_eq!(hits_in(SOURCE_AUDITS[0], bad, &ctx()), []); let data = "#[test]\nfn t() {\n let s = include_str!(\"fixtures/a.svg\");\n assert_eq!(s.len(), 4);\n}\n"; assert_eq!(hits(data), []); + let name = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", name), [], "a suffix check on a generated name"); + let read = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert!(fs::read_to_string(p).unwrap().contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", read), [(4, "reads-source")], "the test reads the file"); + let helper = "#[cfg(test)]\nmod tests {\n fn load(p: &Path) -> String {\n if p.ends_with(\".rs\") {\n return fs::read_to_string(p).unwrap();\n }\n String::new()\n }\n #[test]\n fn t() {\n assert_eq!(load(newest()), \"x\");\n }\n}\n"; + assert_eq!(only("reads-source", helper), [(4, "reads-source")], "a helper in the test module reads the file"); + let split = "#[test]\nfn t() {\n for p in listing() {\n if !p.ends_with(\".rs\") {\n continue;\n }\n assert_eq!(load(&p), \"x\");\n }\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", split), [(4, "reads-source")], "a separate test helper reads the file"); + } + + #[test] + fn sibling_attributes_do_not_end_the_cfg_scan() { + let case = "#[cfg(target_os = \"macos\")]\n#[test_case(1; \"one\")]\nfn t(n: u8) {\n assert_eq!(f(n), 1);\n}\n"; + assert_eq!(only("never-run", case), [(3, "never-run")]); + let bodyless = "#[cfg(target_os = \"macos\")]\nuse x::y;\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", bodyless), [], "a cfg on a bodyless item"); + } + + #[test] + fn same_named_tests_in_other_modules_are_compared_by_line() { + let src = "#[cfg(target_os = \"macos\")]\nmod mac {\n #[test]\n fn smoke() {\n assert_eq!(f(), 1);\n }\n}\nmod common {\n #[test]\n fn smoke() {\n assert_eq!(f(), 1);\n }\n}\n"; + let base = lint_file("crates/x/src/child.rs", src, &ctx()); + let gated = Ctx { module_cfgs: [("crates/x/src/child.rs".to_owned(), vec!["windows".to_owned()])].into_iter().collect(), ..ctx() }; + let head = lint_file("crates/x/src/child.rs", src, &gated); + let off: Vec = head.iter().filter(|h| h.rule == Rule::NeverRun && off_since(&base, h)).map(|h| h.line).collect(); + assert_eq!(off, [10], "common::smoke is newly off; mac::smoke was off before"); } #[test] @@ -5508,4 +5776,191 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } + + #[test] + fn each_loading_path_is_followed_to_its_root() { + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let run = |files: &[(&str, &str)]| { + let files: HashMap = files.iter().map(|(p, s)| ((*p).to_owned(), (*s).to_owned())).collect(); + let read = |p: &str| files.get(p).cloned(); + let ctx = Ctx { module_cfgs: module_cfgs(&["crates/x/src/a/child.rs".to_owned()], &read), ..ctx() }; + hits_in("crates/x/src/a/child.rs", test, &ctx).into_iter().filter(|h| h.1 == "never-run").count() + }; + // `a.rs` loads the child, and `lib.rs` and `main.rs` both load `a.rs`. + let open = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod a;\n"), + ("crates/x/src/main.rs", "mod a;\n"), + ("crates/x/src/a.rs", "mod child;\n"), + ]; + assert_eq!(run(&open), 0, "the ungated path through main.rs runs it"); + let shut = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod a;\n"), + ("crates/x/src/main.rs", "#[cfg(windows)]\nmod a;\n"), + ("crates/x/src/a.rs", "mod child;\n"), + ]; + assert_eq!(run(&shut), 1, "both paths are off"); + // `a/mod.rs` and the binary root `a/main.rs` both load the child; only `a/mod.rs` sits + // under a gate. + let second = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod a;\n"), + ("crates/x/src/a/mod.rs", "mod child;\n"), + ("crates/x/src/a/main.rs", "mod child;\n"), + ]; + assert_eq!(run(&second), 0, "the first parent's ancestors do not gate the second path"); + } + + #[test] + fn a_base_parent_that_stopped_loading_a_child_is_listed() { + let files: HashMap<&str, &str> = [("crates/x/src/main.rs", "mod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read); + assert_eq!( + gates.get("crates/x/src/child.rs").map(|g| (g.preds.clone(), g.sources.len())), + Some((vec![], 1)), + "an ungated loader is still a source" + ); + let paths = ["crates/x/src/child.rs".to_owned()]; + let head = module_gates(&paths, &|_| Some(String::new())); + let cfgs = head_cfgs(&paths, &head, &gates, &|_| false); + assert_eq!(cfgs.get("crates/x/src/child.rs").map(Vec::as_slice), Some(&["any()".to_owned()][..]), "no file loads it any more"); + let ctx = Ctx { module_cfgs: cfgs, ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in("crates/x/src/child.rs", test, &ctx), [(2, "never-run")]); + assert_eq!(head_cfgs(&paths, &gates, &gates, &|_| false).get("crates/x/src/child.rs").map(Vec::len), Some(0), "still loaded"); + let kept = head_cfgs(&paths, &head, &gates, &|_| true); + assert!(kept.get("crates/x/src/child.rs").is_none_or(Vec::is_empty), "a `#[path]` elsewhere may load it"); + let tree = [("tests/it/main.rs".to_owned(), "#[path = \"../../crates/x/src/child.rs\"]\nmod child;\n".to_owned())]; + let read_tree = |p: &str| tree.iter().find(|(f, _)| f == p).map(|(_, s)| s.clone()); + let listed: Vec = tree.iter().map(|(f, _)| f.clone()).collect(); + let index = OnceCell::new(); + assert!(path_names(&index, &listed, &read_tree, "crates/x/src/child.rs")); + assert!(!path_names(&index, &listed, &read_tree, "crates/y/src/child.rs"), "a different file with the same basename"); + assert!(!path_names(&index, &listed, &read_tree, "crates/x/src/other.rs")); + } + + #[test] + fn a_child_whose_ancestor_is_no_longer_loaded_is_dead() { + let child = ["crates/x/src/a/child.rs".to_owned()]; + let base: HashMap<&str, &str> = [("crates/x/src/lib.rs", "mod a;\n"), ("crates/x/src/a.rs", "mod child;\n")].into_iter().collect(); + let head: HashMap<&str, &str> = [("crates/x/src/lib.rs", ""), ("crates/x/src/a.rs", "mod child;\n")].into_iter().collect(); + let base = module_gates(&child, &|p| base.get(p).map(|s| (*s).to_owned())); + let head = module_gates(&child, &|p| head.get(p).map(|s| (*s).to_owned())); + assert!(!base["crates/x/src/a/child.rs"].dead); + assert!(head["crates/x/src/a/child.rs"].dead, "a.rs still loads it, but nothing loads a.rs"); + assert_eq!(head_cfgs(&child, &head, &base, &|_| false).get("crates/x/src/a/child.rs").map(Vec::as_slice), Some(&["any()".to_owned()][..])); + } + + #[test] + fn removed_path_loaders_select_unchanged_siblings() { + let parent = "crates/x/src/retype.rs"; + let child = "crates/x/src/retype_tests.rs"; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let files = vec![child.to_owned()]; + let dirs = vec!["crates/x/src/retype/".to_owned()]; + for deleted in [false, true] { + let changed = if deleted { BTreeMap::new() } else { [(parent.to_owned(), None)].into_iter().collect() }; + for gate in ["", "#[cfg(target_os = \"macos\")]\n"] { + let source = format!("{gate}#[path = \"./retype_tests.rs\"]\nmod tests;\n"); + let base = [("crates/x/src/lib.rs", "mod retype;\n"), (parent, source.as_str())]; + let read_base = |p: &str| base.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let loaders = path_loads(&source, parent); + let below = unchanged_children(&files, &changed, &dirs, &loaders); + assert_eq!(below, files, "deleted={deleted}, gate={gate}"); + let base_gates = module_gates_from(&below, &read_base, &loaders); + assert!(base_gates[child].sources.iter().any(|(p, _)| p == parent)); + let head = module_gates(&below, &|_| None); + let head_ctx = Ctx { module_cfgs: head_cfgs(&below, &head, &base_gates, &|_| false), ..ctx() }; + let base_ctx = Ctx { module_cfgs: base_gates.into_iter().map(|(p, g)| (p, g.preds)).collect(), ..ctx() }; + let before = lint_file(child, test, &base_ctx); + let after = lint_file(child, test, &head_ctx); + let newly_off = after.iter().filter(|h| h.rule == Rule::NeverRun && off_since(&before, h)).count(); + assert_eq!(newly_off, usize::from(gate.is_empty()), "deleted={deleted}, gate={gate}"); + } + } + let inline = path_loads("mod inner { #[path = \"../inline_tests.rs\"] mod tests; }", parent); + assert_eq!(inline.iter().map(|l| l.path.as_str()).collect::>(), ["crates/x/src/retype/inline_tests.rs"]); + } + + /// Both unchanged targets of a chain of `#[path]` declarations are selected at the base. + #[test] + fn base_path_loaders_select_transitive_targets() { + let parent = "crates/x/src/retype.rs"; + let child = "crates/x/src/retype_installed.rs"; + let grandchild = "crates/x/src/retype_installed_tests.rs"; + let base = [ + (parent, "#[path = \"retype_installed.rs\"] mod installed;\n"), + (child, "#[path = \"retype_installed_tests.rs\"] mod tests;\n"), + (grandchild, "#[path = \"retype.rs\"] mod parent;\n"), + ]; + let reads = RefCell::new(Vec::new()); + let read_base = |p: &str| { + reads.borrow_mut().push(p.to_owned()); + base.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()) + }; + let loaders = base_path_loads(&[parent.to_owned()], &read_base); + let files = vec![child.to_owned(), grandchild.to_owned()]; + let changed = [(parent.to_owned(), None)].into_iter().collect(); + assert_eq!(unchanged_children(&files, &changed, &[], &loaders), files); + assert_eq!(*reads.borrow(), [parent, child, grandchild], "a cycle does not read a target again"); + } + + #[test] + fn dead_routes_do_not_enable_a_gated_live_route() { + let files = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"a.rs\"]\nmod a;\n"), + ("crates/x/src/a.rs", "mod child;\n"), + ("crates/x/src/a/mod.rs", "mod child;\n"), + ]; + let read = |p: &str| files.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let path = "crates/x/src/a/child.rs"; + let ctx = Ctx { module_cfgs: module_cfgs(&[path.to_owned()], &read), ..ctx() }; + assert_eq!(hits_in(path, "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n", &ctx), [(2, "never-run")]); + } + + #[test] + fn inline_routes_are_checked_alongside_file_parents() { + let path = "crates/x/src/a/child.rs"; + for gate in ["", "#[cfg(target_os = \"macos\")]\n"] { + let root = format!("{gate}mod a {{ mod child; }}\n"); + let files = [("crates/x/src/lib.rs", root.as_str()), ("crates/x/src/a.rs", "mod child;\n")]; + let read = |p: &str| files.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let gates = module_gates(&[path.to_owned()], &read); + assert!(!gates[path].dead, "{gate}"); + let ctx = Ctx { module_cfgs: gates.into_iter().map(|(p, g)| (p, g.preds)).collect(), ..ctx() }; + let hits = hits_in(path, "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n", &ctx); + assert_eq!(hits.iter().filter(|h| h.1 == "never-run").count(), usize::from(!gate.is_empty()), "{gate}"); + } + } + + #[test] + fn suffix_selected_source_reads_include_streams() { + for read in ["File::open(p)", "File :: open(p)", "reader.read_to_end(&mut bytes)", "reader.read_to_string(&mut text)", "fs::read(p)"] { + let src = format!( + "#[test]\nfn t() {{\n let p = newest();\n if p.ends_with(\".rs\") {{\n let got = {read};\n assert_eq!(check(got), 1);\n }}\n}}\n" + ); + assert_eq!(only("reads-source", &src), [(4, "reads-source")], "{read}"); + assert_eq!(only("reads-source", &src.replace(".rs", ".svg")), [], "{read}"); + } + let name = "#[test]\nfn t() {\n let p = newest();\n assert_eq!(p.ends_with(\".rs\"), wanted());\n}\n"; + assert_eq!(only("reads-source", name), []); + } + + #[test] + fn path_names_reuses_a_lazy_workspace_index() { + let files = vec!["src/lib.rs".to_owned(), "src/other.rs".to_owned()]; + let reads = RefCell::new(Vec::new()); + let read = |p: &str| { + reads.borrow_mut().push(p.to_owned()); + Some("#[path = \"nested/child.rs\"] mod child;\n".to_owned()) + }; + let index = OnceCell::new(); + assert!(reads.borrow().is_empty()); + assert!(path_names(&index, &files, &read, "src/nested/child.rs")); + assert!(!path_names(&index, &files, &read, "src/child.rs"), "a different file with the same basename"); + assert!(!path_names(&index, &files, &read, "src/missing.rs")); + assert!(!path_names(&index, &files, &read, "src/other.rs")); + assert_eq!(*reads.borrow(), files); + let own = OnceCell::new(); + assert!(!path_names(&own, &["src/child.rs".to_owned()], &read, "src/child.rs")); + } } From 3026e08314d433a6b376f8808337ba9520defb3b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:30:12 -0800 Subject: [PATCH 30/50] Step and Repeat: refuse a grid whose copies would hold too many objects The 10,000-cell limit did not count the artwork in each cell, so a large selection repeated over many cells had no bound on the objects it made. The command now also refuses a grid whose new copies would hold more than 250,000 objects, counting the art of opacity masks and the group a multi-object selection goes into. --- crates/engine/src/cmd/stepandrepeat.rs | 10 +++++++++- crates/engine/src/cmd/stepandrepeat/tests.rs | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index bf15cc340e..16684a3284 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -12,6 +12,8 @@ use vectorcraft_doc::{Node, Scaling}; const CMD: &str = "object.stepAndRepeat"; const MAX_CELLS: usize = 10_000; +/// The most objects the copies may hold in all, counting every object inside each copy. +const MAX_COPIED_OBJECTS: usize = 250_000; const EPS: f64 = 1e-9; pub fn specs() -> Vec { @@ -20,7 +22,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] @@ -174,6 +176,12 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { if rows.saturating_mul(cols) > MAX_CELLS { return Err(bad(CMD, format!("more than {MAX_CELLS} copies"))); } + // Each copy holds every object of the selection, the art of opacity masks included, and the + // group that a selection of several objects goes into. + let objects = roots.iter().filter_map(|r| d.node(*r)).fold(usize::from(roots.len() > 1), |sum, n| sum.saturating_add(n.count_with_masks())); + if objects.saturating_mul(rows * cols - 1) > MAX_COPIED_OBJECTS { + return Err(bad(CMD, format!("the copies would hold more than {MAX_COPIED_OBJECTS} objects"))); + } let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0)); let cells = layout(w, h, gx, gy, rows, cols, alt); let center = b.center().to_vec2(); diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index 4d807f7d8d..133d79ff48 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -131,6 +131,21 @@ fn rejects_bad_params_and_a_selection_that_does_not_fit() { assert!(e.execute(CMD, &json!({})).is_err()); } +#[test] +fn rejects_a_grid_whose_copies_would_hold_too_many_objects() { + let (mut s, _) = setup(); + for i in 1..25 { + s.execute("shape.rectangle", &json!({"x": i, "y": 0, "width": 10, "height": 10})).unwrap(); + } + s.execute("select.all", &json!({})).unwrap(); + let (count, steps) = (s.doc().unwrap().doc.node_count(), undo_steps(&s)); + // 25 objects and the group they go into, in each of 9,999 copies, are more than the limit, + // though the cells are not. + let e = s.execute(CMD, &json!({"rows": 100, "columns": 100})).unwrap_err(); + assert!(e.to_string().contains("objects"), "{e}"); + assert_eq!((s.doc().unwrap().doc.node_count(), undo_steps(&s)), (count, steps)); +} + #[test] fn rejects_a_negative_margin_and_gaps_that_fold_the_grid_back() { let (mut s, _) = setup(); From 6598763bfc09bdce631c516a5314da1554715180 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:42:41 -0800 Subject: [PATCH 31/50] xtask: test-lint follows path targets' children, head path gates and inline path dirs - Files in the directory of a `#[path]` target are checked with it, so a plain `mod child;` under the target is not missed when the declaration is removed. - A helper inside one arm of an `if` or `match` on the left of `||` no longer counts as always called; only the condition does. - A `.ends_with(".rs")` check counts as reading source only when the checked name is passed to a file read (directly, through a helper, or by a stream read in the same test), or when it filters an iterator over a file listing. A predicate over generated names is not reported. - An inline module's `#[path]` sets the directory of the declarations inside it. - Scoped and `--all` runs pass the head's `#[path]` declarations into gate evaluation, so a `cfg` added to one gates its target. --- xtask/src/test_lint.rs | 175 +++++++++++++++++++++++++++++++++++------ 1 file changed, 149 insertions(+), 26 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 2644bf2044..a9f4b50819 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -283,7 +283,13 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); if opts.all { let sources = read_all(root, &files)?; - let module_cfgs = module_cfgs(&files, &|p| read_small(root, p)); + // Every `#[path]` declaration is another way in, so its `cfg` gates the file it loads. + let loaders: Vec = sources.iter().flat_map(|(p, s)| path_loads(s, p)).collect(); + let module_cfgs = module_gates_from(&files, &|p| read_small(root, p), &loaders) + .into_iter() + .filter(|(_, g)| !g.preds.is_empty()) + .map(|(p, g)| (p, g.preds)) + .collect(); let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs }; let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); print!("{}", report(&hits, sources.len())); @@ -328,7 +334,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let loaders = base_path_loads(&present.iter().chain(&deleted).cloned().collect::>(), &read_base); let below = unchanged_children(&files, &changed, &module_dirs, &loaders); let gated: Vec = present.iter().chain(&below).cloned().collect(); - let gates = module_gates(&gated, &|p| read_small(root, p)); + // The head's `#[path]` declarations reachable from the changed files gate their targets too. + let head_loaders = base_path_loads(&present.iter().cloned().collect::>(), &|p| read_small(root, p)); + let gates = module_gates_from(&gated, &|p| read_small(root, p), &head_loaders); let base_gates = module_gates_from(&gated, &read_base, &loaders); // A changed or deleted file that loaded a child at the base may have stopped loading it, which // the head's gates do not show; the base comparison below still drops a test that was already @@ -428,16 +436,21 @@ fn base_path_loads(paths: &[String], read: &dyn Fn(&str) -> Option) -> V } /// The unchanged files whose tests a changed or deleted file can turn off: those under one of -/// `module_dirs`, and those a `#[path]` declaration in `loaders` loaded at the base. +/// `module_dirs`, those a `#[path]` declaration in `loaders` loaded at the base, and those in the +/// directory of such a file, where its own `mod` declarations load their children. fn unchanged_children( files: &[String], changed: &BTreeMap>>, module_dirs: &[String], loaders: &[PathLoad], ) -> Vec { + let load_dirs: Vec = loaders.iter().filter_map(|l| l.path.rsplit_once('/').map(|(dir, _)| format!("{dir}/"))).collect(); files .iter() - .filter(|p| !changed.contains_key(*p) && (module_dirs.iter().any(|d| p.starts_with(d.as_str())) || loaders.iter().any(|l| l.path == **p))) + .filter(|p| { + !changed.contains_key(*p) + && (module_dirs.iter().chain(&load_dirs).any(|d| p.starts_with(d.as_str())) || loaders.iter().any(|l| l.path == **p)) + }) .cloned() .collect() } @@ -1619,6 +1632,10 @@ fn always_calls(s: &str, helpers: &[String], depth: usize) -> bool { always_calls(&s[1..s.len() - 1], helpers, depth + 1) } else if let Some(at) = top_level_at(s, "||").first().copied().or_else(|| top_level_at(s, "&&").first().copied()) { always_calls(&s[..at], helpers, depth + 1) + } else if let Some(&at) = top_level_at(s, "{").first() { + // An `if` or `match` always runs only its condition or scrutinee, the text before its + // first block; a call inside one arm may be skipped. + always_calls(&s[..at], helpers, depth + 1) } else { calls_any(s, helpers) } @@ -3135,8 +3152,8 @@ fn reads_source_hits(file: &File) -> Vec { let literal = raw.unwrap_or(&arg); let rs = match word { // A suffix check alone may test a generated name; it counts when it selects files - // from a listing or the file's test code also reads a file. - b"ends_with" => literal == "\".rs\"" && (selects(m, at) || reads_files(file)), + // from a listing or the checked path is passed to a file read. + b"ends_with" => literal == "\".rs\"" && (selects(m, at) || reads_checked(file, at)), // The last path literal in the argument names the file read: `root.join("src/lib.rs")`, // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), @@ -3154,32 +3171,92 @@ fn reads_source_hits(file: &File) -> Vec { } /// Whether the call at `at` sits in the closure of a `filter`, `filter_map`, `find`, `any`, -/// `all`, `position` or `retain` call, which picks entries out of a listing. +/// `all`, `position` or `retain` call on an iterator whose chain names a listing (`read_dir`, `files`, +/// `listing`, `walk` and the like), which picks entries out of the listing. fn selects(m: &[u8], at: usize) -> bool { const PICKS: &[&[u8]] = &[b"filter", b"filter_map", b"find", b"find_map", b"any", b"all", b"position", b"retain"]; + const LISTINGS: &[&str] = &["read_dir", "files", "listing", "walk", "walkdir", "glob", "entries", "paths", "sources"]; m[..at].iter().enumerate().rev().filter(|&(_, &c)| c == b'(').find(|&(open, _)| matching(m, open).is_none_or(|close| close > at)).is_some_and( |(open, _)| { let head = m[..open].trim_ascii_end(); let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); - PICKS.contains(&&head[head.len() - name..]) + if !PICKS.contains(&&head[head.len() - name..]) { + return false; + } + // The receiver chain: back from the pick to the start of its statement. + let start = head[..head.len() - name].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}' | b'=')).map_or(0, |p| p + 1); + let chain = String::from_utf8_lossy(&head[start..head.len() - name]); + chain.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(|w| LISTINGS.iter().any(|l| w == *l || w.ends_with(&format!("_{l}")))) }, ) } -/// Whether the test code of the file (the tests, and the test modules and helpers around them) -/// reads a file or lists a directory: a helper elsewhere in it may read what a test selects. -fn reads_files(file: &File) -> bool { - file.regions.iter().any(|&(from, to)| { - [&b"read_to_string"[..], b"read_to_end", b"read_dir", b"include_str", b"read", b"open"].iter().any(|w| { - words(&file.m, w, from, to).into_iter().any(|p| { - if *w == b"open" && !norm(&file.m[..p]).ends_with("File::") { - return false; +/// The reading calls whose argument names the file read. +const READS: &[&[u8]] = &[b"read_to_string", b"read_to_end", b"read_dir", b"include_str", b"read", b"open"]; + +/// The argument spans `(open, close)` of the reading calls in the test code of the file (the tests, +/// and the test modules and helpers around them). +fn read_calls(file: &File) -> Vec<(usize, usize)> { + let m = &file.m; + let mut out = vec![]; + for &(from, to) in &file.regions { + for w in READS { + for p in words(m, w, from, to) { + if *w == b"open" && !norm(&m[..p]).ends_with("File::") { + continue; } - let next = skip_ws(&file.m, p + w.len()); - let next = if file.m.get(next) == Some(&b'!') { skip_ws(&file.m, next + 1) } else { next }; - file.m.get(next) == Some(&b'(') + let next = skip_ws(m, p + w.len()); + let next = if m.get(next) == Some(&b'!') { skip_ws(m, next + 1) } else { next }; + if m.get(next) == Some(&b'(') + && let Some(close) = matching(m, next) + { + out.push((next, close)); + } + } + } + } + out +} + +/// Whether the path checked by the `.ends_with` at `at` is read: its receiver, a plain name, is an +/// argument of a reading call, or of a call to a function in the file whose body reads a file. +fn reads_checked(file: &File, at: usize) -> bool { + let m = &file.m; + let before = m[..at].trim_ascii_end(); + let Some(dot) = before.strip_suffix(b".") else { return false }; + let dot = dot.trim_ascii_end(); + let len = dot.iter().rev().take_while(|&&c| is_ident(c)).count(); + let recv = &dot[dot.len() - len..]; + // A call, an index or a field chain is not a plain name: its value cannot be followed. + if len == 0 || recv[0].is_ascii_digit() || dot[..dot.len() - len].trim_ascii_end().ends_with(b".") { + return false; + } + let reads = read_calls(file); + let passes = |open: usize, close: usize| !words(m, recv, open + 1, close).is_empty(); + // A stream method such as `reader.read_to_end(…)` takes a buffer, not the path: it counts when + // it reads in the same test as the check. + let region = file.regions.iter().find(|&&(from, to)| from <= at && at < to); + let streams = + |open: usize| m[..open].trim_ascii_end().iter().rev().skip_while(|&&c| is_ident(c)).find(|c| !c.is_ascii_whitespace()) == Some(&b'.'); + if reads.iter().any(|&(open, close)| passes(open, close) || streams(open) && region.is_some_and(|&(from, to)| from <= open && open < to)) { + return true; + } + // Functions whose body holds a reading call, called with the checked name. + words(m, b"fn", 0, m.len()).into_iter().any(|f| { + let name_at = skip_ws(m, f + 2); + let name_len = m[name_at..].iter().take_while(|&&c| is_ident(c)).count(); + let Some(body) = m[name_at..].iter().position(|&c| c == b'{' || c == b';').map(|p| name_at + p).filter(|&b| m[b] == b'{') else { + return false; + }; + let Some(end) = matching(m, body) else { return false }; + name_len > 0 + && reads.iter().any(|&(open, _)| open > body && open < end) + && file.regions.iter().any(|&(from, to)| { + words(m, &m[name_at..name_at + name_len], from, to).into_iter().any(|c| { + let open = skip_ws(m, c + name_len); + c != name_at && m.get(open) == Some(&b'(') && matching(m, open).is_some_and(|close| passes(open, close)) + }) }) - }) }) } @@ -3674,7 +3751,7 @@ fn path_loads(src: &str, parent: &str) -> Vec { } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); let rel = path_attr(&m, src.as_bytes(), item, at)?; - let chain = inline_mods(&m, at); + let chain = inline_mods(&m, src.as_bytes(), at); Some(PathLoad { path: module_path(parent, &chain, &rel), parent: parent.to_owned(), chain }) }) .collect() @@ -3707,7 +3784,7 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, for at in words(&m, b"mod", 0, m.len()) { let start = skip_ws(&m, at + 3); let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); - if end == start || m.get(skip_ws(&m, end)) != Some(&b';') || inline_mods(&m, at) != want.chain { + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') || inline_mods(&m, src.as_bytes(), at) != want.chain { continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); @@ -3771,8 +3848,10 @@ fn join_path(base: &str, rel: &str) -> String { } /// The names of the inline `mod { … }` blocks around `at` in the masked text `m`, outermost -/// first. A `mod x;` inside them loads a file under their directory instead of a sibling file. -fn inline_mods(m: &[u8], at: usize) -> Vec { +/// first. A `mod x;` inside them loads a file under their directory instead of a sibling file. An +/// inline module with a `#[path = "dir"]` attribute gives `dir`, the directory it sets, in place of +/// its name. +fn inline_mods(m: &[u8], src: &[u8], at: usize) -> Vec { m[..at] .iter() .enumerate() @@ -3781,8 +3860,12 @@ fn inline_mods(m: &[u8], at: usize) -> Vec { let head = m[..open].trim_ascii_end(); let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); let before = head[..head.len() - name].trim_ascii_end(); - (name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident)) - .then(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned()) + if name == 0 || !before.ends_with(b"mod") || before[..before.len() - 3].last().copied().is_some_and(is_ident) { + return None; + } + let kw = before.len() - 3; + let item = m[..kw].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + Some(path_attr(m, src, item, kw).unwrap_or_else(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned())) }) .collect() } @@ -4155,6 +4238,8 @@ mod tests { assert_eq!(census_in(outer, &ctx()), [], "a helper on the left of an outer || always runs"); let guarded = "#[test]\nfn t() {\n assert!((ready && verify_entry()) || COLORS.iter().all(|c| c.is_some()));\n}\n"; assert_eq!(census_in(guarded, &ctx()), [(2, "census")], "a helper behind an && on the left is skipped when ready is false"); + let arm = "#[test]\nfn t() {\n assert!((if ready { verify_entry() } else { false }) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(arm, &ctx()), [(2, "census")], "a helper in one arm of an if on the left is skipped when ready is false"); let in_message = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some(), \"{:?}\", verify_entry(c));\n }\n}\n"; assert_eq!(census_in(in_message, &ctx()), [(2, "census")], "a helper in a failure message runs only after a failure"); let first = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| verify_entry(c) || c.is_some()));\n}\n"; @@ -5237,6 +5322,10 @@ mod tests { assert_eq!(hits(data), []); let name = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n"; assert_eq!(only("reads-source", name), [], "a suffix check on a generated name"); + let other_read = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n#[test]\nfn u() {\n assert!(fs::read_to_string(\"data.json\").unwrap().contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", other_read), [], "another test reads a file the suffix check did not name"); + let names = "#[test]\nfn t() {\n assert!(generated_names().iter().all(|name| name.ends_with(\".rs\")));\n}\n"; + assert_eq!(only("reads-source", names), [], "a suffix predicate over generated names"); let read = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert!(fs::read_to_string(p).unwrap().contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", read), [(4, "reads-source")], "the test reads the file"); let helper = "#[cfg(test)]\nmod tests {\n fn load(p: &Path) -> String {\n if p.ends_with(\".rs\") {\n return fs::read_to_string(p).unwrap();\n }\n String::new()\n }\n #[test]\n fn t() {\n assert_eq!(load(newest()), \"x\");\n }\n}\n"; @@ -5957,6 +6046,40 @@ mod tests { assert_eq!(*reads.borrow(), [parent, child, grandchild], "a cycle does not read a target again"); } + /// A file that a `#[path]` target loads with a plain `mod` is selected with the target. + #[test] + fn base_path_loaders_select_plain_children_of_targets() { + let parent = "crates/x/src/platform.rs"; + let loaders = path_loads("#[path = \"backend/mod.rs\"]\nmod backend;\n", parent); + let files = vec!["crates/x/src/backend/mod.rs".to_owned(), "crates/x/src/backend/child.rs".to_owned()]; + let changed = [(parent.to_owned(), None)].into_iter().collect(); + assert_eq!(unchanged_children(&files, &changed, &[], &loaders), files); + } + + /// A `#[path]` on an enclosing inline module sets the directory of the declarations inside it. + #[test] + fn inline_path_overrides_set_the_directory() { + let loads = path_loads("#[path = \".\"]\nmod wrapper {\n #[path = \"child.rs\"]\n mod inner;\n}\n", "crates/x/src/lib.rs"); + assert_eq!(loads.iter().map(|l| l.path.as_str()).collect::>(), ["crates/x/src/child.rs"]); + } + + /// A `cfg` on the head's `#[path]` declaration gates the file it loads, unless another route runs. + #[test] + fn head_path_loaders_gate_their_targets() { + let parent = "crates/x/src/platform.rs"; + let child = "crates/x/src/backend_tests.rs"; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + for (extra, off) in [("", true), ("#[path = \"backend_tests.rs\"]\nmod also;\n", false)] { + let lib = format!("mod platform;\n{extra}"); + let files = [("crates/x/src/lib.rs", lib.as_str()), (parent, "#[cfg(windows)]\n#[path = \"backend_tests.rs\"]\nmod tests;\n")]; + let read = |p: &str| files.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let loaders = base_path_loads(&["crates/x/src/lib.rs".to_owned(), parent.to_owned()], &read); + let gates = module_gates_from(&[child.to_owned()], &read, &loaders); + let ctx = Ctx { module_cfgs: gates.into_iter().map(|(p, g)| (p, g.preds)).collect(), ..ctx() }; + assert_eq!(hits_in(child, test, &ctx).iter().any(|h| h.1 == "never-run"), off, "{extra}"); + } + } + #[test] fn dead_routes_do_not_enable_a_gated_live_route() { let files = [ From c683302d4e3c11fe2c373c3746ad9aed8a8f5bb0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:00:09 -0800 Subject: [PATCH 32/50] Text Wrap: Make's no-type warning checks the wrap objects without copying their shapes Make Text Wrap called wrap_sources to learn whether a new wrap object sits above area type, which copied every wrap shape of every area text object in the document into text space and threw the copies away. wrap_source_objects gives the same text objects and wrap objects without making those copies, and Make uses it. --- crates/doc/src/text.rs | 2 +- crates/doc/src/text/tests.rs | 9 +++++++++ crates/doc/src/text/wrap.rs | 16 ++++++++++++++++ crates/engine/src/cmd/textwrap.rs | 2 +- 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 073a0f2efd..7ba5cb6199 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -44,7 +44,7 @@ pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList, TabAlign, TabStop, }; -pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_sources, wrap_work}; +pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_source_objects, wrap_sources, wrap_work}; /// A text object. `runs` split into paragraphs at `\n`. /// diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 9371947565..8a17fd880b 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -695,6 +695,15 @@ fn a_wrap_object_below_every_area_type_object_makes_no_outline() { }); assert_eq!(sources, 1); assert_eq!(wrap::OUTLINES_MADE.with(|c| c.get()), 1, "only the wrap object above the type is outlined"); + // The objects alone come without a copy of any shape into text space. + let mut found = vec![]; + wrap_source_objects(&d, |n, objects| found.push((n.id, objects.iter().map(|o| o.id).collect::>()))); + let mut expected = vec![]; + wrap_sources(&d, |n, objects, _| expected.push((n.id, objects.iter().map(|o| o.id).collect::>()))); + assert_eq!(found, expected); + wrap::SHAPES_COPIED.with(|c| c.set(0)); + wrap_source_objects(&d, |_, _| {}); + assert_eq!(wrap::SHAPES_COPIED.with(|c| c.get()), 0, "no wrap shape is copied"); } #[test] diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index 33fdcb4687..2061de7092 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -11,6 +11,8 @@ use crate::{Document, Node, NodeId, NodeKind}; thread_local! { /// How many wrap outlines [`each_text`] has made on this thread (for tests). pub(super) static OUTLINES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many wrap shapes [`shapes_of`] has copied into text space on this thread (for tests). + pub(super) static SHAPES_COPIED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Outline of a wrap object in document coordinates: its paths, or its bounds for other art. @@ -167,6 +169,8 @@ fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec { .iter() .rev() .map(|(_, s)| { + #[cfg(test)] + SHAPES_COPIED.with(|c| c.set(c.get() + 1)); let mut path = s.path.clone(); path.transform(inv); WrapShape { path, wrap: s.wrap } @@ -189,6 +193,18 @@ pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a N } } +/// [`wrap_sources`] without the shapes: each area text object that gets wrap shapes, with the wrap +/// objects whose outlines make them, bottom first. No shape is copied into text space. +pub fn wrap_source_objects<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>)) { + for layer in &doc.layers { + each_text(layer, |n, above| { + if matches!(n.kind, NodeKind::Text(_)) && !above.is_empty() { + f(n, above.iter().rev().map(|(s, _)| *s).collect()); + } + }); + } +} + /// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the /// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged /// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes diff --git a/crates/engine/src/cmd/textwrap.rs b/crates/engine/src/cmd/textwrap.rs index ade875b4c9..6daa8cdd26 100644 --- a/crates/engine/src/cmd/textwrap.rs +++ b/crates/engine/src/cmd/textwrap.rs @@ -115,7 +115,7 @@ fn make(s: &mut Session, p: &Value) -> Result { } let mut out = json!({ "ids": objects.iter().map(|i| i.0).collect::>() }); let mut wraps = false; - vectorcraft_doc::text::wrap_sources(&s.doc()?.doc, |_, sources, _| wraps |= sources.iter().any(|n| objects.contains(&n.id))); + vectorcraft_doc::text::wrap_source_objects(&s.doc()?.doc, |_, sources| wraps |= sources.iter().any(|n| objects.contains(&n.id))); if !wraps { out["warning"] = json!(NO_AREA_TYPE_BELOW); } From b3c1a31cfa870d11e7df40fe7ffe37fa3b06cc04 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:00:36 -0800 Subject: [PATCH 33/50] JavaScript: proxy checks follow GetFunctionRealm, subclass order and for-in sources - A non-object `prototype` on `new.target` walks its bound and proxy chain (GetFunctionRealm), so a get trap that revokes the proxy throws a TypeError instead of running the constructor. - A subclassable built-in such as Number no longer unwraps a revoked `new.target` before its own argument conversion runs. - for-in records how many proxies came before the object that first listed each name, and the recheck does not ask those proxies for a descriptor, so a proxy that did not list a name cannot hide an inherited enumerable one. - Names from an ownKeys trap take fuel for their code units, and so do the names the ownKeys invariant check hashes. - The DataView argument test expects TypeError for a non-buffer and RangeError for a bad offset or length. --- crates/js/src/class_ops.rs | 26 ++++++++++++- crates/js/src/heap.rs | 4 ++ crates/js/src/interp.rs | 67 ++++++++++++++++++++++++++-------- crates/js/src/proxy.rs | 16 ++++++++ crates/js/src/proxy_tests.rs | 71 +++++++++++++++++++++++++++++++++--- docs/mcp.md | 3 +- 6 files changed, 164 insertions(+), 23 deletions(-) diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 8f69f066df..93f8afb3e6 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -176,10 +176,32 @@ impl Interp { } /// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14). + /// Before falling back it runs GetFunctionRealm (section 7.3.22) on `new.target`, which + /// throws a `TypeError` for a revoked proxy in its bound or proxy chain. pub(crate) fn prototype_from(&mut self, new_target: ObjId, fallback: ObjId) -> JsResult { match self.get_from(new_target, &key("prototype"), &Value::Object(new_target))? { Value::Object(p) => Ok(p), - _ => Ok(fallback), + _ => { + self.function_realm(new_target)?; + Ok(fallback) + } + } + } + + /// GetFunctionRealm (section 7.3.22). There is one realm, so this only walks the bound + /// and proxy chain of `f` and throws a `TypeError` when it reaches a revoked proxy. + /// Each hop takes a unit of fuel. + fn function_realm(&mut self, mut f: ObjId) -> JsResult<()> { + loop { + let next = match self.symbol_lookup_target(f)? { + Some(t) => t, + None => match self.func_of(&Value::Object(f)) { + Some(Func::Bound { target, .. }) => target, + _ => return Ok(()), + }, + }; + self.use_fuel()?; + f = next; } } @@ -313,7 +335,7 @@ impl Interp { Some(Func::Native { f: native, constructor: true, name, .. }) => { // `Proxy` does not read `new.target` (section 26.2.1.1). let subclass = nt != callee && name != "Proxy"; - if !boundary && subclass && !forwarding && self.unwrapped_proxy_target(nt)? != callee && !self.subclassable(callee)? { + if !boundary && subclass && !forwarding && !self.subclassable(callee)? && self.unwrapped_proxy_target(nt)? != callee { return Err(self.type_error("this built-in cannot be subclassed")); } let intrinsic = match self.get_own_property(callee, &key("prototype"))? { diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 89fb2c0a2e..236896882b 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -215,6 +215,9 @@ pub(crate) struct ArgMap { #[derive(Clone, Debug)] pub(crate) struct ForIn { pub(crate) keys: Vec, + /// For each name, how many proxies came before the object that first listed it on the + /// chain; empty when no name came after a proxy. A missing entry counts as 0. + pub(crate) starts: Vec, pub(crate) pos: usize, pub(crate) object: Option, } @@ -1180,6 +1183,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u Class::ForIn(state) => { work.extend(state.object.iter().map(|o| o.0)); strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::(); + strings.bytes += state.starts.len() * crate::interp::SOURCE_ENTRY_BYTES; } Class::Symbol(s) => strings.add_symbol(s), Class::IterRecord(r) => { diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 0f1cabf42d..e40a8919b0 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -571,6 +571,9 @@ pub(crate) const MAX_APPLY_ARGS: usize = 1 << 16; /// The estimated bytes of a name's entries in the list and the set `for-in` builds. pub(crate) const KEY_ENTRY_BYTES: usize = 32; +/// The bytes of one entry in the list of proxy counts `for-in` keeps for each name. +pub(crate) const SOURCE_ENTRY_BYTES: usize = std::mem::size_of::(); + /// The most units of a computed property name an error about a property of `null` or `undefined` /// names; a longer name is left out of the message. const NAMED_KEY_UNITS: usize = 256; @@ -3298,9 +3301,12 @@ impl Interp { /// /// For a String object, the heap budget for all its index names is checked before any is /// built. Each index name and each property visited takes a unit of fuel. - fn enumerable_keys(&mut self, id: ObjId) -> JsResult> { + /// + /// The second list holds, for each name, how many proxies came before the object that + /// listed it. It is empty or shorter than the names when the missing entries are 0. + fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec, Vec)> { if self.options.e4x && self.is_xml(&Value::Object(id)) { - return self.xml_enumerate(id); + return Ok((self.xml_enumerate(id)?, Vec::new())); } let slot = self.temp_roots.len(); self.temp_roots.push(Value::Undefined); @@ -3313,12 +3319,15 @@ impl Interp { /// `ownKeys` trap and the next object with its `getPrototypeOf` trap. /// `temp_roots[slot]` roots the current proxy through that lookup, then the returned prototype. /// Descriptors are checked when iteration reaches each name. - fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult> { + fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec, Vec)> { let mut seen = std::collections::HashSet::new(); let mut held = HeldBytes::new(self); let mut out = Vec::new(); + let mut starts: Vec = Vec::new(); + let mut proxies = 0u32; let mut cur = Some(id); while let Some(o) = cur { + let before = out.len(); if self.is_proxy(o) { if let Some(root) = self.temp_roots.get_mut(slot) { *root = Value::Object(o); @@ -3333,6 +3342,8 @@ impl Interp { seen.insert(k.clone()); out.push(k); } + self.note_listed(&mut starts, &mut held, before, out.len(), proxies)?; + proxies = proxies.saturating_add(1); cur = self.get_prototype_of(o)?; if let Some(root) = self.temp_roots.get_mut(slot) { *root = cur.map_or(Value::Undefined, Value::Object); @@ -3379,14 +3390,28 @@ impl Interp { } } cur = obj.proto; + self.note_listed(&mut starts, &mut held, before, out.len(), proxies)?; } - Ok(out) + Ok((out, starts)) + } + + /// Records that the names from `before` to `len` came after `proxies` proxies, counting + /// the new entries. Nothing is recorded when `proxies` is 0 or no name was added, since a + /// missing entry counts as 0. + fn note_listed(&mut self, starts: &mut Vec, held: &mut HeldBytes, before: usize, len: usize, proxies: u32) -> JsResult<()> { + if proxies == 0 || len == before { + return Ok(()); + } + held.add(self, len.saturating_sub(starts.len()).saturating_mul(SOURCE_ENTRY_BYTES))?; + starts.resize(before, 0); + starts.resize(len, proxies); + Ok(()) } fn op_for_in_start(&mut self) -> JsResult<()> { let v = self.peek(0)?; - let (keys, object) = if v.is_nullish() { - (Vec::new(), None) + let ((keys, starts), object) = if v.is_nullish() { + ((Vec::new(), Vec::new()), None) } else { let o = self.to_object(&v)?; // A wrapper made by ToObject is not on the stack; a collection while the names are @@ -3395,16 +3420,16 @@ impl Interp { self.temp_roots.push(Value::Object(o)); // Listing a namespace object's exports does not read them (ECMA-262 2015 section // 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed. - let keys = self.enumerable_keys(o).and_then(|keys| { - let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::(); + let keys = self.enumerable_keys(o).and_then(|(keys, starts)| { + let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::() + starts.len() * SOURCE_ENTRY_BYTES; self.reserve_heap(bytes)?; self.heap.bytes = self.heap.bytes.saturating_add(bytes); - Ok(keys) + Ok((keys, starts)) }); self.temp_roots.truncate(saved); (keys?, Some(o)) }; - let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, pos: 0, object })), None)); + let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, starts, pos: 0, object })), None)); self.replace(1, Value::Object(iter)) } @@ -3413,10 +3438,15 @@ impl Interp { loop { let Class::ForIn(state) = &mut self.object_mut(iter)?.class else { return internal("not a for-in iterator") }; let Some(k) = state.keys.get(state.pos).cloned() else { return self.jump_to(target) }; + let skip = state.starts.get(state.pos).copied().unwrap_or(0); state.pos += 1; let object = state.object; let Some(o) = object else { continue }; - let visit = if self.options.e4x && self.is_xml(&Value::Object(o)) { self.scope_has(o, &k)? } else { self.for_in_still_has(o, &k)? }; + let visit = if self.options.e4x && self.is_xml(&Value::Object(o)) { + self.scope_has(o, &k)? + } else { + self.for_in_still_has(o, &k, skip)? + }; if visit { return self.push(Value::String(Str::from_rc(k))); } @@ -3429,16 +3459,21 @@ impl Interp { /// the objects that follow it are searched. A name deleted or made non-enumerable after the /// names were listed is skipped, on an ordinary object as on a proxy. A proxy's `has` trap is /// not asked. Each proxy on the chain takes a unit of fuel. - fn for_in_still_has(&mut self, o: ObjId, k: &Key) -> JsResult { + /// + /// `skip` is how many proxies came before the object that first listed `k`. Those proxies + /// did not list `k`, so the first `skip` proxies the walk reaches are not asked through + /// their `getOwnPropertyDescriptor` trap and cannot hide an inherited name. + fn for_in_still_has(&mut self, o: ObjId, k: &Key, skip: u32) -> JsResult { // One root slot holds the prototype the walk has reached; each hop replaces it. let mark = self.temp_roots.len(); self.temp_roots.push(Value::Undefined); - let r = self.for_in_still_has_rooted(o, k, mark); + let r = self.for_in_still_has_rooted(o, k, skip, mark); self.temp_roots.truncate(mark); r } - fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &Key, slot: usize) -> JsResult { + fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &Key, skip: u32, slot: usize) -> JsResult { + let mut passed = 0u32; loop { let p = match self.lookup(cur, k)? { Lookup::Found(prop) => return Ok(prop.enumerable()), @@ -3446,7 +3481,9 @@ impl Interp { Lookup::Proxy(p) => p, }; self.use_fuel()?; - if let Some(prop) = self.get_own_property(p, k)? { + let asked = passed >= skip; + passed = passed.saturating_add(1); + if asked && let Some(prop) = self.get_own_property(p, k)? { return Ok(prop.enumerable()); } let Some(next) = self.get_prototype_of(p)? else { return Ok(false) }; diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index 650cc3a97b..fcb103b50c 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -477,6 +477,8 @@ impl Interp { match v { Value::String(s) => { held.add(self, string_bytes(s.len()).saturating_add(3 * KEY_ENTRY_BYTES))?; + // Flattening and hashing the name read every code unit of it. + crate::string_builtins::charge_units(self, s.len())?; let k = s.flat(); if !seen.insert(k.clone()) && duplicate.is_none() { duplicate = Some(PropKey::Str(k.clone())); @@ -530,9 +532,14 @@ impl Interp { if extensible && fixed.is_empty() { return Ok(()); } + // Building the set and each lookup in it hash every code unit of the name. + for k in keys { + crate::string_builtins::charge_units(self, k.len())?; + } let mut unchecked: HashSet<&[u16]> = keys.iter().map(|k| &**k).collect(); let mut unchecked_syms: HashSet = syms.iter().map(Sym::addr).collect(); for k in &fixed { + charge_lookup(self, k)?; if !take(&mut unchecked, &mut unchecked_syms, k) { let name = self.pk_name(k)?; return Err(self.invariant("ownKeys", &format!("left out the non-configurable property '{name}' of its target"))); @@ -542,6 +549,7 @@ impl Interp { return Ok(()); } for k in &configurable { + charge_lookup(self, k)?; if !take(&mut unchecked, &mut unchecked_syms, k) { let name = self.pk_name(k)?; return Err(self.invariant("ownKeys", &format!("left out the property '{name}' of its non-extensible target"))); @@ -768,6 +776,14 @@ fn pk_root(k: &PropKey) -> Value { } } +/// Takes the fuel for hashing the name `k` to look it up; a Symbol is looked up by address. +fn charge_lookup(interp: &mut Interp, k: &PropKey) -> JsResult<()> { + match k { + PropKey::Str(name) => crate::string_builtins::charge_units(interp, name.len()), + PropKey::Sym(_) => Ok(()), + } +} + /// Removes `k` from the keys a trap gave that are not yet matched: whether it was there. fn take(names: &mut HashSet<&[u16]>, syms: &mut HashSet, k: &PropKey) -> bool { match k { diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 55887b2c67..dec2f794d0 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -1743,11 +1743,11 @@ fn binary_constructors_validate_arguments_before_reading_new_target_prototype() return false; }); var buffer = new ArrayBuffer(4); - ok = ok && [function () { Reflect.construct(DataView, [{}], nt); }, - function () { Reflect.construct(DataView, [buffer, -1], nt); }, - function () { Reflect.construct(DataView, [buffer, 5], nt); }, - function () { Reflect.construct(DataView, [buffer, 0, 5], nt); }].every(function (f) { - try { f(); } catch (e) { return (e instanceof RangeError || e instanceof TypeError) && reads === 0; } + ok = ok && [[TypeError, function () { Reflect.construct(DataView, [{}], nt); }], + [RangeError, function () { Reflect.construct(DataView, [buffer, -1], nt); }], + [RangeError, function () { Reflect.construct(DataView, [buffer, 5], nt); }], + [RangeError, function () { Reflect.construct(DataView, [buffer, 0, 5], nt); }]].every(function (c) { + try { c[1](); } catch (e) { return e instanceof c[0] && reads === 0; } return false; }); var a = Reflect.construct(ArrayBuffer, [2], nt), u = Reflect.construct(Uint8Array, ['2'], nt); @@ -1766,6 +1766,67 @@ fn binary_constructors_validate_arguments_before_reading_new_target_prototype() ); } +#[test] +fn a_new_target_revoked_while_its_prototype_is_read_is_a_type_error() { + type_errors(&[ + "var r = Proxy.revocable(function () {}, { get: function () { r.revoke(); return 1; } }); + var ran = false; + Reflect.construct(function () { ran = true; }, [], r.proxy);", + "var r = Proxy.revocable(function () {}, { get: function () { r.revoke(); return 1; } }); + Reflect.construct(Array, [], r.proxy);", + ]); + truth( + "var proto = {}; + var r = Proxy.revocable(function () {}, { get: function () { r.revoke(); return proto; } }); + Object.getPrototypeOf(Reflect.construct(function () {}, [], r.proxy)) === proto", + ); +} + +#[test] +fn long_names_from_an_own_keys_trap_take_fuel_by_length() { + let src = "var k = 'x'; while (k.length < 262144) k += k; + var p = new Proxy({}, { ownKeys: function () { return [k]; } }); + for (var i = 0; i < 20; i++) Reflect.ownKeys(p);"; + assert_eq!(limit(src, Limits { fuel: 200_000, ..Limits::default() }), LimitKind::Fuel); +} + +#[test] +fn for_in_over_a_proxy_visits_an_inherited_name_the_proxy_did_not_list() { + truth( + "var proto = { x: 1 }; + var p = new Proxy(Object.create(proto), { + ownKeys: function () { return []; }, + getOwnPropertyDescriptor: function () { return { value: 0, enumerable: false, configurable: true }; }, + getPrototypeOf: function () { return proto; } + }); + var seen = []; + for (var name in p) seen.push(name); + seen.join() === 'x'", + ); + truth( + "var b = new Proxy({ x: 1 }, {}); + var a = new Proxy(Object.create(b), { + ownKeys: function () { return ['x']; }, + getOwnPropertyDescriptor: function () { return undefined; }, + getPrototypeOf: function () { return b; } + }); + var seen = []; + for (var name in a) seen.push(name); + seen.join() === 'x'", + ); +} + +#[test] +fn a_subclassable_built_in_does_not_unwrap_a_revoked_new_target() { + truth( + "class C extends Number { constructor(v) { r.revoke(); super(v); } } + var r = Proxy.revocable(C, {}); + var thrown = {}, caught; + try { Reflect.construct(C, [{ valueOf: function () { throw thrown; } }], r.proxy); } catch (e) { caught = e; } + caught === thrown", + ); +} + #[test] fn proxy_invariants_preserve_namespace_initialization_errors() { let mut realm = es(); diff --git a/docs/mcp.md b/docs/mcp.md index 9beb97cdee..53a267c341 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2862,7 +2862,8 @@ and a run with `module: true` also have the globals `Proxy`, with `Proxy.revocable`, and `Reflect` (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string and Symbol property keys. A trap is a script call: it takes fuel and counts against the limit on nested calls. The copy of the property name it is given, key lists retained by enumeration callers, and the names retained during -a `for-in` prototype walk count against the heap limit. A trap result that breaks one of the proxy invariants, +a `for-in` prototype walk count against the heap limit. Each name an `ownKeys` trap returns takes fuel for its +UTF-16 code units, as does each name the proxy invariants check. A trap result that breaks one of the proxy invariants, or any operation on a revoked proxy, throws a `TypeError`. A proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets `Proxy` and `Reflect` at its first ECMAScript 2015 run and keeps them for later `.jsx` runs. From f01f2ce6c0ee1a8223e37bf8c95e3d6ab93d0574 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:26:04 -0800 Subject: [PATCH 34/50] Fix #10463: $.evalFile reads File URI paths File.parent gives a folder in URI notation (/c/Users/..., with %20 for a space). $.evalFile joined that text to the script's folder as written, so on Windows $.evalFile(File($.fileName).parent + '/more.jsx') looked under C:\c\Users\... and reported "include file not found". When an absolute path starting with one / names no file the script may read, $.evalFile now also tries it with its escapes decoded and, on Windows, with /c/... as the drive C:. The path as written is still tried first, and the scope check, the .. refusal and the file limits apply to every form. Share and device paths are not converted, and #include lines are read as before. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/files.rs | 2 +- crates/engine/src/script/include.rs | 49 ++++++++++++++++++++++++--- crates/engine/src/tests/script_run.rs | 34 +++++++++++++++++++ docs/mcp.md | 4 ++- docs/target-app-parity.md | 2 +- 6 files changed, 85 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 6ad6c51d8f..37a661dfcb 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 1cded460ab..85c01d6a74 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1352,7 +1352,7 @@ fn encode(s: &str) -> String { } /// `s` with its `%xx` escapes read as UTF-8 bytes; `s` as it is when they do not make UTF-8. -fn decode(s: &str) -> String { +pub(crate) fn decode(s: &str) -> String { let b = s.as_bytes(); let mut out = Vec::with_capacity(b.len()); let mut i = 0; diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index acaee51910..058d37f35b 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -359,6 +359,32 @@ fn has_parent(p: &str) -> bool { p.split(['/', '\\']).any(|name| name == "..") } +/// The paths `value` can name in a `File`'s URI notation, as `File.parent` and `File.fullName` give +/// them, other than `value` as written: on a platform that reads drive letters (`windows`), `/c/…` +/// is the drive path `C:/…`, and on every platform `%20` and the other escapes are decoded. Only a +/// path that starts with one `/` has them; `$.evalFile` tries them after `value` as written +/// misses. A `//host/share` path, and a form with a `..` name, is left out. +pub fn uri_forms(value: &str, windows: bool) -> Vec { + if !value.starts_with('/') || value.starts_with("//") { + return Vec::new(); + } + let drive = value.strip_prefix('/').filter(|_| windows && !value.starts_with("//")).and_then(|rest| { + let (first, after) = rest.split_once('/').unwrap_or((rest, "")); + let letter = first.as_bytes(); + (letter.len() == 1 && letter[0].is_ascii_alphabetic()).then(|| format!("{}:/{after}", letter[0].to_ascii_uppercase() as char)) + }); + let mut forms = Vec::new(); + for form in drive.iter().map(String::as_str).chain(drive.is_none().then_some(value)) { + let decoded = crate::script::files::decode(form); + for f in [decoded.as_str(), form] { + if f != value && !has_parent(f) && !(windows && f.replace('\\', "/").starts_with("//")) && !forms.iter().any(|g| g == f) { + forms.push(f.to_string()); + } + } + } + forms +} + /// A real path as people read it. fn display(path: &Path) -> Arc { Arc::from(crate::cmd::findfiles::plain(path.to_path_buf()).to_string_lossy().as_ref()) @@ -575,13 +601,18 @@ impl Files { let refused = || (FailKind::Error, format!("script file read refused: {value}")); // A script given as text has no folder, and so no file it may read. let Some(dir) = dir.filter(|_| !has_parent(value)) else { return Err(refused()) }; - // Each candidate, and whether the scope's refusal passes it over. - let mut candidates: Vec<(Option, bool)> = vec![(Some(dir.join(path)), false)]; + // Each candidate, and whether the scope's refusal passes it over. The path as written comes + // first; for `$.evalFile` only, when it misses, fails or is refused, the forms of a path in + // URI notation are tried, and when none of them is read either, the error of the path as written stands. + let forms = if search { Vec::new() } else { uri_forms(value, cfg!(windows)) }; + let mut literal_error = None; + let mut candidates: Vec<(Option, bool)> = vec![(Some(dir.join(path)), !forms.is_empty())]; + candidates.extend(forms.into_iter().map(|f| (Some(dir.join(f)), true))); if search && !path.is_absolute() { candidates.extend(self.include_path.iter().map(|p| ((!has_parent(p)).then(|| dir.join(p).join(path)), false))); candidates.extend(self.jsinclude.iter().filter(|p| p.is_absolute()).map(|p| (Some(p.join(path)), true))); } - for (candidate, passed_over_when_refused) in candidates { + for (i, (candidate, passed_over_when_refused)) in candidates.into_iter().enumerate() { let Some(candidate) = candidate else { return Err(refused()) }; self.probes += 1; if self.probes > MAX_PROBES { @@ -590,12 +621,22 @@ impl Files { match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) { Ok(found) => return Ok(found), Err(ScriptRead::Missing) => {} - Err(ScriptRead::Refused) if passed_over_when_refused => {} + Err(ScriptRead::Refused) if passed_over_when_refused => { + if i == 0 { + literal_error = Some(refused()); + } + } Err(ScriptRead::Refused) => return Err(refused()), Err(ScriptRead::TooLarge) => return Err((FailKind::Limit, format!("script file is too large: {value}"))), + Err(ScriptRead::Failed(e)) if i == 0 && passed_over_when_refused => { + literal_error = Some((FailKind::Error, format!("cannot read script file {value}: {e}"))); + } Err(ScriptRead::Failed(e)) => return Err((FailKind::Error, format!("cannot read script file {value}: {e}"))), } } + if let Some(error) = literal_error { + return Err(error); + } Err((FailKind::Error, format!("include file not found: {value}"))) } diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index fe56754ca3..7e81dbc730 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -301,6 +301,40 @@ fn files_are_checked_before_they_are_read() { assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err()); } +/// `$.evalFile` also tries a path in a `File`'s URI notation, as `File.parent` gives +/// it: on Windows `/c/…` as the drive path `C:/…`, and on every platform with its escapes decoded, +/// after the path as written misses. Relative, share, device and `..` forms are not tried. +#[test] +fn include_paths_in_uri_notation_name_a_windows_drive() { + use crate::script::include::uri_forms; + assert_eq!(uri_forms("/c/Users/Test/more.jsx", true), ["C:/Users/Test/more.jsx"]); + assert_eq!(uri_forms("/d", true), ["D:/"]); + assert_eq!(uri_forms("/c/My%20Scripts/more.jsx", true), ["C:/My Scripts/more.jsx", "C:/My%20Scripts/more.jsx"]); + assert_eq!(uri_forms("/home/My%20Scripts/more.jsx", false), ["/home/My Scripts/more.jsx"]); + assert!(uri_forms("/c/Users/Test/more.jsx", false).is_empty()); + for kept in + ["//host/share/more.jsx", "//?/c/more.jsx", "/c/x/../more.jsx", "/Users/more.jsx", "more.jsx", "my%20file.jsx", "C:/more.jsx", "/1/more.jsx"] + { + assert!(uri_forms(kept, true).is_empty(), "{kept}: {:?}", uri_forms(kept, true)); + } + assert_eq!(uri_forms("/c/%2E%2E/more.jsx", true), ["C:/%2E%2E/more.jsx"], "an escaped `..` is not decoded into a parent name"); + // From a folder whose name has a space, `File.parent` gives `%20`, and the sibling is read. + let dir = fresh_folder("uri forms"); + std::fs::write(dir.join("more.jsx"), "'more';").unwrap(); + let main = dir.join("main.jsx"); + std::fs::write(&main, "vc.log(File($.fileName).parent + '');\nvc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n").unwrap(); + let r = two_docs().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert!(r["log"][0].as_str().is_some_and(|p| p.contains("uri%20forms")), "{r}"); + assert_eq!(r["log"][1], "more", "{r}"); + // A file whose name holds `%20` as written is read before the decoded name. + std::fs::write(dir.join("part%20one.jsx"), "'literal';").unwrap(); + std::fs::write(dir.join("part one.jsx"), "'decoded';").unwrap(); + let literal = dir.join("part%20one.jsx").to_string_lossy().replace('\\', "/"); + std::fs::write(&main, format!("vc.log($.evalFile({literal:?}));\n")).unwrap(); + let r = two_docs().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["literal"]), "{r}"); +} + #[test] fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { let dir = fresh_folder("es2015"); diff --git a/docs/mcp.md b/docs/mcp.md index 5a32fe1e32..a8c23770b5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3480,7 +3480,9 @@ through `$`: `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global environment, so its functions and variables stay defined, and returns its last value (`undefined` for an empty - file). Its preprocessor lines are read as the script's are. `timeout` is a number of milliseconds from 0; the file + file). Its preprocessor lines are read as the script's are. An absolute path in a `File`'s URI notation, as + `File.parent` gives it, is read too: when the path as written names no file it may read, `%20` and the other + escapes are decoded, and on Windows `/c/…` names the drive `C:`. `timeout` is a number of milliseconds from 0; the file is read at once and `timeout` is not waited on. The run's fuel and limits apply to the file. An empty path, a missing file and a refused path throw errors the script can catch. - `$.fileName` is the file of the code that reads it: the script, a file it included with `#include`, or a file diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1cda4bba80..3b9c712257 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1138,7 +1138,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. - Scripts: an uncaught error that one or more `finally` blocks pass on unchanged, in the script or in a function it called, is reported at the line and column where it was thrown, in `script.run`'s report and the Script Console. An error a `finally` block throws is reported at that throw, and one its `return`, `break` or `continue` discards is not reported. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. - Scripts: an error a `finally` block passes on is still reported where it was thrown when the block's allocations collect garbage under a small heap limit, and a `finally` block that `return`, `break` or `continue` leaves drops the saved location of its error as it leaves, so a collection no longer counts that code as live. VectorCraft's own rule. `crates/js/src/host_tests.rs`. - - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, `$.fileName` gives the file of the code that reads it (the file being run for code that `eval` or `Function` compiled), and `$.includePath` the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). + - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, `$.fileName` gives the file of the code that reads it (the file being run for code that `eval` or `Function` compiled), and `$.includePath` the include folders. `$.evalFile` also reads absolute paths in a `File`'s URI notation, with escapes decoded and `/c/...` naming drive C: on Windows. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). - Scripts: `#targetengine name` (and `//@targetengine name`) runs the script in a named engine that lasts for the session, and a later script that names it sees the globals and functions earlier ones left ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/)); `$.engineName` gives the name ([the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: a script without the line and `#targetengine main` get a new engine each run, the line comes once in the script itself before its code, a session keeps 8 named engines with 64 MiB of heap each, an error or a stop keeps the globals the run set while the documents go back, kept host functions act for the run that calls them, `script.engines` lists the engines and `script.engine.drop` drops one, and the web build has none. `crates/engine/src/tests/script_engines.rs`. - Scripts: `$.fileName` is a read-only name of the script file in use ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: it names the file of the code that reads it, so a function a file included with `#include` or run with `$.evalFile` defined, or one an earlier run of a named engine kept, gives its own file and not the calling file; code from a script given as `source`, and kept code whose place the engine dropped, gives an empty name, and code that `eval` or `Function` compiled gives the file being run. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`. - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. From 6a13fa05ac88f17dc7d83ac081eb0450e77b8bc4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:39:44 -0800 Subject: [PATCH 35/50] Import PDF: a PDF with editing data opens on its trim boxes unless a box is picked Opening a PDF with editing data without naming a box gives its trim boxes, but the Import PDF dialog always sent cropTo, so OK with Crop To left as it started opened the crop boxes instead. Opening such a file, Crop To now starts on Trim Box, also once a password unlocks it, and OK names the box only when one was picked. Picking Crop Box still opens the crop boxes, and a place still starts on Crop Box. --- crates/ui-egui/src/dialogs/import_pdf.rs | 36 +++++++++++++++--- .../ui-egui/src/dialogs/tests_import_pdf.rs | 37 +++++++++++++++++++ 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 8bf7e37874..fd141eb74b 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -9,7 +9,9 @@ //! without a password; `null` until it is checked or cleared, when it follows the pages picked: on //! for All, off for a range; picking the other of All and Range sets it back to `null`; `linksOn` //! is the effective flag, `__linkable` is false for a file `linkPages` does not take, such as one -//! over its size limit), `cropTo`, `textAs` (`text` | `outlines`; it starts from the `pdfTextAs` +//! over its size limit), `cropTo` (when opening, it starts on `trim` for a file with editing data, +//! else `crop`; OK names the box only when it was picked, so a file with the starting box opens +//! as it does without the dialog), `textAs` (`text` | `outlines`; it starts from the `pdfTextAs` //! preference for a PDF (`__pdf`; Editable for a `.ai` or `.ait` file), or from the `textAs` a place //! gives (`__textAsGiven`), and OK keeps a PDF's choice there; a linked place shows the file's own //! text, so placing linked leaves it as it is, and Outlines clears Import PDF Pages as Links) and @@ -146,6 +148,9 @@ struct State { pages: Vec, link_pages: Option, crop: CropTo, + /// Whether Crop To was picked. Opening, a box left as it starts ([`opening_crop`]) is not + /// named, so a file with editing data opens on its trim boxes, as it opens without the dialog. + crop_chosen: bool, text_as: TextAs, pdf: bool, password: String, @@ -212,10 +217,13 @@ impl State { /// Reads the file with the typed password. `Ok(true)` when the file has pages to pick; `Ok(false)` when OK /// goes straight on to open or place it. fn unlock(&mut self) -> Result { - let info = vectorcraft_pdf::info(&self.file.bytes, self.password().as_deref()).map_err(|e| e.to_string())?; + let opened = vectorcraft_pdf::open_pdf(&self.file.bytes, self.password().as_deref()).map_err(|e| e.to_string())?; self.locked = false; - self.page_count = info.pages.len(); - Ok(info.pages.len() > 1 && !self.password_only) + self.page_count = opened.page_count(); + if !self.crop_chosen && self.place.is_none() { + self.crop = opening_crop(Some(&opened)); + } + Ok(self.page_count > 1 && !self.password_only) } /// The Text choice the preview renders with (a linked place: as editable text). @@ -270,6 +278,7 @@ impl State { let text = text()?; let i = CropTo::IDS.iter().position(|id| *id == text).ok_or("cropTo is not a crop box")?; self.crop = CropTo::ALL.get(i).copied().unwrap_or_default(); + self.crop_chosen = true; } "textAs" => { let id = text()?; @@ -459,7 +468,9 @@ fn pages_body(ui: &mut egui::Ui, s: &mut State, preview: Option<&(Revision, Arc< }); Stack::new().show(ui, |ui, _| { let crops: Vec> = CropTo::ALL.iter().zip(CropTo::LABELS).map(|(crop, label)| Entry::new(*crop, *label)).collect(); + let before = s.crop; Field::new(tl!("Crop To")).show(ui, |ui, _| Select::new(tl!("Crop To"), Bind::bound(&mut s.crop), &crops).show(ui)); + s.crop_chosen |= s.crop != before; let linked = s.places_linked(); let texts = [Entry::new(TextAs::Text, tl!("Editable")), Entry::new(TextAs::Outlines, tl!("Outlines"))]; Field::new(tl!("Text")).show(ui, |ui, _| Select::new(tl!("Text"), Bind::bound(&mut s.text_as), &texts).enabled(!linked).show(ui)); @@ -506,6 +517,12 @@ fn pick_pages(ui: &mut egui::Ui, s: &mut State, count: usize, current: usize) { } } +/// The box Crop To starts on when opening the file `opened`: Trim Box for a file with editing +/// data, which opens on its trim boxes when no box is named, else Crop Box. +fn opening_crop(opened: Option<&vectorcraft_pdf::Opened>) -> CropTo { + if opened.is_some_and(vectorcraft_pdf::Opened::has_illustrator_data) { CropTo::Trim } else { CropTo::default() } +} + /// Open `bytes` (or place them with the `file.place` params `place`) through the dialog when the /// file is a PDF (or `.ai`/`.ait`) with several pages or a password; false when there's nothing to /// ask (the caller goes on), including, when opening, a file that carries its VectorCraft document @@ -528,6 +545,7 @@ fn offer_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option 1 => (count, false), Err(PdfError::NeedsPassword) => (0, true), @@ -544,7 +562,8 @@ fn offer_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option Result<(), String> { } crate::place::run_for_user(app, &p).map(|_| ()) } else { - let mut p = json!({"cropTo": s.crop.id(), "password": s.password(), "textAs": s.text_as.id()}); + let mut p = json!({"password": s.password(), "textAs": s.text_as.id()}); + // A box left as it starts ([`opening_crop`]) is not named: a file with editing data then + // opens on its trim boxes, from its editing layers where it can, as without the dialog. + if s.crop_chosen { + p["cropTo"] = json!(s.crop.id()); + } // An empty range under Range opens every page. if !s.all_pages && !s.pages.is_empty() { p["pages"] = json!(format_pages(&s.pages)); diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index c9383d0f44..8b0bedd950 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -409,6 +409,43 @@ fn opening_an_ai_with_editing_data_reads_it_without_asking() { assert!(!is_open(&app)); } +/// A PDF with editing data opens on its trim boxes when no box is named. Opening one, Crop To starts +/// on Trim Box, also once a password unlocks it, and OK with it left so names no box: the pages open +/// on their trim boxes, as without the dialog. Picking Crop Box opens the crop boxes, and a place +/// starts on Crop Box. +#[test] +fn opening_a_pdf_with_editing_data_keeps_its_trim_boxes_unless_a_box_is_picked() { + let trimmed = |password: Option<&str>| { + let mut first = PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f"); + first.entries = "/PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>".into(); + first.trim = Some([10.0, 10.0, 90.0, 90.0]); + let mut second = PdfPage::new(200.0, 100.0, "1 0 0 rg 0 0 30 30 re f"); + second.trim = Some([10.0, 10.0, 190.0, 90.0]); + pdf(&[first, second], password) + }; + let mut app = app(); + assert!(import_pdf::offer(&mut app, "two.pdf", &trimmed(None), None, None)); + assert_eq!(field(&app, "cropTo"), "trim"); + confirm(&mut app).unwrap(); + assert_eq!(artboard_widths(&app), [80.0, 180.0], "the trim boxes"); + + let mut app = self::app(); + assert!(import_pdf::offer(&mut app, "two.pdf", &trimmed(None), None, None)); + set(&mut app, "cropTo", json!("crop")); + confirm(&mut app).unwrap(); + assert_eq!(artboard_widths(&app), [100.0, 200.0], "an explicit crop box"); + + let mut app = self::app(); + assert!(import_pdf::offer(&mut app, "locked.pdf", &trimmed(Some("pw")), None, None)); + set(&mut app, "password", json!("pw")); + confirm(&mut app).unwrap(); + assert_eq!((field(&app, "__locked"), field(&app, "cropTo")), (json!(false), json!("trim")), "unlocked"); + + let mut app = self::app(); + assert!(import_pdf::offer(&mut app, "two.pdf", &trimmed(None), None, Some(&json!({})))); + assert_eq!(field(&app, "cropTo"), "crop", "a place"); +} + /// A `.ai` whose editing data can't be read asks nothing either, and every page opens from the PDF /// part. Asking at that point is #6134. #[test] From ce596d4f579d048c183db7bf711dc88a56104c88 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:47:43 -0800 Subject: [PATCH 36/50] Arrange Tools: Mark Bounds of Each draws no empty group for an object too small for corner legs Each corner leg is at most half the side it runs along. An object wider or taller than the flat limit but with both half-sides under it got a Corner Marks group with no paths in it. Such an object now gets no corner marks, and a selection of only such objects is refused with "nothing to mark: the selection is too small for corner marks" and no undo step. The Rectangle style still marks it. Follows up #10148. --- crates/engine/src/cmd/addons/arrange/marks.rs | 21 +++++++++++++++--- .../src/cmd/addons/arrange/marks/tests.rs | 22 +++++++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 42 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange/marks.rs b/crates/engine/src/cmd/addons/arrange/marks.rs index fc01a8730d..f9bfa01329 100644 --- a/crates/engine/src/cmd/addons/arrange/marks.rs +++ b/crates/engine/src/cmd/addons/arrange/marks.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Mark Bounds of Each", ["Object", "Plug-ins", "Arrange Tools"], None, - "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", + "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", has_selection, mark_bounds )] @@ -55,10 +55,16 @@ fn corners(r: Rect) -> Vec<(Point, f64, f64)> { out } +/// The lengths of the across and down legs of the corner marks of `r`: `length`, at most half the +/// side each runs along. +fn legs(r: Rect, length: f64) -> (f64, f64) { + (length.min(r.width() / 2.0), length.min(r.height() / 2.0)) +} + /// The corner marks of `r` with legs `length` long, each at most half its side: one open path per /// corner, a line where `r` has no width or no height. fn corner_paths(r: Rect, length: f64) -> Vec { - let (lx, ly) = (length.min(r.width() / 2.0), length.min(r.height() / 2.0)); + let (lx, ly) = legs(r, length); corners(r) .into_iter() .filter_map(|(p, sx, sy)| { @@ -103,14 +109,23 @@ fn mark_bounds(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let symbols = d.symbol_boxes(); let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len()); + let mut too_small = false; for id in roots { let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue }; let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) }; - if let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) { + let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) else { continue }; + // Corner legs are at most half a side, so an object too small for any leg gets no marks. + let (lx, ly) = legs(r, length); + if rectangle || lx > FLAT || ly > FLAT { marked.push((anchor(d, id), r)); + } else { + too_small = true; } } if marked.is_empty() { + if too_small { + return Err(bad(C, "nothing to mark: the selection is too small for corner marks")); + } return Err(bad(C, "nothing to mark: the selection has no bounds")); } let ap = Appearance::basic(Paint::None, Paint::solid(color), weight); diff --git a/crates/engine/src/cmd/addons/arrange/marks/tests.rs b/crates/engine/src/cmd/addons/arrange/marks/tests.rs index dc44f47d5b..13c9401464 100644 --- a/crates/engine/src/cmd/addons/arrange/marks/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/marks/tests.rs @@ -325,6 +325,28 @@ fn flat_objects_get_lines_and_guides_and_empty_groups_none() { assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0))); } +#[test] +fn an_object_too_small_for_corner_legs_gets_no_empty_group() { + let mut s = session(); + // Wider than the flat limit, but each leg (half the side at most) is shorter than it. + let tiny = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 1.5e-9, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[tiny]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string(); + assert!(refused.contains("nothing to mark") && refused.contains("too small for corner marks"), "{refused}"); + assert_eq!(steps(&s), n, "no undo step"); + assert!(*s.doc().unwrap().doc == *before); + // The rectangle style still marks it, and a real object beside it gets its corner marks alone. + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + assert_eq!(r["count"], 1); + s.execute("edit.undo", &json!({})).unwrap(); + let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0); + select(&mut s, &[tiny, a]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(r["count"], 1); + assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0))); +} + #[test] fn bad_params_are_refused_and_it_is_off_without_a_selection() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 5a32fe1e32..021109ca94 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17787,7 +17787,7 @@ with strokes and vector effects included and raster effects left out (see its ro | `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | -| `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group or clipping sublayer that holds it. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | +| `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group or clipping sublayer that holds it. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and with `corners` neither does an object whose sides are too short for any leg; a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1cda4bba80..b006d3d335 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3170,7 +3170,7 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange ## Arrange Tools add-on: Mark Bounds of Each (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws marks on each top-level selected object's bounds (at most 20000 objects), rather than around the whole selection. Draw is Corner Marks by default (four inward L-shaped marks in a group named Corner Marks), or Rectangle (one closed path named Bounds). Bounds is Geometric Bounds by default (strokes not counted), or Visual Bounds (strokes, brush art and effects as drawn). Length is 0.001 to 1000000 pt (10 by default), with each corner leg capped at half the side it runs along; Length is off in the dialog for Rectangle. Weight is 0.01 to 1000 pt (1 by default), and Color defaults to red (`#ff0000`); an RGB color takes the document's color mode. The marks have no fill and the stroke given. Each goes directly above its object, or above the outermost clip group or clipping sublayer that holds it; a clipping top-level layer keeps the marks inside it. Clip groups are measured by their clipping path, other groups by their members together. For flat objects, corner marks become lines along their nonzero side. Guides and objects without bounds, such as empty groups, are skipped; nothing to mark is an error with no undo step. The new marks become selected, in one undo step. The dialog has Preview; OK keeps the marks and Cancel removes the preview. Tests: `each_object_gets_inward_corner_marks_above_it_in_one_step`, `length_weight_color_and_the_rectangle_style`, `a_leg_is_at_most_half_the_side_it_runs_along_vertically`, `geometric_bounds_leave_strokes_out_and_visual_bounds_count_them`, `visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out`, `visual_bounds_enclose_brush_art_on_paths_and_in_groups`, `groups_by_their_members_and_clip_groups_by_the_clipping_path`, `marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer`, `flat_objects_get_lines_and_guides_and_empty_groups_none` and `bad_params_are_refused_and_it_is_off_without_a_selection` in `cmd::addons::arrange::marks::tests` in `vectorcraft-engine`; `real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them` and `mark_bounds_sends_the_dialog_values_to_its_command` in `crates/ui-egui/src/addons/arrange/tests.rs` in `vectorcraft-ui-egui`; and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws marks on each top-level selected object's bounds (at most 20000 objects), rather than around the whole selection. Draw is Corner Marks by default (four inward L-shaped marks in a group named Corner Marks), or Rectangle (one closed path named Bounds). Bounds is Geometric Bounds by default (strokes not counted), or Visual Bounds (strokes, brush art and effects as drawn). Length is 0.001 to 1000000 pt (10 by default), with each corner leg capped at half the side it runs along; Length is off in the dialog for Rectangle. Weight is 0.01 to 1000 pt (1 by default), and Color defaults to red (`#ff0000`); an RGB color takes the document's color mode. The marks have no fill and the stroke given. Each goes directly above its object, or above the outermost clip group or clipping sublayer that holds it; a clipping top-level layer keeps the marks inside it. Clip groups are measured by their clipping path, other groups by their members together. For flat objects, corner marks become lines along their nonzero side; an object whose sides are too short for any leg gets no corner marks. Guides and objects without bounds, such as empty groups, are skipped; nothing to mark is an error with no undo step. The new marks become selected, in one undo step. The dialog has Preview; OK keeps the marks and Cancel removes the preview. Tests: `each_object_gets_inward_corner_marks_above_it_in_one_step`, `length_weight_color_and_the_rectangle_style`, `a_leg_is_at_most_half_the_side_it_runs_along_vertically`, `geometric_bounds_leave_strokes_out_and_visual_bounds_count_them`, `visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out`, `visual_bounds_enclose_brush_art_on_paths_and_in_groups`, `groups_by_their_members_and_clip_groups_by_the_clipping_path`, `marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer`, `flat_objects_get_lines_and_guides_and_empty_groups_none`, `an_object_too_small_for_corner_legs_gets_no_empty_group` and `bad_params_are_refused_and_it_is_off_without_a_selection` in `cmd::addons::arrange::marks::tests` in `vectorcraft-engine`; `real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them` and `mark_bounds_sends_the_dialog_values_to_its_command` in `crates/ui-egui/src/addons/arrange/tests.rs` in `vectorcraft-ui-egui`; and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. ## Arrange Tools add-on: Group by Row (2026-11-29) From 8f76825e7a47f6be9a1fde84530dadc2675e3100 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:50:16 -0800 Subject: [PATCH 37/50] Import PDF: name Crop To only when it differs from the box it started on A keyboard preview canceled with Escape restores the starting box, so it no longer counts as a pick. --- crates/ui-egui/src/dialogs/import_pdf.rs | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index fd141eb74b..5121f37c16 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -10,9 +10,9 @@ //! for All, off for a range; picking the other of All and Range sets it back to `null`; `linksOn` //! is the effective flag, `__linkable` is false for a file `linkPages` does not take, such as one //! over its size limit), `cropTo` (when opening, it starts on `trim` for a file with editing data, -//! else `crop`; OK names the box only when it was picked, so a file with the starting box opens -//! as it does without the dialog), `textAs` (`text` | `outlines`; it starts from the `pdfTextAs` -//! preference for a PDF (`__pdf`; Editable for a `.ai` or `.ait` file), or from the `textAs` a place +//! else `crop`; OK names the box only when it differs from the box it started on, so a file with +//! the starting box opens as it does without the dialog), `textAs` (`text` | `outlines`; it starts +//! from the `pdfTextAs` preference for a PDF (`__pdf`; Editable for a `.ai` or `.ait` file), or from the `textAs` a place //! gives (`__textAsGiven`), and OK keeps a PDF's choice there; a linked place shows the file's own //! text, so placing linked leaves it as it is, and Outlines clears Import PDF Pages as Links) and //! `password`. `__locked` is set until the password is accepted: OK then unlocks the file, and with @@ -148,9 +148,9 @@ struct State { pages: Vec, link_pages: Option, crop: CropTo, - /// Whether Crop To was picked. Opening, a box left as it starts ([`opening_crop`]) is not - /// named, so a file with editing data opens on its trim boxes, as it opens without the dialog. - crop_chosen: bool, + /// The box Crop To started on ([`opening_crop`] when opening). OK names the box only when + /// it differs from this box. + start_crop: CropTo, text_as: TextAs, pdf: bool, password: String, @@ -220,8 +220,9 @@ impl State { let opened = vectorcraft_pdf::open_pdf(&self.file.bytes, self.password().as_deref()).map_err(|e| e.to_string())?; self.locked = false; self.page_count = opened.page_count(); - if !self.crop_chosen && self.place.is_none() { + if self.crop == self.start_crop && self.place.is_none() { self.crop = opening_crop(Some(&opened)); + self.start_crop = self.crop; } Ok(self.page_count > 1 && !self.password_only) } @@ -278,7 +279,6 @@ impl State { let text = text()?; let i = CropTo::IDS.iter().position(|id| *id == text).ok_or("cropTo is not a crop box")?; self.crop = CropTo::ALL.get(i).copied().unwrap_or_default(); - self.crop_chosen = true; } "textAs" => { let id = text()?; @@ -468,9 +468,7 @@ fn pages_body(ui: &mut egui::Ui, s: &mut State, preview: Option<&(Revision, Arc< }); Stack::new().show(ui, |ui, _| { let crops: Vec> = CropTo::ALL.iter().zip(CropTo::LABELS).map(|(crop, label)| Entry::new(*crop, *label)).collect(); - let before = s.crop; Field::new(tl!("Crop To")).show(ui, |ui, _| Select::new(tl!("Crop To"), Bind::bound(&mut s.crop), &crops).show(ui)); - s.crop_chosen |= s.crop != before; let linked = s.places_linked(); let texts = [Entry::new(TextAs::Text, tl!("Editable")), Entry::new(TextAs::Outlines, tl!("Outlines"))]; Field::new(tl!("Text")).show(ui, |ui, _| Select::new(tl!("Text"), Bind::bound(&mut s.text_as), &texts).enabled(!linked).show(ui)); @@ -563,7 +561,7 @@ fn offer_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option Result<(), String> { let mut p = json!({"password": s.password(), "textAs": s.text_as.id()}); // A box left as it starts ([`opening_crop`]) is not named: a file with editing data then // opens on its trim boxes, from its editing layers where it can, as without the dialog. - if s.crop_chosen { + if s.crop != s.start_crop { p["cropTo"] = json!(s.crop.id()); } // An empty range under Range opens every page. From 21bca7558070bd25a7a1e840922199ee174fbee7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:50:28 -0800 Subject: [PATCH 38/50] JavaScript: format the for-in visit check as rustfmt does The gate's fmt step failed at b3c1a31: rustfmt with max_width 150 and use_small_heuristics Max puts the e4x if/else in Interp's for-in step on one line, and the previous commit wrapped it over five. --- crates/js/src/interp.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index e40a8919b0..5f0cf5c1a6 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -3442,11 +3442,7 @@ impl Interp { state.pos += 1; let object = state.object; let Some(o) = object else { continue }; - let visit = if self.options.e4x && self.is_xml(&Value::Object(o)) { - self.scope_has(o, &k)? - } else { - self.for_in_still_has(o, &k, skip)? - }; + let visit = if self.options.e4x && self.is_xml(&Value::Object(o)) { self.scope_has(o, &k)? } else { self.for_in_still_has(o, &k, skip)? }; if visit { return self.push(Value::String(Str::from_rc(k))); } From 709791372438c59f24f7619ee8b1587a080d2eaf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:58:35 -0800 Subject: [PATCH 39/50] Docs: $.evalFile tries the path as written before its URI forms The parity entry now says the path as written is read first, and the decoded URI forms are tried only when it is missing, fails to read or is refused. A file over the size limit stops the lookup. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b9c712257..ff3ac14a89 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1138,7 +1138,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. - Scripts: an uncaught error that one or more `finally` blocks pass on unchanged, in the script or in a function it called, is reported at the line and column where it was thrown, in `script.run`'s report and the Script Console. An error a `finally` block throws is reported at that throw, and one its `return`, `break` or `continue` discards is not reported. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. - Scripts: an error a `finally` block passes on is still reported where it was thrown when the block's allocations collect garbage under a small heap limit, and a `finally` block that `return`, `break` or `continue` leaves drops the saved location of its error as it leaves, so a collection no longer counts that code as live. VectorCraft's own rule. `crates/js/src/host_tests.rs`. - - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, `$.fileName` gives the file of the code that reads it (the file being run for code that `eval` or `Function` compiled), and `$.includePath` the include folders. `$.evalFile` also reads absolute paths in a `File`'s URI notation, with escapes decoded and `/c/...` naming drive C: on Windows. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). + - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, `$.fileName` gives the file of the code that reads it (the file being run for code that `eval` or `Function` compiled), and `$.includePath` the include folders. `$.evalFile` tries the path as written first; only when that file is missing, fails to read (a file over the size limit stops the lookup) or is refused does it read an absolute path in a `File`'s URI notation, with escapes decoded and `/c/...` naming drive C: on Windows. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). - Scripts: `#targetengine name` (and `//@targetengine name`) runs the script in a named engine that lasts for the session, and a later script that names it sees the globals and functions earlier ones left ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/)); `$.engineName` gives the name ([the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: a script without the line and `#targetengine main` get a new engine each run, the line comes once in the script itself before its code, a session keeps 8 named engines with 64 MiB of heap each, an error or a stop keeps the globals the run set while the documents go back, kept host functions act for the run that calls them, `script.engines` lists the engines and `script.engine.drop` drops one, and the web build has none. `crates/engine/src/tests/script_engines.rs`. - Scripts: `$.fileName` is a read-only name of the script file in use ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: it names the file of the code that reads it, so a function a file included with `#include` or run with `$.evalFile` defined, or one an earlier run of a named engine kept, gives its own file and not the calling file; code from a script given as `source`, and kept code whose place the engine dropped, gives an empty name, and code that `eval` or `Function` compiled gives the file being run. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`. - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. From fd6c41368b3f2c8994800d2c0e6b3fb7ae744e5a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:59:07 -0800 Subject: [PATCH 40/50] Import PDF: unlocking a file refreshes the box Crop To started on A box set while the file was locked no longer leaves the old starting box, so a later pick of Crop Box is still named. --- crates/ui-egui/src/dialogs/import_pdf.rs | 9 ++++++--- crates/ui-egui/src/dialogs/tests_import_pdf.rs | 9 +++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 5121f37c16..d128aba2e4 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -220,9 +220,12 @@ impl State { let opened = vectorcraft_pdf::open_pdf(&self.file.bytes, self.password().as_deref()).map_err(|e| e.to_string())?; self.locked = false; self.page_count = opened.page_count(); - if self.crop == self.start_crop && self.place.is_none() { - self.crop = opening_crop(Some(&opened)); - self.start_crop = self.crop; + if self.place.is_none() { + let start_crop = opening_crop(Some(&opened)); + if self.crop == self.start_crop { + self.crop = start_crop; + } + self.start_crop = start_crop; } Ok(self.page_count > 1 && !self.password_only) } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 8b0bedd950..1d1d434f2d 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -441,6 +441,15 @@ fn opening_a_pdf_with_editing_data_keeps_its_trim_boxes_unless_a_box_is_picked() confirm(&mut app).unwrap(); assert_eq!((field(&app, "__locked"), field(&app, "cropTo")), (json!(false), json!("trim")), "unlocked"); + let mut app = self::app(); + assert!(import_pdf::offer(&mut app, "locked.pdf", &trimmed(Some("pw")), None, None)); + set(&mut app, "cropTo", json!("media")); + set(&mut app, "password", json!("pw")); + confirm(&mut app).unwrap(); + set(&mut app, "cropTo", json!("crop")); + confirm(&mut app).unwrap(); + assert_eq!(artboard_widths(&app), [100.0, 200.0]); + let mut app = self::app(); assert!(import_pdf::offer(&mut app, "two.pdf", &trimmed(None), None, Some(&json!({})))); assert_eq!(field(&app, "cropTo"), "crop", "a place"); From 4c883f94ccbba24d177a4cd9e2cd5e6ea82c8dd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 16:28:48 -0800 Subject: [PATCH 41/50] Print: the Size list shows the chosen printer's paper sizes File > Print offered the same built-in sizes for every printer, so a card printer's CR80 size could not be chosen. The Size list now holds the paper sizes the chosen printer's driver lists: the CUPS PPD's PaperDimension entries on macOS and Linux, and the printer's forms on Windows. A size the dialog has itself (Letter, A4) keeps its own id under the driver's name; others print as a custom size of the driver's width and height. Custom is always offered, and a printer whose driver lists nothing keeps the built-in list. The lookup runs on a worker thread and the dialog updates when it answers; the Windows lookup stops after 10 seconds. Each opening of the dialog and each printer change reads the driver again. A paper the new printer does not list becomes a custom size of the same width and height. The preset editor keeps the built-in list. --- apps/vectorcraft/src/host_services.rs | 2 +- apps/vectorcraft/src/printing.rs | 108 +++++++++- crates/ui-egui/src/dialogs/print.rs | 184 ++++++++++++++++- crates/ui-egui/src/dialogs/tests_print.rs | 238 +++++++++++++++++++++- crates/ui-egui/src/print.rs | 89 ++++++++ 5 files changed, 608 insertions(+), 13 deletions(-) diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 47813f192e..9e416d7711 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -188,7 +188,7 @@ pub(crate) fn services(window: Parent) -> Services { check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))), open_in_application: Some(Box::new(open_in_application)), // File → Print: the system's printers and print queue. - print: Some(Box::new(printing::SystemPrint)), + print: Some(Box::new(printing::SystemPrint::default())), // The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens // only while the active tool uses the wheel. #[cfg(all(windows, not(target_vendor = "win7")))] diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index fb28192f05..6725b72884 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -1,11 +1,16 @@ //! Desktop printer transport. VectorCraft composes every page and copy before submission; //! craft-print owns discovery and spooling. use std::process::Command; -use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer}; +use vectorcraft_ui_egui::print::{Paper, Papers, PrintJob, PrintService, Printer}; mod direct_pdf; -pub struct SystemPrint; +#[derive(Default)] +pub struct SystemPrint { + /// Channels for pending paper-size lookups, removed when each worker answers or disconnects. + papers: std::collections::HashMap>>, +} + impl PrintService for SystemPrint { fn printers(&mut self) -> Vec { system::printers() @@ -15,7 +20,7 @@ impl PrintService for SystemPrint { Ok(sent(job.title, job.printer, ¬e)) } fn shared_print(&self) -> Option { - Some(std::sync::Arc::new(|job| SystemPrint.print(job))) + Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e)))) } fn turns_landscape(&self) -> bool { // macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright @@ -28,6 +33,31 @@ impl PrintService for SystemPrint { fn setup(&mut self, printer: Option<&str>) -> Result<(), String> { system::setup(printer) } + fn papers(&mut self, printer: &str) -> Papers { + let receive = self.papers.entry(printer.to_string()).or_insert_with(|| { + let (send, receive) = std::sync::mpsc::channel(); + let printer = printer.to_string(); + let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || { + let _ = send.send(installed_papers(&printer)); + }); + receive + }); + let result = match receive.try_recv() { + Ok(papers) => Papers::Ready(papers), + Err(std::sync::mpsc::TryRecvError::Disconnected) => Papers::Ready(Vec::new()), + Err(std::sync::mpsc::TryRecvError::Empty) => return Papers::Pending, + }; + self.papers.remove(printer); + result + } +} + +/// Look up only an installed printer's own name. +fn installed_papers(printer: &str) -> Vec { + if printer.is_empty() || !system::printers().iter().any(|p| p.name == printer) { + return Vec::new(); + } + system::papers(printer) } /// The status after the job `title` went to `printer` (the default one without a name), with the @@ -40,10 +70,80 @@ fn sent(title: &str, printer: Option<&str>, note: &str) -> String { } mod system { - use super::{Command, PrintJob, Printer}; + use super::{Command, Paper, PrintJob, Printer}; pub fn printers() -> Vec { craft::print::printers().into_iter().map(Printer::from).collect() } + /// The paper sizes of an installed printer's driver: its CUPS PPD, or Windows' printer settings. + pub fn papers(printer: &str) -> Vec { + #[cfg(windows)] + { + // The name goes in as an environment variable, never into the script's text. + const SCRIPT: &str = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Add-Type -AssemblyName System.Drawing; $s = New-Object System.Drawing.Printing.PrinterSettings; \ + $s.PrinterName = $env:VC_PRINTER; foreach ($p in $s.PaperSizes) { \"$($p.RawKind)`t$($p.PaperName)`t$($p.Width)`t$($p.Height)\" }"; + use std::os::windows::process::CommandExt as _; + // CREATE_NO_WINDOW: no console window opens over the app. + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let mut command = Command::new("powershell.exe"); + command.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("VC_PRINTER", printer).creation_flags(CREATE_NO_WINDOW); + paper_output(&mut command).map(|out| vectorcraft_ui_egui::print::windows_papers(&String::from_utf8_lossy(&out))).unwrap_or_default() + } + #[cfg(not(windows))] + { + use std::io::Read as _; + // CUPS queue names never hold `/`, so the name can't leave the PPD folder. + if printer.contains(['/', '\\']) || printer.starts_with('.') { + return Vec::new(); + } + const PPD_CAP: u64 = 16 << 20; + let mut bytes = Vec::new(); + let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); + if read.is_err() { + return Vec::new(); + } + vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) + } + } + /// Drain output while polling the child, and stop discovery after ten seconds. + #[cfg(windows)] + fn paper_output(command: &mut Command) -> Option> { + use std::io::Read as _; + use std::process::Stdio; + use std::time::{Duration, Instant}; + + const LIMIT: Duration = Duration::from_secs(10); + let started = Instant::now(); + let mut child = command.stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?; + let (send, receive) = std::sync::mpsc::channel(); + let stdout = child.stdout.take(); + let reader = std::thread::Builder::new().name("printer-paper-output".into()).spawn(move || { + let mut bytes = Vec::new(); + // Retain at most 16 MiB, but drain the rest so the child can finish. + let read = stdout.map(|mut out| { + out.by_ref().take(16 << 20).read_to_end(&mut bytes)?; + std::io::copy(&mut out, &mut std::io::sink()) + }); + let _ = send.send(read.and_then(Result::ok).map(|_| bytes)); + }); + if reader.is_err() { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + loop { + match child.try_wait() { + Ok(Some(status)) => { + return if status.success() { receive.recv_timeout(LIMIT.saturating_sub(started.elapsed())).ok().flatten() } else { None }; + } + Ok(None) if started.elapsed() < LIMIT => std::thread::sleep(Duration::from_millis(25)), + _ => { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + } + } + } pub fn print(job: &PrintJob) -> Result { if job.direct_pdf { return super::direct_pdf::print(job); diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 05d46c3979..3021537994 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -46,6 +46,7 @@ use vectorcraft_pdf::{ }; use super::form; +use crate::print::{Paper, Papers}; use crate::{VectorcraftApp, graphics}; pub(crate) const SECTIONS: [&str; 7] = ["General", "Marks and Bleed", "Output", "Graphics", "Color Management", "Advanced", "Summary"]; @@ -111,6 +112,12 @@ struct Open { preview: Option<(Stamp, Arc>)>, /// The printer row's driver controls, as the dialog was last given them. driver: DriverControls, + /// The printer the Media list was made for, and the paper sizes its driver offers. + papers: (String, Vec), + /// Whether the chosen printer still has a lookup running. + papers_pending: bool, + /// The ids of the Size choices the dialog was last given. + media: Vec, } /// The document (uid, revision) and the settings a cached preview belongs to. @@ -132,24 +139,105 @@ struct Drained { ok: Option, settings: Value, sheet: usize, + /// The printer chosen (empty: the default printer or PDF File). + printer: String, } -/// The lists the rows offer that the app holds (the profiles, the flattener presets). +/// The lists the rows offer that the app holds (the profiles, the flattener presets, the printer's papers). #[derive(Default)] struct Lists { profiles: Vec, flatteners: Vec, + /// The Size choices: the printer's paper sizes, or the dialog's own papers when it offers none. + media: Vec<(String, String)>, } impl Lists { - fn of(app: &VectorcraftApp) -> Self { + fn of(app: &VectorcraftApp, papers: &[Paper], media: &str) -> Self { Self { profiles: vectorcraft_color::cms::profiles().iter().map(|p| p.name.clone()).collect(), flatteners: app.session.flattener_presets().iter().map(|p| p.name.clone()).collect(), + media: media_choices(papers, media), } } } +/// The prefix of a Size choice that is one of the printer's own paper sizes (`printer:CR80`). +const PRINTER_PAPER: &str = "printer:"; + +/// The dialog's own papers, as (id, label). +fn own_media() -> Vec<(String, String)> { + Media::IDS.iter().zip(Media::LABELS).map(|(i, l)| (i.to_string(), tl!(*l).to_string())).collect() +} + +/// The Size choices for a printer whose driver offers `papers`, with `current` (the row's choice) kept when it is one of +/// the dialog's own papers. A paper the dialog has itself, by size, keeps the dialog's id (so `letter` stays `letter`) +/// under the driver's name; the others are `printer:`. Custom is always offered. No papers: the dialog's own +/// list. +fn media_choices(papers: &[Paper], current: &str) -> Vec<(String, String)> { + let mut out = if papers.is_empty() { + own_media() + } else { + let mut out: Vec<(String, String)> = Vec::new(); + for p in papers { + let id = own_media_of(p).map_or_else(|| format!("{PRINTER_PAPER}{}", p.key), |m| m.id().to_string()); + if out.iter().all(|(i, _)| *i != id) { + out.push((id, p.label.clone())); + } + } + out.push((Media::Custom.id().to_string(), tl!(Media::Custom.label()).to_string())); + out + }; + if !current.is_empty() && !current.starts_with(PRINTER_PAPER) && out.iter().all(|(i, _)| i != current) { + // A built-in paper the printer doesn't list stays chosen until it is changed. + let label = Media::from_name(current).map_or_else(|| current.trim_start_matches(PRINTER_PAPER).to_string(), |m| tl!(m.label()).to_string()); + out.push((current.to_string(), label)); + } + out +} + +/// The dialog's own paper of the size of `p`, either way up, to within half a point. +fn own_media_of(p: &Paper) -> Option { + let (w, h) = (p.width.min(p.height), p.width.max(p.height)); + Media::ALL.iter().copied().find(|m| m.size().is_some_and(|(mw, mh)| (mw.min(mh) - w).abs() <= 0.5 && (mw.max(mh) - h).abs() <= 0.5)) +} + +/// The printer's paper the Size row names (`printer:CR80`), when it is one of `papers`. +fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a Paper> { + let key = fields.text("media")?.strip_prefix(PRINTER_PAPER)?; + papers.iter().find(|p| p.key == key) +} + +/// The print settings of `fields`, with Width and Height at the size of the printer's paper the Size row names. +fn settings_with_paper(fields: &DialogFields, papers: &[Paper]) -> Value { + let mut out = settings(fields); + if let Some(paper) = printer_paper(fields, papers) { + out["width"] = json!(paper.width); + out["height"] = json!(paper.height); + } + out +} + +/// The paper sizes the driver of `printer` offers (none for preset editing, the default printer and PDF File). +fn papers_of(app: &mut VectorcraftApp, mode: PrintMode, printer: &str) -> (Vec, bool) { + if mode == PrintMode::PresetEditor || printer.is_empty() || printer == PDF_FILE { + return (Vec::new(), false); + } + match app.services.print.as_mut().map(|s| s.papers(printer)) { + Some(Papers::Ready(papers)) => (papers, false), + Some(Papers::Pending) => (Vec::new(), true), + None => (Vec::new(), false), + } +} + +/// The printer `destination` names, empty for none. +fn printer_of(destination: &Destination) -> String { + match destination { + Destination::Printer(name) => name.clone(), + _ => String::new(), + } +} + /// Open the Print dialog on the document's print settings and the system's default printer. pub fn open(app: &mut VectorcraftApp) -> Result { let st = app.session.active().ok_or("no document")?; @@ -207,7 +295,15 @@ fn start( let taken: Vec = taken_names(app); let named = editing.clone(); let driver = driver(has_setup(app), &state.settings.destination); - let mut hosted = HostedPrint::new(state, fields, sections(&Lists::of(app))) + let printer = printer_of(&state.settings.destination); + let (papers, papers_pending) = papers_of(app, mode, &printer); + if papers_pending { + ctx.request_repaint(); + } + let media = fields.text("media").map(str::to_string).unwrap_or_default(); + let lists = Lists::of(app, &papers, &media); + let media: Vec = lists.media.iter().map(|(i, _)| i.clone()).collect(); + let mut hosted = HostedPrint::new(state, fields, sections(&lists)) .mode(mode) .layout(PrintLayout::Sections) .driver(driver) @@ -220,7 +316,8 @@ fn start( hosted.set_json_field(&ctx, "name", json!(name))?; } let id = dialogs.with(|h| h.open(hosted)); - app.print_dialog.open = Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver }); + app.print_dialog.open = + Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver, papers: (printer, papers), papers_pending, media }); Ok(Value::Null) } @@ -320,6 +417,10 @@ pub(super) fn settings(fields: &DialogFields) -> Value { for k in NOT_SETTINGS { p.remove(k); } + // A printer's own paper prints as a custom size: the pump keeps Width and Height at its size. + if p.get("media").and_then(Value::as_str).is_some_and(|m| m.starts_with(PRINTER_PAPER)) { + p.insert("media".into(), json!(Media::Custom.id())); + } Value::Object(nested(p)) } @@ -363,6 +464,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, ok: p.take_ok(), settings: settings(p.fields_mut()), sheet: p.sheet_index(), + printer: printer_of(&p.state().settings.destination), } }) else { // Closed: its answer was acted on when the OK was held. @@ -372,6 +474,73 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, for event in std::mem::take(&mut d.events) { apply_preset_event(app, dialogs, open, &mut d.settings, event); } + // Another printer, or its driver's answer arriving: the Size list becomes the driver's paper sizes. A preset can + // choose a size the list lacks, so the Size row is read after the preset events and the list is made again to + // hold it. + let mut media = on(dialogs, |p| p.fields().text("media").map(str::to_string)).flatten().unwrap_or_default(); + let printer_changed = d.printer != open.papers.0; + let mut papers_changed = false; + // The paper chosen from the previous list, read before the list is replaced. + let chosen = on(dialogs, |p| printer_paper(p.fields(), &open.papers.1).cloned()).flatten(); + if printer_changed || open.papers_pending { + // The held answer still names a paper from the previous list. + if let Some(answer) = &mut d.ok + && let Some(paper) = printer_paper(&answer.fields, &open.papers.1) + { + answer.fields.set("width", paper.width); + answer.fields.set("height", paper.height); + answer.fields.set("media", Media::Custom.id()); + } + let (papers, pending) = papers_of(app, open.mode, &d.printer); + papers_changed = printer_changed || !pending; + open.papers = (d.printer.clone(), papers); + open.papers_pending = pending; + } + if open.papers_pending { + ctx.request_repaint(); + } + // A paper the new printer doesn't list becomes a custom size of the same Width and Height. + if papers_changed + && media.starts_with(PRINTER_PAPER) + && let Some(s) = on(dialogs, |p| { + let fields = p.fields_mut(); + if printer_paper(fields, &open.papers.1).is_some() { + return None; + } + if let Some(paper) = &chosen { + fields.set("width", paper.width); + fields.set("height", paper.height); + } + fields.set("media", Media::Custom.id()); + Some(settings(fields)) + }) + .flatten() + { + media = Media::Custom.id().to_string(); + d.settings = s; + } + if papers_changed || (!media.is_empty() && !open.media.contains(&media)) { + let lists = Lists::of(app, &open.papers.1, &media); + open.media = lists.media.iter().map(|(i, _)| i.clone()).collect(); + on(dialogs, |p| p.set_sections(sections(&lists))); + ctx.request_repaint(); + } + // One of the printer's papers: Width and Height hold its size, which is what prints. + let papers = &open.papers.1; + if let Some(s) = on(dialogs, |p| { + let fields = p.fields_mut(); + let paper = printer_paper(fields, papers)?; + let size = (fields.number("width"), fields.number("height")); + (size != (Some(paper.width), Some(paper.height))).then(|| { + fields.set("width", paper.width); + fields.set("height", paper.height); + settings(fields) + }) + }) + .flatten() + { + d.settings = s; + } if open.mode == PrintMode::Print { let same = serde_json::from_value::(d.settings.clone()) .ok() @@ -508,7 +677,9 @@ fn drags(moves: EditEvents) -> Vec<(f64, f64)> { /// Print, or Done: keep the settings with the document (one undo step when they changed), then print them; settings /// that can't print are refused, and the dialog stays open. The preset editor saves the preset under `name` instead. fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &str) -> Result<(), String> { - let settings = settings(&answer.fields); + // The answer holds the fields as they were when OK was pressed, which can be before the pump set a printer's + // paper's size. + let settings = settings_with_paper(&answer.fields, &open.papers.1); if open.mode == PrintMode::PresetEditor { return save_preset(app, open, name, settings); } @@ -696,6 +867,7 @@ fn sections(lists: &Lists) -> Vec { let composite: Vec<&str> = OutputMode::IDS.iter().copied().filter(|i| *i != separations).collect(); let scaling_on: Vec<&str> = tiles.iter().copied().chain([PrintScaling::Custom.id()]).collect(); let counts: Vec = (2..=i64::from(vectorcraft_pdf::MAX_COPIES)).collect(); + let media = if lists.media.is_empty() { own_media() } else { lists.media.clone() }; let artboards = vec![ (PrintArtboards::All.id().to_string(), tl!("All").into()), (PrintArtboards::Range.id().to_string(), tl!("Range:").into()), @@ -712,7 +884,7 @@ fn sections(lists: &Lists) -> Vec { .under_option(PrintArtboards::Range.id()), flag("skipBlank", tl!("Skip Blank Artboards")).enabled_when_in("artboards", [PrintArtboards::All.id(), PrintArtboards::Range.id()]), Param::section(tl!("Media")), - pick::("media", tl!("Size:")), + Param::new("media", tl!("Size:"), ParamKind::choice(media.into_iter().map(|(i, l)| (i, l.into())).collect(), None)), length("width", tl!("Width:")).enabled_when("media", "custom"), length("height", tl!("Height:")).enabled_when("media", "custom"), Param::section(tl!("Orientation")), diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 183d6f1056..48002b08d8 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -1,14 +1,14 @@ //! File → Print: the Print dialog hosted on the window (Print and Done, the preview's drag), the //! print service it prints through (a mock here) and the PDF it saves without one. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; use craft::print::ui::Printer; use serde_json::{Value, json}; use vectorcraft_engine::Session; -use crate::print::{PrintJob, PrintService}; +use crate::print::{Papers, PrintJob, PrintService}; use crate::{Services, VectorcraftApp}; /// What the mock service was sent: (printer, title, PDF). @@ -234,6 +234,240 @@ fn print_does_not_send_or_update_the_other_drawing() { assert!(!is_open(&app)); } +/// The printers the paper service was asked for, in order. +type Asked = Rc>>; + +/// Two printers: Office's driver lists no papers, and Card's lists US Letter and a CR80 card. +struct PaperPrint(Jobs, Asked); + +impl PrintService for PaperPrint { + fn printers(&mut self) -> Vec { + vec![Printer::new("Office").is_default(true), Printer::new("Card")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(self.0.clone()).print(job) + } + + fn papers(&mut self, printer: &str) -> Papers { + self.1.borrow_mut().push(printer.to_string()); + let paper = |key: &str, label: &str, width, height| crate::print::Paper { key: key.into(), label: label.into(), width, height }; + Papers::Ready(match printer { + "Card" => vec![paper("Letter", "US Letter", 612.0, 792.0), paper("CR80", "CR80 Card", 153.0, 243.0)], + _ => vec![], + }) + } +} + +/// The driver returns its papers on the second test frame. +struct PendingPaperPrint(PaperPrint, Rc>); + +impl PrintService for PendingPaperPrint { + fn printers(&mut self) -> Vec { + vec![Printer::new("Card").is_default(true)] + } + + fn print(&mut self, job: &PrintJob) -> Result { + self.0.print(job) + } + + fn papers(&mut self, printer: &str) -> Papers { + if self.1.get() < 2 { Papers::Pending } else { self.0.papers(printer) } + } +} + +#[test] +fn preset_editor_keeps_its_own_sizes_without_asking_the_default_printer() { + let asked = Asked::default(); + let service = PendingPaperPrint(PaperPrint(Jobs::default(), asked.clone()), Rc::new(Cell::new(2))); + let services = Services { print: Some(Box::new(service)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("ui.printPresetDialog", json!({})).unwrap(); + assert!(asked.borrow().is_empty()); + set(&mut app, "media", json!("a3")); + for _ in 0..2 { + pump(&mut app); + } + assert_eq!(fields(&app)["media"], "a3"); + assert!(asked.borrow().is_empty(), "preset editing never asks for printer paper sizes"); +} + +#[test] +fn pending_paper_sizes_arrive_on_a_later_frame() { + let asked = Asked::default(); + let frame = Rc::new(Cell::new(0)); + let service = PendingPaperPrint(PaperPrint(Jobs::default(), asked.clone()), frame.clone()); + let services = Services { print: Some(Box::new(service)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err()); + frame.set(1); + pump(&mut app); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err()); + set(&mut app, "media", json!("a3")); + frame.set(2); + pump(&mut app); + assert_eq!(fields(&app)["media"], "a3", "the chosen size survives discovery"); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_ok()); + pump(&mut app); + pump(&mut app); + assert_eq!(*asked.borrow(), ["Card"], "ready results are not polled again"); +} + +#[test] +fn the_media_sizes_follow_the_printer_chosen() { + let (jobs, asked) = (Jobs::default(), Asked::default()); + let services = Services { print: Some(Box::new(PaperPrint(jobs.clone(), asked.clone()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err(), "Office's driver has no CR80 card"); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + // The card printer's Letter is the dialog's own Letter. + set(&mut app, "media", json!("letter")); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + let f = fields(&app); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); + confirm(&mut app); + assert!(!is_open(&app)); + let job = jobs.borrow(); + let page = &vectorcraft_pdf::info(&job[0].2, None).unwrap().pages[0]; + let (short, long) = (page.width.min(page.height), page.width.max(page.height)); + assert!((short - 153.0).abs() < 0.5 && (long - 243.0).abs() < 0.5, "printed on the card: {} × {}", page.width, page.height); + let saved = app.session.active().unwrap().doc.print_setup.clone().unwrap(); + assert_eq!(saved["media"], "custom", "the document keeps the card as its size"); + // Each printer's driver is asked once, when it is chosen. + assert_eq!(*asked.borrow(), ["Office", "Card"]); +} + +#[test] +fn switching_printers_keeps_an_unlisted_paper_as_a_custom_size() { + let services = Services { print: Some(Box::new(PaperPrint(Jobs::default(), Asked::default()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + // The printer changes in the same frame as the card is chosen, before Width and Height take its size. + set(&mut app, "media", json!("printer:CR80")); + set(&mut app, "printer", json!("Office")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "custom"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err()); +} + +#[test] +fn confirming_after_switching_printers_keeps_the_selected_paper_size() { + let jobs = Jobs::default(); + let services = Services { print: Some(Box::new(PaperPrint(jobs.clone(), Asked::default()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + set(&mut app, "media", json!("printer:CR80")); + set(&mut app, "printer", json!("Office")); + confirm(&mut app); + assert!(!is_open(&app)); + let job = jobs.borrow(); + assert_eq!(job.len(), 1); + assert_eq!(job[0].0.as_deref(), Some("Office")); + let page = &vectorcraft_pdf::info(&job[0].2, None).unwrap().pages[0]; + let (short, long) = (page.width.min(page.height), page.width.max(page.height)); + assert!((short - 153.0).abs() < 0.5 && (long - 243.0).abs() < 0.5, "printed on the card: {} × {}", page.width, page.height); +} + +#[test] +fn a_printer_paper_prints_at_its_size_and_a_preset_replaces_it() { + let jobs = Jobs::default(); + let services = Services { print: Some(Box::new(PaperPrint(jobs.clone(), Asked::default()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("print.presets.save", json!({"name": "Big", "settings": {"media": "custom", "width": 400, "height": 500}})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + // A preset's own size replaces the card's. + set(&mut app, "preset", json!("Big")); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!((f["media"].as_str(), f["width"].as_f64(), f["height"].as_f64()), (Some("custom"), Some(400.0), Some(500.0)), "{f}"); + // The card chosen and OK pressed before the dialog is served again still prints on the card. + set(&mut app, "media", json!("printer:CR80")); + confirm(&mut app); + assert!(!is_open(&app)); + let job = jobs.borrow(); + let page = &vectorcraft_pdf::info(&job[0].2, None).unwrap().pages[0]; + let (short, long) = (page.width.min(page.height), page.width.max(page.height)); + assert!((short - 153.0).abs() < 0.5 && (long - 243.0).abs() < 0.5, "printed on the card: {} × {}", page.width, page.height); +} + +#[test] +fn a_preset_size_the_printer_does_not_list_stays_a_choice() { + let services = Services { print: Some(Box::new(PaperPrint(Jobs::default(), Asked::default()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("print.presets.save", json!({"name": "Tall", "settings": {"media": "a3"}})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + assert!(try_set(&mut app, "media", json!("a3")).is_err(), "the card printer lists no A3"); + set(&mut app, "preset", json!("Tall")); + pump(&mut app); + pump(&mut app); + assert_eq!(fields(&app)["media"], "a3"); + // A3 is offered while it is chosen, so choosing another size and going back works. + set(&mut app, "media", json!("letter")); + set(&mut app, "media", json!("a3")); +} + +#[test] +fn a_ppd_lists_its_paper_dimensions_by_name() { + let ppd = "*OpenUI *PageSize/Media Size: PickOne\r\n\ + *PageSize Letter/US Letter: \"<>setpagedevice\"\r\n\ + *PageSize CR80/CR80 Card: \"<>setpagedevice\"\r\n\ + *CloseUI: *PageSize\r\n\ + *PaperDimension Letter: \"612 792\"\r\n\ + *PaperDimension CR80: \"153 243\"\r\n\ + *PaperDimension CR80: \"100 100\"\r\n\ + *PaperDimension Stamp/Stamp: \"20 20\"\r\n\ + *PaperDimension Bad: \"612\"\r\n\ + *PaperDimension Roll/Banner Roll: \"612 14400\"\r\n"; + let papers = crate::print::ppd_papers(ppd); + let got: Vec<(&str, &str, f64, f64)> = papers.iter().map(|p| (p.key.as_str(), p.label.as_str(), p.width, p.height)).collect(); + // The repeated CR80, a size below 72 pt and a line without a height are left out. + assert_eq!(got, [("Letter", "US Letter", 612.0, 792.0), ("CR80", "CR80 Card", 153.0, 243.0), ("Roll", "Banner Roll", 612.0, 14400.0)]); +} + +#[test] +fn windows_paper_sizes_are_read_in_hundredths_of_an_inch() { + let out = "1\tLetter\t850\t1100\r\n\ + 256\tCard\t213\t338\r\n\ + 256\tBanner\t850\t2000\r\n\ + 256\t\t213\t338\r\nbroken line\r\n9\tTiny\t10\t10\r\n"; + let papers = crate::print::windows_papers(out); + let got: Vec<(&str, &str, f64, f64)> = papers.iter().map(|p| (p.key.as_str(), p.label.as_str(), p.width, p.height)).collect(); + assert_eq!(got.len(), 4, "{got:?}"); + assert_eq!((got[0].0, got[0].1), ("Letter", "Letter")); + assert!((got[0].2 - 612.0).abs() < 1e-9 && (got[0].3 - 792.0).abs() < 1e-9); + assert_eq!((got[1].0, got[1].1), ("Card", "Card")); + assert_eq!((got[2].0, got[2].1), ("Banner", "Banner")); + assert_eq!((got[3].0, got[3].1), ("256", "256"), "no name: the number"); +} + /// A print queue that puts each page on the paper as it is, as `lp` does. struct UprightQueue(Jobs); diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 863c94673d..7989474924 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -52,6 +52,95 @@ pub trait PrintService { fn setup(&mut self, _printer: Option<&str>) -> Result<(), String> { Err("there are no printer settings to open here".into()) } + /// The driver's paper sizes, in its order, without waiting for a program. The dialog polls + /// pending lookups and offers its own sizes until the driver returns a nonempty list. + fn papers(&mut self, _printer: &str) -> Papers { + Papers::Ready(Vec::new()) + } +} + +/// A driver's paper sizes, or a lookup still running on a worker. +pub enum Papers { + /// The lookup finished; an empty list uses the dialog's sizes. + Ready(Vec), + /// Poll again on a later frame. + Pending, +} + +/// A paper size a printer's driver offers. +#[derive(Clone, Debug, PartialEq)] +pub struct Paper { + /// The driver's keyword for it (`Letter`, `CR80`), or its form name on Windows (the number when unnamed). + pub key: String, + /// What the driver calls it (`US Letter`); the keyword when it gives no name. + pub label: String, + /// Width in points. + pub width: f64, + /// Height in points. + pub height: f64, +} + +/// Most sizes kept from one driver; a PPD is a text file from the printer vendor. +const MAX_PAPERS: usize = 400; +/// Longest paper label kept, in characters. +const MAX_PAPER_LABEL: usize = 128; +/// The smallest and largest paper side the print settings take (`media: custom`), in points. +const PAPER_SIDE: std::ops::RangeInclusive = 72.0..=14400.0; + +/// `paper`, unless the list is full, its key is taken or a side is outside 72–14400 pt. +fn push_paper(papers: &mut Vec, paper: Paper) { + let fits = PAPER_SIDE.contains(&paper.width) && PAPER_SIDE.contains(&paper.height); + if fits && papers.len() < MAX_PAPERS && papers.iter().all(|p| p.key != paper.key) { + papers.push(Paper { label: paper.label.chars().take(MAX_PAPER_LABEL).collect(), ..paper }); + } +} + +/// The paper sizes of a PPD: each `*PaperDimension` entry (`*PaperDimension CR80/CR80 Card: "153 243"`), named by +/// its own label or else by the `*PageSize` entry with the same keyword. Sizes outside 72–14400 pt, repeated keywords +/// and malformed lines are skipped. +pub fn ppd_papers(ppd: &str) -> Vec { + fn entry<'a>(line: &'a str, key: &str) -> Option<(&'a str, &'a str, &'a str)> { + let rest = line.strip_prefix('*')?.strip_prefix(key)?.strip_prefix(' ')?; + let (head, value) = rest.split_once(':')?; + let (name, label) = head.split_once('/').map_or((head.trim(), ""), |(n, l)| (n.trim(), l.trim())); + (!name.is_empty() && !name.contains(char::is_whitespace)).then_some((name, label, value.trim())) + } + let mut labels: Vec<(&str, &str)> = Vec::new(); + let mut papers: Vec = Vec::new(); + for line in ppd.lines().map(|l| l.trim_end_matches('\r')) { + if let Some((name, label, _)) = entry(line, "PageSize") { + if !label.is_empty() && labels.len() < MAX_PAPERS { + labels.push((name, label)); + } + } else if let Some((name, label, value)) = entry(line, "PaperDimension") { + let mut nums = value.trim_matches('"').split_whitespace().map(str::parse::); + let (Some(Ok(width)), Some(Ok(height)), None) = (nums.next(), nums.next(), nums.next()) else { continue }; + push_paper(&mut papers, Paper { key: name.into(), label: label.into(), width, height }); + } + } + for p in &mut papers { + if p.label.is_empty() { + let label = labels.iter().find(|(n, _)| *n == p.key).map_or(p.key.as_str(), |(_, l)| l); + p.label = label.chars().take(MAX_PAPER_LABEL).collect(); + } + } + papers +} + +/// The paper sizes in tab-separated lines of number, name, width and height (hundredths of an inch), as Windows' +/// printer settings list them (`PrinterSettings.PaperSizes`). The same limits as [`ppd_papers`] apply. +pub fn windows_papers(out: &str) -> Vec { + let mut papers: Vec = Vec::new(); + for line in out.lines() { + let fields: Vec<&str> = line.trim_end_matches('\r').split('\t').map(str::trim).collect(); + let [key, label, w, h] = fields[..] else { continue }; + let (Ok(w), Ok(h)) = (w.parse::(), h.parse::()) else { continue }; + if !key.is_empty() { + let label = if label.is_empty() { key } else { label }; + push_paper(&mut papers, Paper { key: label.into(), label: label.into(), width: w * 0.72, height: h * 0.72 }); + } + } + papers } /// `print.printers`: the system's printers, and what the print service offers. From c33f0cfa133d170df1bdd533a19704643a212038 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 18:06:39 -0800 Subject: [PATCH 42/50] Print: each printer choice reads the driver's paper sizes again A lookup that was still running when the person chose another printer stayed in the service, and choosing that printer again returned its old answer without reading the driver. Reopening the dialog on a printer whose lookup was still running did the same. `PrintService::papers` now takes `fresh`, which the dialog sets when it opens and when the printer changes. The desktop service keeps one lookup in flight and replaces it on a fresh call or a call for another printer, so an earlier answer is dropped. --- apps/vectorcraft/src/printing.rs | 87 +++++++++++++++++++---- crates/ui-egui/src/dialogs/print.rs | 11 +-- crates/ui-egui/src/dialogs/tests_print.rs | 46 +++++++++++- crates/ui-egui/src/print.rs | 4 +- 4 files changed, 126 insertions(+), 22 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 9e64fcc75c..e7f5db9a69 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -7,8 +7,8 @@ mod direct_pdf; #[derive(Default)] pub struct SystemPrint { - /// Channels for pending paper-size lookups, removed when each worker answers or disconnects. - papers: std::collections::HashMap>>, + /// The paper-size lookup in flight, dropped when its worker answers or disconnects. + papers: PaperLookup, } impl PrintService for SystemPrint { @@ -36,21 +36,33 @@ impl PrintService for SystemPrint { fn scripts_may_print(&self) -> bool { true } - fn papers(&mut self, printer: &str) -> Papers { - let receive = self.papers.entry(printer.to_string()).or_insert_with(|| { + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + self.papers.poll(printer, fresh, |printer| installed_papers(&printer)) + } +} + +/// The paper-size lookup in flight: the printer it reads and its worker's channel. +#[derive(Default)] +struct PaperLookup(Option<(String, std::sync::mpsc::Receiver>)>); + +impl PaperLookup { + /// Poll the lookup of `printer`. A new lookup runs `read` on a worker when `fresh` is set, when the one in flight + /// reads another printer, or when none is in flight; the earlier one's answer is dropped. + fn poll(&mut self, printer: &str, fresh: bool, read: impl FnOnce(String) -> Vec + Send + 'static) -> Papers { + if fresh || self.0.as_ref().is_none_or(|(p, _)| p != printer) { let (send, receive) = std::sync::mpsc::channel(); - let printer = printer.to_string(); + let name = printer.to_string(); let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || { - let _ = send.send(installed_papers(&printer)); + let _ = send.send(read(name)); }); - receive - }); - let result = match receive.try_recv() { - Ok(papers) => Papers::Ready(papers), - Err(std::sync::mpsc::TryRecvError::Disconnected) => Papers::Ready(Vec::new()), - Err(std::sync::mpsc::TryRecvError::Empty) => return Papers::Pending, + self.0 = Some((printer.to_string(), receive)); + } + let result = match self.0.as_ref().map(|(_, receive)| receive.try_recv()) { + Some(Ok(papers)) => Papers::Ready(papers), + Some(Err(std::sync::mpsc::TryRecvError::Empty)) => return Papers::Pending, + Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) | None => Papers::Ready(Vec::new()), }; - self.papers.remove(printer); + self.0 = None; result } } @@ -233,6 +245,55 @@ mod tests { } } +#[cfg(test)] +mod paper_lookup_tests { + use super::PaperLookup; + use vectorcraft_ui_egui::print::{Paper, Papers}; + + fn paper(key: &str) -> Vec { + vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }] + } + + /// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers. + fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec { + let mut polled = lookup.poll(printer, true, move |_| paper(key)); + loop { + match polled { + Papers::Ready(papers) => return papers, + Papers::Pending => std::thread::yield_now(), + } + polled = lookup.poll(printer, false, |_| panic!("polling starts no lookup")); + } + } + + /// A read that answers `key` once `gate` lets it. + fn gated(key: &'static str) -> (std::sync::mpsc::Sender<()>, impl FnOnce(String) -> Vec + Send + 'static) { + let (open, gate) = std::sync::mpsc::channel::<()>(); + (open, move |_| { + let _ = gate.recv(); + paper(key) + }) + } + + #[test] + fn a_fresh_lookup_drops_the_answer_of_an_earlier_one() { + let mut lookup = PaperLookup::default(); + let (open, read) = gated("Old"); + assert!(matches!(lookup.poll("Card", true, read), Papers::Pending)); + let (other, read) = gated("Office"); + assert!(matches!(lookup.poll("Office", true, read), Papers::Pending)); + let _ = open.send(()); + let _ = other.send(()); + // Back on the card printer. + assert_eq!(answer(&mut lookup, "Card", "New"), paper("New")); + // The dialog opens again on the card printer while a lookup of it is still running. + let (open, read) = gated("Stale"); + assert!(matches!(lookup.poll("Card", true, read), Papers::Pending)); + let _ = open.send(()); + assert_eq!(answer(&mut lookup, "Card", "Newer"), paper("Newer")); + } +} + #[cfg(test)] mod turn_tests { use super::sent; diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 3021537994..6828d54559 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -218,12 +218,13 @@ fn settings_with_paper(fields: &DialogFields, papers: &[Paper]) -> Value { out } -/// The paper sizes the driver of `printer` offers (none for preset editing, the default printer and PDF File). -fn papers_of(app: &mut VectorcraftApp, mode: PrintMode, printer: &str) -> (Vec, bool) { +/// The paper sizes the driver of `printer` offers (none for preset editing, the default printer and PDF File). `fresh` +/// starts a new lookup: the dialog opened or the printer changed. +fn papers_of(app: &mut VectorcraftApp, mode: PrintMode, printer: &str, fresh: bool) -> (Vec, bool) { if mode == PrintMode::PresetEditor || printer.is_empty() || printer == PDF_FILE { return (Vec::new(), false); } - match app.services.print.as_mut().map(|s| s.papers(printer)) { + match app.services.print.as_mut().map(|s| s.papers(printer, fresh)) { Some(Papers::Ready(papers)) => (papers, false), Some(Papers::Pending) => (Vec::new(), true), None => (Vec::new(), false), @@ -296,7 +297,7 @@ fn start( let named = editing.clone(); let driver = driver(has_setup(app), &state.settings.destination); let printer = printer_of(&state.settings.destination); - let (papers, papers_pending) = papers_of(app, mode, &printer); + let (papers, papers_pending) = papers_of(app, mode, &printer, true); if papers_pending { ctx.request_repaint(); } @@ -491,7 +492,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, answer.fields.set("height", paper.height); answer.fields.set("media", Media::Custom.id()); } - let (papers, pending) = papers_of(app, open.mode, &d.printer); + let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed); papers_changed = printer_changed || !pending; open.papers = (d.printer.clone(), papers); open.papers_pending = pending; diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 48002b08d8..c52e5782da 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -249,7 +249,7 @@ impl PrintService for PaperPrint { MockPrint(self.0.clone()).print(job) } - fn papers(&mut self, printer: &str) -> Papers { + fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { self.1.borrow_mut().push(printer.to_string()); let paper = |key: &str, label: &str, width, height| crate::print::Paper { key: key.into(), label: label.into(), width, height }; Papers::Ready(match printer { @@ -271,11 +271,51 @@ impl PrintService for PendingPaperPrint { self.0.print(job) } - fn papers(&mut self, printer: &str) -> Papers { - if self.1.get() < 2 { Papers::Pending } else { self.0.papers(printer) } + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + if self.1.get() < 2 { Papers::Pending } else { self.0.papers(printer, fresh) } } } +/// The lookups the dialog asked for, as (printer, fresh). +type Lookups = Rc>>; + +/// Two printers whose drivers never answer. +struct SlowPaperPrint(Jobs, Lookups); + +impl PrintService for SlowPaperPrint { + fn printers(&mut self) -> Vec { + vec![Printer::new("Office").is_default(true), Printer::new("Card")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(self.0.clone()).print(job) + } + + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + self.1.borrow_mut().push((printer.to_string(), fresh)); + Papers::Pending + } +} + +#[test] +fn choosing_a_printer_again_starts_a_new_paper_lookup() { + let lookups = Lookups::default(); + let services = Services { print: Some(Box::new(SlowPaperPrint(Jobs::default(), lookups.clone()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + set(&mut app, "printer", json!("Office")); + pump(&mut app); + pump(&mut app); + let log = lookups.borrow(); + let fresh: Vec<&str> = log.iter().filter(|(_, f)| *f).map(|(p, _)| p.as_str()).collect(); + assert_eq!(fresh, ["Office", "Card", "Office"], "the opening and each printer change start a lookup: {log:?}"); + assert_eq!(log.last(), Some(&("Office".to_string(), false)), "later frames poll the lookup in flight: {log:?}"); +} + #[test] fn preset_editor_keeps_its_own_sizes_without_asking_the_default_printer() { let asked = Asked::default(); diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index d6c7794912..0451cb5b5c 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -65,7 +65,9 @@ pub trait PrintService { } /// The driver's paper sizes, in its order, without waiting for a program. The dialog polls /// pending lookups and offers its own sizes until the driver returns a nonempty list. - fn papers(&mut self, _printer: &str) -> Papers { + /// `fresh` is set when the dialog opens or the printer changes: the driver is read again, + /// and a lookup still running from an earlier choice is dropped. + fn papers(&mut self, _printer: &str, _fresh: bool) -> Papers { Papers::Ready(Vec::new()) } } From f251709e54caee8253c339a0bb839a462ea4fd1b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 20:24:47 -0800 Subject: [PATCH 43/50] Print: a paper keyword at another size on the new printer becomes Custom Paper keywords belong to each printer's driver. When the printer changes and the new driver lists the chosen keyword at a different size, the Size row now keeps the previous Width and Height as a Custom size instead of taking the new printer's dimensions. A keyword listed at the same size stays chosen. --- crates/ui-egui/src/dialogs/print.rs | 10 ++++-- crates/ui-egui/src/dialogs/tests_print.rs | 41 +++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 6828d54559..314e2bc032 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -208,6 +208,11 @@ fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a P papers.iter().find(|p| p.key == key) } +/// Whether two papers have the same Width and Height, to within half a point. +fn same_size(a: &Paper, b: &Paper) -> bool { + (a.width - b.width).abs() <= 0.5 && (a.height - b.height).abs() <= 0.5 +} + /// The print settings of `fields`, with Width and Height at the size of the printer's paper the Size row names. fn settings_with_paper(fields: &DialogFields, papers: &[Paper]) -> Value { let mut out = settings(fields); @@ -500,12 +505,13 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, if open.papers_pending { ctx.request_repaint(); } - // A paper the new printer doesn't list becomes a custom size of the same Width and Height. + // A paper the new printer doesn't list, or lists under the same keyword at another size, becomes a custom size of + // the same Width and Height. if papers_changed && media.starts_with(PRINTER_PAPER) && let Some(s) = on(dialogs, |p| { let fields = p.fields_mut(); - if printer_paper(fields, &open.papers.1).is_some() { + if printer_paper(fields, &open.papers.1).is_some_and(|new| chosen.as_ref().is_none_or(|old| same_size(old, new))) { return None; } if let Some(paper) = &chosen { diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index c52e5782da..10ec8a5a70 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -403,6 +403,47 @@ fn switching_printers_keeps_an_unlisted_paper_as_a_custom_size() { assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err()); } +/// Three card printers: Card and Twin list a CR80 card at 153 × 243 points, and Badge lists a CR80 at 200 × 300. +struct CardPrinters; + +impl PrintService for CardPrinters { + fn printers(&mut self) -> Vec { + vec![Printer::new("Card").is_default(true), Printer::new("Twin"), Printer::new("Badge")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { + let (width, height) = if printer == "Badge" { (200.0, 300.0) } else { (153.0, 243.0) }; + Papers::Ready(vec![crate::print::Paper { key: "CR80".into(), label: "CR80 Card".into(), width, height }]) + } +} + +#[test] +fn a_paper_keyword_another_printer_lists_at_another_size_becomes_a_custom_size() { + let services = Services { print: Some(Box::new(CardPrinters)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + // Twin's CR80 is the same size, so it stays chosen. + set(&mut app, "printer", json!("Twin")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:CR80", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); + // Badge's CR80 is another size: the card keeps its size as a custom size. + set(&mut app, "printer", json!("Badge")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "custom", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); +} + #[test] fn confirming_after_switching_printers_keeps_the_selected_paper_size() { let jobs = Jobs::default(); From 18b8e7108616ff948899f0e209c5b8a481950c61 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 20:25:00 -0800 Subject: [PATCH 44/50] Docs: the ownKeys invariant check charges code units only for names it looks up For an extensible target whose own properties are all configurable, the check reads each property's descriptor for one unit of fuel and returns before it looks any name up, so it does not charge for code units. The paragraph in docs/mcp.md now says which part of the check charges per key and which part charges per code unit. --- docs/mcp.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 53a267c341..eedc98c89d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2863,7 +2863,9 @@ globals `Proxy`, with `Proxy.revocable`, and `Reflect` (https://262.ecma-interna and 26.2), with string and Symbol property keys. A trap is a script call: it takes fuel and counts against the limit on nested calls. The copy of the property name it is given, key lists retained by enumeration callers, and the names retained during a `for-in` prototype walk count against the heap limit. Each name an `ownKeys` trap returns takes fuel for its -UTF-16 code units, as does each name the proxy invariants check. A trap result that breaks one of the proxy invariants, +UTF-16 code units. The `ownKeys` invariant check takes one unit of fuel for each of the target's own keys. When the +target is non-extensible or has a non-configurable property, the check also looks names up in the trap's result, and +each name it looks up takes fuel for its UTF-16 code units. A trap result that breaks one of the proxy invariants, or any operation on a revoked proxy, throws a `TypeError`. A proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets `Proxy` and `Reflect` at its first ECMAScript 2015 run and keeps them for later `.jsx` runs. From 8c78d72c9f70c79a4c866cc4b55809318b07ed6b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:07:58 -0800 Subject: [PATCH 45/50] Scripts: for-in asks only the proxies that listed a name - A for-in loop now records, for each proxy whose ownKeys trap it called, the positions of the names that proxy returned, and asks a proxy for a name's descriptor only when that proxy listed the name. A proxy that did not list a name no longer hides an inherited one, and the proxy that did is still asked after a prototype change moves it on the chain. The records keep their proxies reachable and count against the heap limit. - The check before each name walks own properties object by object, so a typed array without the element a name gives no longer hides that name on its prototypes. - Function.prototype.apply reads the list's length with ToLength in a run with the ES2015 option, so a negative length gives no arguments; other runs keep ToUint32. - Docs: typeof on a revoked proxy does not throw, and a setPrototypeOf trap that returns true may leave the prototype unchanged. --- crates/js/src/heap.rs | 18 +++- crates/js/src/interp.rs | 172 +++++++++++++++++++++-------------- crates/js/src/proxy_tests.rs | 68 ++++++++++++++ docs/mcp.md | 7 +- docs/target-app-parity.md | 2 +- 5 files changed, 190 insertions(+), 77 deletions(-) diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 236896882b..d69e34fae4 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -215,13 +215,22 @@ pub(crate) struct ArgMap { #[derive(Clone, Debug)] pub(crate) struct ForIn { pub(crate) keys: Vec, - /// For each name, how many proxies came before the object that first listed it on the - /// chain; empty when no name came after a proxy. A missing entry counts as 0. - pub(crate) starts: Vec, + /// The proxies whose `ownKeys` trap returned a listed name, each with the positions in `keys` + /// of the names it returned. + pub(crate) listed: Vec, pub(crate) pos: usize, pub(crate) object: Option, } +/// A proxy on a `for-in` loop's chain and the positions, in ascending order, of the listed names +/// its `ownKeys` trap returned. The loop asks the proxy for a name's descriptor only when the +/// name's position is here. +#[derive(Clone, Debug)] +pub(crate) struct Listed { + pub(crate) proxy: ObjId, + pub(crate) positions: Vec, +} + /// What kind of object it is, with the internal state that kind has. #[derive(Clone)] pub(crate) enum Class { @@ -1182,8 +1191,9 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } Class::ForIn(state) => { work.extend(state.object.iter().map(|o| o.0)); + work.extend(state.listed.iter().map(|l| l.proxy.0)); strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::(); - strings.bytes += state.starts.len() * crate::interp::SOURCE_ENTRY_BYTES; + strings.bytes += crate::interp::listed_bytes(&state.listed); } Class::Symbol(s) => strings.add_symbol(s), Class::IterRecord(r) => { diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 1d9adccef3..5f1f170b8b 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -26,8 +26,8 @@ use crate::ast::BinaryOp; use crate::bytecode::{Code, CodeKind, NamePrefix, Op, Source}; use crate::compiler::{CompileFail, compile_program}; use crate::heap::{ - ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, ModuleExports, NativeKind, OBJECT_BYTES, - OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes, + ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, Listed, ModuleExports, NativeKind, + OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes, }; use crate::parser::SuperRules; use crate::string_builtins::flat_charged; @@ -571,9 +571,17 @@ pub(crate) const MAX_APPLY_ARGS: usize = 1 << 16; /// The estimated bytes of a name's entries in the list and the set `for-in` builds. pub(crate) const KEY_ENTRY_BYTES: usize = 32; -/// The bytes of one entry in the list of proxy counts `for-in` keeps for each name. +/// The bytes of one position in the lists of names `for-in` keeps for each proxy that listed them. pub(crate) const SOURCE_ENTRY_BYTES: usize = std::mem::size_of::(); +/// The bytes of a `for-in` loop's record of one proxy that listed names, without its positions. +const LISTED_ENTRY_BYTES: usize = std::mem::size_of::(); + +/// The bytes of a `for-in` loop's records of the proxies that listed its names. +pub(crate) fn listed_bytes(listed: &[Listed]) -> usize { + listed.iter().map(|l| LISTED_ENTRY_BYTES.saturating_add(l.positions.len().saturating_mul(SOURCE_ENTRY_BYTES))).sum() +} + /// The most units of a computed property name an error about a property of `null` or `undefined` /// names; a longer name is left out of the message. const NAMED_KEY_UNITS: usize = 256; @@ -3324,9 +3332,9 @@ impl Interp { /// For a String object, the heap budget for all its index names is checked before any is /// built. Each index name and each property visited takes a unit of fuel. /// - /// The second list holds, for each name, how many proxies came before the object that - /// listed it. It is empty or shorter than the names when the missing entries are 0. - fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec, Vec)> { + /// The second list holds each proxy whose `ownKeys` trap returned a listed name, with the + /// positions of the names it returned. + fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec, Vec)> { if self.options.e4x && self.is_xml(&Value::Object(id)) { return Ok((self.xml_enumerate(id)?, Vec::new())); } @@ -3341,31 +3349,45 @@ impl Interp { /// `ownKeys` trap and the next object with its `getPrototypeOf` trap. /// `temp_roots[slot]` roots the current proxy through that lookup, then the returned prototype. /// Descriptors are checked when iteration reaches each name. - fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec, Vec)> { - let mut seen = std::collections::HashSet::new(); + fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec, Vec)> { + // Each name met on the chain, with its position in `out` when it is listed. + let mut seen: std::collections::HashMap> = std::collections::HashMap::new(); let mut held = HeldBytes::new(self); - let mut out = Vec::new(); - let mut starts: Vec = Vec::new(); - let mut proxies = 0u32; + let mut out: Vec = Vec::new(); + let mut listed: Vec = Vec::new(); + let next_pos = |out: &Vec| u32::try_from(out.len()).unwrap_or(u32::MAX); let mut cur = Some(id); while let Some(o) = cur { - let before = out.len(); if self.is_proxy(o) { if let Some(root) = self.temp_roots.get_mut(slot) { *root = Value::Object(o); } let keys = self.own_keys(o)?; + let mut positions = Vec::new(); for k in keys { self.use_fuel()?; - if seen.contains(&k) { - continue; + let pos = match seen.get(&k) { + Some(pos) => *pos, + None => { + held.add(self, string_bytes(k.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; + let pos = next_pos(&out); + seen.insert(k.clone(), Some(pos)); + out.push(k); + Some(pos) + } + }; + // A name an earlier object has but does not list is not listed again. + if let Some(pos) = pos { + held.add(self, SOURCE_ENTRY_BYTES)?; + positions.push(pos); } - held.add(self, string_bytes(k.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; - seen.insert(k.clone()); - out.push(k); } - self.note_listed(&mut starts, &mut held, before, out.len(), proxies)?; - proxies = proxies.saturating_add(1); + if !positions.is_empty() { + held.add(self, LISTED_ENTRY_BYTES)?; + positions.sort_unstable(); + positions.dedup(); + listed.push(Listed { proxy: o, positions }); + } cur = self.get_prototype_of(o)?; if let Some(root) = self.temp_roots.get_mut(slot) { *root = cur.map_or(Value::Undefined, Value::Object); @@ -3384,16 +3406,16 @@ impl Interp { for i in 0..len { self.use_fuel()?; let k = index_key(u32::try_from(i).unwrap_or(u32::MAX)); - if !seen.contains(&k) { + if !seen.contains_key(&k) { held.add(self, string_bytes(k.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; - seen.insert(k.clone()); + seen.insert(k.clone(), Some(next_pos(&out))); out.push(k); } } } - if is_array && !seen.contains(&key("length")) { + if is_array && !seen.contains_key(&key("length")) { held.add(self, string_bytes(6) + KEY_ENTRY_BYTES)?; - seen.insert(key("length")); + seen.insert(key("length"), None); } for _ in 0..self.object(o)?.props.len() { self.use_fuel()?; @@ -3402,37 +3424,27 @@ impl Interp { .object(o)? .props .iter() - .filter(|(k, _)| !seen.contains(*k)) + .filter(|(k, _)| !seen.contains_key(*k)) .fold(0usize, |bytes, (k, _)| bytes.saturating_add(string_bytes(k.len()) + 2 * KEY_ENTRY_BYTES)); held.add(self, retained)?; let obj = self.object(o)?; for (k, p) in obj.props.iter() { - if seen.insert(k.clone()) && p.enumerable() { - out.push(k.clone()); + if !seen.contains_key(k) { + let pos = p.enumerable().then(|| next_pos(&out)); + seen.insert(k.clone(), pos); + if pos.is_some() { + out.push(k.clone()); + } } } cur = obj.proto; - self.note_listed(&mut starts, &mut held, before, out.len(), proxies)?; } - Ok((out, starts)) - } - - /// Records that the names from `before` to `len` came after `proxies` proxies, counting - /// the new entries. Nothing is recorded when `proxies` is 0 or no name was added, since a - /// missing entry counts as 0. - fn note_listed(&mut self, starts: &mut Vec, held: &mut HeldBytes, before: usize, len: usize, proxies: u32) -> JsResult<()> { - if proxies == 0 || len == before { - return Ok(()); - } - held.add(self, len.saturating_sub(starts.len()).saturating_mul(SOURCE_ENTRY_BYTES))?; - starts.resize(before, 0); - starts.resize(len, proxies); - Ok(()) + Ok((out, listed)) } fn op_for_in_start(&mut self) -> JsResult<()> { let v = self.peek(0)?; - let ((keys, starts), object) = if v.is_nullish() { + let ((keys, listed), object) = if v.is_nullish() { ((Vec::new(), Vec::new()), None) } else { let o = self.to_object(&v)?; @@ -3442,16 +3454,16 @@ impl Interp { self.temp_roots.push(Value::Object(o)); // Listing a namespace object's exports does not read them (ECMA-262 2015 section // 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed. - let keys = self.enumerable_keys(o).and_then(|(keys, starts)| { - let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::() + starts.len() * SOURCE_ENTRY_BYTES; + let keys = self.enumerable_keys(o).and_then(|(keys, listed)| { + let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::() + listed_bytes(&listed); self.reserve_heap(bytes)?; self.heap.bytes = self.heap.bytes.saturating_add(bytes); - Ok((keys, starts)) + Ok((keys, listed)) }); self.temp_roots.truncate(saved); (keys?, Some(o)) }; - let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, starts, pos: 0, object })), None)); + let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, listed, pos: 0, object })), None)); self.replace(1, Value::Object(iter)) } @@ -3460,11 +3472,12 @@ impl Interp { loop { let Class::ForIn(state) = &mut self.object_mut(iter)?.class else { return internal("not a for-in iterator") }; let Some(k) = state.keys.get(state.pos).cloned() else { return self.jump_to(target) }; - let skip = state.starts.get(state.pos).copied().unwrap_or(0); + let pos = u32::try_from(state.pos).unwrap_or(u32::MAX); state.pos += 1; let object = state.object; let Some(o) = object else { continue }; - let visit = if self.options.e4x && self.is_xml(&Value::Object(o)) { self.scope_has(o, &k)? } else { self.for_in_still_has(o, &k, skip)? }; + let visit = + if self.options.e4x && self.is_xml(&Value::Object(o)) { self.scope_has(o, &k)? } else { self.for_in_still_has(iter, o, &k, pos)? }; if visit { return self.push(Value::String(Str::from_rc(k))); } @@ -3478,40 +3491,58 @@ impl Interp { /// names were listed is skipped, on an ordinary object as on a proxy. A proxy's `has` trap is /// not asked. Each proxy on the chain takes a unit of fuel. /// - /// `skip` is how many proxies came before the object that first listed `k`. Those proxies - /// did not list `k`, so the first `skip` proxies the walk reaches are not asked through - /// their `getOwnPropertyDescriptor` trap and cannot hide an inherited name. - fn for_in_still_has(&mut self, o: ObjId, k: &Key, skip: u32) -> JsResult { - // One root slot holds the prototype the walk has reached; each hop replaces it. + /// `pos` is the position of `k` in the names of the loop `iter`. A proxy is asked through its + /// `getOwnPropertyDescriptor` trap only when its `ownKeys` trap returned `k` while the names + /// were listed, wherever it sits on the chain now; any other proxy cannot hide an inherited + /// name. A typed array without the element `k` names does not hide its prototypes' `k`. + fn for_in_still_has(&mut self, iter: ObjId, o: ObjId, k: &Key, pos: u32) -> JsResult { + // One root slot holds the proxy the walk has reached, then the prototype it gave. let mark = self.temp_roots.len(); self.temp_roots.push(Value::Undefined); - let r = self.for_in_still_has_rooted(o, k, skip, mark); + let r = self.for_in_still_has_rooted(iter, o, k, pos, mark); self.temp_roots.truncate(mark); r } - fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &Key, skip: u32, slot: usize) -> JsResult { - let mut passed = 0u32; + fn for_in_still_has_rooted(&mut self, iter: ObjId, mut cur: ObjId, k: &Key, pos: u32, slot: usize) -> JsResult { + let mut steps = 0usize; loop { - let p = match self.lookup(cur, k)? { - Lookup::Found(prop) => return Ok(prop.enumerable()), - Lookup::Missing => return Ok(false), - Lookup::Proxy(p) => p, - }; - self.use_fuel()?; - let asked = passed >= skip; - passed = passed.saturating_add(1); - if asked && let Some(prop) = self.get_own_property(p, k)? { + if self.is_proxy(cur) { + if let Some(root) = self.temp_roots.get_mut(slot) { + *root = Value::Object(cur); + } + self.use_fuel()?; + if self.for_in_listed_by(iter, cur, pos)? + && let Some(prop) = self.get_own_property(cur, k)? + { + return Ok(prop.enumerable()); + } + let Some(next) = self.get_prototype_of(cur)? else { return Ok(false) }; + if let Some(root) = self.temp_roots.get_mut(slot) { + *root = Value::Object(next); + } + cur = next; + continue; + } + if let Some(prop) = self.ordinary_own_property(cur, k)? { return Ok(prop.enumerable()); } - let Some(next) = self.get_prototype_of(p)? else { return Ok(false) }; - if let Some(root) = self.temp_roots.get_mut(slot) { - *root = Value::Object(next); + let Some(next) = self.object(cur)?.proto else { return Ok(false) }; + steps += 1; + if steps > 1_000_000 { + return internal("prototype chain too long"); } cur = next; } } + /// Whether the `ownKeys` trap of `proxy` returned the name at `pos` when the loop `iter` + /// listed its names. + fn for_in_listed_by(&self, iter: ObjId, proxy: ObjId, pos: u32) -> JsResult { + let Class::ForIn(state) = &self.object(iter)?.class else { return internal("not a for-in iterator") }; + Ok(state.listed.iter().any(|l| l.proxy == proxy && l.positions.binary_search(&pos).is_ok())) + } + // ---- calls ---- pub(crate) fn is_callable(&self, v: &Value) -> bool { @@ -3634,9 +3665,10 @@ impl Interp { } /// The elements of an array-like `apply` argument (section 15.3.4.3), its length read with - /// ToUint32. + /// ToUint32, or with ToLength in a run with [`crate::Options::es2015`] (ECMA-262 2015 sections + /// 19.2.3.1 and 7.3.17), where a negative length gives no elements. fn list_from_array_like(&mut self, list: &Value) -> JsResult> { - self.array_like_list(list, false) + self.array_like_list(list, self.options.es2015) } /// CreateListFromArrayLike (ECMA-262 2020 section 7.3.17) for `Reflect.apply` and diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index dec2f794d0..0bbe6e0b02 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -1816,6 +1816,74 @@ fn for_in_over_a_proxy_visits_an_inherited_name_the_proxy_did_not_list() { ); } +#[test] +fn for_in_asks_only_the_proxies_that_listed_a_name() { + // `a` lists `x` and has no descriptor for it; `b` did not list `x`, so its descriptor does + // not hide `c`'s. + let chain = |a_desc: &str| { + format!( + "var c = {{ x: 1 }}; + var b = new Proxy({{}}, {{ + ownKeys: function () {{ return []; }}, + getOwnPropertyDescriptor: function () {{ return {{ value: 0, enumerable: false, configurable: true }}; }}, + getPrototypeOf: function () {{ return c; }} + }}); + var a = new Proxy({{}}, {{ + ownKeys: function () {{ return ['x']; }}, + getOwnPropertyDescriptor: function () {{ return {a_desc}; }}, + getPrototypeOf: function () {{ return b; }} + }}); + var seen = []; + for (var name in a) seen.push(name);" + ) + }; + truth(&format!("{} seen.join() === 'x'", chain("undefined"))); + // A non-enumerable descriptor from the proxy that listed `x` still hides `c`'s. + truth(&format!("{} seen.join() === ''", chain("{ value: 0, enumerable: false, configurable: true }"))); + // The proxy that listed `y` is asked after a prototype change moves it nearer the start. + truth( + "var b = new Proxy({}, { + ownKeys: function () { return ['x', 'y']; }, + getOwnPropertyDescriptor: function () { return { value: 1, enumerable: true, configurable: true }; } + }); + var a = new Proxy({}, { ownKeys: function () { return []; }, getPrototypeOf: function () { return b; } }); + var o = Object.create(a); + var seen = []; + for (var name in o) { seen.push(name); if (name === 'x') Object.setPrototypeOf(o, b); } + seen.join() === 'x,y'", + ); +} + +#[test] +fn for_in_reaches_a_name_past_a_typed_array_without_that_element() { + truth( + "var ta = new Uint8Array(1); + Object.setPrototypeOf(ta, { 2: 'x' }); + var seen = []; + for (var name in ta) seen.push(name); + var p = new Proxy({}, { ownKeys: function () { return []; }, getPrototypeOf: function () { return ta; } }); + var viaProxy = []; + for (var name in p) viaProxy.push(name); + seen.join() === '0,2' && viaProxy.join() === '0,2'", + ); +} + +#[test] +fn apply_reads_the_list_length_with_to_length_in_es2015() { + truth( + "function count() { return arguments.length; } + var p = new Proxy(count, {}); + count.apply(null, { length: -1 }) === 0 && p.apply(null, { length: -1 }) === 0 && count.apply(null, null) === 0 + && count.apply(null, { length: 2.5 }) === 2", + ); + // Without the option the length is read with ToUint32, so -1 is too many arguments. + let legacy = Realm::with_options(Options::default(), Limits::default()).run( + "function count() { return arguments.length; } + (function () { try { count.apply(null, { length: -1 }); } catch (e) { return e instanceof RangeError; } return false; })()", + ); + assert_eq!(legacy, Ok(JsValue::Bool(true))); +} + #[test] fn a_subclassable_built_in_does_not_unwrap_a_revoked_new_target() { truth( diff --git a/docs/mcp.md b/docs/mcp.md index 0c01c449f2..45c12b571c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2872,7 +2872,9 @@ a `for-in` prototype walk count against the heap limit. Each name an `ownKeys` t UTF-16 code units. The `ownKeys` invariant check takes one unit of fuel for each of the target's own keys. When the target is non-extensible or has a non-configurable property, the check also looks names up in the trap's result, and each name it looks up takes fuel for its UTF-16 code units. A trap result that breaks one of the proxy invariants, -or any operation on a revoked proxy, throws a `TypeError`. A +or an operation that uses a revoked proxy's internal methods (reading, writing or deleting a property, `in`, `Object.keys`, +a call or `new`), throws a `TypeError`. `typeof` on a revoked proxy does not throw: it gives `"function"` or +`"object"` as it did before the proxy was revoked. A proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets `Proxy` and `Reflect` at its first ECMAScript 2015 run and keeps them for later `.jsx` runs. A `.jsx` script or a `source` string run as a script has neither global in a fresh engine. @@ -2922,7 +2924,8 @@ the same key twice (two Symbols are the same key only when they are the same Sym result is checked against the target's non-configurable keys of both kinds. A `for-in` prototype walk keeps the current proxy reachable through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from the receiver's prototype chain. A `for-in` loop checks each proxy candidate's descriptor -when iteration reaches that name. An `ownKeys` result is read and its elements are validated before duplicate +when iteration reaches that name, and asks only the proxies whose `ownKeys` trap returned the name, wherever they sit +on the chain then; a typed array without the element a name gives does not hide that name on its prototypes. An `ownKeys` result is read and its elements are validated before duplicate names are rejected; a later getter's exception takes precedence over the duplicate-name error. Deleting a binding in a `with` scope calls the proxy's `deleteProperty` trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 68c2b10d59..b92f36889e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1205,7 +1205,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - - A realm made with `Options::es2015` also has `Object.setPrototypeOf(o, proto)` (ECMA-262 2015 section 19.1.2.18, https://262.ecma-international.org/6.0/#sec-object.setprototypeof), which returns `o` with `proto` as its prototype. `undefined` or `null` for `o`, a `proto` that is neither an object nor `null`, a non-extensible object given a different prototype, and a prototype whose chain leads back to the object are `TypeError`s; any other primitive `o` is returned unchanged. `Object.prototype` keeps its `null` prototype, as later editions give it (https://262.ecma-international.org/11.0/#sec-immutable-prototype-exotic-objects). For a proxy it calls the handler's `setPrototypeOf` trap, or sets the target's prototype when the handler has none, and a `false` result, a revoked proxy and a trap that breaks the invariant of section 9.5.2 are `TypeError`s. It uses the same [[SetPrototypeOf]] as `Reflect.setPrototypeOf`, so the cycle check stops at a proxy in the chain and each prototype it passes takes fuel. A realm made without the option has no `Object.setPrototypeOf`. Tests: `crates/js/src/es2015_object_tests.rs`. + - A realm made with `Options::es2015` also has `Object.setPrototypeOf(o, proto)` (ECMA-262 2015 section 19.1.2.18, https://262.ecma-international.org/6.0/#sec-object.setprototypeof), which returns `o` with `proto` as its prototype. `undefined` or `null` for `o`, a `proto` that is neither an object nor `null`, a non-extensible object given a different prototype, and a prototype whose chain leads back to the object are `TypeError`s; any other primitive `o` is returned unchanged. `Object.prototype` keeps its `null` prototype, as later editions give it (https://262.ecma-international.org/11.0/#sec-immutable-prototype-exotic-objects). For a proxy it calls the handler's `setPrototypeOf` trap, or sets the target's prototype when the handler has none, and a `false` result, a revoked proxy and a trap that breaks the invariant of section 9.5.2 are `TypeError`s. When the trap returns `true`, the call returns the proxy, and the proxy's prototype is whatever the trap left, which may be unchanged for an extensible target. It uses the same [[SetPrototypeOf]] as `Reflect.setPrototypeOf`, so the cycle check stops at a proxy in the chain and each prototype it passes takes fuel. A realm made without the option has no `Object.setPrototypeOf`. Tests: `crates/js/src/es2015_object_tests.rs`. - With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals (with a computed name too), `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function, a generator method included, has a `prototype` and is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 1,285 of 1,289 runs of 669 tests pass. The 4 others expect the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. From 8fa6a542077a803d45560050d99000ea47997cf9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:10:19 -0800 Subject: [PATCH 46/50] Print: a paper keeps its size while a printer is looked up and in a new preset While the newly chosen printer's driver has not answered, the Size list keeps the previous printer's sizes, so a printer paper stays chosen at its size. It becomes Custom only when the answer lists it at another size or not at all. A preset created in the same pass as a printer paper is chosen now saves that paper's Width and Height, the size the dialog shows, instead of the size before it. --- crates/ui-egui/src/dialogs/print.rs | 16 ++++-- crates/ui-egui/src/dialogs/tests_print.rs | 65 +++++++++++++++++++++++ 2 files changed, 77 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 314e2bc032..8ec1176cfa 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -112,7 +112,8 @@ struct Open { preview: Option<(Stamp, Arc>)>, /// The printer row's driver controls, as the dialog was last given them. driver: DriverControls, - /// The printer the Media list was made for, and the paper sizes its driver offers. + /// The printer the Media list was made for, and the paper sizes its driver offers (while its lookup runs, the sizes + /// of the printer before it). papers: (String, Vec), /// Whether the chosen printer still has a lookup running. papers_pending: bool, @@ -498,8 +499,13 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, answer.fields.set("media", Media::Custom.id()); } let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed); - papers_changed = printer_changed || !pending; - open.papers = (d.printer.clone(), papers); + // While the new printer's lookup runs, the Size list keeps the sizes before it, so the paper chosen keeps its + // name and size until the driver answers. + papers_changed = !pending; + open.papers.0 = d.printer.clone(); + if !pending { + open.papers.1 = papers; + } open.papers_pending = pending; } if open.papers_pending { @@ -654,7 +660,9 @@ fn apply_preset_event(app: &mut VectorcraftApp, dialogs: &WindowDialogs, open: & } } NamedPresetEvent::Create { name, .. } => { - match app.run("print.presets.save", json!({ "name": name, "preset": DEFAULT_PRESET, "settings": settings })) { + // A printer's paper chosen this pass is saved at its size, which the dialog shows once the pump has run. + let saved = on(dialogs, |p| settings_with_paper(p.fields(), &open.papers.1)).unwrap_or_else(|| settings.clone()); + match app.run("print.presets.save", json!({ "name": name, "preset": DEFAULT_PRESET, "settings": saved })) { Ok(r) => open.preset = r["name"].as_str().unwrap_or(&name).to_string(), Err(e) => app.status(e), } diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 10ec8a5a70..f325276084 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -444,6 +444,71 @@ fn a_paper_keyword_another_printer_lists_at_another_size_becomes_a_custom_size() assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); } +/// Card lists a CR80 card; Twin's driver answers with the same CR80 once `ready` is set. +struct PendingTwin(Rc>); + +impl PrintService for PendingTwin { + fn printers(&mut self) -> Vec { + vec![Printer::new("Card").is_default(true), Printer::new("Twin")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + if printer == "Twin" && !self.0.get() { Papers::Pending } else { CardPrinters.papers(printer, fresh) } + } +} + +#[test] +fn a_paper_stays_chosen_while_the_new_printer_looks_up_its_sizes() { + let ready = Rc::new(Cell::new(false)); + let services = Services { print: Some(Box::new(PendingTwin(ready.clone()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + set(&mut app, "printer", json!("Twin")); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:CR80", "Twin's driver has not answered yet: {f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); + // Twin lists the same CR80, so it stays chosen. + ready.set(true); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:CR80", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); +} + +#[test] +fn a_preset_saved_as_a_printer_paper_is_chosen_keeps_its_size() { + let services = Services { print: Some(Box::new(PaperPrint(Jobs::default(), Asked::default()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + press(&mut app, "New…"); + pump(&mut app); + call(&mut app, "ui.text", json!({"text": "Cards"})); + // The card is chosen in the frame the name is confirmed, before Width and Height take its size. + let ctx = ctx(&app); + let (enter, _reply) = craft::automation::ControlRequest::new("ui.key", json!({"key": "Enter"})); + let _ = crate::control::handle(&mut app, &ctx, &enter); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + pump(&mut app); + let saved = app.session.prefs.print_presets.iter().find(|p| p.name == "Cards").expect("the preset was saved").settings.clone(); + assert_eq!((saved.media, saved.width, saved.height), (vectorcraft_pdf::Media::Custom, 153.0, 243.0)); +} + #[test] fn confirming_after_switching_printers_keeps_the_selected_paper_size() { let jobs = Jobs::default(); From e5df2445e39b00d9ee2fcccda695405554719efc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:31:56 -0800 Subject: [PATCH 47/50] Scripts: new IllustratorSaveOptions reads compatibility as ILLUSTRATOR19 A new IllustratorSaveOptions left compatibility unset, so a script that read it before setting it got undefined. It now starts at Compatibility.ILLUSTRATOR19, the documented default, which saveAs already accepts without changing what it writes. --- crates/engine/src/script/dom/save_open.rs | 7 ++++++- crates/engine/src/tests/script_save_open.rs | 22 +++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index fd933f7d60..237576b64d 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -366,7 +366,12 @@ const AI_KEPT: &[(&str, Default)] = &[ ]; fn ai_starts() -> Vec<(&'static str, Data)> { - vec![("compressed", Data::Bool(true)), ("pdfCompatible", Data::Bool(true)), ("embedICCProfile", Data::Bool(false))] + vec![ + ("compatibility", text("Compatibility.ILLUSTRATOR19")), + ("compressed", Data::Bool(true)), + ("pdfCompatible", Data::Bool(true)), + ("embedICCProfile", Data::Bool(false)), + ] } fn eps_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 12db366846..04cfbeb2fc 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -212,6 +212,28 @@ fn omitted_options_are_a_new_options_objects_defaults() { let _ = std::fs::remove_dir_all(base); } +/// A new `IllustratorSaveOptions` reads `compatibility` as its default, ILLUSTRATOR19, and saves +/// with it untouched. +#[test] +fn illustrator_save_options_start_at_illustrator19_compatibility() { + let base = folder("aicompat"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new IllustratorSaveOptions(); vc.log(o.compatibility);\ + app.activeDocument.saveAs(new File({}), o);", + quoted(&dir.join("a.ai")) + ), + ); + assert_eq!(out[0], json!("Compatibility.ILLUSTRATOR19")); + assert!(dir.join("a.ai").is_file()); + let _ = std::fs::remove_dir_all(base); +} + /// A path that resolves to a name that is not valid UTF-8 is refused before anything is written or /// opened, so no file with a lossy copy of the name is touched. #[cfg(unix)] From d54e2cf55b2a8d6497ec0e0efe1d90e520b4b9b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 22:04:15 -0800 Subject: [PATCH 48/50] Print: a kept paper the new printer lists at a built-in size becomes that size When the new printer listed the chosen paper at a size within half a point of one of the dialog's own papers, the Size row kept the `printer:` choice, but the new Size list offers that paper under the built-in id instead. The row then held a choice the list did not contain, and the list was rebuilt and repainted on every frame. The row now switches to the built-in paper the list offers. --- crates/ui-egui/src/dialogs/print.rs | 17 +++++++---- crates/ui-egui/src/dialogs/tests_print.rs | 36 +++++++++++++++++++++++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 8ec1176cfa..6546b2ff5b 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -512,24 +512,29 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, ctx.request_repaint(); } // A paper the new printer doesn't list, or lists under the same keyword at another size, becomes a custom size of - // the same Width and Height. + // the same Width and Height. One the new printer lists at the size of one of the dialog's own papers becomes that + // paper, the choice the new list offers for it. if papers_changed && media.starts_with(PRINTER_PAPER) - && let Some(s) = on(dialogs, |p| { + && let Some((id, s)) = on(dialogs, |p| { let fields = p.fields_mut(); - if printer_paper(fields, &open.papers.1).is_some_and(|new| chosen.as_ref().is_none_or(|old| same_size(old, new))) { - return None; + if let Some(new) = printer_paper(fields, &open.papers.1) + && chosen.as_ref().is_none_or(|old| same_size(old, new)) + { + let own = own_media_of(new)?; + fields.set("media", own.id()); + return Some((own.id().to_string(), settings(fields))); } if let Some(paper) = &chosen { fields.set("width", paper.width); fields.set("height", paper.height); } fields.set("media", Media::Custom.id()); - Some(settings(fields)) + Some((Media::Custom.id().to_string(), settings(fields))) }) .flatten() { - media = Media::Custom.id().to_string(); + media = id; d.settings = s; } if papers_changed || (!media.is_empty() && !open.media.contains(&media)) { diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index f325276084..d2ebf74122 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -444,6 +444,42 @@ fn a_paper_keyword_another_printer_lists_at_another_size_becomes_a_custom_size() assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); } +/// Two printers list a paper named Wide: Near at 611.2 × 792 points, Far at 611.6 × 792, within half a point of Letter. +struct NearLetter; + +impl PrintService for NearLetter { + fn printers(&mut self) -> Vec { + vec![Printer::new("Near").is_default(true), Printer::new("Far")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { + let width = if printer == "Far" { 611.6 } else { 611.2 }; + Papers::Ready(vec![crate::print::Paper { key: "Wide".into(), label: "Wide".into(), width, height: 792.0 }]) + } +} + +#[test] +fn a_kept_paper_the_new_printer_lists_at_a_built_in_size_becomes_that_size() { + let services = Services { print: Some(Box::new(NearLetter)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!("printer:Wide")); + pump(&mut app); + // Far's Wide is within half a point of Near's and of Letter, and its Size list offers it as Letter. + set(&mut app, "printer", json!("Far")); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "letter", "{f}"); + assert!(try_set(&mut app, "media", json!("printer:Wide")).is_err(), "the Size list offers Letter in its place"); +} + /// Card lists a CR80 card; Twin's driver answers with the same CR80 once `ready` is set. struct PendingTwin(Rc>); From 8b8e2467137bbe9171bed5043e96c13a9caa1784 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:58:32 -0800 Subject: [PATCH 49/50] xtask: test-lint keeps the route, suffix and census refinements main lacks - never-run: in changed mode, a file that a crate target loaded at the base and no target loads now counts as compiled out, so removing the last `mod` or `#[path]` declaration on the way to it, or deleting the only target root that loads it, fails the check for its tests. - reads-source: an `ends_with(".rs")` check counts only when it picks entries from a file listing (an iterator filter or a `for` loop over one), or when the function around it reads a file or calls a function in the file that does. A suffix check on a generated name in a test that reads nothing is not reported. - census: a helper on the left of an `||` hides the whole-table check on the right only when it always runs: not behind an `&&`, and not inside one arm of an `if` or `match`. - docs: unchanged-line `never-run` hits fail the command when the change takes away a test's last CI route. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 330 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 323 insertions(+), 9 deletions(-) diff --git a/docs/development.md b/docs/development.md index 4244e28738..cd047d8810 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it, except a `never-run` test in an unchanged file whose last CI route the change takes away: a changed `mod` declaration or `cfg` in a file that loads it, or a removed `mod` or `#[path]` declaration that was the last one loading it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 449885209f..51d7132b4d 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -38,8 +38,10 @@ //! reads do not; //! * `sleep`: `thread::sleep` in test code, or a bare `sleep(…)` in a file that imports it; //! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, -//! `read_to_string` of a path with a `.rs` literal, or a walk that keeps files ending in `.rs`), -//! outside the source audits in [`SOURCE_AUDITS`]; +//! `read_to_string` of a path with a `.rs` literal, or a `.ends_with(".rs")` check that selects +//! files from a listing, is in a function that reads a file or stream, or is in a function that +//! calls a function defined in the file whose body reads one, regardless of the receiver or +//! arguments), outside the source audits in [`SOURCE_AUDITS`]; //! * `census`: a test that loops over a whole table (a `SCREAMING_CASE` constant, `Type::ALL`, //! `Type::iter()`, or a call named `all`, `catalog`, `registry`, `presets`, `swatches`, //! `entries`, `variants`, `commands`, `builtins` or `palette`, or ending or starting with one of @@ -342,7 +344,13 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { descendants(&seeds, &files, &overrides, &base_overrides, &read_work, &read_base).into_iter().filter(|p| !changed.contains_key(p)).collect(); let gated: Vec = present.iter().chain(&below).cloned().collect(); let gates = module_gates(&gated, &read_work, &overrides); - let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); + let mut module_cfgs: HashMap> = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); + // A file that a crate target loaded at the base and no longer loads is compiled out: `any()` + // holds on no target. + let lost = lost_routes(&gated, &read_work, &overrides, &read_base, &base_overrides); + for path in lost.keys() { + module_cfgs.insert(path.clone(), vec!["any()".to_owned()]); + } let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; // The gates the parent declarations gave at the base: a parent edit counts against a child's // test only when the test ran in CI before it. @@ -361,9 +369,13 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { }); !already_off(off, base_src, src, hit) }; + let route_changed = |path: &str| { + route_gate_changed(path, gates.get(path), base_gates.get(path), &base_overrides, &changed) + || lost.get(path).is_some_and(|parents| parents.iter().any(|p| changed.contains_key(p))) + }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { - let parent_changed = route_gate_changed(&path, gates.get(&path), base_gates.get(&path), &base_overrides, &changed); + let parent_changed = route_changed(&path); for hit in lint_file(&path, &src, &ctx) { if touches(&hit, changed.get(&path).and_then(Option::as_ref)) || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) @@ -374,7 +386,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } } } - for path in below.iter().filter(|p| route_gate_changed(p, gates.get(*p), base_gates.get(*p), &base_overrides, &changed)) { + for path in below.iter().filter(|p| route_changed(p)) { let Some(src) = read_work(path) else { continue }; counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); } @@ -1654,7 +1666,7 @@ fn census(v: &View, helpers: &HashSet) -> Vec { /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions /// nested deeper than 64 operators are not judged. An operand that calls one of `helpers` (asserting /// helpers called in the condition) is not a presence check, and a weak right side of an `||` does -/// not count when the left side calls one, since the left side always runs. +/// not count when the left side always calls one ([`always_calls`]). fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool) { let or = top_level_at(cond, "||").first().copied(); if depth > 64 || !cond.contains(".all(") { @@ -1670,7 +1682,7 @@ fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool } }; let (l, r) = (side(&cond[..at]), side(&cond[at + 2..])); - let r = if or.is_some() && (calls_any(&cond[..at], helpers) || rejects(&cond.as_bytes()[..at])) { (false, false) } else { r }; + let r = if or.is_some() && (always_calls(&cond[..at], helpers, depth) || rejects(&cond.as_bytes()[..at])) { (false, false) } else { r }; if or.is_none() { (l.0 && r.0, l.1 || r.1) } else if l == (true, true) || r == (true, true) { @@ -1684,6 +1696,53 @@ fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool } } +/// Whether evaluating the (whitespace-free) condition `s` always calls one of `helpers`: a call +/// behind a top-level `&&` or `||` runs only on one outcome of the operand before it, so only the +/// first operand of either counts. +fn always_calls(s: &str, helpers: &[String], depth: usize) -> bool { + if depth > 64 { + false + } else if s.starts_with('(') && matching(s.as_bytes(), 0) == Some(s.len() - 1) { + always_calls(&s[1..s.len() - 1], helpers, depth + 1) + } else if let Some(at) = top_level_at(s, "||").first().copied().or_else(|| top_level_at(s, "&&").first().copied()) { + always_calls(&s[..at], helpers, depth + 1) + } else if let Some(&at) = top_level_at(s, "{").first() + && let Some(cond) = s[..at].strip_prefix("if").or_else(|| s[..at].strip_prefix("match")) + { + // An `if` or `match` always runs only its condition or scrutinee, the text before its + // first block; a call inside one arm may be skipped. Without whitespace the keyword runs + // into the condition (`ifverify()`); the text before the block is also checked whole, for + // a name that only starts with the keyword. + always_calls(cond, helpers, depth + 1) || always_calls(&s[..at], helpers, depth + 1) + } else if s.starts_with('{') && matching(s.as_bytes(), 0) == Some(s.len() - 1) { + // A plain block runs each of its statements in order. + block_statements(&s[1..s.len() - 1]).into_iter().any(|st| always_calls(st, helpers, depth + 1)) + } else { + calls_any(s, helpers) + } +} + +/// The statements of a (whitespace-free) block body: split at each top-level `;` and after each +/// top-level `}` that no `else` follows (`if a{x();}y();` is two statements). +fn block_statements(body: &str) -> Vec<&str> { + let b = body.as_bytes(); + let (mut out, mut depth, mut start) = (vec![], 0i32, 0); + for (i, &c) in b.iter().enumerate() { + match c { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + _ => {} + } + let end = depth == 0 && (c == b';' || c == b'}' && !body[i + 1..].starts_with("else")); + if end { + out.push(&body[start..=i]); + start = i + 1; + } + } + out.push(&body[start..]); + out.into_iter().filter(|s| !s.is_empty()).collect() +} + /// Whether `s` calls a function or method named in `names`, with or without a turbofish. fn calls_any(s: &str, names: &[String]) -> bool { names.iter().any(|n| { @@ -3206,7 +3265,10 @@ fn reads_source_hits(file: &File) -> Vec { let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); let rs = match word { - b"ends_with" => literal == "\".rs\"", + // A suffix check alone may test a generated name; it counts when it selects files + // from a listing, its function reads a file or stream, or its function calls a + // function defined in this file whose body reads one, with any arguments. + b"ends_with" => literal == "\".rs\"" && (selects(m, at) || reads_checked(file, at)), // The final path step names the file read: the last literal of `root.join("src/lib.rs")` // or `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`; the // extension of a final `.with_extension("json")`. A final step whose argument is not a @@ -3237,6 +3299,112 @@ fn reads_source_hits(file: &File) -> Vec { out } +/// Words that name a file listing in an iterator chain or a loop source. +const LISTINGS: &[&str] = &["read_dir", "files", "listing", "walk", "walkdir", "glob", "entries", "paths", "sources"]; + +/// Whether `text` names a listing ([`LISTINGS`]), as a whole word or as the end of one (`rust_files`). +fn names_listing(text: &str) -> bool { + text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(|w| LISTINGS.iter().any(|l| w == *l || w.ends_with(&format!("_{l}")))) +} + +/// Whether the call at `at` picks entries out of a listing: it sits in the closure of a `filter`, +/// `filter_map`, `find`, `any`, `all`, `position` or `retain` call on an iterator whose chain names +/// a listing (`read_dir`, `files`, `listing`, `walk` and the like), or in the body of a `for` loop +/// over one. +fn selects(m: &[u8], at: usize) -> bool { + const PICKS: &[&[u8]] = &[b"filter", b"filter_map", b"find", b"find_map", b"any", b"all", b"position", b"retain"]; + let in_loop = words(m, b"for", 0, at).into_iter().any(|f| { + let Some(&kw) = words(m, b"in", f, at).first() else { return false }; + loop_open(m, kw + 2, at) + .is_some_and(|open| matching(m, open).is_none_or(|close| close > at) && names_listing(&String::from_utf8_lossy(&m[kw + 2..open]))) + }); + // The parentheses that enclose `at`, innermost first. + let mut depth = 0usize; + let mut enclosing = m[..at].iter().enumerate().rev().filter_map(move |(i, &c)| match c { + b')' => { + depth += 1; + None + } + b'(' if depth > 0 => { + depth -= 1; + None + } + b'(' => Some(i), + _ => None, + }); + in_loop + || enclosing.any(|open| { + let head = m[..open].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + if !PICKS.contains(&&head[head.len() - name..]) { + return false; + } + // The receiver chain: back from the pick to the start of its statement. + let start = head[..head.len() - name].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}' | b'=')).map_or(0, |p| p + 1); + names_listing(&String::from_utf8_lossy(&head[start..head.len() - name])) + }) +} + +/// File and stream reading calls, including directory listings and file opens. +const READS: &[&[u8]] = &[b"read_to_string", b"read_to_end", b"read_dir", b"include_str", b"read", b"open"]; + +/// The argument spans `(open, close)` of the reading calls anywhere in the file. +fn read_calls(file: &File) -> Vec<(usize, usize)> { + let m = &file.m; + let mut out = vec![]; + for w in READS { + for p in words(m, w, 0, m.len()) { + // `fn read(…)` declares a function; it does not read. + if (*w == b"open" && !norm(&m[..p]).ends_with("File::")) || m[..p].trim_ascii_end().ends_with(b"fn") { + continue; + } + let next = skip_ws(m, p + w.len()); + let next = if m.get(next) == Some(&b'!') { skip_ws(m, next + 1) } else { skip_ws(m, skip_turbofish(m, next)) }; + if m.get(next) == Some(&b'(') + && let Some(close) = matching(m, next) + { + out.push((next, close)); + } + } + } + out +} + +/// Whether the function containing the `.ends_with` check reads a file or stream, or calls a +/// function defined in this file whose body reads one, regardless of the receiver or arguments. +fn reads_checked(file: &File, at: usize) -> bool { + let m = &file.m; + let reads = read_calls(file); + // The function around the check (the test, or a helper). + let scope = words(m, b"fn", 0, at) + .into_iter() + .rev() + .find_map(|f| { + let body = f + m[f..at].iter().position(|&c| c == b'{')?; + matching(m, body).filter(|&end| end > at).map(|end| (body, end)) + }) + .or_else(|| file.regions.iter().copied().find(|&(from, to)| from <= at && at < to)); + let Some((from, to)) = scope else { return false }; + if reads.iter().any(|&(open, _)| from < open && open < to) { + return true; + } + // Functions whose body holds a reading call and whose name is called in this scope. + words(m, b"fn", 0, m.len()).into_iter().any(|f| { + let name_at = skip_ws(m, f + 2); + let name_len = m[name_at..].iter().take_while(|&&c| is_ident(c)).count(); + let Some(body) = m[name_at..].iter().position(|&c| c == b'{' || c == b';').map(|p| name_at + p).filter(|&b| m[b] == b'{') else { + return false; + }; + let Some(end) = matching(m, body) else { return false }; + name_len > 0 + && reads.iter().any(|&(open, _)| open > body && open < end) + && words(m, &m[name_at..name_at + name_len], from, to).into_iter().any(|c| { + let open = skip_turbofish(m, skip_ws(m, c + name_len)); + c != name_at && m.get(open) == Some(&b'(') + }) + }) +} + /// The offset of the last `pat` in `expr` outside every bracket and string literal. fn rfind_outer(expr: &str, pat: &str) -> Option { let b = expr.as_bytes(); @@ -4498,6 +4666,30 @@ fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option, overrid .collect() } +/// The files of `paths` that a crate target loaded through a parent at the base (read through +/// `read_base`) and that no crate target loads now, each with the base files of its routes: a change +/// that removes the last `mod` or `#[path]` declaration on the way to a file compiles its tests out. +fn lost_routes( + paths: &[String], + read: &dyn Fn(&str) -> Option, + overrides: &Overrides, + read_base: &dyn Fn(&str) -> Option, + base_overrides: &Overrides, +) -> HashMap> { + paths + .iter() + .filter_map(|path| { + let base = module_gate(path, read_base, base_overrides, 0, Via::Any); + // A head with no route at all is lost too: when no file that could load it is left, the + // parent is unknown and [`module_gate`] counts it as reached, but the base had one. + if !base.reached || base.sources.is_empty() || !module_gate(path, read, overrides, 0, Via::Any).sources.is_empty() { + return None; + } + Some((path.clone(), base.sources.into_iter().map(|(p, _)| p).collect())) + }) + .collect() +} + /// Which routes to a file [`module_gate`] follows: a file that is not a `mod.rs` or a crate root /// declares its modules in a directory named after it when a `mod ;` loads it (`Named`), and /// in its own directory when a `#[path]` loads it (`Path`). @@ -4927,6 +5119,24 @@ mod tests { assert_eq!(census_in(filled, &ctx()), [(2, "census")]); } + #[test] + fn census_counts_a_helper_on_the_left_of_an_or_only_when_it_always_runs() { + let census_in = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let guarded = "#[test]\nfn t() {\n assert!((ready && verify_entry()) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(guarded), [(2, "census")], "a helper behind an && on the left is skipped when ready is false"); + let arm = "#[test]\nfn t() {\n assert!((if ready { verify_entry() } else { false }) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(arm), [(2, "census")], "a helper in one arm of an if on the left is skipped when ready is false"); + let scrutinee = "#[test]\nfn t() {\n assert!((if verify_entry() { true } else { false }) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(scrutinee), [], "the condition of an if on the left always runs"); + let block = "#[test]\nfn t() {\n assert!(({ verify_entry(); false }) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(block), [], "a plain block on the left always runs its statements"); + let block_if = "#[test]\nfn t() {\n assert!(({ if ready { verify_entry(); } false }) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(block_if), [(2, "census")], "a helper in an if inside a block on the left can be skipped"); + let after_if = + "#[test]\nfn t() {\n assert!(({ if ready { setup(); } verify_entry(); false }) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(after_if), [], "a helper after an if statement in the block always runs"); + } + #[test] fn census_is_report_only() { assert!(!Rule::Census.fails()); @@ -7307,4 +7517,108 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } + + #[test] + fn a_suffix_check_reads_source_only_when_the_checked_file_is_read() { + let name = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", name), [], "a suffix check on a generated name"); + let names = "#[test]\nfn t() {\n assert!(generated_names().iter().all(|name| name.ends_with(\".rs\")));\n}\n"; + assert_eq!(only("reads-source", names), [], "a suffix predicate over generated names"); + let other_read = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n#[test]\nfn u() {\n assert!(fs::read_to_string(\"data.json\").unwrap().contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", other_read), [], "another test reads a file the suffix check did not name"); + let same_name = "#[test]\nfn t() {\n let p = generated_name();\n assert!(p.ends_with(\".rs\"));\n}\n#[test]\nfn u() {\n let p = data_path();\n assert!(fs::read_to_string(p).unwrap().contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", same_name), [], "another test reads its own local of the same name"); + let read = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert!(fs::read_to_string(p).unwrap().contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", read), [(4, "reads-source")], "the test reads the file"); + let src = "#[test]\nfn t() {\n let path = newest();\n if path.to_string_lossy().ends_with(\".rs\") {\n assert!(fs::read_to_string(&path).unwrap().contains(\"x\"));\n }\n}\n"; + assert_eq!(only("reads-source", src), [(4, "reads-source")], "the converted path is read"); + let src = "#[test]\nfn t() {\n let path = newest();\n assert!(path.to_string_lossy().ends_with(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", src), [], "the converted path is not read"); + let src = "#[test]\nfn t() {\n assert!(generated_name().to_string_lossy().ends_with(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", src), [], "a conversion of a generated name"); + let src = "#[test]\nfn t() {\n assert!(generated_name().to_string_lossy().ends_with(\".rs\"));\n assert_eq!(fs::read_to_string(other_path()).unwrap(), \"x\");\n}\n"; + assert_eq!(only("reads-source", src), [(3, "reads-source")], "the same function reads a file, regardless of the receiver"); + let src = "#[test]\nfn t() {\n let entry = newest();\n if entry.path.to_string_lossy().ends_with(\".rs\") {\n assert!(fs::read_to_string(&entry.path).unwrap().contains(\"x\"));\n }\n}\n"; + assert_eq!(only("reads-source", src), [(4, "reads-source")], "the test reads the checked field"); + let src = "#[test]\nfn t() {\n assert!(entry.path.to_string_lossy().ends_with(\".rs\"));\n assert_eq!(load(&entry.path), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", src), [(3, "reads-source")], "a separate helper reads the checked field"); + let src = "fn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n#[cfg(test)]\nmod tests {\n #[test]\n fn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert_eq!(load(&p), \"x\");\n }\n}\n"; + assert_eq!(only("reads-source", src), [(9, "reads-source")], "a helper outside the test module reads the checked file"); + let found: Vec<_> = hits_in("crates/x/src/lib.rs", src, &ctx()).into_iter().filter(|h| h.1 == "reads-source").collect(); + assert_eq!(found, [(9, "reads-source")], "the reading helper is outside the test regions of a regular source file"); + let src = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert_eq!(load::(&p), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", src), [(4, "reads-source")], "a generic helper reads the checked file"); + let src = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert_eq!(std::fs::read::<_>(&p).unwrap().len(), 1);\n}\n"; + assert_eq!(only("reads-source", src), [(4, "reads-source")], "a read with a turbofish"); + let src = "#[test]\nfn t() {\n assert!(entry.path.to_string_lossy().ends_with(\".rs\"));\n assert_eq!(load(&other.path), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", src), [(3, "reads-source")], "the helper reads a file, regardless of its argument"); + let derived_helper = "#[test]\nfn t() {\n let path = newest();\n let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();\n assert!(name.ends_with(\".rs\"));\n assert_eq!(load(&path), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", derived_helper), [(5, "reads-source")], "the test calls a reading helper after checking a derived name"); + let other_call = "#[test]\nfn t() {\n assert!(path.ends_with(\".rs\"));\n}\n#[test]\nfn u() {\n assert_eq!(load(&path), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", other_call), [], "only another test calls the reading helper"); + let declared = "#[test]\nfn t() {\n fn read() -> u8 {\n 1\n }\n assert!(generated_name().ends_with(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", declared), [], "a function named read is declared, not called"); + let helper = "#[cfg(test)]\nmod tests {\n fn load(p: &Path) -> String {\n if p.ends_with(\".rs\") {\n return fs::read_to_string(p).unwrap();\n }\n String::new()\n }\n #[test]\n fn t() {\n assert_eq!(load(newest()), \"x\");\n }\n}\n"; + assert_eq!(only("reads-source", helper), [(4, "reads-source")], "a helper in the test module reads the file"); + let split = "#[test]\nfn t() {\n for p in listing() {\n if !p.ends_with(\".rs\") {\n continue;\n }\n assert_eq!(load(&p), \"x\");\n }\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", split), [(4, "reads-source")], "a separate test helper reads the file"); + let walk = "#[test]\nfn t() {\n for entry in std::fs::read_dir(&d).unwrap() {\n let path = entry.unwrap().path();\n let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();\n if !name.ends_with(\".rs\") {\n continue;\n }\n assert!(check(&path));\n }\n}\n"; + assert_eq!(only("reads-source", walk), [(6, "reads-source")], "a suffix check in a loop over a directory listing"); + let derived = "#[test]\nfn t() {\n let path = newest();\n let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();\n if name.ends_with(\".rs\") {\n assert!(std::fs::read_to_string(&path).unwrap().contains(\"x\"));\n }\n}\n"; + assert_eq!(only("reads-source", derived), [(5, "reads-source")], "the checked name comes from the path that is read"); + let generated = + "#[test]\nfn t() {\n for n in 0..3 {\n let name = generated_name(n);\n assert!(name.ends_with(\".rs\"));\n }\n}\n"; + assert_eq!(only("reads-source", generated), [], "a loop over generated names lists no files"); + let nested = "#[test]\nfn t() {\n let n = files.iter().filter(|p| p.to_str().is_some_and(|s| s.ends_with(\".rs\"))).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(only("reads-source", nested), [(3, "reads-source")], "a suffix check nested inside the closure of a listing filter"); + } + + #[test] + fn suffix_selected_source_reads_include_streams() { + for read in ["File::open(p)", "File :: open(p)", "reader.read_to_end(&mut bytes)", "reader.read_to_string(&mut text)", "fs::read(p)"] { + let src = format!( + "#[test]\nfn t() {{\n let p = newest();\n if p.ends_with(\".rs\") {{\n let got = {read};\n assert_eq!(check(got), 1);\n }}\n}}\n" + ); + assert_eq!(only("reads-source", &src), [(4, "reads-source")], "{read}"); + assert_eq!(only("reads-source", &src.replace(".rs", ".svg")), [], "{read}"); + } + let name = "#[test]\nfn t() {\n let p = newest();\n assert_eq!(p.ends_with(\".rs\"), wanted());\n}\n"; + assert_eq!(only("reads-source", name), [], "the suffix check's result is compared, and nothing is read"); + } + + #[test] + fn a_file_whose_last_route_was_removed_is_lost() { + let child = "crates/x/src/a/child.rs"; + let paths = [child.to_owned()]; + let base = [("crates/x/src/lib.rs", "mod a;\n"), ("crates/x/src/a.rs", "mod child;\n")]; + let read_base = |p: &str| base.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + for (lib, lost) in [("", true), ("mod a;\n", false), ("#[path = \"a/child.rs\"]\nmod again;\n", false)] { + let head = [("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", "mod child;\n")]; + let read = |p: &str| head.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let found = lost_routes(&paths, &read, &path_overrides(head), &read_base, &Overrides::new()); + assert_eq!(found.contains_key(child), lost, "{lib:?}"); + if lost { + assert!(found[child].iter().any(|p| p == "crates/x/src/lib.rs"), "the removed declaration's file is a base route"); + } + } + let common = "crates/x/tests/common/mod.rs".to_owned(); + let smoke = [("crates/x/tests/smoke.rs", "mod common;\n")]; + let read_smoke = |p: &str| smoke.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let smoke_routes = with_root_routes(path_overrides(smoke), &[smoke[0].0.to_owned(), common.clone()]); + let deleted = lost_routes( + std::slice::from_ref(&common), + &|_| None, + &with_root_routes(Overrides::new(), std::slice::from_ref(&common)), + &read_smoke, + &smoke_routes, + ); + assert_eq!(deleted.get(&common).map(Vec::as_slice), Some(&[smoke[0].0.to_owned()][..]), "the deleted target root was its only route"); + let kept = lost_routes(std::slice::from_ref(&common), &read_smoke, &smoke_routes, &read_smoke, &smoke_routes); + assert!(kept.is_empty(), "the target root still loads it"); + let never_loaded = [("crates/x/src/lib.rs", ""), ("crates/x/src/a.rs", "mod child;\n")]; + let read = |p: &str| never_loaded.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + assert!(lost_routes(&paths, &read, &Overrides::new(), &read, &Overrides::new()).is_empty(), "a file no target loaded at the base either"); + let ctx = Ctx { module_cfgs: [(child.to_owned(), vec!["any()".to_owned()])].into_iter().collect(), ..ctx() }; + assert_eq!(hits_in(child, "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n", &ctx), [(2, "never-run")]); + } } From 859a6b4dd323b73022e474e52756b2cf0e2f1114 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:33:38 -0800 Subject: [PATCH 50/50] xtask: test-lint decodes escapes in #[path] values A plain #[path = "\x63hild.rs"] after #[cfg_attr(windows, path = "child.rs")] loads child.rs on Linux and FreeBSD, but test-lint compared the undecoded spelling with the file name, dropped that route and reported a test in child.rs as never-run. The plain attribute and the path argument of cfg_attr now decode the escapes of an ordinary string literal with the same unescape the cfg values use. Raw string literals are read as written. --- xtask/src/test_lint.rs | 43 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index c95215cd4c..37bd14d863 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -4820,7 +4820,8 @@ fn path_overrides<'a>(sources: impl IntoIterator) -> } /// The string value of a `#[path = "…"]` attribute in `m[from..to]`, written as an ordinary or a -/// raw string literal (`#[path = r"shared.rs"]`, `#[path = r#"shared.rs"#]`). +/// raw string literal (`#[path = r"shared.rs"]`, `#[path = r#"shared.rs"#]`). The escapes of an +/// ordinary literal are decoded (`"\x63hild.rs"` names `child.rs`); a raw literal is read as written. fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { words(m, b"path", from, to).into_iter().find_map(|at| { let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); @@ -4829,7 +4830,8 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { if !attr || m.get(eq) != Some(&b'=') { return None; } - let hashes = if m.get(q) == Some(&b'r') { + let raw = m.get(q) == Some(&b'r'); + let hashes = if raw { let h = m[q + 1..].iter().take_while(|&&c| c == b'#').count(); q += 1 + h; h @@ -4841,13 +4843,17 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { } let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); let end = find(m, &close, q + 1)?; - Some(String::from_utf8_lossy(&src[q + 1..end]).into_owned()) + let body = String::from_utf8_lossy(&src[q + 1..end]); + Some(if raw { body.into_owned() } else { unescape(&body) }) }) } /// The value of a whitespace-free `path=` argument, for an ordinary or a raw string literal. -fn path_arg(arg: &str) -> Option<&str> { - whole_literal(arg.strip_prefix("path=")?).map(|l| &l[1..l.len() - 1]) +/// The escapes of an ordinary literal are decoded, as in [`path_attr`]. +fn path_arg(arg: &str) -> Option { + let lit = arg.strip_prefix("path=")?; + let body = whole_literal(lit).map(|l| &l[1..l.len() - 1])?; + Some(if lit.starts_with('"') { unescape(body) } else { body.to_owned() }) } /// The `#[cfg_attr(, path = "…")]` overrides in `m[from..to]`, each as its condition and @@ -4867,7 +4873,7 @@ fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, for cut in cuts[1..].iter().copied().chain([text.len()]) { let arg = text.get(start..cut).unwrap_or(""); if let Some(rel) = path_arg(arg) { - out.push((text[..first].to_owned(), rel.to_owned())); + out.push((text[..first].to_owned(), rel)); } start = cut + 1; } @@ -7851,6 +7857,10 @@ mod tests { assert_eq!(cfg_attr_paths(&mask(src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "a,b.rs".to_owned())]); let raw = "#[cfg_attr(unix, path = r#\"a.rs\"#)]\nmod x;\n"; assert_eq!(cfg_attr_paths(&mask(raw), raw.as_bytes(), 0, raw.len()), [("unix".to_owned(), "a.rs".to_owned())]); + let escaped = "#[cfg_attr(unix, path = \"\\x61.rs\")]\nmod x;\n"; + assert_eq!(cfg_attr_paths(&mask(escaped), escaped.as_bytes(), 0, escaped.len()), [("unix".to_owned(), "a.rs".to_owned())]); + let raw_escape = "#[cfg_attr(unix, path = r\"\\x61.rs\")]\nmod x;\n"; + assert_eq!(cfg_attr_paths(&mask(raw_escape), raw_escape.as_bytes(), 0, raw_escape.len()), [("unix".to_owned(), "\\x61.rs".to_owned())]); } #[test] @@ -7873,6 +7883,27 @@ mod tests { assert_eq!(hits_in(&shared, test, &ctx), [], "the raw-string route runs it on Linux"); } + #[test] + fn path_attributes_decode_escapes_in_ordinary_strings() { + let escaped = "#[path = \"\\x63hild.rs\"]\nmod c;\n"; + assert_eq!(path_attr(&mask(escaped), escaped.as_bytes(), 0, escaped.len()).as_deref(), Some("child.rs")); + let raw = "#[path = r\"\\x63hild.rs\"]\nmod c;\n"; + assert_eq!(path_attr(&mask(raw), raw.as_bytes(), 0, raw.len()).as_deref(), Some("\\x63hild.rs"), "a raw string keeps its backslash"); + } + + #[test] + fn an_escaped_plain_path_after_a_cfg_attr_path_is_the_fallback_route() { + // Linux loads `child.rs` through the plain attribute, the fallback of the `cfg_attr` override. + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg_attr(windows, path = \"child.rs\")]\n#[path = \"\\x63hild.rs\"]\nmod c;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let child = "crates/x/src/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [], "the plain attribute's route runs it on Linux"); + } + #[test] fn a_module_loaded_by_two_roots_runs_if_either_runs_it() { let files: HashMap<&str, &str> = [