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 21744a7ada..e7f5db9a69 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 { + /// The paper-size lookup in flight, dropped when its worker answers or disconnects. + papers: PaperLookup, +} + 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 @@ -31,6 +36,43 @@ impl PrintService for SystemPrint { fn scripts_may_print(&self) -> bool { true } + 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 name = printer.to_string(); + let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || { + let _ = send.send(read(name)); + }); + 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.0 = None; + 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 @@ -43,10 +85,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); @@ -133,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/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 607fa12238..cc119c80b6 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -694,6 +694,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/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/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index 14a462d79f..e8e512a448 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -7,6 +7,7 @@ //! (#5532). The reference app has no command for it, so it goes beyond parity and changes no //! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's. +pub mod numbers; #[cfg(test)] mod tests; @@ -65,6 +66,15 @@ pub fn specs() -> Vec { has_selection, release_path ), + cmd!( + "addon.type.numbers", + "Make Numbers Sequence…", + ["Object", "Plug-ins", "Type Tools"], + None, + "{start?: number (1), step?: number (1; its sign is set to run toward `end`; 0: every object gets `start`), end?: number (omitted: the numbers run to the last type object; given: they stop past `end`, and the objects after the last number keep their text), order?: \"stacking\" (stacking order, from the back) | \"rows\" (top to bottom, each row left to right) | \"columns\" (left to right, each column top to bottom) (\"stacking\"; rows and columns group objects whose centers are within half the median height or width), replace?: \"all\" (the whole text) | \"numbers\" (every number in the text: digits, with any `.` or `,` between digits and a `-` before them that does not follow a letter or digit) | \"placeholder\" (every {%n}, in any case) (\"all\"; with numbers or placeholder, objects that hold none are skipped, get no number and order leaves them out; the remaining objects are ordered before end limits the sequence, so objects past end still count for rows and columns; at most 10000 numbers or placeholders are replaced in one run (matches that already read their number do not count); more is an error), shuffle?: false (true: the numbers go to the objects in random order, and order is not used), seed?: whole number (0; the same seed gives the same order; checked even with shuffle off), leadingZeros?: true (non-negative numbers are padded with zeros to the whole digits of the widest of start and end, or of the last number), digits?: 1..30 (with leadingZeros, at least this many whole digits), trailingZeros?: false (true: every number gets as many decimal places as the one with the most), removeUnused?: false (true, with end: the objects left without a number are deleted, except a clipping mask), ids?: [id…], id? (instead of ids; neither: the selection)} number the type objects among the objects (inside groups too), as one undo step. Locked or hidden type is left alone. A frame of threaded type among them is an error. Values are -1e12..1e12, rounded to the most decimal places among start, step and end (at most 6). Replaced text takes the style of the text it replaces, and a match that already reads its number keeps its style. Objects that already read so are left as they are, and when nothing changes no undo step is made → {count (objects changed), ids (numbered, in order), removed}", + has_selection, + numbers::make_numbers + ), ] } diff --git a/crates/engine/src/cmd/addons/typetools/numbers.rs b/crates/engine/src/cmd/addons/typetools/numbers.rs new file mode 100644 index 0000000000..c83c306496 --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/numbers.rs @@ -0,0 +1,384 @@ +//! Make Numbers Sequence (`addon.type.numbers`): numbers the selected type objects from a start +//! value by a step, replacing each object's whole text, the numbers in it, or a `{%n}` placeholder. +//! The objects are taken in stacking order, by rows or by columns. Leading and trailing zeros pad +//! the numbers to one width. Based on Sergey Osokin's MIT-licensed MakeNumbersSequence script +//! (). + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_color::recolor::Rng; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::Rect; +use vectorcraft_render::effects; +use vectorcraft_text::edit; +use vectorcraft_text::retype::is_combining_mark; + +use super::super::super::menucmds::whole_or; +use super::super::super::object::choice; +use super::super::super::textedit::text_mut; +use super::super::super::threads; +use super::super::super::typecmd::refresh_bounds; +use super::super::super::typemenu::text_ids; +use super::super::super::{bad, number_or, switch_or, targets}; +use crate::{EngineError, Result, Session}; + +/// The command id. +pub const COMMAND: &str = "addon.type.numbers"; +/// The orders the objects are numbered in. +pub const ORDERS: [&str; 3] = ["stacking", "rows", "columns"]; +/// What each object's number replaces. +pub const REPLACES: [&str; 3] = ["all", "numbers", "placeholder"]; +/// The placeholder `replace: "placeholder"` replaces, in any case. +pub const PLACEHOLDER: &str = "{%n}"; +/// The largest start, end or step. +const MAX_VALUE: f64 = 1e12; +/// The most decimal places a number keeps. +const MAX_DECIMALS: usize = 6; +/// The largest fixed number of digits. +pub const MAX_DIGITS: u64 = 30; +/// The most type objects one run numbers. +const MAX_TEXTS: usize = 100_000; +/// The most numbers or placeholders one run replaces. +pub(crate) const MAX_MATCHES: usize = 10_000; + +/// What one run does, read from its params. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct Options { + pub start: f64, + /// None: the numbers run to the last type object. + pub end: Option, + pub step: f64, + pub order: &'static str, + pub replace: &'static str, + /// Some(seed): the numbers go to the objects in random order. + pub shuffle: Option, + pub leading_zeros: bool, + /// The least number of whole digits with leading zeros; None: as many as the widest number. + pub digits: Option, + pub trailing_zeros: bool, + pub remove_unused: bool, +} + +impl Options { + pub(crate) fn parse(p: &Value) -> Result { + const C: &str = COMMAND; + let value = |key: &str, default: f64| -> Result { + let v = number_or(p, key, default, C)?; + if !v.is_finite() || v.abs() > MAX_VALUE { + return Err(bad(C, format!("`{key}` must be from -{MAX_VALUE} to {MAX_VALUE}"))); + } + Ok(v) + }; + let start = value("start", 1.0)?; + let step = value("step", 1.0)?; + let end = match p.get("end") { + None | Some(Value::Null) => None, + Some(_) => Some(value("end", 0.0)?), + }; + let order = pick(choice(p, C, "order", &ORDERS)?.unwrap_or("stacking"), &ORDERS); + let replace = pick(choice(p, C, "replace", &REPLACES)?.unwrap_or("all"), &REPLACES); + let seed = whole_or(p, "seed", 0, C)?; + let shuffle = if switch_or(p, "shuffle", false, C)? { Some(seed) } else { None }; + let digits = match p.get("digits") { + None | Some(Value::Null) => None, + Some(_) => { + let d = whole_or(p, "digits", 1, C)?; + if !(1..=MAX_DIGITS).contains(&d) { + return Err(bad(C, format!("`digits` must be from 1 to {MAX_DIGITS}"))); + } + Some(usize::try_from(d).unwrap_or(1)) + } + }; + let remove_unused = switch_or(p, "removeUnused", false, C)?; + if remove_unused && end.is_none() { + return Err(bad(C, "`removeUnused` needs an `end`")); + } + Ok(Self { + start, + end, + step, + order, + replace, + shuffle, + leading_zeros: switch_or(p, "leadingZeros", true, C)?, + digits, + trailing_zeros: switch_or(p, "trailingZeros", false, C)?, + remove_unused, + }) + } +} + +/// `v` as the static entry of `list` it equals. +fn pick(v: &str, list: &[&'static str]) -> &'static str { + list.iter().copied().find(|x| *x == v).unwrap_or(list[0]) +} + +/// The decimal places `v` is written with, at most [`MAX_DECIMALS`]. +fn decimals(v: f64) -> usize { + let s = format!("{v}"); + s.split_once('.').map_or(0, |(_, f)| f.len()).min(MAX_DECIMALS) +} + +/// Round the shortest decimal representation of `v` to fixed point at `places`. +fn scaled(v: f64, places: usize) -> i128 { + let s = format!("{v}"); + let magnitude = s.trim_start_matches('-'); + let (whole, fraction) = magnitude.split_once('.').unwrap_or((magnitude, "")); + let digits = whole.bytes().chain(fraction.bytes().chain(std::iter::repeat(b'0')).take(places)); + let mut value = digits.fold(0_i128, |n, digit| n * 10 + i128::from(digit - b'0')); + if fraction.as_bytes().get(places).is_some_and(|digit| *digit >= b'5') { + value += 1; + } + if v < 0.0 { -value } else { value } +} + +/// `v` scaled by `10^places`, without trailing zeros and with no minus sign on zero. +fn write(v: i128, places: usize) -> String { + let scale = 10_u128.pow(places as u32); + let magnitude = v.unsigned_abs(); + let sign = if v < 0 { "-" } else { "" }; + let whole = magnitude / scale; + if places == 0 { + return format!("{sign}{whole}"); + } + let fraction = magnitude % scale; + let s = format!("{sign}{whole}.{fraction:0places$}"); + s.trim_end_matches('0').trim_end_matches('.').to_string() +} + +/// The numbers for `count` objects as text: from `start` by `step` (its sign set to run toward +/// `end`), stopping past `end`, then padded with zeros as `o` says. +pub(crate) fn sequence(o: &Options, count: usize) -> Vec { + let places = [Some(o.start), Some(o.step), o.end].into_iter().flatten().map(decimals).max().unwrap_or(0); + let step = match o.end { + Some(end) if (o.start <= end) == (o.step < 0.0) => -o.step, + _ => o.step, + }; + // Count steps at the supported decimal precision so an inclusive end survives rounding. + let scaled = |v: f64| scaled(v, places); + let start_i = scaled(o.start); + let step_i = scaled(step); + let fit = match o.end { + Some(end) if step_i != 0 => usize::try_from((scaled(end) - start_i) / step_i + 1).unwrap_or(usize::MAX), + _ => count, + }; + let values: Vec = (0..count.min(fit)).map(|i| start_i + i as i128 * step_i).collect(); + let mut out: Vec = values.iter().map(|v| write(*v, places)).collect(); + if o.trailing_zeros { + let most = out.iter().map(|s| s.split_once('.').map_or(0, |(_, f)| f.len())).max().unwrap_or(0); + if most > 0 { + for s in &mut out { + let have = s.split_once('.').map_or(0, |(_, f)| f.len()); + if have == 0 { + s.push('.'); + } + s.extend(std::iter::repeat_n('0', most - have)); + } + } + } + if o.leading_zeros { + let last = o.end.map(scaled).unwrap_or_else(|| values.last().copied().unwrap_or(start_i)); + // Whole digits as written, after rounding to `places`. + let whole = |v: i128| { + let s = write(v, places); + let s = s.trim_start_matches('-'); + s.split_once('.').map_or(s.len(), |(w, _)| w.len()) + }; + let width = whole(start_i).max(whole(last)).max(o.digits.unwrap_or(1)); + for s in &mut out { + if s.starts_with('-') { + continue; + } + let have = s.split_once('.').map_or(s.len(), |(w, _)| w.len()); + if have < width { + s.insert_str(0, &"0".repeat(width - have)); + } + } + } + out +} + +/// The byte ranges of `text` a number replaces: each run of ASCII digits, with any `.` or `,` +/// followed by more digits inside it, and a `-` before it that does not follow a letter or digit. +pub(crate) fn number_spans(text: &str) -> Vec<(usize, usize)> { + let b = text.as_bytes(); + let mut out = vec![]; + let mut i = 0; + while i < b.len() { + if !b[i].is_ascii_digit() { + i += 1; + continue; + } + let signed = i > 0 && b[i - 1] == b'-' && !text[..i - 1].chars().rev().find(|c| !is_combining_mark(*c)).is_some_and(char::is_alphanumeric); + let start = if signed { i - 1 } else { i }; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + while i + 1 < b.len() && matches!(b[i], b'.' | b',') && b[i + 1].is_ascii_digit() { + i += 1; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + } + out.push((start, i)); + } + out +} + +/// The byte ranges of `text` that hold the placeholder, in any case. +pub(crate) fn placeholder_spans(text: &str) -> Vec<(usize, usize)> { + let lower = text.to_ascii_lowercase(); + lower.match_indices(PLACEHOLDER).map(|(i, m)| (i, i + m.len())).collect() +} + +/// `ids` in rows (top to bottom, each row left to right) or columns (left to right, each top to +/// bottom), by the centres of `bounds`. Objects whose centres are within half the median height +/// (width for columns) of a row's first object share its row. +fn by_position(ids: Vec<(NodeId, Rect)>, rows: bool) -> Vec { + let along = |r: &Rect| if rows { r.center().y } else { r.center().x }; + let across = |r: &Rect| if rows { r.center().x } else { r.center().y }; + let mut sizes: Vec = ids.iter().map(|(_, r)| if rows { r.height() } else { r.width() }).collect(); + sizes.sort_by(f64::total_cmp); + let n = sizes.len(); + let median = match n { + 0 | 1 => 0.0, + _ if n.is_multiple_of(2) => (sizes[n / 2 - 1] + sizes[n / 2]) / 2.0, + _ => sizes[n / 2], + }; + let tolerance = median / 2.0; + let mut ids = ids; + ids.sort_by(|a, b| along(&a.1).total_cmp(&along(&b.1))); + let mut out = Vec::with_capacity(ids.len()); + let mut row: Vec<(NodeId, Rect)> = vec![]; + for item in ids { + if row.first().is_some_and(|first| along(&item.1) - along(&first.1) > tolerance) { + row.sort_by(|a, b| across(&a.1).total_cmp(&across(&b.1))); + out.extend(row.drain(..).map(|(id, _)| id)); + } + row.push(item); + } + row.sort_by(|a, b| across(&a.1).total_cmp(&across(&b.1))); + out.extend(row.into_iter().map(|(id, _)| id)); + out +} + +/// One replacement in a text: its start and end bytes and the number that goes there. +type Edit = (usize, usize, String); + +/// Each span of `spans` in `text` replaced by `number`, as edits from the last to the first. A +/// span that already reads `number` is left out, so its formatting stays. +pub(crate) fn edits(text: &str, spans: Vec<(usize, usize)>, number: &str) -> Vec { + spans.into_iter().rev().filter(|(a, b)| text.get(*a..*b) != Some(number)).map(|(a, b)| (a, b, number.to_string())).collect() +} + +pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMAND; + let o = Options::parse(p)?; + let named = targets(s, p)?; + let d = &s.doc()?.doc; + if let Some(id) = named.iter().find(|id| d.node(**id).is_none()) { + return Err(EngineError::NoNode(*id)); + } + // Type objects, groups' included, in stacking order from the back; locked or hidden ones stay. + let mut texts = text_ids(d, &named); + { + let editable = d.editable(); + texts.retain(|id| editable(*id)); + } + let paths = d.index_paths(texts.iter().copied()); + texts.sort_by(|a, b| paths.get(a).cmp(&paths.get(b))); + if texts.len() > MAX_TEXTS { + return Err(bad(C, format!("too many type objects: at most {MAX_TEXTS}"))); + } + let threads = threads::ThreadIndex::of(d); + if texts.iter().any(|id| threads.threaded(*id)) { + return Err(bad(C, "threaded type can't be numbered: its frames share one story")); + } + let plain = |id: NodeId| match d.node(id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => t.plain_text(), + _ => String::new(), + }; + // Only objects that hold a number or the placeholder count, for the order too. + let mut texts: Vec<(NodeId, String)> = texts + .into_iter() + .map(|id| (id, plain(id))) + .filter(|(_, t)| match o.replace { + "numbers" => t.bytes().any(|b| b.is_ascii_digit()), + "placeholder" => !placeholder_spans(t).is_empty(), + _ => true, + }) + .collect(); + if o.order != "stacking" && o.shuffle.is_none() { + let placed: Vec<(NodeId, Rect)> = texts + .iter() + .map(|(id, _)| (*id, effects::preview::bounds_of(d, &[*id], false).unwrap_or(Rect::new(f64::MAX, f64::MAX, f64::MAX, f64::MAX)))) + .collect(); + let mut by_id: std::collections::HashMap = texts.into_iter().collect(); + texts = by_position(placed, o.order == "rows").into_iter().filter_map(|id| by_id.remove(&id).map(|t| (id, t))).collect(); + } + // The objects are shuffled, not the numbers, so an end limit can number any of them. + if let Some(seed) = o.shuffle { + let mut rng = Rng::new(seed); + for i in (1..texts.len()).rev() { + let j = usize::try_from(rng.next_u64() % (i as u64 + 1)).unwrap_or(0); + texts.swap(i, j); + } + } + let numbers = sequence(&o, texts.len()); + let mut plans: Vec<(NodeId, Vec)> = vec![]; + let mut matches = 0; + for ((id, text), number) in texts.iter().zip(&numbers) { + let spans = match o.replace { + "numbers" => number_spans(text), + "placeholder" => placeholder_spans(text), + _ => vec![], + }; + // Checked before any replacement text is made. + matches += spans.iter().filter(|(a, b)| text.get(*a..*b) != Some(number.as_str())).count(); + if matches > MAX_MATCHES { + return Err(bad(C, format!("too many numbers or placeholders to replace: at most {MAX_MATCHES}"))); + } + let changes = match o.replace { + "numbers" | "placeholder" => edits(text, spans, number), + _ => vec![(0, text.len(), number.clone())], + }; + // The text it would have, to leave out objects that already read so. + let mut after = text.clone(); + for (a, b, n) in &changes { + after.replace_range(*a..*b, n); + } + if after != *text { + plans.push((*id, changes)); + } + } + let numbered: Vec = texts.iter().take(numbers.len()).map(|(id, _)| id.0).collect(); + // A clipping group's or layer's mask is its first child; removing it would make the next child the mask. + let mask = |id: NodeId| { + d.parent_of(id).and_then(|g| d.node(g)).is_some_and(|g| g.clips() && g.children().and_then(|c| c.first()).is_some_and(|c| c.id == id)) + }; + let removed: Vec = + if o.remove_unused { texts.iter().skip(numbers.len()).map(|(id, _)| *id).filter(|id| !mask(*id)).collect() } else { vec![] }; + if plans.is_empty() && removed.is_empty() { + return Ok(json!({ "count": 0, "ids": numbered, "removed": [] })); + } + let count = plans.len(); + s.edit("Make Numbers Sequence", |d, sel| { + for (id, changes) in &plans { + let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; + for (a, b, n) in changes { + t.splice_paras(*a, *b, n); + edit::replace_range(&mut t.runs, *a, *b, n); + t.ruby_after_replace(*a, *b, n.len()); + } + refresh_bounds(t); + } + d.remove_many(&removed)?; + if !removed.is_empty() { + sel.remove_all(removed.iter().copied()); + } + Ok(()) + })?; + Ok(json!({ "count": count, "ids": numbered, "removed": removed.iter().map(|id| id.0).collect::>() })) +} diff --git a/crates/engine/src/cmd/addons/typetools/numbers/tests.rs b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs new file mode 100644 index 0000000000..e7d51d47b4 --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs @@ -0,0 +1,337 @@ +//! Make Numbers Sequence: the numbers a sequence gives, what each replace mode changes, the +//! orders, removed objects, one undo step, and bad params refused without a change. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use super::{COMMAND as C, Options, number_spans, placeholder_spans, sequence}; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn text_at(s: &mut Session, x: f64, y: f64, words: &str) -> NodeId { + NodeId(s.execute("text.create", &json!({"x": x, "y": y, "text": words, "size": 20})).unwrap()["id"].as_u64().unwrap()) +} + +fn plain(s: &Session, id: NodeId) -> String { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn seq(p: Value, count: usize) -> Vec { + sequence(&Options::parse(&p).unwrap(), count) +} + +#[test] +fn a_sequence_steps_toward_its_end_and_pads_with_zeros() { + assert_eq!(seq(json!({"start": 1, "step": 5, "end": 20}), 10), ["01", "06", "11", "16"], "stops past the end"); + assert_eq!(seq(json!({"start": 10, "step": 3, "end": 1, "leadingZeros": false}), 10), ["10", "7", "4", "1"], "the step turns to run down"); + assert_eq!(seq(json!({"start": 8, "digits": 3}), 3), ["008", "009", "010"]); + assert_eq!(seq(json!({"start": -1, "step": 1}), 3), ["-1", "0", "1"], "negative numbers get no zeros"); + assert_eq!(seq(json!({"start": 0.1, "step": 0.1, "leadingZeros": false}), 3), ["0.1", "0.2", "0.3"], "no rounding noise"); + assert_eq!(seq(json!({"start": 1, "step": 0.25, "trailingZeros": true}), 3), ["1.00", "1.25", "1.50"]); + assert_eq!(seq(json!({"start": 4, "step": 0}), 3), ["4", "4", "4"]); + assert_eq!( + seq(json!({"start": 1e9 + 0.1, "step": 0.1, "end": 1e9 + 0.3}), 5), + ["1000000000.1", "1000000000.2", "1000000000.3"], + "a value that rounds to the end counts" + ); + assert_eq!( + seq(json!({"start": 10000000000.1, "step": 0.1, "end": 10000000000.3}), 5), + ["10000000000.1", "10000000000.2", "10000000000.3"], + "large values keep the inclusive decimal end" + ); + assert_eq!(seq(json!({"start": 1e12, "step": 0.000001, "end": 1e12}), 3), ["1000000000000"], "an end equal to the start counts"); + assert_eq!( + seq(json!({"start": 999999999999.9_f64, "step": 0.000001}), 3), + ["999999999999.9", "999999999999.900001", "999999999999.900002"], + "large values keep their decimal digits when scaled for a small step" + ); + assert_eq!( + seq(json!({"start": 999999999999.9_f64, "step": 0.000001, "end": 999999999999.9_f64}), 3), + ["999999999999.9"], + "the end uses the same decimal scaling as the start" + ); + assert_eq!(seq(json!({"start": 0.1, "step": 3.3}), 4), ["00.1", "03.4", "06.7", "10"], "padded to the rounded last number"); + assert_eq!(seq(json!({"start": 1, "step": 1_000_000_000_000_u64}), 9009).last().map(String::as_str), Some("9008000000000001")); + assert_eq!(seq(json!({"start": -0.25, "step": 0.125}), 5), ["-0.25", "-0.125", "0", "0.125", "0.25"]); + assert_eq!(seq(json!({"start": -0.0000001, "step": 0}), 1), ["0"], "rounded zero has no minus sign"); + assert_eq!(seq(json!({"start": 9.9999999, "step": 0}), 1), ["10"], "width uses the rounded whole part"); + assert_eq!(seq(json!({"start": -0.0000005, "step": 0}), 1), ["-0.000001"], "decimal ties round away from zero"); +} + +#[test] +fn unthreaded_type_checks_the_threads_once() { + let mut s = session(); + let ids: Vec = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect(); + let scans = super::threads::thread_scans(); + super::make_numbers(&mut s, &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + assert_eq!(super::threads::thread_scans() - scans, 1, "selection size does not multiply thread scans"); + assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::>(), ["1", "2", "3"]); +} + +#[test] +fn threaded_type_is_refused() { + let mut s = session(); + let a = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "1 2 3", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + let n = steps(&s); + assert!(s.execute(C, &json!({"ids": [a, b]})).is_err()); + assert_eq!((plain(&s, NodeId(a)), steps(&s)), ("1 2 3".to_string(), n)); +} + +#[test] +fn the_spans_find_numbers_and_placeholders() { + assert_eq!(number_spans("No. 12, page 3.5 of 1,000."), [(4, 6), (13, 16), (20, 25)]); + assert!(number_spans("none").is_empty()); + assert_eq!(placeholder_spans("a{%N}b{%n}"), [(1, 5), (6, 10)]); +} + +#[test] +fn the_whole_text_gets_numbered_in_stacking_order_as_one_step() { + let mut s = session(); + let ids: Vec = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect(); + let n = steps(&s); + let out = s.execute(C, &json!({"ids": [ids[2].0, ids[0].0, ids[1].0], "start": 7})).unwrap(); + assert_eq!(out["count"], json!(3)); + assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::>(), ["7", "8", "9"], "from the back"); + assert_eq!(steps(&s), n + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(ids.iter().all(|id| plain(&s, *id) == "x"), "undone"); +} + +#[test] +fn numbers_and_placeholders_are_replaced_inside_the_text() { + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, "Seat 99, row 4"); + let b = text_at(&mut s, 40.0, 140.0, "no digits"); + let c = text_at(&mut s, 40.0, 180.0, "Seat 1"); + s.execute(C, &json!({"ids": [a.0, b.0, c.0], "replace": "numbers", "start": 5})).unwrap(); + assert_eq!([plain(&s, a), plain(&s, b), plain(&s, c)], ["Seat 5, row 5", "no digits", "Seat 6"], "text with no number is skipped"); + let d = text_at(&mut s, 40.0, 220.0, "Tag {%N} / {%n}"); + let e = text_at(&mut s, 40.0, 260.0, "Tag 3"); + s.execute(C, &json!({"ids": [d.0, e.0], "replace": "placeholder", "start": 2})).unwrap(); + assert_eq!([plain(&s, d), plain(&s, e)], ["Tag 2 / 2", "Tag 3"]); +} + +#[test] +fn ruby_follows_each_number_or_placeholder_replacement() { + let mut s = session(); + let word = "漢字"; + for (replace, words) in [("numbers", "1 2 漢字"), ("placeholder", "{%n} {%N} 漢字")] { + let id = text_at(&mut s, 40.0, 100.0, words); + let start = words.find(word).unwrap(); + s.execute("type.ruby", &json!({"ids": [id.0], "start": start, "end": start + word.len(), "text": "かんじ"})).unwrap(); + s.execute(C, &json!({"ids": [id.0], "replace": replace, "start": 123456})).unwrap(); + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not text") }; + let text = t.plain_text(); + assert_eq!(text, "123456 123456 漢字"); + assert_eq!(t.ruby.len(), 1); + let ruby = &t.ruby[0]; + assert_eq!(&text[ruby.start..ruby.end], word, "ruby follows both replacements in {replace} mode"); + assert_eq!(ruby.text, "かんじ"); + } +} + +#[test] +fn rows_and_columns_order_by_position() { + let mut s = session(); + // Created bottom-right first, so stacking order differs from both positions. + let br = text_at(&mut s, 300.0, 200.0, "x"); + let tl = text_at(&mut s, 40.0, 100.0, "x"); + let bl = text_at(&mut s, 40.0, 200.0, "x"); + let tr = text_at(&mut s, 300.0, 102.0, "x"); + let ids = json!([br.0, tl.0, bl.0, tr.0]); + s.execute(C, &json!({"ids": ids, "order": "rows"})).unwrap(); + assert_eq!([tl, tr, bl, br].map(|id| plain(&s, id)), ["1", "2", "3", "4"], "a small offset stays in its row"); + s.execute(C, &json!({"ids": ids, "order": "columns"})).unwrap(); + assert_eq!([tl, bl, tr, br].map(|id| plain(&s, id)), ["1", "2", "3", "4"]); +} + +#[test] +fn an_end_leaves_the_rest_or_removes_it() { + let mut s = session(); + let ids: Vec = (0..4).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect(); + let all = json!(ids.iter().map(|id| id.0).collect::>()); + s.execute(C, &json!({"ids": all, "end": 2})).unwrap(); + assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::>(), ["1", "2", "x", "x"]); + let out = s.execute(C, &json!({"ids": all, "start": 5, "end": 6, "removeUnused": true})).unwrap(); + assert_eq!(out["removed"], json!([ids[2].0, ids[3].0])); + assert!(s.doc().unwrap().doc.node(ids[3]).is_none()); +} + +#[test] +fn shuffle_gives_every_number_once() { + let mut s = session(); + let ids: Vec = (0..6).map(|i| text_at(&mut s, 40.0, 60.0 + 40.0 * f64::from(i), "x")).collect(); + let all = json!(ids.iter().map(|id| id.0).collect::>()); + s.execute(C, &json!({"ids": all, "shuffle": true, "seed": 3, "leadingZeros": false})).unwrap(); + let mut got: Vec = ids.iter().map(|id| plain(&s, *id)).collect(); + assert_ne!(got, ["1", "2", "3", "4", "5", "6"], "seed 3 moves them"); + got.sort(); + assert_eq!(got, ["1", "2", "3", "4", "5", "6"]); +} + +#[test] +fn shuffle_with_an_end_can_number_any_object() { + let mut numbered = [false; 6]; + for seed in 0..40 { + let mut s = session(); + let ids: Vec = (0..6).map(|i| text_at(&mut s, 40.0, 60.0 + 40.0 * f64::from(i), "x")).collect(); + let all = json!(ids.iter().map(|id| id.0).collect::>()); + let out = s.execute(C, &json!({"ids": all, "shuffle": true, "seed": seed, "end": 2, "removeUnused": true})).unwrap(); + assert_eq!(out["removed"].as_array().unwrap().len(), 4); + for (i, id) in ids.iter().enumerate() { + numbered[i] |= s.doc().unwrap().doc.node(*id).is_some(); + } + } + assert_eq!(numbered, [true; 6], "every object is numbered for some seed"); +} + +#[test] +fn the_same_seed_numbers_and_removes_the_same_objects() { + let run = || { + let mut s = session(); + let ids: Vec = (0..8).map(|i| text_at(&mut s, 40.0, 40.0 + 40.0 * f64::from(i), "x")).collect(); + let all = json!(ids.iter().map(|id| id.0).collect::>()); + let out = s.execute(C, &json!({"ids": all, "shuffle": true, "seed": 11, "end": 4, "removeUnused": true})).unwrap(); + let texts: Vec> = ids.iter().map(|id| s.doc().unwrap().doc.node(*id).map(|_| plain(&s, *id))).collect(); + let removed: Vec = + out["removed"].as_array().unwrap().iter().map(|r| ids.iter().position(|id| Some(id.0) == r.as_u64()).unwrap()).collect(); + (texts, removed) + }; + let (texts, removed) = run(); + assert_eq!(removed.len(), 4); + assert_eq!(run(), (texts, removed), "seed 11 gives each object the same number and removes the same ones"); +} + +fn group_of(s: &mut Session, ids: &[NodeId]) -> NodeId { + s.execute("select.set", &json!({"ids": ids.iter().map(|id| id.0).collect::>()})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.doc().unwrap().doc.parent_of(ids[0]).unwrap() +} + +#[test] +fn a_negative_number_in_the_text_is_replaced_with_its_sign() { + assert_eq!(number_spans("Seat -4, A-4"), [(5, 7), (11, 12)], "a hyphen after a letter is not a sign"); + assert_eq!(number_spans("É-4"), [(3, 4)], "nor after a letter outside ASCII"); + assert_eq!(number_spans("E\u{301}-4"), [(4, 5)], "nor after a letter with a combining mark"); + assert_eq!(number_spans("क्-4"), [(7, 8)], "nor after a letter with a virama"); + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, "Seat -4"); + let b = text_at(&mut s, 40.0, 140.0, "Seat 9"); + s.execute(C, &json!({"ids": [a.0, b.0], "replace": "numbers", "start": 2, "step": -3})).unwrap(); + assert_eq!([plain(&s, a), plain(&s, b)], ["Seat 2", "Seat -1"]); +} + +#[test] +fn a_match_that_already_reads_the_number_is_not_edited() { + let text = "5 and 4"; + assert_eq!(super::edits(text, number_spans(text), "5"), [(6, 7, "5".to_string())]); +} + +#[test] +fn too_many_matches_in_one_run_are_refused() { + let mut unchanged = session(); + let text = vec!["1"; super::MAX_MATCHES + 1].join(" "); + let id = text_at(&mut unchanged, 40.0, 100.0, &text); + let before = steps(&unchanged); + let out = unchanged.execute(C, &json!({"ids": [id.0], "start": 1, "replace": "numbers"})).unwrap(); + assert_eq!(out["count"], 0); + assert_eq!(plain(&unchanged, id), text); + assert_eq!(steps(&unchanged), before); + + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, &"{%n}".repeat(super::MAX_MATCHES + 1)); + let n = steps(&s); + assert!(s.execute(C, &json!({"ids": [a.0], "replace": "placeholder"})).is_err()); + assert_eq!(steps(&s), n); + // Whole texts are not matches: the object limit covers them. + s.execute("edit.undo", &json!({})).unwrap(); + text_at(&mut s, 40.0, 140.0, "x"); + // Each duplicate of the whole selection doubles it: 2^14 objects in 14 steps. + for _ in 0..14 { + s.execute("edit.duplicate", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + } + let count = s.doc().unwrap().selection.objects.len(); + assert!(count > super::MAX_MATCHES, "{count} objects"); + let out = s.execute(C, &json!({"step": 0})); + assert!(out.is_ok()); + let out = out.unwrap(); + assert!(out["count"].as_u64().unwrap() > super::MAX_MATCHES as u64); +} + +#[test] +fn locked_and_hidden_type_in_a_group_is_left_alone() { + let mut s = session(); + let ids: Vec = (0..3).map(|i| text_at(&mut s, 40.0, 100.0 + 40.0 * f64::from(i), "x")).collect(); + let group = group_of(&mut s, &ids); + s.execute("object.setProps", &json!({"ids": [ids[1].0], "locked": true})).unwrap(); + s.execute("object.setProps", &json!({"ids": [ids[2].0], "visible": false})).unwrap(); + let out = s.execute(C, &json!({"ids": [group.0], "end": 1, "removeUnused": true})).unwrap(); + assert_eq!(out["removed"], json!([])); + assert_eq!(ids.iter().map(|id| plain(&s, *id)).collect::>(), ["1", "x", "x"]); +} + +#[test] +fn removing_unused_type_keeps_a_clipping_mask_and_the_selection() { + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, "x"); + let b = text_at(&mut s, 40.0, 140.0, "x"); + // The top object becomes the mask; it sits lowest on the page, so rows number it last. + let mask = text_at(&mut s, 40.0, 300.0, "x"); + s.execute("select.set", &json!({"ids": [a.0, b.0, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let group = s.doc().unwrap().doc.parent_of(mask).unwrap(); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + let out = s.execute(C, &json!({"order": "rows", "end": 1, "removeUnused": true})).unwrap(); + assert_eq!(out["removed"], json!([b.0]), "the mask stays"); + assert!(s.doc().unwrap().doc.node(mask).is_some()); + assert_eq!(s.doc().unwrap().selection.objects, [group], "the group stays selected"); +} + +#[test] +fn rows_are_found_among_the_type_that_gets_numbers() { + let mut s = session(); + let upper = text_at(&mut s, 300.0, 100.0, "1"); + let lower = text_at(&mut s, 40.0, 135.0, "1"); + let h1 = NodeId(s.execute("text.create", &json!({"x": 40, "y": 400, "text": "Title", "size": 200})).unwrap()["id"].as_u64().unwrap()); + let h2 = NodeId(s.execute("text.create", &json!({"x": 40, "y": 700, "text": "Title", "size": 200})).unwrap()["id"].as_u64().unwrap()); + s.execute(C, &json!({"ids": [upper.0, lower.0, h1.0, h2.0], "replace": "numbers", "order": "rows", "start": 1, "leadingZeros": false})).unwrap(); + assert_eq!([plain(&s, upper), plain(&s, lower)], ["1", "2"], "headings without numbers do not merge the rows"); +} + +#[test] +fn a_run_that_changes_nothing_makes_no_step_and_bad_params_fail() { + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, "1"); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({"ids": [a.0]})).unwrap()["count"], json!(0)); + assert_eq!(steps(&s), n); + for p in [ + json!({"ids": [a.0], "start": "one"}), + json!({"ids": [a.0], "step": 1e13}), + json!({"ids": [a.0], "order": "diagonal"}), + json!({"ids": [a.0], "digits": 0}), + json!({"ids": [a.0], "removeUnused": true}), + json!({"ids": [a.0], "shuffle": "yes"}), + json!({"ids": [a.0], "seed": "x"}), + ] { + assert!(s.execute(C, &p).is_err(), "{p} fails"); + } + assert_eq!((plain(&s, a), steps(&s)), ("1".to_string(), n)); +} diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 84b8bc1a4f..0edfc53c54 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -1,5 +1,3 @@ -#[cfg(not(target_arch = "wasm32"))] -use super::write_atomic; use super::{EngineError, Result, Session, Value, bad, json}; // ---------- the file system (none on the web, where commands take and return bytes) ---------- @@ -325,8 +323,30 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { // Work that stops early for a cancel can leave a truncated result: none of it is written. vectorcraft_doc::cancel::check()?; may_write(path)?; - // Never a half-written file: see [`write_atomic`]. - write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e)) + // Never a half-written file: see [`vectorcraft_format::write_atomic`]. + write_checked(path, |f| std::io::Write::write_all(f, bytes)).map_err(|e| write_error(path, e)) +} + +/// [`vectorcraft_format::write_atomic_with`] for `path`, which [`may_write`] allowed. While writes +/// are checked ([`crate::file_access::writes_checked`]), the folder that receives the file is +/// checked again as it is opened, and the file goes into that open folder +/// ([`vectorcraft_format::write_atomic_checked`]): a folder on the path that is replaced after the +/// check does not redirect the write. +#[cfg(not(target_arch = "wasm32"))] +fn write_checked(path: &str, fill: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>) -> std::io::Result<()> { + let path = std::path::Path::new(path); + if !crate::file_access::writes_checked() { + return vectorcraft_format::write_atomic_with(path, fill); + } + vectorcraft_format::write_atomic_checked(path, fill, |opened| { + // On Unix `opened` is the open folder's real path with the file's name: compared as it is, + // without looking the folder up again. Elsewhere it is `path` itself. + #[cfg(unix)] + let checked = crate::file_access::check_write_real(opened); + #[cfg(not(unix))] + let checked = crate::file_access::check_write_unrecorded(&opened.to_string_lossy()); + checked.map_err(std::io::Error::other) + }) } /// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the @@ -344,7 +364,7 @@ fn write_error(path: &str, error: std::io::Error) -> EngineError { pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; - vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e)) + write_checked(path, |f| fill(f)).map_err(|e| write_error(path, e)) } /// The save commands' writer: preserves a filesystem location refusal as a typed error. Other @@ -358,7 +378,7 @@ pub fn write_save_file(path: &str, bytes: &[u8]) -> Result<()> { pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; - vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| save_write_error(path, e)) + write_checked(path, |f| fill(f)).map_err(|e| save_write_error(path, e)) } #[cfg(not(target_arch = "wasm32"))] @@ -751,4 +771,43 @@ mod tests { assert_eq!(naming_in_error(EngineError::Other(raw.clone()), &file).to_string(), raw); let _ = std::fs::remove_dir_all(base); } + + /// The second check of a checked write compares the open folder's real path as it is: a folder + /// on that path replaced afterwards by a link into the write root does not make a place outside + /// the root pass. + #[cfg(unix)] + #[test] + fn a_checked_write_compares_the_open_folder_without_looking_it_up_again() { + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-real-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (root, out) = (base.join("root"), base.join("out")); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(out.join("x")).unwrap(); + let real = out.join("x/doc.svg"); + std::fs::remove_dir(out.join("x")).unwrap(); + std::os::unix::fs::symlink(&root, out.join("x")).unwrap(); + let roots = AutomationRoots::new(&[], &[root.as_path()]).unwrap(); + assert!(confine(roots.as_ref(), || crate::file_access::check_write_unrecorded(&real.to_string_lossy())).is_ok(), "looked up, it passes"); + let checked = confine(roots.as_ref(), || crate::file_access::check_write_real(&real)); + assert!(checked.is_err_and(|e| e.contains("outside the write root"))); + let _ = std::fs::remove_dir_all(base); + } + + /// A checked write through a link to a folder whose name is not valid UTF-8, inside the write + /// root, is saved. + #[cfg(target_os = "linux")] + #[test] + fn a_checked_write_saves_into_a_folder_whose_name_is_not_text() { + use std::os::unix::ffi::OsStrExt; + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-bytes-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let bytes = base.join(std::ffi::OsStr::from_bytes(b"folder-\xff")); + std::fs::create_dir_all(&bytes).unwrap(); + std::os::unix::fs::symlink(&bytes, base.join("text")).unwrap(); + let roots = AutomationRoots::new(&[], &[base.as_path()]).unwrap(); + let path = base.join("text/doc.svg").to_string_lossy().into_owned(); + confine(roots.as_ref(), || write_file(&path, b"new")).unwrap(); + assert_eq!(std::fs::read(bytes.join("doc.svg")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(base); + } } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 27353207d1..21433cf412 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -758,12 +758,13 @@ pub(super) const ALLOWED: &[&str] = &[ /// Commands a plug-in may not call although no rule refuses them, in order: they change the /// preferences, a tool's options, a drag's state or the font names the whole app knows, list the -/// fonts installed on the system as `text.fontList` does, run plug-ins again, or read a file and -/// report where it is on disk. +/// fonts installed on the system as `text.fontList` does, run plug-ins again, read a file and +/// report where it is on disk, or edit text once per match with no limit on the matches in one call. pub(super) const DENIED: &[&str] = &[ "addon.cleanup.splitText", "addon.pathtools.movePointsTogether", "addon.pen.nextSegment", + "addon.type.numbers", "color.contrast", "effect.refreshDeferred", "graphicStyle.setOptions", diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index d60d292480..bddee74038 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1933,7 +1933,8 @@ fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec = family.into_iter().map(str::to_string).collect(); let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &fonts), &wanted); - let first = index.matches(&pieces[0].path); + // Every match, as Retype reads them: the first MAX_CANDIDATES can all be faces drawn alike. + let first = index.all_matches(&pieces[0].path); let face = match family { Some(f) => first.iter().find(|m| m.face.family == f).unwrap_or_else(|| panic!("the first glyph matches no glyph of {f}")), None => &first[0], @@ -1942,7 +1943,7 @@ 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/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index da8fac61ea..8ca5e7caa0 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, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), 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, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), 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/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(); 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); } diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 7daa75e0ae..a3bc2b5876 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -100,16 +100,9 @@ impl AutomationRoots { /// May the file or folder at `path` be read (or written)? It must lie inside one of the roots /// of that kind. `Err` says why not. pub fn check(&self, path: &str, access: Access) -> Result<(), String> { - let roots = match access { - Access::Read => &self.read, - Access::Write => &self.write, - }; - // The messages are spelled out whole, as the translation catalogs match them. + let roots = self.of(access); if roots.is_empty() { - return match access { - Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")), - Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")), - }; + return Err(refused(roots, path, access)); } // Resolving a path on another computer connects to it: unless a root is on a network // share, such a path is refused by its name before anything is looked up. @@ -120,12 +113,22 @@ impl AutomationRoots { return Ok(()); } } - let shown: Vec = roots.iter().map(|r| r.shown.display().to_string()).collect(); - match (shown.as_slice(), access) { - ([root], Access::Read) => Err(format!("automation path rejected: outside the read root {root}: {path}")), - ([root], Access::Write) => Err(format!("automation path rejected: outside the write root {root}: {path}")), - (_, Access::Read) => Err(format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", "))), - (_, Access::Write) => Err(format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", "))), + Err(refused(roots, path, access)) + } + + /// [`AutomationRoots::check`] for `real`, a path whose links have been followed already: it is + /// compared with the roots as it is, and not looked up again. + #[cfg(unix)] + pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> { + let roots = self.of(access); + if roots.iter().any(|r| inside(real, &r.resolved)) { Ok(()) } else { Err(refused(roots, &real.display().to_string(), access)) } + } + + /// The roots of the kind `access`. + fn of(&self, access: Access) -> &[Root] { + match access { + Access::Read => &self.read, + Access::Write => &self.write, } } @@ -157,6 +160,24 @@ impl AutomationRoots { } } +/// Why `path` is refused `access` under `roots`, the roots of that kind. +fn refused(roots: &[Root], path: &str, access: Access) -> String { + // The messages are spelled out whole, as the translation catalogs match them. + if roots.is_empty() { + return match access { + Access::Read => format!("automation filesystem access is not granted: read authority is absent: {path}"), + Access::Write => format!("automation filesystem access is not granted: write authority is absent: {path}"), + }; + } + let shown: Vec = roots.iter().map(|r| r.shown.display().to_string()).collect(); + match (shown.as_slice(), access) { + ([root], Access::Read) => format!("automation path rejected: outside the read root {root}: {path}"), + ([root], Access::Write) => format!("automation path rejected: outside the write root {root}: {path}"), + (_, Access::Read) => format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", ")), + (_, Access::Write) => format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", ")), + } +} + /// Where the roots are in force on a thread ([`confine`], [`unconfined`]). #[derive(Clone, Debug)] enum Scope { @@ -371,18 +392,34 @@ impl ScriptGate { also.check(path, access)?; } let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; - let allowed = real.is_some_and(|real| { - let scoped = match access { - Access::Read => self.read.allows(&real) || self.write.allows(&real), - Access::Write => self.write.allows(&real), - }; - // A read-only file is not written over, also where a rename could replace it. - let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly()); - let held = matches!(access, Access::Write) && self.held.contains(&real); - let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real); - !read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked) - }); - if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } + if real.is_some_and(|real| self.allows_real(&real, access)) { Ok(()) } else { Err(format!("Script file access denied: {path}")) } + } + + /// [`ScriptGate::check`] for `real`, a path whose links have been followed already: it is + /// compared as it is, and not looked up again. + #[cfg(unix)] + pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> { + if let Some(also) = &self.also { + also.check_real(real, access)?; + } + if !ScriptScope::refused_by_name(real) && self.allows_real(real, access) { + Ok(()) + } else { + Err(format!("Script file access denied: {}", real.display())) + } + } + + /// May the place at the real path `real` be read (or written) through this gate alone? + fn allows_real(&self, real: &Path, access: Access) -> bool { + let scoped = match access { + Access::Read => self.read.allows(real) || self.write.allows(real), + Access::Write => self.write.allows(real), + }; + // A read-only file is not written over, also where a rename could replace it. + let read_only = matches!(access, Access::Write) && std::fs::metadata(real).is_ok_and(|m| m.is_file() && m.permissions().readonly()); + let held = matches!(access, Access::Write) && self.held.iter().any(|h| h == real); + let linked = matches!(access, Access::Read) && self.linked.has(real) && !self.read.keeps_out(real); + !read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked) } } @@ -462,8 +499,7 @@ pub fn is_path_key(key: &str) -> bool { /// May `path` be written here? Always, without roots in force and outside a script's command /// ([`with_script_gate`]). pub fn check_write(path: &str) -> Result<(), String> { - current().map_or(Ok(()), |r| r.check(path, Access::Write))?; - check_gate(path, Access::Write)?; + check_write_unrecorded(path)?; WRITES.with(|w| { if let Some(paths) = w.borrow_mut().as_mut() && !paths.iter().any(|(p, _)| p == path) @@ -474,6 +510,26 @@ pub fn check_write(path: &str) -> Result<(), String> { Ok(()) } +/// [`check_write`] without recording `path` as written. +pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { + current().map_or(Ok(()), |r| r.check(path, Access::Write))?; + check_gate(path, Access::Write) +} + +/// [`check_write_unrecorded`] for `real`, the path of a file in a folder whose links have been +/// followed already (the folder a checked write has opened): it is compared as it is, so the folder +/// is not looked up again by its path. +#[cfg(unix)] +pub(crate) fn check_write_real(real: &Path) -> Result<(), String> { + current().map_or(Ok(()), |r| r.check_real(real, Access::Write))?; + GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write)) +} + +/// Whether a write here is checked: roots are in force, or a script's command runs. +pub(crate) fn writes_checked() -> bool { + current().is_some() || in_script_command() +} + /// A file's modification time and length; `None` when there is no file at `path`. type Stamp = Option<(Option, u64)>; @@ -1200,6 +1256,7 @@ mod tests { fn a_script_gate_does_not_write_over_a_read_only_file() { let (base, _) = folders("gate-read-only"); let out = base.join("out/kept.svg"); + let _cleanup = ReadOnlyFixture { file: out.clone(), folder: base.clone() }; std::fs::write(&out, "").unwrap(); let gate = ScriptGate { read: ScriptScope::default(), @@ -1218,14 +1275,47 @@ mod tests { assert!(document_write(), "an open document's file is written"); let mut perms = std::fs::metadata(&out).unwrap().permissions(); perms.set_readonly(true); - std::fs::set_permissions(&out, perms.clone()).unwrap(); + std::fs::set_permissions(&out, perms).unwrap(); assert_eq!(check(&kept), (false, true), "a read-only file is read but not written"); assert!(check(&fresh).0, "a new file next to it is written"); assert!(!document_write(), "also when it is an open document's file"); - #[allow(clippy::permissions_set_readonly_false)] - perms.set_readonly(false); - std::fs::set_permissions(&out, perms).unwrap(); - let _ = std::fs::remove_dir_all(base); + } + + /// Makes `file` writable again and removes `folder` when the test ends, a failed assertion + /// included: Windows does not delete a read-only file. + struct ReadOnlyFixture { + file: PathBuf, + folder: PathBuf, + } + + impl Drop for ReadOnlyFixture { + fn drop(&mut self) { + if let Ok(meta) = std::fs::metadata(&self.file) { + let mut perms = meta.permissions(); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + let _ = std::fs::set_permissions(&self.file, perms); + } + let _ = std::fs::remove_dir_all(&self.folder); + } + } + + #[test] + fn a_read_only_fixture_is_removed_when_its_test_fails() { + let (base, _) = folders("read-only-fixture"); + let file = base.join("out/locked.svg"); + std::fs::write(&file, "").unwrap(); + let failed = std::panic::catch_unwind(|| { + let _cleanup = ReadOnlyFixture { file: file.clone(), folder: base.clone() }; + let mut perms = std::fs::metadata(&file).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&file, perms).unwrap(); + assert!(std::fs::metadata(&file).unwrap().permissions().readonly(), "the fixture is read-only"); + panic!("a failed assertion"); + }); + let payload = failed.err().unwrap_or_else(|| panic!("the closure did not panic")); + assert_eq!(payload.downcast_ref::<&str>(), Some(&"a failed assertion"), "the test's own panic, not a setup failure"); + assert!(!base.exists(), "{} is left", base.display()); } #[test] diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 2d86ff76f0..5a911d599a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -978,9 +978,16 @@ pub(super) fn after_kept_command(h: &Host) { /// selection cannot be put back, the edit is undone too. The points the run read of the item's /// paths stay valid through the change ([`paths::see_all_points`]). fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { + edit_item_with(h, item, |h| command(h, id, params)) +} + +/// Runs `f` on the item's document as [`edit_item`] runs its command. `f` runs after the document +/// is made active, so bounds it reads take in type that the switch measured again (in the +/// document's own composite fonts, [`Session::set_active`]). +fn edit_item_with(h: &Host, item: Item, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { paths::see_all_points(h); let kept = h.dom.editing.replace(Some(item)); - let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params))); + let r = atomically(h, |h| on_doc(h, item.doc.uid, true, f)); h.dom.editing.set(kept); r } @@ -2565,14 +2572,18 @@ fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { let item = this_item(h, a)?; refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; - let c = h.dom.coords.get(); - let now = f.to_script(c, Point::new(r.x0, r.y0)); - let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); - let (dx, dy) = (to.x - r.x0, to.y - r.y0); - if dx.abs() > 1e-9 || dy.abs() > 1e-9 { - edit_item(h, item, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?; - } + // Measured once the document is active. + edit_item_with(h, item, |h| { + let (Some(r), f) = item_rect(h, item, false)? else { return Ok(()) }; + let c = h.dom.coords.get(); + let now = f.to_script(c, Point::new(r.x0, r.y0)); + let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); + let (dx, dy) = (to.x - r.x0, to.y - r.y0); + if dx.abs() > 1e-9 || dy.abs() > 1e-9 { + command(h, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?; + } + Ok(()) + })?; Ok(Data::Undefined) } @@ -2606,18 +2617,21 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer { } refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; - let now = if width { r.width() } else { r.height() }; - if now <= 0.0 { - return Err(HostError::Error(format!("the object has no {what} to scale"))); - } - if (now - size).abs() < 1e-9 { - return Ok(Data::Undefined); - } - let pct = size / now * 100.0; - let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; - let p = json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}); - edit_item(h, item, "object.scale", &p)?; + // Measured once the document is active, so the ratio applies to the bounds the scale works on. + edit_item_with(h, item, |h| { + let (Some(r), _) = item_rect(h, item, false)? else { return Ok(()) }; + let now = if width { r.width() } else { r.height() }; + if now <= 0.0 { + return Err(HostError::Error(format!("the object has no {what} to scale"))); + } + if (now - size).abs() < 1e-9 { + return Ok(()); + } + let pct = size / now * 100.0; + let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; + command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?; + Ok(()) + })?; Ok(Data::Undefined) } 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/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_dom.rs b/crates/engine/src/tests/script_dom.rs index 1a2948545b..a9c6264fb5 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -167,6 +167,37 @@ fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was"); } +/// Type in a document in the back that the switch to that document measures again (here: not +/// measured yet) is sized and moved by the bounds measured after the switch. +#[test] +fn page_item_size_and_position_setters_measure_type_in_a_back_document_after_the_switch() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Wide type here", "size": 40})).unwrap()["id"].as_u64().unwrap()); + let uid = s.active().unwrap().uid; + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let front = s.active().unwrap().uid; + let unmeasure = |s: &mut Session| { + let st = s.document_mut(uid).unwrap(); + if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).map(|n| &mut n.kind) { + t.cached_bounds = None; + t.cached_baselines.clear(); + } + }; + let mut got = Vec::new(); + for (set, want) in + [("t.width = 150; vc.log(t.width);", 150.0), ("t.height = 90; vc.log(t.height);", 90.0), ("t.top = 200; vc.log(t.top);", 200.0)] + { + unmeasure(&mut s); + let out = log(&mut s, &format!("var t = app.documents[1].pageItems[0]; {set}")); + got.push((set, out[0].as_f64().unwrap(), want)); + } + for (set, got, want) in got { + assert!((got - want).abs() < 1e-6, "{set} read {got}"); + } + assert_eq!(s.active().unwrap().uid, front, "the front document stays in front"); +} + /// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the /// visible bounds. #[test] diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index fe56754ca3..2373640149 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"); @@ -370,6 +404,37 @@ fn a_js_script_reads_object_literal_extensions_and_function_names_and_a_jsx_scri assert!(run(&mut s, "var a = 1; var o = { a };").unwrap_err().to_string().contains("SyntaxError")); } +#[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}"); + // 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); +} + #[test] fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() { let dir = fresh_folder("es2020"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 12db366846..b683ddbbd9 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -10,13 +10,77 @@ use crate::*; const DENIED: &str = "Script file access denied"; +/// A test's folder, removed when the test ends, a failed assertion included. A read-only file in +/// it, which Windows does not delete, is made writable first when the first removal fails. +struct Workspace(PathBuf); + +impl std::ops::Deref for Workspace { + type Target = Path; + + fn deref(&self) -> &Path { + &self.0 + } +} + +impl AsRef for Workspace { + fn as_ref(&self) -> &Path { + &self.0 + } +} + +impl Drop for Workspace { + fn drop(&mut self) { + if std::fs::remove_dir_all(&self.0).is_err() { + make_writable(&self.0); + let _ = std::fs::remove_dir_all(&self.0); + } + } +} + +/// Clears the read-only flag of every file and folder in `path`, `path` included. Links are not +/// followed. +fn make_writable(path: &Path) { + let Ok(meta) = std::fs::symlink_metadata(path) else { return }; + if meta.file_type().is_symlink() { + return; + } + let mut perms = meta.permissions(); + if perms.readonly() { + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + let _ = std::fs::set_permissions(path, perms); + } + if meta.is_dir() { + for entry in std::fs::read_dir(path).into_iter().flatten().flatten() { + make_writable(&entry.path()); + } + } +} + /// A fresh folder for test `name`, by its real path, with `main` for the script. -fn folder(name: &str) -> PathBuf { +fn folder(name: &str) -> Workspace { let base = std::env::temp_dir().join(format!("vc-script-save-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); std::fs::create_dir_all(base.join("main")).unwrap(); std::fs::create_dir_all(base.join("outside")).unwrap(); - std::fs::canonicalize(&base).unwrap() + Workspace(std::fs::canonicalize(&base).unwrap()) +} + +/// A test that fails leaves no folder behind, also when it made a file in it read-only. +#[test] +fn a_failed_test_leaves_no_folder() { + let base = folder("failed"); + let path = base.to_path_buf(); + let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let locked = base.join("main/locked.txt"); + std::fs::write(&locked, b"x").unwrap(); + let mut perms = std::fs::metadata(&locked).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&locked, perms).unwrap(); + panic!("a failed assertion"); + })); + assert!(failed.is_err()); + assert!(!path.exists(), "{} is left", path.display()); } /// A session whose scripts keep their data folders in `base/settings/Script Data`. @@ -212,6 +276,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)] diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index f314fcdd15..d759ff6d9f 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -82,6 +82,285 @@ fn create_new(path: &Path) -> io::Result { OpenOptions::new().write(true).create_new(true).open(path) } +/// [`write_atomic_with`] for a `path` the caller has allowed by its name. On Unix the folder that +/// holds the file is opened once, and `allowed` is asked again with the path that open folder has +/// then, joined with the file's name. The temporary file, the replacement, a copy over the file +/// where the folder refuses the replacement, and the folder flush all go through that open folder, +/// and none of them looks its path up again. A folder replaced (or swapped for a link) before it is +/// opened fails `allowed`. A folder replaced after it is opened does not receive the file. A link at +/// the final name is followed once before the folder is opened, as [`write_atomic_with`] follows it; +/// a link put there later is replaced, never followed. Elsewhere this is `allowed(path)` followed by +/// [`write_atomic_with`]. +#[cfg(unix)] +pub fn write_atomic_checked( + path: &Path, + fill: impl FnOnce(&mut File) -> io::Result<()>, + allowed: impl FnOnce(&Path) -> io::Result<()>, +) -> io::Result<()> { + use rustix::fs::{AtFlags, Mode, OFlags}; + // A path written as a folder (`draft.svg/`, `draft.svg/.`) is not a file path: `file_name` + // would drop the slash and save `draft.svg`. + let spelled = std::os::unix::ffi::OsStrExt::as_bytes(path.as_os_str()); + if spelled.ends_with(b"/") || spelled.ends_with(b"/.") || spelled == b"." { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display()))); + } + let resolved = resolve_link(path)?; + let name = resolved + .file_name() + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", resolved.display())))? + .to_os_string(); + let parent = resolved.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + let dir = open_folder(parent)?; + let real = opened_folder_path(&dir, parent)?; + let target = real.join(stored_name(&dir, &real, &name)); + allowed(&target)?; + // Only whether a file is there: its permissions are read again once it is about to be replaced. + let replacing = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW).is_ok(); + let tmp_name = temp_path(&target)?.file_name().map(std::ffi::OsStr::to_os_string).unwrap_or_default(); + // Replacing a file: owner-only while it is written, as in `write_atomic_with`. + let mode = if replacing { Mode::RUSR | Mode::WUSR } else { Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::WGRP | Mode::ROTH | Mode::WOTH }; + let new_file = OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC; + let remove_tmp = || { + // Best effort: the temporary file is all there is to clean up. + let _ = rustix::fs::unlinkat(&dir, &tmp_name, AtFlags::empty()); + }; + // The folder may have moved since it was opened: messages name it where it is now. + let now = |file: &std::ffi::OsStr| folder_now(&dir, &real).join(file); + let synced = || { + // Opened for reading here: the folder handle above may allow name lookups only. + let flushed = + rustix::fs::openat(&dir, ".", OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()).and_then(|d| rustix::fs::fsync(&d)); + flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() })) + }; + let open_target = |write: bool| -> io::Result { + let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY }; + Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?)) + }; + match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) { + Ok(mut f) => { + let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); + if let Err(e) = filled { + drop(f); + remove_tmp(); + return Err(e); + } + // The file's permissions as they are now, after `fill`, as in `write_atomic_with`: a + // change made to them meanwhile is kept. Best effort; a file that can't be looked at + // leaves the replacement owner-only. + if let Ok(old) = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW) { + let _ = keep_permissions_at(&dir, &name, &old, &f); + } + drop(f); + #[cfg(test)] + let refuse = RENAME_REFUSED.with(std::cell::Cell::get); + #[cfg(not(test))] + let refuse = false; + let renamed = if refuse { Err(rustix::io::Errno::ACCESS) } else { rustix::fs::renameat(&dir, &tmp_name, &dir, &name) }; + let Err(refused) = renamed else { return synced() }; + // The file as it was is copied beside the temporary file, through the open folder, or + // to the system's folder where the open folder takes no new file. + let old_name = Path::new(&tmp_name).with_extension("old").into_os_string(); + let old_elsewhere = std::env::temp_dir().join(&old_name); + let old_in_folder = std::cell::Cell::new(true); + let over = Over { + tmp: &|| now(&tmp_name), + create_old: &|| match rustix::fs::openat(&dir, &old_name, new_file, Mode::RUSR | Mode::WUSR) { + Ok(f) => { + old_in_folder.set(true); + Ok(File::from(f)) + } + Err(e) if e == rustix::io::Errno::EXIST => Err(e.into()), + Err(_) => { + old_in_folder.set(false); + create_private(&old_elsewhere) + } + }, + old: &|| if old_in_folder.get() { now(&old_name) } else { old_elsewhere.clone() }, + remove_old: &|| { + // Best effort: an unfinished copy is of no use. + if old_in_folder.get() { + let _ = rustix::fs::unlinkat(&dir, &old_name, AtFlags::empty()); + } else { + let _ = std::fs::remove_file(&old_elsewhere); + } + }, + open_tmp: &|| { + Ok(File::from(rustix::fs::openat(&dir, &tmp_name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty())?)) + }, + remove_tmp: &remove_tmp, + open_target: &open_target, + synced: &synced, + }; + write_over_in(&over, refused.into()) + } + // A folder that isn't there, a full volume: nothing can be saved there. + Err(e) if matches!(io::Error::from(e).kind(), io::ErrorKind::NotFound | io::ErrorKind::StorageFull | io::ErrorKind::QuotaExceeded) => { + Err(e.into()) + } + Err(refused) => { + // The folder takes no temporary file: it is written in the system's folder and copied in. + let elsewhere = std::env::temp_dir().join(&tmp_name); + let mut f = create_private(&elsewhere).map_err(|_| io::Error::from(refused))?; + let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); + drop(f); + let remove = || { + // Best effort: the temporary file is all there is to clean up. + let _ = std::fs::remove_file(&elsewhere); + }; + if let Err(e) = filled { + remove(); + return Err(e); + } + let old = elsewhere.with_extension("old"); + let over = Over { + tmp: &|| elsewhere.clone(), + create_old: &|| create_private(&old), + old: &|| old.clone(), + remove_old: &|| { + let _ = std::fs::remove_file(&old); + }, + open_tmp: &|| File::open(&elsewhere), + remove_tmp: &remove, + open_target: &open_target, + synced: &synced, + }; + write_over_in(&over, refused.into()) + } + } +} + +/// See the Unix version. +#[cfg(not(unix))] +pub fn write_atomic_checked( + path: &Path, + fill: impl FnOnce(&mut File) -> io::Result<()>, + allowed: impl FnOnce(&Path) -> io::Result<()>, +) -> io::Result<()> { + allowed(path)?; + write_atomic_with(path, fill) +} + +/// The path folder `dir` has now, which `parent` named when it was opened: `parent` with its links +/// followed, when that is still the folder `dir` holds (the same device and inode). A folder +/// replaced in between is an error. +#[cfg(unix)] +fn opened_folder_path(dir: &std::os::fd::OwnedFd, parent: &Path) -> io::Result { + let real = std::fs::canonicalize(parent)?; + let (open, now) = (rustix::fs::fstat(dir)?, rustix::fs::stat(&real)?); + if (open.st_dev, open.st_ino) != (now.st_dev, now.st_ino) { + // Not a permission the file system refused: [`read_only_location`] does not take it for one. + return Err(io::Error::other(format!("{}: the folder changed while it was opened", parent.display()))); + } + Ok(real) +} + +/// The name the entry `name` in the open folder `dir`, whose real path is `real`, is stored under. +/// On a volume that ignores letter case, `report.svg` can be stored as `Report.svg`, the name a +/// grant for that file was given. `name` itself when nothing is there, or when the entry the path +/// leads to is not the one in `dir` (the same device and inode, links not followed). +#[cfg(unix)] +fn stored_name(dir: &std::os::fd::OwnedFd, real: &Path, name: &std::ffi::OsStr) -> std::ffi::OsString { + use rustix::fs::AtFlags; + let Ok(here) = rustix::fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) else { return name.to_os_string() }; + let Ok(stored) = std::fs::canonicalize(real.join(name)) else { return name.to_os_string() }; + let same = stored.parent() == Some(real) && rustix::fs::lstat(&stored).is_ok_and(|s| (s.st_dev, s.st_ino) == (here.st_dev, here.st_ino)); + match stored.file_name() { + Some(stored) if same => stored.to_os_string(), + _ => name.to_os_string(), + } +} + +/// The folder at `parent`, opened for looking names up in it. On Linux, Android and FreeBSD that +/// is `O_PATH`, and on Apple platforms `O_SEARCH`: neither needs permission to list the folder, so +/// a folder that can be written and searched but not listed still takes the file. Where the system +/// refuses `O_SEARCH`, the folder is opened for reading. +#[cfg(unix)] +fn open_folder(parent: &Path) -> io::Result { + use rustix::fs::{Mode, OFlags}; + #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] + let access = OFlags::PATH; + #[cfg(target_vendor = "apple")] + { + // `O_EXEC`, which with `O_DIRECTORY` is `O_SEARCH` (). + let search = OFlags::from_bits_retain(0x4000_0000); + match rustix::fs::open(parent, search | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()) { + Err(e) if e == rustix::io::Errno::INVAL => {} + opened => return Ok(opened?), + } + } + #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "freebsd")))] + let access = OFlags::RDONLY; + Ok(rustix::fs::open(parent, access | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty())?) +} + +/// The path the open folder `dir` has now, which may differ from `opened`, its real path when it +/// was opened, after it moved. `opened` where the system does not say. +#[cfg(unix)] +fn folder_now(dir: &std::os::fd::OwnedFd, opened: &Path) -> PathBuf { + #[cfg(any(target_os = "linux", target_os = "android"))] + if let Ok(now) = std::fs::read_link(format!("/proc/self/fd/{}", std::os::fd::AsRawFd::as_raw_fd(dir))) + && now.is_absolute() + { + return now; + } + #[cfg(target_vendor = "apple")] + if let Ok(now) = rustix::fs::getpath(dir) { + return PathBuf::from(::from_vec(now.into_bytes())); + } + let _ = dir; + opened.to_path_buf() +} + +/// [`keep_permissions`] for the temporary file `tmp`, about to replace `name` in folder `dir`, whose +/// file has the status `old`. A name that does not hold a plain file has none to keep. The ACL is +/// read only from that same file (the same device and inode); when it can't be, the replacement +/// keeps no group or other permissions. +#[cfg(unix)] +fn keep_permissions_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: &rustix::fs::Stat, tmp: &File) -> io::Result<()> { + use rustix::fs::{FileType, Mode}; + if FileType::from_raw_mode(old.st_mode) != FileType::RegularFile { + return Ok(()); + } + let mut mode = Mode::from_raw_mode(old.st_mode); + let gid = rustix::fs::Gid::from_raw(old.st_gid); + let kept_group = rustix::fs::fstat(tmp).is_ok_and(|t| t.st_gid == old.st_gid) || rustix::fs::fchown(tmp, None, Some(gid)).is_ok(); + if !kept_group || !keep_acl_at(dir, name, old, tmp) { + mode.remove(Mode::RWXG | Mode::RWXO); + } + rustix::fs::fchmod(tmp, mode).map_err(io::Error::from) +} + +/// [`keep_acl`] for `name` in folder `dir`, when it is still the file with the status `old`. The +/// file is opened with `O_PATH` without following a link, which needs no permission to read it, and +/// its ACL is read through `/proc/self/fd`, which names that open file. +#[cfg(target_os = "linux")] +fn keep_acl_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: &rustix::fs::Stat, tmp: &File) -> bool { + use rustix::fs::{Mode, OFlags}; + use rustix::io::Errno; + const ACL: &str = "system.posix_acl_access"; + let Ok(target) = rustix::fs::openat(dir, name, OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty()) else { + return false; + }; + if !rustix::fs::fstat(&target).is_ok_and(|t| (t.st_dev, t.st_ino) == (old.st_dev, old.st_ino)) { + return false; + } + let opened = format!("/proc/self/fd/{}", std::os::fd::AsRawFd::as_raw_fd(&target)); + let mut buf = vec![0u8; 64 << 10]; + match rustix::fs::getxattr(opened.as_str(), ACL, &mut buf[..]) { + Ok(n) => buf.get(..n).is_some_and(|acl| rustix::fs::fsetxattr(tmp, ACL, acl, rustix::fs::XattrFlags::empty()).is_ok()), + Err(e) if e == Errno::NODATA => match rustix::fs::fremovexattr(tmp, ACL) { + Ok(()) => true, + Err(e) => e == Errno::NODATA || e == Errno::NOTSUP, + }, + Err(e) => e == Errno::NOTSUP, + } +} + +#[cfg(all(unix, not(target_os = "linux")))] +fn keep_acl_at(_: &std::os::fd::OwnedFd, _: &std::ffi::OsStr, _: &rustix::fs::Stat, _: &File) -> bool { + true +} + /// [`write_atomic_with`], with `create` making the temporary file beside the target and `rename` /// moving it over the target. fn write_atomic_stepping( @@ -130,47 +409,114 @@ fn write_atomic_stepping( /// the copy into `target` fails it is damaged: `tmp` and the copy of the old content stay and the /// error says where they are. fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { - let opened = File::open(tmp).and_then(|from| Ok((from, OpenOptions::new().write(true).create(true).truncate(false).open(target)?))); + let old = tmp.with_extension("old"); + let over = Over { + tmp: &|| tmp.to_path_buf(), + create_old: &|| create_private(&old), + old: &|| old.clone(), + remove_old: &|| { + let _ = std::fs::remove_file(&old); + }, + open_tmp: &|| File::open(tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(tmp); + }, + open_target: &|write| if write { OpenOptions::new().write(true).create(true).truncate(false).open(target) } else { File::open(target) }, + synced: &|| sync_written_parent(target), + }; + write_over_in(&over, refused) +} + +/// How [`write_over_in`] reaches its files: by their paths, or through a folder opened once +/// ([`write_atomic_checked`]). +struct Over<'a> { + /// Where the temporary file is when an error message names it (its folder may have moved). + tmp: &'a dyn Fn() -> PathBuf, + /// A new file, for its owner only and never replacing one, that the file as it was is copied to. + create_old: &'a dyn Fn() -> io::Result, + /// Where the file `create_old` made is when an error message names it. + old: &'a dyn Fn() -> PathBuf, + /// Best effort: removes the file `create_old` made. + remove_old: &'a dyn Fn(), + open_tmp: &'a dyn Fn() -> io::Result, + /// Best effort. + remove_tmp: &'a dyn Fn(), + /// The target for writing (created when missing, not truncated) when `true`, for reading when + /// `false`. + open_target: &'a dyn Fn(bool) -> io::Result, + /// The target's folder flushed, after the target is written. + synced: &'a dyn Fn() -> io::Result<()>, +} + +/// [`write_over`] through `over`. +fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { + let opened = (over.open_tmp)().and_then(|from| Ok((from, (over.open_target)(true)?))); let Ok((mut from, mut to)) = opened else { // Best effort: the temporary file is all there is to clean up. - let _ = std::fs::remove_file(tmp); + (over.remove_tmp)(); return Err(refused); }; - // Nothing to keep of a file that is new or empty. - let old = to.metadata().map_or(true, |m| m.len() > 0).then(|| tmp.with_extension("old")); - if let Some(old) = &old - && let Err(e) = keep_old(target, old) + // Nothing to keep of a file that is new or empty. The copy is read from the file `to` writes + // into: one put at its name meanwhile is not copied in its place. + let kept = to.metadata().map_or(true, |m| m.len() > 0); + if kept + && let Err(e) = (over.open_target)(false).and_then(|mut target| { + if !same_file(&target, &to) { + return Err(io::Error::other("the file was replaced while it was opened")); + } + keep_old(&mut target, over) + }) { - // Best effort: a partial copy is of no use. - let _ = std::fs::remove_file(old); - let why = - format!("{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", tmp.display()); + let why = format!( + "{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", + (over.tmp)().display() + ); return Err(io::Error::new(refused.kind(), RecoveryError(why))); } let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to)); drop((from, to)); - match (copied, old) { - (Ok(()), old) => { + match (copied, kept) { + (Ok(()), kept) => { // Best effort: the file is saved, so the copies are no longer needed. - let _ = std::fs::remove_file(tmp); - if let Some(old) = old { - let _ = std::fs::remove_file(old); + (over.remove_tmp)(); + if kept { + (over.remove_old)(); } - sync_written_parent(target) + (over.synced)() } - (Err(e), Some(old)) => Err(io::Error::new( + (Err(e), true) => Err(io::Error::new( e.kind(), - RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", tmp.display(), old.display())), + RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", (over.tmp)().display(), (over.old)().display())), )), - (Err(e), None) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", tmp.display())))), + (Err(e), false) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", (over.tmp)().display())))), } } -/// A flushed copy of `target` as it is, at `old` (for its owner only). -fn keep_old(target: &Path, old: &Path) -> io::Result<()> { - let mut to = create_private(old)?; - io::copy(&mut File::open(target)?, &mut to)?; - sync_file(&to) +/// A flushed copy of what `target` holds, in the file `over.create_old` makes. A copy this call made +/// and could not finish is removed; a file already at that name is left as it is. +fn keep_old(target: &mut File, over: &Over<'_>) -> io::Result<()> { + let mut to = (over.create_old)()?; + let copied = io::copy(target, &mut to).and_then(|_| sync_file(&to)); + if copied.is_err() { + drop(to); + (over.remove_old)(); + } + copied +} + +/// Whether `a` and `b` are open on the same file (the same device and inode). Always `true` off +/// Unix. +fn same_file(a: &File, b: &File) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + matches!((a.metadata(), b.metadata()), (Ok(a), Ok(b)) if (a.dev(), a.ino()) == (b.dev(), b.ino())) + } + #[cfg(not(unix))] + { + let _ = (a, b); + true + } } /// A new file for its owner only (Unix): the system's temporary folder is shared. @@ -325,6 +671,9 @@ thread_local! { static FLUSHES_LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) }; /// Tests: how many plain `fsync` fallbacks were made on this thread. static PLAIN_FSYNCS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: [`write_atomic_checked`]'s folder refuses the rename. + #[cfg(unix)] + static RENAME_REFUSED: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// A symbolic link keeps pointing at its file: write the file it names. @@ -466,6 +815,282 @@ mod tests { true } + /// A folder `root/inside` and a folder `outside` beside `root`, by their real paths, and a check + /// that allows paths under `root` only. + #[cfg(unix)] + fn checked_folders(name: &str) -> (PathBuf, PathBuf, PathBuf) { + let d = std::fs::canonicalize(dir(name)).unwrap(); + let (root, outside) = (d.join("root"), d.join("outside")); + std::fs::create_dir_all(root.join("inside")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + (d, root, outside) + } + + #[cfg(unix)] + fn under(root: &Path) -> impl FnOnce(&Path) -> io::Result<()> + '_ { + move |p: &Path| if p.starts_with(root) { Ok(()) } else { Err(io::Error::other(format!("{} is outside", p.display()))) } + } + + /// A folder on the path that is a link to a folder outside when the write starts fails the check + /// made on the folder that is opened, and nothing is written outside. + #[cfg(unix)] + #[test] + fn a_checked_write_refuses_a_folder_replaced_before_it_is_opened() { + let (d, root, outside) = checked_folders("checked-before"); + std::fs::remove_dir(root.join("inside")).unwrap(); + std::os::unix::fs::symlink(&outside, root.join("inside")).unwrap(); + let r = write_atomic_checked(&root.join("inside/doc.txt"), |f| f.write_all(b"new"), under(&root)); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("is outside")), "{r:?}"); + assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing is left outside"); + let _ = std::fs::remove_dir_all(d); + } + + /// A folder on the path replaced by a link to a folder outside after it is checked and opened + /// does not redirect the write: the file goes into the folder that was opened. + #[cfg(unix)] + #[test] + fn a_checked_write_stays_in_the_folder_it_opened() { + let (d, root, outside) = checked_folders("checked-after"); + let check = under(&root); + let r = write_atomic_checked( + &root.join("inside/doc.txt"), + |f| f.write_all(b"new"), + |p| { + check(p)?; + std::fs::rename(root.join("inside"), root.join("moved"))?; + std::os::unix::fs::symlink(&outside, root.join("inside")) + }, + ); + r.unwrap(); + assert!(!outside.join("doc.txt").exists(), "the write followed the replaced folder"); + assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + + /// A link put at the file's name after the check is replaced by the file, not followed. + #[cfg(unix)] + #[test] + fn a_checked_write_replaces_a_link_put_at_its_name() { + let (d, root, outside) = checked_folders("checked-link"); + std::fs::write(outside.join("other.txt"), b"keep").unwrap(); + let path = root.join("inside/doc.txt"); + let check = under(&root); + write_atomic_checked( + &path, + |f| f.write_all(b"new"), + |p| { + check(p)?; + std::os::unix::fs::symlink(outside.join("other.txt"), &path) + }, + ) + .unwrap(); + assert_eq!(std::fs::read(outside.join("other.txt")).unwrap(), b"keep"); + assert!(std::fs::symlink_metadata(&path).unwrap().is_file()); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + + /// Permissions taken away from the file while the new content is written stay taken away. + #[cfg(unix)] + #[test] + fn a_checked_write_keeps_permissions_changed_while_it_fills() { + use std::os::unix::fs::PermissionsExt; + let (d, root, _) = checked_folders("checked-mode"); + let path = root.join("inside/doc.txt"); + std::fs::write(&path, b"old").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + let fill = |f: &mut File| { + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?; + f.write_all(b"new") + }; + write_atomic_checked(&path, fill, under(&root)).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + + /// A folder that changed between being opened and being looked up by its path is not reported + /// as a read-only location. + #[cfg(unix)] + #[test] + fn a_changed_folder_is_not_a_read_only_location() { + let (d, root, outside) = checked_folders("checked-identity"); + let opened = open_folder(&root.join("inside")).unwrap(); + let e = opened_folder_path(&opened, &outside).unwrap_err(); + assert!(e.to_string().contains("the folder changed while it was opened"), "{e}"); + assert!(!read_only_location(&e), "{e:?}"); + let _ = std::fs::remove_dir_all(d); + } + + /// A checked write whose folder moved after it was opened, refused the rename, and failed to + /// copy into the file: the temporary file and the copy of the old content stay in that folder, + /// and the error names them where they are now. (FreeBSD does not say where an open folder is + /// now: there the error names them where the folder was opened.) + #[cfg(unix)] + #[test] + fn a_checked_write_names_the_kept_file_where_its_folder_moved() { + let (d, root, _) = checked_folders("checked-moved"); + std::fs::write(root.join("inside/doc.txt"), b"original").unwrap(); + let check = under(&root); + let r = write_atomic_checked( + &root.join("inside/doc.txt"), + |f| f.write_all(b"new"), + |p| { + check(p)?; + std::fs::rename(root.join("inside"), root.join("moved"))?; + RENAME_REFUSED.with(|c| c.set(true)); + // The temporary file's flush and the copy of the old content work, the next doesn't. + FLUSHES_LEFT.with(|c| c.set(Some(2))); + Ok(()) + }, + ); + RENAME_REFUSED.with(|c| c.set(false)); + FLUSHES_LEFT.with(|c| c.set(None)); + let message = r.unwrap_err().to_string(); + let kept = |ext: &str| -> PathBuf { + let found: Vec<_> = std::fs::read_dir(root.join("moved")) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.extension().is_some_and(|x| x == ext)) + .collect(); + let [kept] = found.as_slice() else { panic!("one .{ext} file: {found:?}") }; + std::fs::canonicalize(kept).unwrap() + }; + let (tmp, old) = (kept("tmp"), kept("old")); + assert_eq!((std::fs::read(&tmp).unwrap(), std::fs::read(&old).unwrap()), (b"new".to_vec(), b"original".to_vec())); + let named_in = + if cfg!(any(target_os = "linux", target_os = "android", target_vendor = "apple")) { root.join("moved") } else { root.join("inside") }; + for file in [&tmp, &old] { + let named = named_in.join(file.file_name().unwrap()); + assert!(message.contains(&named.display().to_string()), "{} in {message}", named.display()); + } + let _ = std::fs::remove_dir_all(d); + } + + /// A refused rename copies the old content through the file handle it then overwrites: when a + /// different file is at the name by the time it is opened for reading, nothing is overwritten and + /// the new content stays in the temporary file. + #[cfg(unix)] + #[test] + fn a_refused_rename_copies_aside_the_file_it_overwrites() { + let d = dir("no-rename-swapped"); + let (path, other, tmp) = (d.join("doc.txt"), d.join("other.txt"), d.join("doc.tmp")); + std::fs::write(&path, b"original").unwrap(); + std::fs::write(&other, b"someone else's").unwrap(); + std::fs::write(&tmp, b"new").unwrap(); + let old = d.join("doc.old"); + let over = Over { + tmp: &|| tmp.clone(), + create_old: &|| create_private(&old), + old: &|| old.clone(), + remove_old: &|| { + let _ = std::fs::remove_file(&old); + }, + open_tmp: &|| File::open(&tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(&tmp); + }, + open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&other) }, + synced: &|| Ok(()), + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert!(e.to_string().contains("the file was replaced while it was opened"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + assert_eq!(std::fs::read(&tmp).unwrap(), b"new"); + assert!(!old.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// A path written as a folder is refused, and no file is made under the name before the slash. + #[cfg(unix)] + #[test] + fn a_checked_write_refuses_a_path_written_as_a_folder() { + let (d, root, _) = checked_folders("checked-slash"); + for spelled in ["inside/draft.svg/", "inside/draft.svg/."] { + let r = write_atomic_checked(&root.join(spelled), |f| f.write_all(b"new"), under(&root)); + assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::InvalidInput), "{spelled}"); + } + assert!(!root.join("inside/draft.svg").exists()); + write_atomic_checked(&root.join("inside/draft.svg"), |f| f.write_all(b"new"), under(&root)).unwrap(); + assert_eq!(std::fs::read(root.join("inside/draft.svg")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + + /// On a volume that ignores letter case, a write to `report.txt` where `Report.txt` is stored + /// is checked as `Report.txt`, the name a grant for the file has. (Skipped where the volume keeps + /// letter case apart.) + #[cfg(unix)] + #[test] + fn a_checked_write_checks_the_stored_name_of_the_file() { + let (d, root, _) = checked_folders("checked-case"); + let stored = root.join("inside/Report.txt"); + std::fs::write(&stored, b"old").unwrap(); + if !root.join("inside/report.txt").exists() { + let _ = std::fs::remove_dir_all(d); + return; + } + let exact = |p: &Path| if p == stored { Ok(()) } else { Err(io::Error::other(format!("{} is not granted", p.display()))) }; + write_atomic_checked(&root.join("inside/report.txt"), |f| f.write_all(b"new"), exact).unwrap(); + assert_eq!(std::fs::read(&stored).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + + /// A replaced file that its owner may write but not read keeps the ACL that lets someone else + /// read it. (Skipped on a file system without ACLs, and for root, which can read any file.) + #[cfg(target_os = "linux")] + #[test] + fn a_checked_write_keeps_the_acl_of_a_file_its_owner_cannot_read() { + use std::os::unix::fs::PermissionsExt; + const ACL: &str = "system.posix_acl_access"; + let (d, root, _) = checked_folders("checked-acl-write-only"); + let path = root.join("inside/doc.txt"); + std::fs::write(&path, b"old").unwrap(); + // u::-w-, u:nobody:r--, g::---, m::r--, o::--- + let mut acl = 2u32.to_le_bytes().to_vec(); + for (tag, perm, id) in [(0x01u16, 2u16, u32::MAX), (0x02, 4, 65534), (0x04, 0, u32::MAX), (0x10, 4, u32::MAX), (0x20, 0, u32::MAX)] { + acl.extend(tag.to_le_bytes()); + acl.extend(perm.to_le_bytes()); + acl.extend(id.to_le_bytes()); + } + match rustix::fs::setxattr(&path, ACL, &acl, rustix::fs::XattrFlags::empty()) { + Ok(()) => {} + Err(e) if e == rustix::io::Errno::NOTSUP => { + let _ = std::fs::remove_dir_all(d); + return; + } + Err(e) => panic!("setting the ACL: {e}"), + } + if File::open(&path).is_ok() { + // Root reads any file. + let _ = std::fs::remove_dir_all(d); + return; + } + write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)).unwrap(); + let mut buf = vec![0u8; 4096]; + let n = rustix::fs::getxattr(&path, ACL, &mut buf[..]).unwrap(); + assert_eq!(buf.get(..n).unwrap(), acl.as_slice(), "the ACL is kept"); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + + /// A folder that can be written and searched but not listed takes the file. (The permission + /// does not hold for root, which can list any folder.) + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + #[test] + fn a_checked_write_saves_into_a_folder_that_cannot_be_listed() { + use std::os::unix::fs::PermissionsExt; + let (d, root, _) = checked_folders("checked-search-only"); + let folder = root.join("inside"); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o300)).unwrap(); + let r = write_atomic_checked(&folder.join("doc.txt"), |f| f.write_all(b"new"), under(&root)); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + // The folder flush needs it opened for reading: the file is written, and the error says so. + assert!(r.as_ref().map_or_else(|e| e.get_ref().is_some_and(|e| e.is::()), |()| true), "{r:?}"); + assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + /// The other files in `d` besides `keep`. fn leftovers(d: &Path, keep: &str) -> Vec { std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect() @@ -722,6 +1347,33 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A refused rename where a file is already at the name the old content would be copied to: + /// that file is left as it is, and the temporary file with the new content stays. + #[test] + fn a_refused_rename_leaves_a_file_already_at_the_backup_name() { + let d = dir("no-rename-backup-taken"); + let path = d.join("doc.vectorcraft"); + std::fs::write(&path, b"original").unwrap(); + let r = write_atomic_stepping( + &path, + |f| f.write_all(b"new"), + create_new, + |tmp, _| { + std::fs::write(tmp.with_extension("old"), b"an earlier copy")?; + denied() + }, + ); + let message = r.unwrap_err().to_string(); + let mut left = leftovers(&d, "doc.vectorcraft"); + left.sort(); + let [old, tmp] = left.as_slice() else { panic!("the earlier copy and the new content: {left:?}") }; + assert!(message.contains(tmp.as_str()), "{message}"); + assert_eq!(std::fs::read(d.join(old)).unwrap(), b"an earlier copy"); + assert_eq!(std::fs::read(d.join(tmp)).unwrap(), b"new"); + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + let _ = std::fs::remove_dir_all(&d); + } + /// A refused rename where the old content can't be copied aside (here: no flush works): the /// file is left as it was, the temporary file with the whole new content stays and the error /// names it. diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 654f0ac065..9975527f78 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -58,7 +58,7 @@ use vectorcraft_doc::{Document, ImageBlob}; #[cfg(all(unix, not(target_arch = "wasm32")))] pub use atomic::sync_parent; #[cfg(not(target_arch = "wasm32"))] -pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; +pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_checked, write_atomic_with, write_new_with}; use craft_gzip::Gz; pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode}; use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json}; diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index b6678b813c..d13e08bfdc 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -6,7 +6,8 @@ //! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`), //! the iterators of arrays, strings and `arguments` objects (in `iterator`), the generator //! objects' prototypes with `GeneratorFunction` (in `generator`), `Map`, `Set`, `WeakMap` and -//! `WeakSet` (in `collections`) and `ArrayBuffer`, `DataView` and the typed arrays (in `binary`). +//! `WeakSet` (in `collections`), `ArrayBuffer`, `DataView` and the typed arrays (in `binary`), and +//! `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 @@ -21,8 +22,9 @@ mod global; pub(crate) mod iterator; mod json; mod math; -mod object; +pub(crate) mod object; pub(crate) mod promise; +mod reflect; mod symbol; use std::rc::Rc; @@ -197,6 +199,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; @@ -231,6 +240,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)?; @@ -275,6 +285,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { promise::install(interp)?; collections::install(interp)?; binary::install(interp)?; + reflect::install(interp, false)?; } Ok(()) } @@ -536,6 +547,18 @@ 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) => { + 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)?; // The tag's getter can run script that collects, and the object of a primitive is @@ -607,17 +630,33 @@ fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) - Ok(Value::Bool(interp.own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?)) } +/// `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 { @@ -703,6 +742,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)) @@ -716,13 +756,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/array.rs b/crates/js/src/builtins/array.rs index 1afff8a1f1..ac8dd4639c 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -107,16 +107,20 @@ fn index_count(class: &Class) -> usize { } /// The objects of the prototype chain from `obj`, with how many properties (and String object or -/// typed array indices) each holds. -fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> { +/// typed array 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 }; out.push((id, o.props.len().saturating_add(index_count(&o.class)))); cur = o.proto; } - out + Some(out) } impl Indices { @@ -124,10 +128,13 @@ impl Indices { let mut it = Indices { obj, lo, hi, ascending, maps, sparse: None }; // An object of a host class with an indexer holds its elements in the host, not in // properties, so every index of the range is visited. - if hi.saturating_sub(lo) > DENSE_SPAN && interp.host_indexer(obj)?.is_none() { - let present: usize = chain(interp, obj).iter().map(|(_, n)| *n).fold(0, usize::saturating_add); + if hi.saturating_sub(lo) > DENSE_SPAN + && interp.host_indexer(obj)?.is_none() + && 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) @@ -141,12 +148,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()?; } @@ -174,7 +182,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. @@ -183,7 +191,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, @@ -250,10 +258,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 ---- @@ -381,13 +389,23 @@ 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 { + 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/binary.rs b/crates/js/src/builtins/binary.rs index 3ec93edc07..5a48799007 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 { @@ -424,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). @@ -511,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")), @@ -527,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/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/json.rs b/crates/js/src/builtins/json.rs index 2b022bc858..a6d8babc9e 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.heap.object(o).is_some_and(|x| matches!(x.class, Class::Array { .. })) { - let len = length_of(interp, o)?; - interp.reserve_heap((len as usize).saturating_mul(crate::heap::PROP_BYTES))?; + if interp.is_array(&val)? { + 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 @@ -415,6 +428,7 @@ enum Item { struct Writing { obj: ObjId, keys: Vec, + _held_keys: Option, array: bool, next: usize, count: usize, @@ -464,7 +478,7 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult 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)), @@ -628,26 +646,35 @@ 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 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)); } - interp.reserve_heap((len as usize).saturating_mul(crate::heap::PROP_BYTES))?; + 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); 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 { 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); } @@ -658,7 +685,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 af377a213f..21b0b5e0c3 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::symbol::PropKey; use crate::value::{Str, Value}; @@ -23,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 { @@ -33,16 +38,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(); @@ -88,8 +85,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(); @@ -109,7 +139,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: impl IntoIterator) -> JsResult { let a = new_array(interp, 0)?; interp.rooted(&[Value::Object(a)], |interp| { for (i, k) in names.into_iter().enumerate() { @@ -122,16 +152,24 @@ fn names_array(interp: &mut Interp, names: Vec) -> JsResult { /// The object's own property keys: its names, then its Symbols (ECMA-262 11th edition, section /// 9.1.11). -fn own_prop_keys(interp: &mut Interp, o: ObjId) -> JsResult> { - let mut keys: Vec = interp.own_keys(o)?.into_iter().map(PropKey::Str).collect(); - keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym)); - Ok(keys) +fn own_prop_keys(interp: &mut Interp, o: ObjId) -> JsResult<(Vec, crate::interp::HeldBytes)> { + 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). 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). @@ -172,6 +210,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")?; @@ -198,7 +258,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 { @@ -227,33 +287,33 @@ 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) }; - for k in own_prop_keys(interp, o)? { - interp.use_fuel()?; - let Some(prop) = interp.get_own_pk(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() - }, - }; - desc.configurable = Some(false); - if freeze && desc.is_data() { - desc.writable = Some(false); + 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)?; + 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)?; } - interp.define_own_pk(o, k, &desc, true)?; - } - if let Some(obj) = interp.heap.object_mut(o) { - obj.extensible = false; - } - Ok(Value::Object(o)) + Ok(Value::Object(o)) + }) } fn seal(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { @@ -268,26 +328,34 @@ 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; - for k in own_prop_keys(interp, o)? { - 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)); - } + if interp.is_extensible(o)? { + return Ok(Value::Bool(false)); } - Ok(Value::Bool(!interp.heap.object(o).is_some_and(|o| o.extensible))) + let (keys, _held) = own_prop_keys(interp, o)?; + 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)); + } + } + Ok(Value::Bool(true)) + }) } fn is_sealed(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { @@ -301,20 +369,21 @@ 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). 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, syms: Vec::new(), ordered: None, held }) }) } diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs new file mode 100644 index 0000000000..dd63167fed --- /dev/null +++ b/crates/js/src/builtins/reflect.rs @@ -0,0 +1,269 @@ +//! `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, to_desc}; +use super::{arg, create_at, method, native, new_array}; +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::symbol::PropKey; +use crate::value::{Str, 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. 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)?; + // 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))?; + 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)?; + } + 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))); + interp.rooted(&[Value::Object(reflect)], |interp| reflect_methods(interp, reflect))?; + 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. +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)?; + 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)?; + 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 ---- + +/// `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'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(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(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 })?; + 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` contains its private revocation slot. +fn revoke(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + 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) +} + +// ---- 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.create_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_value(&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_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_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_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_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_prop_key(&arg(args, 1), |interp, k| match interp.own_pk(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_prop_key(&arg(args, 1), |interp, k| interp.has_pk_indexed(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 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")?; + // 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 +/// 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_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 +/// `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/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 ed114612d4..93f8afb3e6 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -13,12 +13,13 @@ use std::rc::Rc; +use crate::LimitKind; use crate::bytecode::{Code, NamePrefix}; use crate::heap::{ Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, Func, HIDDEN, OBJECT_BYTES, ObjId, Object, Prop, PropMap, WRITABLE, key, string_bytes, }; -use crate::interp::{ARROW_THIS, Abrupt, Desc, Entry, ErrorType, Interp, JsResult, binding_bytes, closure_bytes, internal}; +use crate::interp::{ARROW_THIS, Abrupt, Desc, Entry, ErrorType, Interp, JsResult, ProxyCall, binding_bytes, closure_bytes, internal}; use crate::symbol::PropKey; use crate::value::{Str, Value}; @@ -150,6 +151,9 @@ impl Interp { pub(crate) fn is_constructor(&self, v: &Value) -> bool { let mut v = v.clone(); for _ in 0..MAX_BOUND_CHAIN { + if let Some(Class::Proxy(p)) = v.as_object().and_then(|o| self.heap.object(o)).map(|o| &o.class) { + return p.constructor; + } match self.func_of(&v) { Some(Func::Closure { code, .. }) => return !(code.arrow || code.method || code.generator), Some(Func::Native { constructor, .. }) => return constructor, @@ -164,7 +168,7 @@ impl Interp { /// Does the built-in constructor `f` make objects that a subclass may give its own /// prototype? It does when its `prototype` is one of the realm's built-in prototypes. fn subclassable(&self, f: ObjId) -> JsResult { - let Some(Prop::Data { value: Value::Object(p), .. }) = self.get_own_property(f, &key("prototype"))? else { return Ok(false) }; + let Some(Prop::Data { value: Value::Object(p), .. }) = self.ordinary_own_property(f, &key("prototype"))? else { return Ok(false) }; let i = &self.intrinsics; Ok([i.object_proto, i.function_proto, i.array_proto, i.string_proto, i.number_proto, i.boolean_proto, i.regexp_proto, i.date_proto] .contains(&p) @@ -172,10 +176,32 @@ 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 { + /// 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; } } @@ -199,17 +225,73 @@ impl Interp { /// Constructs `f` with `args` and `new_target` (`f` itself when `None`) and pushes the /// result, or the frame that makes it, after taking the stack back to `start`. The operands /// at `start` and above keep `f` and `args` reachable. - pub(crate) fn construct(&mut self, start: usize, f: Value, mut args: Vec, new_target: Option) -> JsResult<()> { + pub(crate) fn construct(&mut self, start: usize, f: Value, args: Vec, new_target: Option) -> JsResult<()> { + self.construct_at(start, f, args, new_target, false) + } + + /// Construct (ECMA-262 2020 section 7.3.13) from Rust, as `Reflect.construct` needs it: runs + /// a constructor written in JavaScript to its end and gives the new object. + pub(crate) fn construct_value(&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 start = self.stack.len(); + let frames = self.frames.len(); + // The operands keep `f`, `new_target` and the arguments reachable, as for `new`. + let r = self.push(f.clone()).and_then(|()| self.push(new_target.clone())).and_then(|()| { + for a in args { + self.push(a.clone())?; + } + self.construct_at(start, f.clone(), args.to_vec(), new_target.as_object(), true) + }); + let r = match r { + Ok(()) if self.frames.len() > frames => self.execute(), + Ok(()) => self.pop(), + Err(e) => Err(e), + }; + self.stack.truncate(start); + self.reentry -= 1; + r + } + + /// [`Interp::construct`], the frame a constructor written in JavaScript enters marked as a + /// 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` // that is the bound function becomes the target (section 9.4.1.2). let mut steps = 0usize; - while let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) { - self.use_fuel()?; + let mark = self.temp_roots.len(); + let r = loop { + if let Some(p) = f.as_object().filter(|&p| self.is_proxy(p)) { + let nt = Value::Object(new_target.unwrap_or(p)); + new_target = nt.as_object(); + match self.proxy_construct(p, &args, &nt) { + Ok(ProxyCall::Target(target)) => { + f = Value::Object(target); + self.temp_roots.push(f.clone()); + continue; + } + Ok(ProxyCall::Done(v)) => { + self.stack.truncate(start); + break self.push(v); + } + Err(e) => break Err(e), + } + } + let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) else { + break self.construct_function(start, f, args, new_target, boundary, forwarding); + }; + if let Err(e) = self.use_fuel() { + break Err(e); + } steps += 1; if steps > MAX_BOUND_CHAIN { - return Err(self.type_error("the value is not a constructor")); + break Err(self.type_error("the value is not a constructor")); } let mut all = bound_args.to_vec(); all.append(&mut args); @@ -218,7 +300,21 @@ impl Interp { new_target = Some(target); } f = Value::Object(target); - } + }; + self.temp_roots.truncate(mark); + r + } + + /// 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, + 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) { @@ -227,18 +323,19 @@ impl Interp { Some(Func::Closure { code, .. }) if code.method => Err(self.type_error("a method is not a constructor")), Some(Func::Closure { code, env }) if code.derived => { self.stack.truncate(start); - self.enter_function(Entry { callee, code, env, this: Value::Undefined, args, new_target: Some(nt) }, None, false) + self.enter_function(Entry { callee, code, env, this: Value::Undefined, args, new_target: Some(nt) }, None, boundary) } Some(Func::Closure { code, env }) => { let fallback = self.intrinsics.object_proto; let proto = self.prototype_from(nt, fallback)?; 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, new_target: Some(nt) }, Some(obj), false) + self.enter_function(Entry { callee, code, env, this: Value::Object(obj), args, new_target: Some(nt) }, Some(obj), boundary) } - Some(Func::Native { f: native, constructor: true, .. }) => { - let subclass = nt != callee; - if subclass && !self.subclassable(callee)? { + 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.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"))? { @@ -251,21 +348,56 @@ 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); + 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` 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) + || 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(); + let early = if subclass && !converts_first { Some(self.prototype_from(nt, fallback)?) } else { None }; + self.temp_roots.extend(early.map(Value::Object)); let held = self.held_bytes; let r = native(self, Value::Undefined, &args, true); self.held_bytes = held; - let v = r?; - if subclass && let Value::Object(o) = v { - let proto = self.rooted(std::slice::from_ref(&v), |i| { - let fallback = intrinsic.unwrap_or(i.intrinsics.object_proto); - i.prototype_from(nt, fallback) - })?; + let r = r.and_then(|v| { + let Value::Object(o) = v else { return Ok(v) }; + if !subclass || self.is_proxy(o) || args.iter().any(|a| crate::interp::same_value(a, &v)) { + return Ok(v); + } + let proto = match early { + Some(p) => p, + None => self.rooted(std::slice::from_ref(&v), |i| i.prototype_from(nt, fallback))?, + }; if self.object(o)?.proto == intrinsic && !self.chain_reaches(proto, o)? { self.object_mut(o)?.proto = Some(proto); } - } - v + Ok(v) + }); + self.temp_roots.truncate(mark); + r? }; self.stack.truncate(start); self.push(v) @@ -274,7 +406,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 && !forwarding { return Err(self.type_error("this built-in cannot be subclassed")); } let was = std::mem::replace(&mut self.constructing, true); @@ -467,21 +599,13 @@ 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), } } - /// 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 { @@ -522,7 +646,29 @@ 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) => 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), 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/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/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 28fb8c3408..397521b8a3 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -302,6 +302,22 @@ fn a_function_eval_declares_on_the_global_object_sees_global_lexical_bindings() assert_eq!(realm.run(local), Ok(JsValue::Number(8.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!(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. + 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/file_classes.rs b/crates/js/src/file_classes.rs index 6c802ebec4..84062f9801 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -138,9 +138,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 9b13d5fd6e..d69e34fae4 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -215,10 +215,22 @@ pub(crate) struct ArgMap { #[derive(Clone, Debug)] pub(crate) struct ForIn { pub(crate) keys: 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 { @@ -268,6 +280,9 @@ 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), /// An `XMPMeta` object and its metadata ([`crate::xmp_classes`]). Xmp(Box), /// An object the `XMPFile` constructor made ([`crate::xmp_classes`]). @@ -523,6 +538,16 @@ pub(crate) struct View { pub(crate) elem: Elem, } +/// 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. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum XmlKind { @@ -605,6 +630,8 @@ impl Class { Class::String(_) => "String", Class::RegExp(_) => "RegExp", Class::Date(_) => "Date", + Class::Proxy(p) if p.callable => "Function", + Class::Proxy(_) => "Object", // The value of a namespace object's @@toStringTag (ECMA-262 2015 section 26.3.1). Class::ModuleNamespace(_) => "Module", Class::UnitValue(_) => "UnitValue", @@ -749,6 +776,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 Symbol without its description. pub(crate) const SYMBOL_BYTES: usize = 48; /// The estimated bytes of the measurement a `UnitValue` object holds. @@ -776,8 +805,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, } @@ -1162,7 +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 += crate::interp::listed_bytes(&state.listed); } Class::Symbol(s) => strings.add_symbol(s), Class::IterRecord(r) => { @@ -1220,6 +1251,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; + } Class::Map(c) | Class::Set(c) => { for v in c.values() { mark_value(v, work, strings); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index dea7247502..06d3f2e220 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -293,6 +293,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/host_classes.rs b/crates/js/src/host_classes.rs index cbbc5a5adb..10bcc8b49c 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -402,14 +402,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`]. @@ -421,15 +425,127 @@ impl Interp { } } -/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given. +/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given. Every +/// class's name, parent and members are checked before any class is added, and a failure part way +/// through removes the classes and globals this call added, so a failed call leaves the realm as it +/// was. pub(crate) fn install(i: &mut Interp, classes: Vec, instances: Vec<(String, Data)>) -> JsResult<()> { + let members = match checked_members(&i.host_classes, &classes) { + Ok(m) => m, + Err(message) => return Err(i.throw(ErrorType::Type, &message)), + }; + let mark = i.temp_roots.len(); + let mut undo = Undo { classes: i.host_classes.len(), globals: Vec::new(), objects: Vec::new() }; + let r = install_checked(i, classes, members, instances, &mut undo); + if r.is_err() { + undo.roll_back(i); + } + i.temp_roots.truncate(mark); + r +} + +/// What [`install`] puts back when it fails part way. +struct Undo { + /// How many classes the realm had before the call. + classes: usize, + /// Each global the call defined, with the property it replaced, in the order defined. The + /// replaced values stay in the interpreter's temporary roots until [`install`] returns, so a + /// collection during the call does not free them. + globals: Vec<(Key, Option)>, + /// The class and prototype of the object made for each family and handle before the call. An + /// instance of the call can give such an object one of the call's classes. + objects: Vec<(MadeKey, u32, Option)>, +} + +impl Undo { + fn define_global(&mut self, i: &mut Interp, name: &str, prop: Prop) -> JsResult<()> { + let global = i.global; + let k = key(name); + let was = i.object(global)?.props.get(&k).cloned(); + match &was { + Some(Prop::Data { value, .. }) => i.temp_roots.push(value.clone()), + Some(Prop::Accessor { get, set, .. }) => i.temp_roots.extend(get.iter().chain(set).map(|&f| Value::Object(f))), + None => {} + } + i.define(global, k.clone(), prop)?; + self.globals.push((k, was)); + Ok(()) + } + + fn roll_back(self, i: &mut Interp) { + let global = i.global; + for (k, was) in self.globals.into_iter().rev() { + let Ok(o) = i.object_mut(global) else { break }; + match was { + Some(prop) => { + o.props.insert(k, prop); + } + None => { + o.props.remove(&k); + i.heap.bytes = i.heap.bytes.saturating_sub(crate::interp::binding_bytes(k.len())); + } + } + } + for (made, class, proto) in self.objects { + let Some(&id) = i.host_objects.get(&made) else { continue }; + if is_made(&i.heap, &i.host_classes, id, &made) + && let Ok(o) = i.object_mut(id) + && let Class::Host(h) = &mut o.class + { + h.class = class; + o.proto = proto; + } + } + i.host_classes.truncate(self.classes); + forget_collected(&mut i.host_objects, &i.heap, &i.host_classes); + } +} + +/// The members of each of `classes` as `reflect` lists them ([`reflected_members`]), once every +/// class has a name that neither `existing` nor an earlier class of `classes` has, and a parent +/// that one of them has. → the error's message for the first class that does not. +fn checked_members(existing: &[Entry], classes: &[HostClass]) -> Result>, String> { + let mut names: HashSet<&str> = existing.iter().map(|e| &*e.name).collect(); + let mut out = Vec::with_capacity(classes.len()); for class in classes { - install_class(i, class)?; + if names.contains(class.name.as_str()) { + return Err(format!("the host class {} is defined twice", class.name)); + } + if let Some(p) = &class.parent + && !names.contains(p.as_str()) + { + return Err(format!("the host class {p} is not defined")); + } + out.push(reflected_members(class)?); + names.insert(&class.name); + } + Ok(out) +} + +/// [`install`] once [`checked_members`] has passed, recording in `undo` what it changes. +fn install_checked( + i: &mut Interp, + classes: Vec, + members: Vec>, + instances: Vec<(String, Data)>, + undo: &mut Undo, +) -> JsResult<()> { + for (class, members) in classes.into_iter().zip(members) { + install_class(i, class, members, undo)?; + } + if !instances.is_empty() { + for (made, &id) in &i.host_objects { + if is_made(&i.heap, &i.host_classes, id, made) + && let Ok(o) = i.object(id) + && let Class::Host(h) = &o.class + { + undo.objects.push((made.clone(), h.class, o.proto)); + } + } } for (name, d) in instances { let v = i.write_hosted(d)?; - let global = i.global; - i.define(global, key(&name), Prop::Data { value: v, flags: 0 })?; + undo.define_global(i, &name, Prop::Data { value: v, flags: 0 })?; } Ok(()) } @@ -450,22 +566,16 @@ pub(crate) fn install_globals(i: &mut Interp, globals: Vec<(String, HostFunction Ok(()) } -fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { - if i.host_classes.iter().any(|e| *e.name == *class.name) { - return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); - } +/// Adds `class`, which [`checked_members`] passed with `members`. +fn install_class(i: &mut Interp, class: HostClass, members: Rc<[Reflected]>, undo: &mut Undo) -> JsResult<()> { let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX); let (parent, family, parent_class) = match &class.parent { None => (i.intrinsics.object_proto, own, None), Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) { Some((n, e)) => (e.proto, e.family, u32::try_from(n).ok()), - None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), + None => return Err(Abrupt::Internal(format!("the host class {p} was checked but is not defined"))), }, }; - let members = match reflected_members(&class) { - Ok(m) => m, - Err(message) => return Err(i.throw(ErrorType::Type, &message)), - }; let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent))); let mark = i.temp_roots.len(); i.temp_roots.push(Value::Object(proto)); @@ -486,8 +596,7 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { unavailable: Rc::new(names(unavailable)), members, }); - let global = i.global; - i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) + undo.define_global(i, &class.name, Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) } /// The members of `class` as `reflect` lists them, each with its [`HostClass::info`] entry. → the diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 03b96e9835..31c46c0685 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -1056,6 +1056,72 @@ fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it() assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into())); } +/// A class named `name` with the parent `parent` and one read-only member `size`. +fn sized_class(name: &str, parent: Option<&str>) -> HostClass { + let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0))); + HostClass { + name: name.into(), + parent: parent.map(Into::into), + members: vec![("size".to_string(), HostMember::Get(value))], + info: Vec::new(), + index: None, + construct: None, + } +} + +#[test] +fn a_rejected_class_leaves_the_earlier_classes_of_its_call_undefined() { + let doubled = || { + let mut c = sized_class("Bad", None); + c.members.push(c.members[0].clone()); + c + }; + for (bad, message) in [(sized_class("Bad", Some("Missing")), "Missing is not defined"), (doubled(), "names the member size twice")] { + let mut r = realm(1_000_000); + let e = r.define_host_classes(vec![sized_class("First", None), bad], vec![("first".into(), host_ref("First", &[1.0]))]).unwrap_err(); + assert!(e.message.contains(message), "{}", e.message); + assert_eq!(r.run("[typeof First, typeof first, typeof Bad].join()").unwrap(), JsValue::String("undefined,undefined,undefined".into())); + r.define_host_classes(vec![sized_class("First", None)], vec![("first".into(), host_ref("First", &[1.0]))]).unwrap(); + assert_eq!(r.run("first.size").unwrap(), JsValue::Number(1.0)); + } +} + +#[test] +fn a_child_class_may_follow_its_parent_in_the_same_call_but_not_precede_it() { + let mut r = realm(1_000_000); + let e = r.define_host_classes(vec![sized_class("Leaf", Some("Base")), sized_class("Base", None)], Vec::new()).unwrap_err(); + assert!(e.message.contains("Base is not defined"), "{}", e.message); + assert_eq!(r.run("typeof Leaf + typeof Base").unwrap(), JsValue::String("undefinedundefined".into())); + r.define_host_classes(vec![sized_class("Base", None), sized_class("Leaf", Some("Base"))], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap(); + assert_eq!(r.run("it instanceof Base && it.size === 1").unwrap(), JsValue::Bool(true)); +} + +#[test] +fn a_failed_instance_removes_the_classes_and_globals_of_its_call_and_restores_held_objects() { + let mut r = realm(1_000_000); + r.define_host_classes(vec![sized_class("Base", None)], vec![("held".into(), host_ref("Base", &[1.0]))]).unwrap(); + r.run("var keep = 'kept'").unwrap(); + let instances = vec![("keep".into(), host_ref("Leaf", &[1.0])), ("other".into(), host_ref("Missing", &[2.0]))]; + let e = r.define_host_classes(vec![sized_class("Leaf", Some("Base"))], instances).unwrap_err(); + assert!(e.message.contains("unknown class Missing"), "{}", e.message); + let source = "[keep, typeof Leaf, typeof other, held.constructor === Base, held.hasOwnProperty('size'), held.size].join()"; + assert_eq!(r.run(source).unwrap(), JsValue::String("kept,undefined,undefined,true,true,1".into())); +} + +#[test] +fn a_failed_call_restores_a_replaced_global_that_a_collection_in_the_call_would_free() { + let mut r = realm(1_000_000); + r.define_host_classes(vec![sized_class("Base", None)], Vec::new()).unwrap(); + r.run("var keep = { sentinel: 1 }").unwrap(); + let instances = + vec![("keep".into(), host_ref("Base", &[1.0])), ("next".into(), host_ref("Base", &[2.0])), ("other".into(), host_ref("Missing", &[3.0]))]; + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let e = r.define_host_classes(Vec::new(), instances); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert!(e.unwrap_err().message.contains("unknown class Missing")); + assert_eq!(r.run("[keep.sentinel, typeof next].join()").unwrap(), JsValue::String("1,undefined".into())); +} + #[test] fn assigning_a_name_a_prototype_has_does_not_call_the_indexer() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index dac4a0c729..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; @@ -131,6 +131,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, @@ -156,6 +158,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, @@ -190,6 +193,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, @@ -318,6 +322,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 built-in functions have the `name` and the `length` that can be redefined that /// ECMAScript 2015 gives them ([`crate::builtins::es2015_names`]): set once the realm first /// reads code with [`Options::es2015`], and kept after that. @@ -499,6 +506,62 @@ 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; + + 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; @@ -506,7 +569,18 @@ 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 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. @@ -697,6 +771,7 @@ impl Interp { global_lex, global_vars: std::collections::HashSet::new(), next_es2015: None, + es2015_installed: false, builtin_names: false, template_objects: std::collections::HashMap::new(), intrinsics: Intrinsics::placeholder(), @@ -1533,7 +1608,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) { @@ -1586,7 +1661,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) } @@ -1605,8 +1708,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)), } @@ -1660,14 +1773,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(()) } } @@ -1682,7 +1788,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)) @@ -1704,7 +1810,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). @@ -1772,9 +1878,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: &Key) -> JsResult> { + if self.is_proxy(id) { + return self.proxy_get_own_property(id, &PropKey::Str(k.clone())); + } + 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") => { @@ -1843,10 +1957,66 @@ impl Interp { Ok(o.props.get(k).cloned()) } + /// 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 { + 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(SetLookup::Proxy(o)); + } + if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) { + return Ok(SetLookup::ReadOnly); + } + if let Some(p) = self.ordinary_own_property(o, k)? { + return Ok(SetLookup::Found(p)); + } + 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; + if steps > 1_000_000 { + return internal("prototype chain too long"); + } + } + Ok(SetLookup::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)> { + let mut cur = Some(id); + let mut steps = 0usize; + while let Some(o) = cur { + if self.is_proxy(o) { + return Ok((o, Lookup::Proxy(o))); + } + if let Some(p) = self.ordinary_own_property(o, k)? { + return Ok((o, Lookup::Found(p))); + } + // A typed array's prototypes are not searched for a numeric name (section 9.4.5.4). + if crate::builtins::binary::typed_key(self, o, k).is_some() { + return Ok((o, Lookup::Missing)); + } + cur = self.object(o)?.proto; + steps += 1; + if steps > 1_000_000 { + return internal("prototype chain too long"); + } + } + Ok((id, Lookup::Missing)) + } + /// [[GetOwnProperty]] as a script reaches it (`hasOwnProperty`, `Object.keys` and the like): /// [`Self::get_own_property`], except that an export of a module namespace object read before /// its module initialized it is a `ReferenceError` (ECMA-262 2015 section 9.4.6.5). - pub(crate) fn own_property(&mut self, id: ObjId, k: &[u16]) -> JsResult> { + pub(crate) fn own_property(&mut self, id: ObjId, k: &Key) -> JsResult> { self.check_namespace_export(id, k)?; self.get_own_property(id, k) } @@ -1872,75 +2042,96 @@ impl Interp { Ok(()) } - /// [[GetProperty]]: the property found on the object or its prototype chain. - pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult> { - Ok(self.find_property_on(id, k)?.map(|(_, p)| p)) + /// [[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: &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); + 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) }; + if let Some(root) = self.temp_roots.get_mut(mark) { + *root = Value::Object(next); + } + self.use_fuel()?; + cur = next; + } + } + } + })(); + self.temp_roots.truncate(mark); + r } - /// [`Self::find_property`], with the object on the prototype chain that has the property. - fn find_property_on(&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((o, p))); - } - // A typed array's prototypes are not searched for a numeric name (section 9.4.5.4). - if crate::builtins::binary::typed_key(self, o, k).is_some() { - return Ok(None); - } - cur = self.object(o)?.proto; - steps += 1; - if steps > 1_000_000 { - return internal("prototype chain too long"); - } + /// 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: &Key) -> JsResult { + match self.lookup(id, k)? { + Lookup::Found(_) => Ok(true), + Lookup::Missing => Ok(false), + Lookup::Proxy(p) => self.proxy_has(p, &PropKey::Str(k.clone())), } - Ok(None) } - pub(crate) fn has_property(&self, id: ObjId, k: &[u16]) -> JsResult { - Ok(self.find_property(id, k)?.is_some()) - } - - /// [[Get]] starting at `start`, with `receiver` as `this` for a getter. - pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + /// [[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: &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)? { return self.host_index(&f, start, crate::Data::Number(f64::from(i)), false); } - let found = self.find_property_on(start, k)?; + let (holder, found) = self.lookup_on(start, k)?; // A module's export read before the module ran is in its temporal dead zone (ECMA-262 // 2015 section 9.4.6.8), whether the read starts at the namespace object or reaches it // through a prototype chain. - if let Some((holder, _)) = &found { - self.check_namespace_export(*holder, k)?; + if matches!(found, Lookup::Found(_)) { + self.check_namespace_export(holder, k)?; } - match found.map(|(_, p)| p) { + match found { // A name the object and its prototypes lack is the indexer's answer too. - None => match self.host_indexer(start)? { + Lookup::Missing => match self.host_indexer(start)? { Some(f) => self.host_index(&f, start, Self::indexer_key(k), false), None => Ok(Value::Undefined), }, - 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, &[]), + 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, &PropKey::Str(k.clone()), receiver, true), } } /// [[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 { - let found = self.find_property_on(start, k)?; - if let Some((holder, _)) = &found { - self.check_namespace_export(*holder, k)?; + pub(crate) fn get_property_only(&mut self, start: ObjId, k: &Key, receiver: &Value) -> JsResult { + let (holder, found) = self.lookup_on(start, k)?; + if matches!(found, Lookup::Found(_)) { + self.check_namespace_export(holder, k)?; } - match found.map(|(_, p)| p) { - 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 found { + 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, &PropKey::Str(k.clone()), receiver, false), } } @@ -1961,7 +2152,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()))); } @@ -2006,6 +2197,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, &PropKey::Str(k.clone()), 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); @@ -2057,7 +2255,7 @@ impl Interp { /// A module namespace object's [[DefineOwnProperty]] (ECMA-262 2020 section 9.4.6.5): only a /// descriptor that leaves an export as it is (enumerable, writable, not configurable, its /// current value) succeeds. - fn define_namespace_export(&mut self, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult { + fn define_namespace_export(&mut self, id: ObjId, k: &Key, desc: &Desc, throw: bool) -> JsResult { let Some(Prop::Data { value, .. }) = self.own_property(id, k)? else { return self.reject_bool(throw, k, "a module namespace object is not extensible"); }; @@ -2188,8 +2386,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. - pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult> { + /// 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)?; // A typed array's indices come first, as a String object's do (section 9.4.5.6). let string_len = match &o.class { @@ -2200,7 +2401,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()?; @@ -2216,7 +2418,19 @@ impl Interp { if is_array { out.push(key("length")); } - Ok(out) + Ok(HeldKeys { keys: out, syms: Vec::new(), ordered: None, held }) + } + + 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. @@ -2236,8 +2450,15 @@ 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<()> { + 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(()); + } if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) { return crate::builtins::binary::set_element(self, id, n, &v); } @@ -2245,7 +2466,7 @@ impl Interp { if matches!(self.object(id)?.class, Class::ModuleNamespace(_)) { return self.reject(throw, &k, "a module namespace object is read-only"); } - match self.get_own_property(id, &k)? { + match self.ordinary_own_property(id, &k)? { Some(Prop::Data { flags, .. }) => { if flags & WRITABLE == 0 { return self.reject(throw, &k, "it is read-only"); @@ -2256,25 +2477,23 @@ impl Interp { Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), None => {} } - let mut inherited = None; - let mut cur = self.object(id)?.proto; - let mut steps = 0usize; - while let Some(o) = cur { - // A write that reaches a module namespace object on the prototype chain is refused - // there too: its [[Set]] returns false for every key. - if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) { - return self.reject(throw, &k, "a module namespace object is read-only"); + let proto = self.object(id)?.proto; + let lookup = match proto { + Some(p) => self.lookup_for_set(p, &k)?, + None => SetLookup::Missing, + }; + let inherited = match lookup { + SetLookup::ReadOnly => return self.reject(throw, &k, "a module namespace object is read-only"), + 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"); + } + return Ok(()); } - if let Some(p) = self.get_own_property(o, &k)? { - inherited = Some(p); - break; - } - cur = self.object(o)?.proto; - steps += 1; - if steps > 1_000_000 { - return internal("prototype chain too long"); - } - } + 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), Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), @@ -2345,11 +2564,19 @@ 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, &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"))); + } + return Ok(deleted); + } // A typed array's element cannot be deleted, and a numeric name it has no element for // is not a property it can hold (section 9.4.5.6 of later editions). if crate::builtins::binary::typed_key(self, id, k).is_some() { - if self.get_own_property(id, k)?.is_none() { + if self.ordinary_own_property(id, k)?.is_none() { return Ok(true); } if throw { @@ -2358,7 +2585,7 @@ impl Interp { } return Ok(false); } - match self.get_own_property(id, k)? { + match self.ordinary_own_property(id, k)? { None => Ok(true), Some(p) if p.configurable() => { let o = self.object_mut(id)?; @@ -2397,8 +2624,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") } @@ -3095,14 +3331,69 @@ 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 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 self.xml_enumerate(id); + return Ok((self.xml_enumerate(id)?, Vec::new())); } - let mut seen = std::collections::HashSet::new(); - let mut out = Vec::new(); + 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 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)> { + // 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 = 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 { + 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()?; + 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); + } + } + 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); + } + continue; + } let obj = self.object(o)?; let string_len = match &obj.class { Class::String(s) => Some(s.len()), @@ -3115,32 +3406,46 @@ 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_key(&k) { + held.add(self, string_bytes(k.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; + seen.insert(k.clone(), Some(next_pos(&out))); out.push(k); } } } - if is_array { - seen.insert(key("length")); + if is_array && !seen.contains_key(&key("length")) { + held.add(self, string_bytes(6) + KEY_ENTRY_BYTES)?; + seen.insert(key("length"), None); } for _ in 0..self.object(o)?.props.len() { self.use_fuel()?; } + let retained = self + .object(o)? + .props + .iter() + .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; } - Ok(out) + Ok((out, listed)) } 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, listed), 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 @@ -3149,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| { - let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::(); + 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) + 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, 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)) } @@ -3167,20 +3472,85 @@ 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 pos = u32::try_from(state.pos).unwrap_or(u32::MAX); 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(iter, o, &k, pos)? }; + 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): 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. + /// + /// `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(iter, o, k, pos, mark); + self.temp_roots.truncate(mark); + r + } + + 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 { + 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.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 { - 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, + }) } pub(crate) fn func_of(&self, v: &Value) -> Option { @@ -3194,7 +3564,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, .. } if code.class_ctor => { return Err(self.type_error("a class constructor cannot be called without 'new'")); @@ -3282,8 +3664,23 @@ impl Interp { } } - /// The elements of an array-like `apply` argument (section 15.3.4.3). + /// The elements of an array-like `apply` argument (section 15.3.4.3), its length read with + /// 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, self.options.es2015) + } + + /// CreateListFromArrayLike (ECMA-262 2020 section 7.3.17) for `Reflect.apply` and + /// `Reflect.construct`: the length is read with ToLength (section 7.1.20), so a negative + /// length gives no elements. + pub(crate) fn create_list_from_array_like(&mut self, list: &Value) -> JsResult> { + self.array_like_list(list, true) + } + + /// The elements of the array-like `list`, its length read with ToLength when `to_length` is + /// set and with ToUint32 otherwise. + fn array_like_list(&mut self, list: &Value, to_length: bool) -> JsResult> { let Value::Object(o) = list else { if list.is_nullish() { return Ok(Vec::new()); @@ -3291,7 +3688,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")); } @@ -4120,7 +4526,9 @@ 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 { // Strict eval code's own environment is in no frame yet, so it is a root while the // declarations reserve heap. @@ -4134,9 +4542,9 @@ impl Interp { /// [`Self::instantiate_global`] with `env` and `var_env` in [`Self::temp_envs`]. fn instantiate_global_rooted(&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)?; } @@ -4188,7 +4596,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?; self.note_global_var(on_global, name)?; } for v in &code.vars { @@ -4526,8 +4940,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) } } } @@ -4640,17 +5055,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 ---- @@ -4708,7 +5140,7 @@ impl Interp { /// before it is copied. pub(crate) fn describe_prefix(&mut self, v: &Value, max_units: usize) -> String { let Value::Object(o) = v else { return self.primitive_to_str(v).prefix_to_rust_string(max_units) }; - 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.prefix_to_rust_string(max_units)), _ => None, }; @@ -4723,7 +5155,7 @@ impl Interp { /// The [`description_hash`] of the text [`Interp::describe`] gives for the object `o`, read /// along its strings without copying them. fn describe_hash(&self, o: ObjId) -> u64 { - let data = |k: &str| match self.find_property(o, &key(k)) { + let data = |k: &str| match self.find_ordinary_property(o, &key(k)) { Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s), _ => None, }; @@ -4747,6 +5179,34 @@ 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, +} + +pub(crate) enum SetLookup { + Found(Prop), + Proxy(ObjId), + Missing, + ReadOnly, + /// 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. +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)] diff --git a/crates/js/src/iteration.rs b/crates/js/src/iteration.rs index c0ce093ebb..749dbf402f 100644 --- a/crates/js/src/iteration.rs +++ b/crates/js/src/iteration.rs @@ -81,14 +81,17 @@ impl Interp { Ok(self.heap.alloc_object(Object::new(Class::IterRecord(Box::new(record)), None))) } - /// The record of a [`Walk`] over an array, an `arguments` object, a string or a `String` - /// object, for a realm without `Symbol.iterator`; any other value is not iterable there. A - /// `String` object is converted to a string first, as the string iterator does. A - /// concatenated string's flattened copy is counted against the heap before it is made. + /// The record of a [`Walk`] over an array, a proxy whose target is an array, an `arguments` + /// object, a string or a `String` object, for a realm without `Symbol.iterator`; any other + /// value is not iterable there. A proxy of an array is walked through its traps, its `length` + /// read again at each step. A `String` object is converted to a string first, as the string + /// iterator does. A concatenated string's flattened copy is counted against the heap before it + /// is made. fn walk_record(&mut self, v: &Value) -> JsResult { let walk = match v { Value::String(s) => Walk::String(Str::from_rc(crate::string_builtins::flat_charged(self, s)?), 0), Value::Object(o) if matches!(self.object(*o)?.class, Class::Array { .. } | Class::Arguments(_)) => Walk::Array(*o, 0.0), + Value::Object(o) if self.is_proxy(*o) && self.is_array(v)? => Walk::Array(*o, 0.0), Value::Object(o) if matches!(self.object(*o)?.class, Class::String(_)) => { let s = self.to_str(v)?; Walk::String(Str::from_rc(crate::string_builtins::flat_charged(self, &s)?), 0) diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index bbf2b0a962..731ef1aed1 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -121,6 +121,11 @@ //! and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1). A //! typed array constructor converts a first argument that is not an object to a length. A buffer longer than the heap //! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated. +//! +//! 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 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; @@ -143,6 +148,7 @@ mod module; mod number; mod number_builtins; mod parser; +mod proxy; mod realm; mod reflect; mod regexp; @@ -204,12 +210,15 @@ pub struct Options { /// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts. /// A realm made with it on also has the later editions' built-ins this engine has: `Symbol` /// with Symbol-keyed properties, the iterators of arrays, strings and `arguments` objects, - /// `Promise` with its job queue, `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView` - /// and the typed arrays. A realm made with it off has the ES5.1 built-ins only, as the - /// app's scripts expect. Those built-ins are chosen when the realm is made: turning the option - /// on or off later with [`Realm::set_es2015`] changes the language later runs read, and does - /// not add or remove them; [`Realm::add_es2015`] adds `Promise` to a realm made without it. - /// Runs with it on also convert `0b` and `0o` strings to numbers. + /// `Promise` with its job queue, `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`, + /// the typed arrays, `Proxy` and `Reflect`. A realm made with it off has the ES5.1 built-ins + /// only, as the app's scripts expect. Those built-ins are chosen when the realm is made: + /// turning the option on or off later with [`Realm::set_es2015`] changes the language later + /// runs read, and does not add or remove them, except that a realm made without it gets + /// `Proxy` and `Reflect` at its first run with the option on and keeps them; a `Proxy` or + /// `Reflect` global that an earlier run defined stays as it is. [`Realm::add_es2015`] adds + /// `Promise` to a realm made without it. Runs with it on also convert `0b` and `0o` strings to + /// numbers. pub es2015: bool, } @@ -369,6 +378,8 @@ mod module_tests; #[cfg(test)] mod promise_tests; #[cfg(test)] +mod proxy_tests; +#[cfg(test)] mod reflect_tests; #[cfg(test)] mod scriptui_tests; diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs new file mode 100644 index 0000000000..fcb103b50c --- /dev/null +++ b/crates/js/src/proxy.rs @@ -0,0 +1,835 @@ +//! 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, 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. +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(_))) + } + + /// 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) }; + match (target, handler) { + (Some(t), Some(_)) => Ok(Some(t)), + _ => Err(self.type_error("the proxy has been revoked")), + } + } + + 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), + _ => 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")) }; + // 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); + 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 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) + } + + /// 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 { + 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: &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_pk(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() { + 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: &PropKey, desc: &Desc) -> JsResult { + let mut roots = desc_values(desc); + 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_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.pk_value(k))?; + if !i.call_trap(&trap, handler, &[Value::Object(target), name, desc_obj])?.truthy() { + return Ok(false); + } + 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 { + 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: &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_pk(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: &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 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.pk_value(k)?; + let v = i.call_trap(&trap, handler, &[Value::Object(target), name, receiver.clone()])?; + 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")) + } + 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. + 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_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")) + } + 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: &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_pk(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 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 { + // 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 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 }) + }) + } + + /// 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)?; + // 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 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)?; + 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())); + } + 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")), + } + } + if let Some(k) = duplicate { + let name = self.pk_name(&k)?; + return Err(self.invariant("ownKeys", &format!("returned the key '{name}' twice"))); + } + Ok(TrapKeys { keys, syms, ordered }) + } + + /// 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)?; + // 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(()); + } + // 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"))); + } + } + if extensible { + 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"))); + } + } + 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), + } + } + } + } + + /// [[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 { + // 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 found = self.lookup_for_set(o, &k)?; + let own = match found { + SetLookup::ReadOnly => return Ok(false), + 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 }, + }; + 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 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()), + } +} + +/// 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 { + 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(); + 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..0bbe6e0b02 --- /dev/null +++ b/crates/js/src/proxy_tests.rs @@ -0,0 +1,2066 @@ +//! `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:?}"), + } +} + +#[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] +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(); + 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))); +} + +#[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); +} + +#[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] +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; + 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 = [ + 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 && 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( + "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:?}"); +} + +#[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('neither a string nor a Symbol') >= 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 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( + "[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] +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_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( + "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", + ); +} + +#[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", + ); + // `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`. +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 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, got = 0; + var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; }, + get: function (t, k) { got++; return k === 'x' ? function () {} : undefined; } }); + var r; + with (p) { r = typeof x; } + 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", + ); +} + +#[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( + "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 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'", + ); +} + +/// 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 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_reach_the_targets_symbol_properties() { + truth( + "var s = Symbol('x'), t = {}; t[s] = 1; + var p = new Proxy(new Proxy(t, {}), {}); + 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 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 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", + ); +} + +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. + 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 + // refused before the elements are read. The array keeps the array iterator as its own. + truth( + "var a = []; a.length = 4294967295; a[Symbol.iterator] = Array.prototype[Symbol.iterator]; + 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'", + ); + // 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", + ); + // 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 array iterator reads every index of the length, and the + // result stops at the heap limit. + assert_eq!(limit("var a = []; a.length = 4294967295; [...a]", walk_limits()), LimitKind::Heap); +} + +#[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))); +} + +#[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')", + ); +} + +#[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_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( + "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", + ); +} + +#[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 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; + 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(); + 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 && [[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); + 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 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 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( + "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(); + 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)", + ); +} + +#[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/crates/js/src/realm.rs b/crates/js/src/realm.rs index 822477780f..fe92e15269 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -264,7 +264,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); @@ -417,6 +418,19 @@ impl Realm { }), }; } + let interp = &mut self.interp; + // 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 }); + } Ok(()) } @@ -753,6 +767,7 @@ impl Realm { /// prototype holds its members, and the global objects `instances`, each made from the /// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be /// replaced. A heap too small for them ends with the error the realm's next run would give. + /// A call that fails adds none of its classes or instances, and can be made again. pub fn define_host_classes(&mut self, classes: Vec, instances: Vec<(String, crate::Data)>) -> Result<(), RunError> { match crate::host_classes::install(&mut self.interp, classes, instances) { Ok(()) => Ok(()), 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/scriptui.rs b/crates/js/src/scriptui.rs index a5f74e7f54..80982a48ce 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -211,7 +211,7 @@ fn range(i: &mut Interp, message: &str) -> Abrupt { /// The value of the own data property `name` of `o`, `undefined` when it has none. 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, }) @@ -317,7 +317,7 @@ fn list_values(i: &Interp, a: ObjId) -> JsResult> { }; (0..length) .map(|n| { - Ok(match i.get_own_property(a, &index_key(n))? { + Ok(match i.ordinary_own_property(a, &index_key(n))? { Some(Prop::Data { value, .. }) => value, _ => Value::Undefined, }) @@ -1841,7 +1841,7 @@ fn lists_unchanged(i: &Interp, order: &[(ObjId, String, f64)], snapshot: &[Value /// Has each list item in `texts` the text it had when it was read? fn texts_unchanged(i: &Interp, texts: &[(ObjId, Value)]) -> JsResult { for (item, read) in texts { - match i.get_own_property(*item, &key("text"))? { + match i.ordinary_own_property(*item, &key("text"))? { Some(Prop::Data { value, .. }) if crate::interp::same_value(&value, read) => {} _ => return Ok(false), } diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 69112d494b..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,18 +316,27 @@ impl Interp { self.reject(true, &name, why) } - pub(crate) fn get_own_sym(&self, id: ObjId, k: &Sym) -> JsResult> { + /// [[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> { + 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. - 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))); + } + 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() { @@ -340,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), } } @@ -359,7 +380,8 @@ 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<()> { let o = self.object_mut(id)?; if o.syms.get_or_insert_with(Box::default).insert(k, prop) { @@ -370,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"); @@ -394,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 { @@ -415,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; @@ -455,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") } } @@ -466,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() => { @@ -483,8 +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> { + 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 { @@ -495,7 +555,7 @@ impl Interp { // ---- either kind of key ---- - pub(crate) fn get_own_pk(&self, id: ObjId, k: &PropKey) -> JsResult> { + pub(crate) fn get_own_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult> { match k { PropKey::Str(name) => self.get_own_property(id, name), PropKey::Sym(s) => self.get_own_sym(id, s), @@ -505,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/crates/js/src/xml.rs b/crates/js/src/xml.rs index bb311cf1a8..877351d4be 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()) }; @@ -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: &[u16]) -> 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/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 8b209fce0a..0bd2b34de5 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -210,7 +210,7 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { if let Some(Class::XmpFile(fields)) = i.heap.object(o).map(|object| &object.class) { return Ok(fields.get(&key(name)).cloned().unwrap_or(Value::Undefined)); } - 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/tests/test262.rs b/crates/js/tests/test262.rs index 691bd523fe..fa81397b00 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -42,6 +42,10 @@ //! [`ES2015_COLLECTION_FEATURES`]; its failures go to `es2015-builtins-failures.txt`. It fails when //! the interpreter panics. //! +//! A seventh 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 @@ -859,6 +863,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 { @@ -977,7 +990,96 @@ 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 +/// 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:\n{}", panic_lines(&before.failures, &after.failures)); } /// The folders under `test/language/` whose module tests [`modules_run`] reads. @@ -1865,3 +1967,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", ""), ""); +} diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 6852f317b3..8dfdfd28e3 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1543,7 +1543,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index b61afe0d4e..d9c6d3c9fe 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -79,8 +79,12 @@ 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; +/// 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; @@ -173,6 +177,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 +291,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 +314,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,17 +502,19 @@ 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, 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 { self.near_matches_among(shape, tolerance, None) } - /// [`Self::near_matches`] among the glyphs of the indexed face with id `face` alone: the 256 - /// of its glyphs closest to `shape` in proportion, which the glyphs of the other faces cannot + /// [`Self::near_matches`] among the glyphs of the indexed face with id `face` alone: the glyphs + /// of the 256 of its outlines closest to `shape` in proportion, which the glyphs of the other faces cannot /// crowd out. Empty when the index does not hold that face. pub fn near_matches_in(&self, shape: &BezPath, tolerance: f64, face: u32) -> Vec { match self.faces.iter().position(|f| f.id() == face) { @@ -544,20 +552,34 @@ impl RetypeIndex { } }; let near = self.ranked_near(&s, only, &mut work); - for (_, e) in near { - if work == 0 { - break; - } + // 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 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, _)| *l == outline).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((outline, p.clone())); + p + } + }; + let Some((pose, residual, rest)) = posed else { continue }; let m = GlyphMatch { face: face.clone(), gid: e.gid, @@ -583,12 +605,18 @@ 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. With `only`, the glyphs of that face (an index into `faces`) alone. - fn ranked_near(&self, s: &Signature, only: Option, work: &mut u64) -> Vec<(f64, &Entry)> { + /// 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`, 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. Each glyph comes with its distance and the number of + /// its outline in the list, the same for every glyph drawn alike. With `only`, the glyphs of + /// that face (an index into `faces`) alone. + fn ranked_near(&self, s: &Signature, only: Option, 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); @@ -610,27 +638,64 @@ 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) { if only.is_some_and(|f| e.face != f) { continue; } 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(); + // 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 => { + // 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)])); + } + } } - 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().enumerate().flat_map(|(k, (d, glyphs))| glyphs.into_iter().map(move |(_, e)| (d, k, 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. @@ -643,6 +708,40 @@ 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 +} + +/// 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 { @@ -1742,6 +1841,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). @@ -2124,6 +2225,100 @@ 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, 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: u64 = + alone.ranked_near(&near_signature(&simple).unwrap(), None, &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(), None, &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 + // 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, None, &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, None, &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] fn near_matches_in_one_face_find_its_glyphs_however_many_faces_are_drawn_alike() { // Source Sans 3 Regular last, after 95 copies of it under other names: every face has @@ -2422,9 +2617,13 @@ 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, None, &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, None, &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, None, &mut work).len(), 1); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index fa9d95b172..49fad8d56f 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -113,4 +113,9 @@ toml = "1" # The files of other crates that this crate's tests read, for CI's test selection. [package.metadata.craft] -reads = ["crates/engine/src/cmd/addons/cutting/banner.rs", "crates/plugins/tests/fixtures/desaturate.wasm"] +reads = [ + "crates/engine/src/cmd/addons/cutting/banner.rs", + "crates/plugins/tests/fixtures/desaturate.wasm", + "packaging/macos/nightly-lib.sh", + "packaging/macos/nightly_plist.py", +] diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index a607911e16..18816efa11 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -108,6 +108,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option pathtools::tangents::open_connected, pathtools::tangent_circle::COMMAND => pathtools::tangent_circle::open, typetools::COMMAND => typetools::open, + typetools::numbers::COMMAND => typetools::numbers::open, color::legend::COMMAND => color::legend::open, color::nearest::COMMAND => color::nearest::open, color::random_fill::COMMAND => color::random_fill::open, diff --git a/crates/ui-egui/src/addons/typetools.rs b/crates/ui-egui/src/addons/typetools.rs index 3f73b835ee..7be80f09fd 100644 --- a/crates/ui-egui/src/addons/typetools.rs +++ b/crates/ui-egui/src/addons/typetools.rs @@ -12,6 +12,8 @@ use crate::VectorcraftApp; use crate::addons::dialogs::{self, Spec}; use crate::menus::{c, cp}; +pub mod numbers; + /// The command the dialog runs. pub const COMMAND: &str = "addon.type.textTweaker"; /// An attribute: (param, label, unit, decimals, values taken, default start and end), as the @@ -40,7 +42,11 @@ pub const RELEASE_MODES: &[(&str, &str)] = &[("Text and Path", "both"), ("Path O /// Object › Plug-ins › Type Tools. pub fn menu() -> Vec { - vec![c("Text Tweaker…", COMMAND), cp("Release Type on a Path…", RELEASE, json!({"mode": "both", "keepOriginal": false}))] + vec![ + c("Text Tweaker…", COMMAND), + cp("Release Type on a Path…", RELEASE, json!({"mode": "both", "keepOriginal": false})), + c("Make Numbers Sequence…", numbers::COMMAND), + ] } /// The attribute row of param `key` (the first, Font Size, for an unknown one). diff --git a/crates/ui-egui/src/addons/typetools/numbers.rs b/crates/ui-egui/src/addons/typetools/numbers.rs new file mode 100644 index 0000000000..68351ad068 --- /dev/null +++ b/crates/ui-egui/src/addons/typetools/numbers.rs @@ -0,0 +1,97 @@ +//! Make Numbers Sequence's dialog: the start, end and step, zeros, the order the type objects are +//! numbered in and what each number replaces. It previews on the canvas and runs +//! `addon.type.numbers` on OK. + +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::addons::dialogs::{self, Spec}; + +/// The command the dialog runs. +pub const COMMAND: &str = "addon.type.numbers"; +const ORDERS: [(&str, &str); 3] = [("stacking", "By Stacking Order"), ("rows", "By Rows"), ("columns", "By Columns")]; +const REPLACES: [(&str, &str); 3] = [("all", "Whole Text"), ("numbers", "Numbers in Text"), ("placeholder", "Only {%n} Placeholder")]; +/// The seeds the dialog offers. +const SEEDS: u64 = 1_000_000; +/// The largest start, end or step, as the command takes it. +const MAX_VALUE: f64 = 1e12; + +/// How the dialog's values reach the command. +pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; + +/// The command's parameters from the dialog's fields. +pub(crate) fn params(fields: &DialogFields) -> Value { + let to_last = fields.bool("toLast").unwrap_or(true); + let mut p = json!({ + "start": fields.number("start").unwrap_or(1.0), + "step": fields.number("step").unwrap_or(1.0), + "order": fields.text("order").unwrap_or("stacking"), + "replace": fields.text("replace").unwrap_or("all"), + "shuffle": fields.bool("shuffle").unwrap_or(false), + "seed": fields.int("seed").unwrap_or(0), + "leadingZeros": fields.bool("leadingZeros").unwrap_or(true), + "trailingZeros": fields.bool("trailingZeros").unwrap_or(false), + }); + if !to_last { + p["end"] = json!(fields.number("end").unwrap_or(10.0)); + p["removeUnused"] = json!(fields.bool("removeUnused").unwrap_or(false)); + } + if fields.bool("leadingZeros").unwrap_or(true) && fields.bool("fixedDigits").unwrap_or(false) { + p["digits"] = json!(fields.int("digits").unwrap_or(3)); + } + p +} + +/// The radio choice over `list`'s `(id, label)` pairs, on its first. +fn radio(list: &[(&str, &'static str)]) -> ParamKind { + ParamKind::radio(list.iter().map(|&(id, label)| (id.to_string(), tl!(label).into())).collect(), list.first().map(|(id, _)| id.to_string())) +} + +/// Opens the dialog numbering from 1 by 1 to the last type object, in stacking order, replacing the +/// whole text, with a new seed each time the document has changed. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + let seed = app.session.active().map_or(0, |st| st.revision % SEEDS); + let fields = DialogFields::from_pairs([ + ("start", FieldValue::Number(1.0)), + ("step", FieldValue::Number(1.0)), + ("toLast", FieldValue::Bool(true)), + ("end", FieldValue::Number(10.0)), + ("removeUnused", FieldValue::Bool(false)), + ("shuffle", FieldValue::Bool(false)), + ("seed", FieldValue::Int(i64::try_from(seed).unwrap_or(0))), + ("leadingZeros", FieldValue::Bool(true)), + ("fixedDigits", FieldValue::Bool(false)), + ("digits", FieldValue::Int(3)), + ("trailingZeros", FieldValue::Bool(false)), + ("order", FieldValue::Text("stacking".into())), + ("replace", FieldValue::Text("all".into())), + ]); + dialogs::open(app, &SPEC, fields, |fields| { + let value = |key: &'static str, label, start| Param::number(key, label, start, 1.0, 6).bounds(Some(-MAX_VALUE), Some(MAX_VALUE)); + let last = FieldValue::Bool(false); + let rows = vec![ + Param::section(tl!("Numbers")), + value("start", tl!("Start:"), 1.0), + value("step", tl!("Step:"), 1.0), + Param::new("toLast", tl!("Number to Last Text"), ParamKind::bool(true)), + value("end", tl!("End:"), 10.0).enabled_when("toLast", last.clone()), + Param::new("removeUnused", tl!("Remove Unused Texts"), ParamKind::bool(false)).enabled_when("toLast", last), + Param::new("shuffle", tl!("Shuffle Numbers"), ParamKind::bool(false)), + Param::new("seed", tl!("Seed:"), ParamKind::int(Some(0), Some(i64::try_from(SEEDS - 1).unwrap_or(i64::MAX)), 0)) + .enabled_when("shuffle", FieldValue::Bool(true)), + Param::section(tl!("Zeros")), + Param::new("leadingZeros", tl!("Leading Zeros"), ParamKind::bool(true)), + Param::new("fixedDigits", tl!("Fixed Number of Digits"), ParamKind::bool(false)).enabled_when("leadingZeros", FieldValue::Bool(true)), + Param::new("digits", tl!("Digits:"), ParamKind::int(Some(1), Some(30), 3)).enabled_when("fixedDigits", FieldValue::Bool(true)), + Param::new("trailingZeros", tl!("Trailing Zeros"), ParamKind::bool(false)), + Param::new("order", tl!("Order:"), radio(&ORDERS)).enabled_when("shuffle", FieldValue::Bool(false)), + Param::new("replace", tl!("Replace:"), radio(&REPLACES)), + ]; + ParamDialog::new(COMMAND, tl!("Make Numbers Sequence"), rows).values(Bind::bound(fields)).previews(true) + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/typetools/numbers/tests.rs b/crates/ui-egui/src/addons/typetools/numbers/tests.rs new file mode 100644 index 0000000000..79acbf8ef1 --- /dev/null +++ b/crates/ui-egui/src/addons/typetools/numbers/tests.rs @@ -0,0 +1,58 @@ +use serde_json::json; +use vectorcraft_engine::Session; + +use crate::VectorcraftApp; +use crate::addons::dialogs::tests::{confirm, dialog_id, frame, open_item, read, set}; + +/// A window's app with three type objects in a column, selected. +fn app() -> (VectorcraftApp, Vec) { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..3) + .map(|i| app.run("text.create", json!({"x": 40, "y": 60 + 40 * i, "text": "Seat 0", "size": 20})).unwrap()["id"].as_u64().unwrap()) + .collect(); + app.run("select.set", json!({"ids": ids})).unwrap(); + (app, ids) +} + +fn texts(app: &VectorcraftApp, ids: &[u64]) -> Vec { + let state = app.session.active().unwrap(); + ids.iter() + .map(|id| match &state.doc.node(vectorcraft_doc::NodeId(*id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + }) + .collect() +} + +/// The dialog's fields reach the command: an end and fixed digits only when turned on, and OK +/// numbers the objects as one undo step. +#[test] +fn the_dialog_numbers_the_selection_on_ok() { + let (mut app, ids) = app(); + let undo = app.session.active().unwrap().history.undo.len(); + open_item(&mut app, "Type Tools", "Make Numbers Sequence…"); + let dialog = dialog_id(&app); + let p = read(&app, dialog, super::params); + assert!(p.get("end").is_none() && p.get("digits").is_none(), "to the last text, auto digits: {p}"); + for (key, value) in [("start", json!(5.0)), ("replace", json!("numbers")), ("fixedDigits", json!(true)), ("digits", json!(2))] { + set(&app, dialog, key, value); + } + set(&app, dialog, "toLast", json!(false)); + set(&app, dialog, "end", json!(6.0)); + frame(&mut app); + let p = read(&app, dialog, super::params); + assert_eq!( + (p["start"].clone(), p["end"].clone(), p["digits"].clone(), p["replace"].clone()), + (json!(5.0), json!(6.0), json!(2), json!("numbers")) + ); + let mut expected = self::app(); + expected.0.run(super::COMMAND, p).unwrap(); + let want = texts(&expected.0, &expected.1); + assert_eq!(want, ["Seat 05", "Seat 06", "Seat 0"]); + assert!(confirm(&app, dialog)); + frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(texts(&app, &ids), want); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); +} diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 8bf7e37874..d128aba2e4 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -9,8 +9,10 @@ //! 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` -//! preference for a PDF (`__pdf`; Editable for a `.ai` or `.ait` file), or from the `textAs` a place +//! 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 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 @@ -146,6 +148,9 @@ struct State { pages: Vec, link_pages: Option, crop: CropTo, + /// 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, @@ -212,10 +217,17 @@ 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.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) } /// The Text choice the preview renders with (a linked place: as editable text). @@ -506,6 +518,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 +546,7 @@ fn offer_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option 1 => (count, false), Err(PdfError::NeedsPassword) => (0, true), @@ -544,7 +563,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 != s.start_crop { + 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/print.rs b/crates/ui-egui/src/dialogs/print.rs index 05d46c3979..6546b2ff5b 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,13 @@ 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 (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, + /// 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 +140,111 @@ 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) +} + +/// 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); + 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). `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, fresh)) { + 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 +302,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, true); + 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 +323,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 +424,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 +471,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 +481,84 @@ 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, printer_changed); + // 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 { + 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. 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((id, s)) = on(dialogs, |p| { + let fields = p.fields_mut(); + 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((Media::Custom.id().to_string(), settings(fields))) + }) + .flatten() + { + media = id; + 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() @@ -478,7 +665,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), } @@ -508,7 +697,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 +887,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 +904,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_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index c9383d0f44..1d1d434f2d 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -409,6 +409,52 @@ 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, "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"); +} + /// 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] diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 183d6f1056..d2ebf74122 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,422 @@ 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, _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 { + "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, 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(); + 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()); +} + +/// 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}"); +} + +/// 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>); + +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(); + 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/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index b4cf91497d..3e4a834cb8 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1544,7 +1544,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/os_window.rs b/crates/ui-egui/src/os_window.rs index 00ce8344e7..2c4abd98cd 100644 --- a/crates/ui-egui/src/os_window.rs +++ b/crates/ui-egui/src/os_window.rs @@ -119,9 +119,50 @@ mod tests { #[test] fn the_two_nightly_ids_are_the_contract_ones() { // The package and bundle identity ends in `.nightly`; the window and AUMID in `.nightly-v1`. - assert_eq!(NIGHTLY_PACKAGE_ID, "ai.storyteller.vectorcraft.nightly"); - assert_eq!(NIGHTLY_APP_ID, "ai.storyteller.vectorcraft.nightly-v1"); - assert_ne!(NIGHTLY_PACKAGE_ID, NIGHTLY_APP_ID); + assert_eq!(id_for(LaunchIdentity::NightlyV1), NIGHTLY_APP_ID); + assert!(NIGHTLY_PACKAGE_ID.ends_with(".nightly"), "{NIGHTLY_PACKAGE_ID}"); + assert_eq!(NIGHTLY_APP_ID.strip_suffix("-v1"), Some(NIGHTLY_PACKAGE_ID), "the window id is the package id plus -v1"); + // The packaging publishes the same package id. + let plist = include_str!("../../../packaging/macos/nightly_plist.py"); + assert_eq!(assigned(plist, "IDENTIFIER", false), Some(NIGHTLY_PACKAGE_ID), "nightly_plist.py"); + let lib = include_str!("../../../packaging/macos/nightly-lib.sh"); + assert_eq!(assigned(lib, "MAC_NIGHTLY_ID", true), Some(NIGHTLY_PACKAGE_ID), "nightly-lib.sh"); + } + + /// The value of the last uncommented top-level `name = value` or `name=value` line, with one pair of + /// single or double quotes removed and a trailing `#` comment after the value ignored. With `shell`, a `#` + /// after a closing quote starts a comment only when whitespace comes before it; Python needs no whitespace. + fn assigned<'a>(source: &'a str, name: &str, shell: bool) -> Option<&'a str> { + source + .lines() + .filter_map(|line| { + let rest = line.strip_prefix(name)?.trim_start().strip_prefix('=')?.trim(); + let quoted = ['\'', '"'].iter().find_map(|q| { + let inner = rest.strip_prefix(*q)?; + let end = inner.find(*q)?; + let after = &inner[end + 1..]; + let comment = (!shell || after.starts_with(char::is_whitespace)) && after.trim_start().starts_with('#'); + (after.trim().is_empty() || comment).then(|| &inner[..end]) + }); + let bare = rest.split_once(" #").map_or(rest, |(value, _)| value.trim_end()); + Some(quoted.unwrap_or(bare)) + }) + .next_back() + } + + #[test] + fn assigned_reads_the_active_line_in_either_quote_style() { + for shell in [false, true] { + assert_eq!(assigned("# ID='old'\nID=\"new\"\n", "ID", shell), Some("new")); + assert_eq!(assigned("ID = 'a'\n", "ID", shell), Some("a")); + assert_eq!(assigned("IDX='a'\n", "ID", shell), None); + assert_eq!(assigned("ID = 'a' # bundle ID\n", "ID", shell), Some("a")); + assert_eq!(assigned("ID=\"a\" # bundle ID\n", "ID", shell), Some("a")); + assert_eq!(assigned("ID=a # bundle ID\n", "ID", shell), Some("a")); + } + // In Python a `#` right after the closing quote starts a comment; in a shell it is part of the word. + assert_eq!(assigned("ID='a'#b\n", "ID", false), Some("a")); + assert_eq!(assigned("ID='a'#b\n", "ID", true), Some("'a'#b")); } #[test] diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index c839b5f232..6bcdd4853e 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -1111,6 +1111,65 @@ fn a_docked_column_is_never_narrower_than_the_panel_minimum() { assert!(body_width(&h, "Properties") >= PANEL_MIN_WIDTH - 0.5, "saved 100 pt wide: {}", body_width(&h, "Properties")); } +/// The opaque rects the last frame painted inside `cell`. +fn opaque_rects_in(shapes: &[egui::epaint::ClippedShape], cell: Rect) -> Vec { + crate::tests_labels::painted_shapes(shapes) + .into_iter() + .filter_map(|(shape, transform, _)| match shape { + egui::Shape::Rect(r) if r.fill.a() == 255 => { + let mut r = r.clone(); + r.rect = transform * r.rect; + cell.expand(0.75).contains_rect(r.rect).then_some(r) + } + _ => None, + }) + .collect() +} + +/// The docked Tools card, in each color scheme and at UI Scaling 100% and 200%: its bar and its body keep to the +/// card's rounded top corners. Every opaque surface that reaches a top corner of the card is rounded there at least as +/// much as the card's foot is, so no square corner shows past the bar's rounded one. +#[test] +fn the_docked_tools_card_keeps_its_rounded_top_corners() { + let near = |a: f32, b: f32| (a - b).abs() <= 0.75; + for scheme in ["classic", "modern"] { + for scaling in [1.0, 2.0] { + let case = format!("{scheme} at {scaling}"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.ui_color_scheme = scheme.into(); + app.session.prefs.ui_scaling = scaling; + Arc::make_mut(&mut app.ui.dock_workspace).replace(builtin_workspace(&[], 2)); + let ctx = crate::testing::ui_context(); + let mut shapes = Vec::new(); + for frame in 0..4 { + let input = egui::RawInput { time: Some(f64::from(frame) * 0.05), screen_rect: Some(SCREEN), ..Default::default() }; + shapes = crate::testing::app_frame(&mut app, &ctx, input).shapes; + } + let cell = app.dock_rt.columns.iter().find(|(panel, _)| panel == crate::toolbar::TOOLS).map(|(_, rect)| *rect); + let cell = cell.unwrap_or_else(|| panic!("{case}: the Tools column is docked")); + let rects = opaque_rects_in(&shapes, cell); + // The card's foot: the largest surface in the column with rounded lower corners. + let foot = rects + .iter() + .filter(|r| r.corner_radius.sw > 0 && r.corner_radius.se > 0) + .max_by(|a, b| a.rect.area().total_cmp(&b.rect.area())) + .unwrap_or_else(|| panic!("{case}: the Tools card is painted: {rects:?}")); + let spans = |r: &&egui::epaint::RectShape| near(r.rect.left(), foot.rect.left()) && near(r.rect.right(), foot.rect.right()); + let top = rects.iter().filter(spans).map(|r| r.rect.top()).fold(foot.rect.top(), f32::min); + let at_top: Vec<_> = rects.iter().filter(|r| near(r.rect.top(), top)).collect(); + let left: Vec<_> = at_top.iter().filter(|r| near(r.rect.left(), foot.rect.left())).collect(); + let right: Vec<_> = at_top.iter().filter(|r| near(r.rect.right(), foot.rect.right())).collect(); + assert!(!left.is_empty() && !right.is_empty(), "{case}: the card's top is painted: {at_top:?}"); + for r in left { + assert!(r.corner_radius.nw >= foot.corner_radius.sw, "{case}: a square corner shows at the card's top left: {r:?}"); + } + for r in right { + assert!(r.corner_radius.ne >= foot.corner_radius.se, "{case}: a square corner shows at the card's top right: {r:?}"); + } + } + } +} + impl Harness { /// The node with key focus in the last frame. fn focused_node(&self) -> Option<&egui::accesskit::Node> { diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index 3220039a1c..284b4a559e 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -522,13 +522,14 @@ fn persistent_panels_reopen_at_startup_with_their_settings() { assert_eq!((r["persistent"].as_bool(), r["view"].as_str(), r["showFind"].as_bool()), (Some(true), Some("largeList"), Some(false))); app.run("ui.libraryPanel", json!({"panel": brand, "persistent": true})).unwrap(); app.run("window.panel.float", json!({"panel": pastels, "x": 40, "y": 90})).unwrap(); + let saved = docking(&app).floating.iter().find(|g| g.contains(&pastels)).unwrap().rect; // A persistent panel reopens even when it was closed. app.run("window.panel.close", json!({"panel": brand})).unwrap(); let next = restarted(&app); assert!(is_open(&next.ui, &pastels) && is_open(&next.ui, &brand), "{}", next.ui.status); assert!(!is_open(&next.ui, &brights), "a panel that isn't persistent closed with the app"); let group = docking(&next).floating.iter().find(|g| g.contains(&pastels)).unwrap(); - assert_eq!(group.rect.min, Pos2::new(40.0, 90.0), "where it was"); + assert_eq!(group.rect.min, saved.min, "where it was"); let s = settings(&next.ui, "swatches", "pastels").unwrap(); assert_eq!((s.view, s.hide_find, s.persistent), (Some(View::LargeList), true, true)); let (_, id) = parse(&brand).unwrap(); @@ -747,11 +748,12 @@ fn previous_and_next_show_the_neighbouring_library_in_the_same_panel() { let first = panel_of(app.run("window.swatchLibrary", json!({"library": "pastels"})).unwrap()); app.run("window.panel.float", json!({"panel": first, "x": 50, "y": 60})).unwrap(); app.run("ui.libraryPanel", json!({"panel": first, "persistent": true, "view": "smallList"})).unwrap(); + let saved = docking(&app).floating.iter().find(|g| g.contains(&first)).unwrap().rect; step::(&mut app, "pastels", 1); let next = panel_id("swatches", SWATCH_IDS[5]); assert!(!is_open(&app.ui, &first) && is_open(&app.ui, &next), "{}", app.ui.status); let group = docking(&app).floating.iter().find(|g| g.contains(&next)).unwrap(); - assert_eq!((group.panels().count(), group.rect.min), (1, Pos2::new(50.0, 60.0)), "in its place"); + assert_eq!((group.panels().count(), group.rect.min), (1, saved.min), "in its place"); let s = settings(&app.ui, "swatches", SWATCH_IDS[5]).unwrap(); assert_eq!((s.view, s.persistent), (Some(View::SmallList), true), "the panel keeps its settings"); assert!(settings(&app.ui, "swatches", "pastels").is_none()); diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index 7aacaaf1f8..a30cf7b559 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -1088,6 +1088,9 @@ fn above_text_puts_the_panel_at_the_top_when_below_the_text_does_not_fit() { } let (node, _, span) = current(&app).unwrap(); above_text(&mut app, &node, span).unwrap(); - assert_eq!(tabs_rect(&app).min.y, 0.0, "view centered at y {center_y}"); + // Neither above the text (off the window) nor below it (inside the canvas): at the window's top. + let (top, canvas) = (tabs_rect(&app).min.y, app.canvas_view().unwrap().rect); + assert!(canvas.top() > 0.0, "canvas {canvas:?}"); + assert_eq!(top, 0.0, "view centered at y {center_y}: panel top {top}, canvas {canvas:?}"); } } diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 61860ee915..0451cb5b5c 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -63,6 +63,97 @@ 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. + /// `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()) + } +} + +/// 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. diff --git a/docs/development.md b/docs/development.md index 6f43d470b9..77e4b736a5 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. A `never-run` test that still builds on macOS or Windows, such as a test of a macOS-only module, is listed without failing; run it locally on that platform. 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. A `never-run` test that still builds on macOS or Windows, such as a test of a macOS-only module, is listed without failing; run it locally on that platform. 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/docs/mcp.md b/docs/mcp.md index 42f5465272..9fae3af0b4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2846,8 +2846,8 @@ VectorCraft's own. Spread, closed when its `next()` throws or gives a result that is not an object, when reading the result's `done` or `value` throws, or when the result says it is done. Destructuring `undefined` or `null` throws a `TypeError`. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In an engine that `#targetengine` keeps and a `.jsx` script -started, which has no `Symbol`, spread, `for`-`of` and array patterns read arrays, `arguments` objects and strings -(by code point), by index, and throw a `TypeError` for any other value; that rule is VectorCraft's own. Object +started, which has no `Symbol`, spread, `for`-`of` and array patterns read arrays, proxies of arrays (through their +traps, reading the length again before each element), `arguments` objects and strings (by code point), by index, and throw a `TypeError` for any other value; that rule is VectorCraft's own. Object literals there also take methods (`{m() {}}`, `{[key]() {}}`), and `__proto__: value` sets the new object's prototype (https://262.ecma-international.org/6.0/, sections 14.3 and B.3.1). Functions get a `name` property (section 9.2.11): a declaration's or expression's own name, or else the name of the binding, parameter, default @@ -2863,7 +2863,84 @@ 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 +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 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. 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 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. +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)` +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; +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`. 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. 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 +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`. +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, 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 +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; 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 +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. 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 @@ -3600,7 +3677,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 @@ -13701,14 +13780,17 @@ 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. Those 256 can -all be glyphs of other fonts drawn alike (a period or a dot): a shape matched whole, whose matches are all near -matches in other fonts than that of the line before it, is also compared with the 256 glyphs of that line's font -closest to it in proportion when it does not join the line, and joins the line when one of them fits. A shape with an -exact match, a shape split into several glyphs, a shape that matches no glyph at all and a shape after an unmatched -shape are not compared again. 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. Those 256 outlines +can all be glyphs of other fonts drawn alike (a period or a dot): a shape matched whole, whose matches are all near +matches in other fonts than that of the line before it, is also compared with the glyphs of the 256 outlines of that +line's font closest to it in proportion when it does not join the line, and joins the line when one of them fits. A +shape with an exact match, a shape split into several glyphs, a shape that matches no glyph at all and a shape after an +unmatched shape are not compared again. 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 @@ -17949,7 +18031,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, @@ -18331,7 +18413,7 @@ enabled only when a selected image has a mask. → `{changed, ids}` ## Type Tools add-on -Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker` and `addon.type.releasePath`, and +Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker`, `addon.type.releasePath` and `addon.type.numbers`, and in the desktop app it lives in Object › Plug-ins › Type Tools (#4924, #5532). Text Tweaker gives one character attribute to the characters letter by letter, from a start value to an end value along a shape, as one undo step; the text stays live and editable. Each value is set as `text.setRangeStyle` sets it (the Character panel), in its units and ranges ([formatting type](https://helpx.adobe.com/illustrator/using/formatting-type.html)), so on scaled @@ -18396,6 +18478,49 @@ Path Options' Preview does (#5360). {"name":"run_command","arguments":{"command":"addon.type.releasePath","params":{"mode":"path","keepOriginal":true}}} ``` +### Make Numbers Sequence + +`addon.type.numbers` numbers the type objects among `ids` (or `id`, else the selection), groups included, from `start` +by `step`, as one undo step. Each number replaces the object's whole text, every number in it, or every `{%n}` +placeholder in it. It is based on Sergey Osokin's MIT-licensed +[MakeNumbersSequence](https://github.com/creold/illustrator-scripts/blob/master/md/Text.md#makenumberssequence) +script. + +- With `end` omitted the numbers run to the last object. With `end`, they stop past it and the objects after the last + number keep their text, or are deleted with `removeUnused`. A type object that is the mask of a clipping group or layer + is not deleted. The sign of `step` is set to run toward `end`. +- Locked or hidden type, also inside a selected group, is not numbered or deleted. +- With `replace` `numbers` or `placeholder`, objects that hold no number or placeholder are skipped and get no number, + and `order` leaves them out. The remaining objects are ordered before `end` limits the sequence, so objects past + `end` still count for rows and columns. A number is a run of digits with any `.` or `,` between digits, + and a `-` before it that does not follow a letter or digit. Replaced text takes the style of the text it replaces; + a number or placeholder that already reads the new number keeps its text and style. With `numbers` or + `placeholder`, one run replaces at most 10,000 numbers or placeholders; more is an error, and nothing changes. +- Values are rounded to the most decimal places among `start`, `step` and `end` (at most 6), so 0.1 by 0.1 gives + 0.1, 0.2, 0.3. +- Objects that already read so are left as they are; when nothing changes no undo step is made. +- A frame of threaded type among the objects is an error, and nothing changes. + +| Parameter | Values (default) | +|---|---| +| `start`, `step` | numbers −1e12…1e12 (1, 1; `step` 0: every object gets `start`) | +| `end` | number −1e12…1e12 (omitted: to the last object) | +| `order` | `stacking` (from the back), `rows` (top to bottom, each row left to right), `columns` (left to right, each column top to bottom) (`stacking`). Objects whose centers are within half the median height (width for columns) of a row's first object share its row | +| `replace` | `all`, `numbers`, `placeholder` (`all`) | +| `shuffle`, `seed` | false; true: the numbers go to the objects in random order, the same `seed` (a whole number, 0) giving the same order, and `order` is not used. A `seed` that is not a whole number is an error even with `shuffle` off | +| `leadingZeros` | true: non-negative numbers are padded with zeros to the whole digits of the wider of `start` and `end` (or the last number) | +| `digits` | 1…30: with `leadingZeros`, at least this many whole digits | +| `trailingZeros` | false; true: every number gets as many decimal places as the one with the most | +| `removeUnused` | false; true needs `end` | + +→ `{count (objects changed), ids (numbered, in order), removed}`. Make Numbers Sequence… opens a dialog (`ui.menuDialog +{command}`, dialog key `addon.type.numbers`) whose fields are the command's parameters, with Preview. + +```json +{"name":"run_command","arguments":{"command":"addon.type.numbers","params":{"start":1,"order":"rows"}}} +{"name":"run_command","arguments":{"command":"addon.type.numbers","params":{"start":5,"end":50,"step":5,"replace":"placeholder","digits":3}}} +``` + ## Unit Converter add-on Unit Converter is a built-in add-on that shows one length in every unit at once (#5528): its commands are diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ddd8739859..1a18319203 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1143,7 +1143,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` 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`. @@ -1196,6 +1196,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 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. An object of a host class with an indexer, such as a script collection of the document's objects, is always visited index by index. `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`. @@ -1205,6 +1206,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. 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`. @@ -3178,7 +3180,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) @@ -3192,6 +3194,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app (it has no command for this), so no area score moves. Object › Plug-ins › Type Tools › Release Type on a Path… splits each selected type on a path into point type holding the same text and the plain path it was set on, or keeps only one of them (#5532). The path keeps its exact shape (open or closed, anchors and handles, the object's transform), layer and place in the stacking order, with no fill and no stroke since type paths carry no paint of their own. The text keeps its runs, character and paragraph attributes and becomes point type on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options don't apply to point type and are dropped. Keep Original leaves the type on a path and adds the released objects above it. Other objects are left alone and a selection with no type on a path makes no undo step; otherwise the run is one undo step, the released objects are selected, and the dialog's Preview works as Type on a Path Options' does (#5360). Tests: `cmd::addons::typetools::tests::release` in `vectorcraft-engine` (each mode, Keep Original, mixed and empty selections, closed, open, curved and flipped paths, transformed and grouped type, multi-style and unicode text with a centred paragraph, empty type, undo and redo, preview, cancel and commit, bad params refused), `release_type_on_a_path_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on › Release Type on a Path. +## Type Tools add-on: Make Numbers Sequence (2026-12-01) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Make Numbers Sequence… numbers the selected type objects from a start value by a step, optionally stopping at an end value, and each number replaces the whole text, every number in it, or every `{%n}` placeholder (#10448). The objects are taken in stacking order, by rows or by columns, or in a seeded random order, with optional leading and trailing zeros, and the objects past the end can be deleted. When numbers or placeholders are replaced, objects that hold none are skipped before the ordering, so they take no number and are never deleted. Locked and hidden type is left alone, a clipping mask is not deleted, and threaded type and bad parameters are refused. A run that changes the document is one undo step, and a run that changes nothing makes none. The dialog has Preview. It is based on Sergey Osokin's MIT-licensed MakeNumbersSequence script. Tests: `cmd::addons::typetools::numbers::tests` in `vectorcraft-engine`, `addons::typetools::numbers::tests` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. + ## Unit Converter add-on (2026-11-14) A VectorCraft addition, so no area score moves. Object › Plug-ins › Unit Converter opens a panel with one number field per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha), as proposed in #5528. A length typed in any field, with units and arithmetic as every number field reads them, updates the others as it is typed; text that does not read leaves them as they were. From Selection reads the selection's width and height as the Transform panel measures them, Width or Height picks which one the fields show, and Apply sets that side of the selection through `object.setBounds` as the Transform panel's W or H field does (its reference point, Constrain Width and Height Proportions and its Transform Object Only, Pattern Only or Both choice) as one undo step, with no step when the size is already that length. Each field's copy button copies its value, with its unit when Copy with Units is on. Agents use `addon.units.convert` and `addon.units.selectionSize`, which change nothing in the document (`docs/mcp.md`). Tests: `cmd::addons::units::tests` in `vectorcraft-engine` (every unit, number-field syntax, preview bounds and selected anchors, bad params and unknown keys refused), `addons::units::tests` in `vectorcraft-ui-egui` (typing, From Selection and a changed selection, Apply with the Transform panel's reference point, proportions, pattern choice and a symbol's registration point, copy, screen-reader names) and `command_sweep`. diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index c95215cd4c..42f3517c7c 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -41,8 +41,10 @@ //! function or method besides reading the clock), also under an `if` or `match` inside that //! loop, and the delay inside a closure passed to `spawn` whose thread handle the test drops; //! * `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 @@ -356,7 +358,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. @@ -375,9 +383,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)) @@ -388,7 +400,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))); } @@ -1673,7 +1685,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(") { @@ -1689,7 +1701,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) { @@ -1703,6 +1715,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| { @@ -3656,7 +3715,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 @@ -3687,6 +3749,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(); @@ -4820,7 +4988,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 +4998,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 +5011,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 +5041,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; } @@ -4957,6 +5131,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`). @@ -5393,6 +5591,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()); @@ -7851,6 +8067,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 +8093,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> = [ @@ -7887,4 +8128,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")]); + } }