diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index b7c70345d0..5d01cc8438 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -46,21 +46,25 @@ pub(crate) struct IncludeRef { } /// What variables hold, as a check learns it: the member chains assigned to them, and the ones -/// holding a File or Folder object. +/// holding a File or Folder object, with the ones of those that every assignment the check read gave +/// a Folder object ([`Analyzer::folders`]). #[derive(Clone, Debug, Default)] pub(crate) struct Known { pub bound: HashMap, pub files: HashSet, + pub folders: HashSet, } impl Known { - /// The names known. + /// The names known, a name that may hold a File object counting twice: a Folder that becomes a + /// possible File object ([`Known::add`]) changes it too. pub fn len(&self) -> usize { - self.bound.len() + self.files.len() + self.bound.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) } /// What `other` adds, up to [`crate::Limits::entries`] names of each kind: a name already - /// bound keeps its chain. + /// bound keeps its chain. A name that holds a File or Folder object on both sides holds a Folder + /// object only when both sides say so; otherwise it may hold a File object. pub fn add(&mut self, other: Known, entries: usize) { for (name, chain) in other.bound { if self.bound.len() < entries || self.bound.contains_key(&name) { @@ -68,7 +72,14 @@ impl Known { } } for name in other.files { - if self.files.len() < entries { + if self.files.contains(&name) { + if !other.folders.contains(&name) { + self.folders.remove(&name); + } + } else if self.files.len() < entries { + if other.folders.contains(&name) { + self.folders.insert(name.clone()); + } self.files.insert(name); } } @@ -255,10 +266,11 @@ struct Assign { after_new: bool, } -/// What a value the check follows holds: a member chain, or a File or Folder object. +/// What a value the check follows holds: a member chain, or a File or Folder object (`folder` when it +/// is a Folder object whatever the path names: [`Operand::file_step`]). enum Held { Chain(String), - File, + File { folder: bool }, } /// `name = (`: a value in grouping parentheses. Its value is the last operand in each pair (ECMA-262 @@ -302,8 +314,9 @@ enum Operand { FileMember { folder: bool }, /// `File.openDialog`, `File.saveDialog` or `Folder.selectDialog` came first: its `(` is next. FileDialog, - /// A call of `File`, `Folder` or one of their dialogs came first, and its `)` is still to come. - FileCall, + /// A call of `File`, `Folder` or one of their dialogs came first, and its `)` is still to come + /// (`folder` for `new Folder(…)`). + FileCall { folder: bool }, /// Grouping parentheses came first, and their `)` is still to come ([`Paren`] only). Pair, /// A member chain came first and is still being read. @@ -320,15 +333,23 @@ impl Operand { /// `Folder.selectDialog(…)`, `Folder.` ([`catalog::FOLDER_PLACES`]) or a variable holding /// one. `file`: `t` is the platform's `File` or `Folder`; `alias`: `t` names a variable holding a /// File or Folder object. + /// + /// Only `new Folder(…)`, `new Folder` and `Folder.` are Folder objects whatever the path + /// names. `Folder(…)` gives a File object when the path names a file, `Folder.selectDialog(…)` + /// gives a File or Folder object for what the user picks, `Folder.current` is the one place a + /// script can assign, and a variable another variable was assigned to may hold a File object. fn file_step(self, t: &Sig, file: bool, alias: bool) -> Operand { match self { Operand::Start if t.word("new") => Operand::New, Operand::Start if file => Operand::FileName { new: false, folder: t.text == catalog::FOLDER }, Operand::New if file => Operand::FileName { new: true, folder: t.text == catalog::FOLDER }, - Operand::Start if alias => Operand::Done(Held::File), - Operand::FileName { .. } | Operand::FileDialog if t.is("(") => Operand::FileCall, + Operand::Start if alias => Operand::Done(Held::File { folder: false }), + Operand::FileName { new, folder } if t.is("(") => Operand::FileCall { folder: new && folder }, + Operand::FileDialog if t.is("(") => Operand::FileCall { folder: false }, Operand::FileName { new: false, folder } if t.is(".") => Operand::FileMember { folder }, - Operand::FileMember { folder: true } if catalog::FOLDER_PLACES.contains(&t.text) => Operand::Done(Held::File), + Operand::FileMember { folder: true } if catalog::FOLDER_PLACES.contains(&t.text) => { + Operand::Done(Held::File { folder: t.text != catalog::FOLDER_CURRENT }) + } Operand::FileMember { folder } if (if folder { catalog::FOLDER_DIALOGS } else { catalog::FILE_DIALOGS }).contains(&t.text) => { Operand::FileDialog } @@ -337,9 +358,13 @@ impl Operand { } /// The operand is a File or Folder object when the `)` of its parentheses comes next: a complete - /// one, or `new File` or `new Folder` without arguments. - fn holds_file(&self) -> bool { - matches!(self, Operand::Done(Held::File) | Operand::FileName { new: true, .. }) + /// one, or `new File` or `new Folder` without arguments. `Some(true)` for a Folder object whatever + /// the path names. + fn held_file(&self) -> Option { + match self { + Operand::Done(Held::File { folder }) | Operand::FileName { new: true, folder } => Some(*folder), + _ => None, + } } } @@ -458,6 +483,14 @@ struct Saved { chain: Option, /// It held a File or Folder object. file: bool, + /// It held a Folder object. + folder: bool, + /// It was in [`Analyzer::maybe_files`]. + maybe_file: bool, + /// The function body or `catch` block declares it, so whether an assignment in it gave the name + /// a value that may be a File object is put back too. For an outer name an assignment emptied, + /// that stays. + local: bool, /// For a root of the document model: whether the script's own variable hid the root. shadowed: Option, /// It was a platform name the script had a meaning of its own for. @@ -525,6 +558,14 @@ struct Analyzer<'s, 'a, 'l> { bound: HashMap, /// Variables holding a File or Folder object. files: HashSet, + /// The variables in `files` holding a Folder object whatever the path names ([`Held::File`]). + folders: HashSet, + /// The variables that an assignment in this scan or in what the scan started with gave a value + /// that may be a File object. Assignments in a branch or a function body are read in order, so + /// such a variable never counts as holding a Folder object ([`Analyzer::folder`]). + maybe_files: HashSet, + /// `maybe_files` ran out of room: no variable counts as holding a Folder object. + maybe_files_full: bool, /// The platform names ([`platform_name`]) the script declares or assigns a meaning of its own /// for: they no longer stand for the platform's objects. own_names: HashSet, @@ -551,8 +592,8 @@ struct Analyzer<'s, 'a, 'l> { /// block it names. catch_names: HashMap, /// The calls of `File`, `Folder` and their dialogs still open, by the bracket depth outside their - /// `(`, up to [`crate::Limits::nesting`] of them. - file_calls: Vec, + /// `(`, up to [`crate::Limits::nesting`] of them, each true for a call that gives a Folder object. + file_calls: Vec<(usize, bool)>, /// The values in grouping parentheses, the values without them that may hold a File, and the /// values of compound assignments, being read, the innermost last, up to /// [`crate::Limits::nesting`] of them. @@ -593,6 +634,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { shadowed: [false; 4], bound: known.bound.clone(), files: known.files.clone(), + folders: known.folders.clone(), + maybe_files: known.files.difference(&known.folders).cloned().collect(), + maybe_files_full: false, own_names: HashSet::new(), scopes: vec![], declared, @@ -685,9 +729,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let consumed = self.continue_chain(&t); let before = self.depth(); if t.kind == T::Punct { - t.file = self.bracket(&t); + let held = self.bracket(&t); + t.file = held.is_some(); + t.folder = held == Some(true); } else { t.file = self.folder_place(&t); + t.folder = t.file && t.text != catalog::FOLDER_CURRENT; } self.conditional(&t); self.add_parameter(&t); @@ -793,19 +840,37 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn bind(&mut self, name: String, path: String) { self.files.remove(&name); + self.folders.remove(&name); if self.bound.contains_key(&name) || self.acc.room(self.bound.len()) { self.bound.insert(name, path); } } - /// `name` holds a File or Folder object. - fn hold_file(&mut self, name: String) { + /// `name` holds a File or Folder object (`folder` for a Folder object whatever the path names). + fn hold_file(&mut self, name: String, folder: bool) { self.bound.remove(&name); + self.folders.remove(&name); + if !folder && !self.maybe_files.contains(&name) { + if self.acc.room(self.maybe_files.len()) { + self.maybe_files.insert(name.clone()); + } else { + self.maybe_files_full = true; + } + } if self.files.contains(&name) || self.acc.room(self.files.len()) { + if folder { + self.folders.insert(name.clone()); + } self.files.insert(name); } } + /// `name` holds a Folder object whatever the path names, and no assignment the check read gave it + /// a value that may be a File object. + fn folder(&self, name: &str) -> bool { + !self.maybe_files_full && self.files.contains(name) && self.folders.contains(name) && !self.maybe_files.contains(name) + } + /// `t`, when it names a parameter of the function whose body's `{` is still to come: kept, up to /// [`crate::Limits::entries`] of them, for the body to declare. A `catch` block's parameter is /// kept for the block. @@ -848,6 +913,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// `name` is declared in the innermost function body (`var name`, `function name`, a + /// parameter): what it held outside is kept ([`Analyzer::keep_outer`]) as the body's own, and + /// the body's variable starts with no assignment read. + fn keep_own(&mut self, name: &str) { + self.keep_outer(name); + if let Some(saved) = self.scopes.last_mut().and_then(|s| s.saved.get_mut(name)) { + saved.local = true; + self.maybe_files.remove(name); + } + } + /// The names [`Declared`] has for the function body whose `{` starts at `start`. fn declared_in(&mut self, start: usize) -> &'a [&'s str] { let declared = self.declared; @@ -865,7 +941,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// outside is kept to put back when the body closes. A name the body's table has no room for /// stays as it is. fn hoist(&mut self, name: &str) { - self.keep_outer(name); + self.keep_own(name); if self.scopes.last().is_some_and(|s| s.saved.contains_key(name)) { self.empty(name); } @@ -889,7 +965,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// What `name` holds now. fn saved(&self, name: &str) -> Saved { let shadowed = catalog::DOM_ROOTS.iter().position(|r| *r == name).and_then(|i| self.shadowed.get(i).copied()); - Saved { chain: self.bound.get(name).cloned(), file: self.files.contains(name), shadowed, own: self.own_names.contains(name) } + Saved { + chain: self.bound.get(name).cloned(), + file: self.files.contains(name), + folder: self.folders.contains(name), + maybe_file: self.maybe_files.contains(name), + local: false, + shadowed, + own: self.own_names.contains(name), + } } /// `name` holds `saved` again. @@ -908,6 +992,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else { self.files.remove(&name); } + if saved.folder { + self.folders.insert(name.clone()); + } else { + self.folders.remove(&name); + } + if saved.local && saved.maybe_file { + self.maybe_files.insert(name.clone()); + } else if saved.local { + self.maybe_files.remove(&name); + } if saved.own { self.own_names.insert(name.clone()); } else { @@ -961,6 +1055,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.make_own(name); self.bound.remove(name); self.files.remove(name); + self.folders.remove(name); self.hide_root(name); } @@ -975,9 +1070,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // ---------- brackets ---------- - /// An open or close bracket: true for the `)` that ends a call of `File` or `Folder`, or grouping - /// parentheses that hold a File or Folder object ([`Analyzer::close_parens`]). - fn bracket(&mut self, t: &Sig<'s>) -> bool { + /// An open or close bracket: `Some` for the `)` that ends a call of `File` or `Folder`, or grouping + /// parentheses that hold a File or Folder object ([`Analyzer::close_parens`]), `Some(true)` when + /// the object is a Folder object. + fn bracket(&mut self, t: &Sig<'s>) -> Option { match t.text { "(" | "[" | "{" => { if std::mem::take(&mut self.suspend) @@ -997,17 +1093,20 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // The first `{` after `catch` and its parentheses at this depth opens its block. let depth = self.depth(); let catch = if t.text == "{" { self.catch.take().filter(|(d, _)| *d == depth).and_then(|(_, name)| name) } else { None }; - let file_call = t.text == "(" && self.calls_for_file(); - if file_call && self.file_calls.len() < self.acc.limits.nesting { - self.file_calls.push(self.depth()); + let file_call = if t.text == "(" { self.calls_for_file() } else { None }; + if let Some(folder) = file_call + && self.file_calls.len() < self.acc.limits.nesting + { + self.file_calls.push((self.depth(), folder)); } self.open(t); if let Some(name) = catch && self.catches.len() < self.acc.limits.nesting { - let saved = self.saved(&name); + let saved = Saved { local: true, ..self.saved(&name) }; let outer = self.catch_names.insert(name.clone(), self.depth()); self.empty(&name); + self.maybe_files.remove(&name); self.catches.push(Catch { depth: self.depth(), name, saved, outer }); } if params { @@ -1021,7 +1120,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // The parameters are the body's own names, and so are the names it declares. for name in params { self.acc.steps = self.acc.steps.saturating_add(1); - self.keep_outer(&name); + self.keep_own(&name); self.unbind(&name); } for &name in self.declared_in(t.start) { @@ -1042,16 +1141,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } self.close_scopes(); let grouped = self.close_parens(t); - if t.text == ")" && self.file_calls.last() == Some(&self.depth()) { - self.file_calls.pop(); - return true; + let depth = self.depth(); + if t.text == ")" + && let Some((_, folder)) = self.file_calls.pop_if(|(d, _)| *d == depth) + { + return Some(folder); } return grouped; } } _ => {} } - false + None } fn open(&mut self, t: &Sig<'s>) { @@ -1071,18 +1172,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// A `(` here calls something that gives a File or Folder object: `File` or `Folder` (with or /// without `new`), or `File.openDialog`, `File.saveDialog` or `Folder.selectDialog`, each the - /// platform's. - fn calls_for_file(&self) -> bool { + /// platform's. `Some(true)` when it gives a Folder object whatever the path names: only + /// `new Folder(…)` ([`Operand::file_step`]). + fn calls_for_file(&self) -> Option { let [h0, h1, h2, h3] = self.h; let platform = |s: Option, name: &str| word(s, name) && !self.own_names.contains(name); - let constructor = (platform(h0, catalog::FILE) || platform(h0, catalog::FOLDER)) && !member_mark(h1); - let dialog = h0.filter(|s| s.kind == T::Ident).is_some_and(|m| { - is(h1, ".") - && !member_mark(h3) - && ((platform(h2, catalog::FILE) && catalog::FILE_DIALOGS.contains(&m.text)) - || (platform(h2, catalog::FOLDER) && catalog::FOLDER_DIALOGS.contains(&m.text))) - }); - constructor || dialog + if (platform(h0, catalog::FILE) || platform(h0, catalog::FOLDER)) && !member_mark(h1) { + return Some(word(h0, catalog::FOLDER) && word(h1, "new")); + } + let m = h0.filter(|s| s.kind == T::Ident && is(h1, ".") && !member_mark(h3))?; + ((platform(h2, catalog::FILE) && catalog::FILE_DIALOGS.contains(&m.text)) + || (platform(h2, catalog::FOLDER) && catalog::FOLDER_DIALOGS.contains(&m.text))) + .then_some(false) } /// `t` names one of the platform's `Folder` places after `Folder.` (`Folder.temp`): a Folder @@ -1113,7 +1214,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if self.in_catch(name.text) { self.declare_in_catch(name.text); } else if self.scopes.last().is_some_and(|s| !s.saved.contains_key(name.text)) { - self.keep_outer(name.text); + self.keep_own(name.text); self.unbind(name.text); } } @@ -1140,7 +1241,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } }; let Some(c) = self.catches.get_mut(i) else { return }; - let empty = Saved { chain: None, file: false, shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true), own: platform_name(name) }; + let empty = Saved { + chain: None, + file: false, + folder: false, + maybe_file: false, + local: false, + shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true), + own: platform_name(name), + }; let outside = std::mem::replace(&mut c.saved, empty); if let Some(scope) = self.scopes.last_mut() { scope.saved.insert(name.to_string(), outside); @@ -1159,8 +1268,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.assign = Some(a); } else if (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text) { self.start_value(a.name, Operand::FileName { new: a.after_new, folder: t.text == catalog::FOLDER }); - } else if !a.after_new && t.kind == T::Ident && self.files.contains(t.text) { - self.start_value(a.name, Operand::Done(Held::File)); + } else if !a.after_new && self.alias(t) { + self.start_value(a.name, Operand::Done(Held::File { folder: false })); } else if !a.after_new && t.is("(") { self.start_group(a.name); } else { @@ -1257,14 +1366,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn group_step(&mut self, t: &Sig<'s>, started: bool, before: usize) { let after = self.depth(); let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text); - let alias = t.kind == T::Ident && self.files.contains(t.text); + let alias = self.alias(t); let Some(g) = self.groups.last_mut().filter(|g| !g.closed) else { return }; if after < g.level { // The `)` of the innermost pair: the operand, when complete, is the pair's value and the // operand of the pair around it. let held = match std::mem::replace(&mut g.operand, Operand::Other) { Operand::Done(held) => Some(held), - Operand::FileName { new: true, .. } => Some(Held::File), + Operand::FileName { new: true, folder } => Some(Held::File { folder }), _ => None, }; g.operand = held.map_or(Operand::Other, Operand::Done); @@ -1275,8 +1384,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if before > g.level { // Inside a bracket of the operand: the `)` back at the pair's depth ends a call of `File`, // `Folder` or one of their dialogs. - if after == g.level && matches!(g.operand, Operand::FileCall) { - g.operand = Operand::Done(Held::File); + if after == g.level + && let Operand::FileCall { folder } = g.operand + { + g.operand = Operand::Done(Held::File { folder }); } return; } @@ -1313,7 +1424,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn paren_step(&mut self, t: &Sig<'s>, before: usize) { let after = self.depth(); let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text); - let alias = t.kind == T::Ident && self.files.contains(t.text); + let alias = self.alias(t); if let Some(p) = self.parens.last_mut() { if before == p.level { p.operand = match std::mem::replace(&mut p.operand, Operand::Other) { @@ -1325,7 +1436,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // The `)` of a call of `File`, `Folder` or a dialog, or of grouping parentheses, ends a // File or Folder object when [`Analyzer::bracket`] set its [`Sig::file`]. p.operand = match p.operand { - Operand::FileCall | Operand::Pair if t.file => Operand::Done(Held::File), + Operand::FileCall { .. } | Operand::Pair if t.file => Operand::Done(Held::File { folder: t.folder }), _ => Operand::Other, }; } @@ -1335,11 +1446,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// The grouping parentheses that the bracket `t` closed, if any (a bracket closes one level): true - /// when `t` is their `)` and their operand is a File or Folder object. - fn close_parens(&mut self, t: &Sig<'s>) -> bool { + /// The grouping parentheses that the bracket `t` closed, if any (a bracket closes one level): `Some` + /// when `t` is their `)` and their operand is a File or Folder object, `Some(true)` for a Folder + /// object. + fn close_parens(&mut self, t: &Sig<'s>) -> Option { let depth = self.depth(); - self.parens.pop_if(|p| depth < p.level).is_some_and(|p| t.is(")") && p.operand.holds_file()) + self.parens.pop_if(|p| depth < p.level).filter(|_| t.is(")")).and_then(|p| p.operand.held_file()) + } + + /// `t` names a variable holding a File or Folder object. + fn alias(&self, t: &Sig<'s>) -> bool { + t.kind == T::Ident && self.files.contains(t.text) } /// `t` follows the last `)` of a grouped value, or ends a value without parentheses at the depth @@ -1365,7 +1482,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let complete = (g.closed || g.bare) && ends; match g.operand { Operand::Done(Held::Chain(path)) if complete => self.bind(g.name, path), - Operand::Done(Held::File) | Operand::FileName { new: true, .. } if complete => self.hold_file(g.name), + Operand::Done(Held::File { folder }) | Operand::FileName { new: true, folder } if complete => self.hold_file(g.name, folder), _ => self.unbind(&g.name), } } @@ -1449,7 +1566,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let bracket: &str = bracket.encode_utf8(&mut buf); self.acc.problem(report::UNCLOSED_BRACKET, Some(line), self.file, Some(bracket)); } - let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files) }; + // A variable that any assignment gave a value that may be a File object leaves as one. + let folders = self.folders.iter().filter(|name| self.folder(name)).cloned().collect(); + let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders }; (std::mem::take(&mut self.includes), module, known) } } diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 7bf8c9d203..19806fb9ad 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -136,12 +136,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } /// `name`, a property of `receiver` read with `.` or as a string literal in brackets, `before` - /// coming before the receiver: when it is a File object's setter, the next token says whether it - /// is set ([`Pending::Setter`]). An update operator in `before` is a prefix (`++f.length`) when - /// the receiver is on its line, or when it starts a line or comes where an expression may start; - /// otherwise it ends the operand before it (`i++` and a line break, then `f.length`). + /// coming before the receiver: when it is the setter of an object that may be a File object (not + /// of one that is a Folder object whatever the path names), the next token says whether it is set + /// ([`Pending::Setter`]). An update operator in `before` is a prefix + /// (`++f.length`) when the receiver is on its line, or when it starts a line or comes where an + /// expression may start; otherwise it ends the operand before it (`i++` and a line break, then + /// `f.length`). fn setter(&mut self, name: &str, receiver: Option>, before: Option>, line: Option) { - if catalog::FILE_SETTERS.contains(&name) && self.file_receiver(receiver, before) { + if catalog::FILE_SETTERS.contains(&name) && self.held_file(receiver, before) == Some(false) { // Before a receiver that ends in `)` (`new File(i++).length`), the operator is inside the // parentheses. let update = before.filter(|b| (b.is("++") || b.is("--")) && receiver.is_some_and(|r| r.kind == T::Ident)); @@ -328,7 +330,21 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// (not a property of the same name), or a File or Folder object made in place or held in /// grouping parentheses ([`Sig::file`]). fn file_receiver(&self, receiver: Option>, before: Option>) -> bool { - receiver.is_some_and(|r| r.file || (r.kind == T::Ident && !member_mark(before) && self.files.contains(r.text))) + self.held_file(receiver, before).is_some() + } + + /// What [`Self::file_receiver`] finds: `Some(true)` for a Folder object whatever the path names + /// ([`Sig::folder`], [`Analyzer::folder`]), `Some(false)` for an object that may be a File object, + /// and `None` for anything else. + fn held_file(&self, receiver: Option>, before: Option>) -> Option { + let r = receiver?; + if r.file { + Some(r.folder) + } else if r.kind == T::Ident && !member_mark(before) && self.alias(&r) { + Some(self.folder(r.text)) + } else { + None + } } fn string(&mut self, t: &Sig<'s>, line: Option) { diff --git a/crates/scriptcheck/src/analyze/sig.rs b/crates/scriptcheck/src/analyze/sig.rs index 1cde2df0fe..edcb642cc5 100644 --- a/crates/scriptcheck/src/analyze/sig.rs +++ b/crates/scriptcheck/src/analyze/sig.rs @@ -14,6 +14,9 @@ pub(super) struct Sig<'s> { /// name in `Folder.temp` and the other places of [`catalog::FOLDER_PLACES`], or the `)` of /// grouping parentheses that hold only such an object or a variable holding one (`(f)`). pub(super) file: bool, + /// The object that [`Sig::file`] marks the end of is a Folder object whatever the path names: + /// `new Folder(…)`, a place of [`catalog::FOLDER_PLACES`], or grouping parentheses that hold one. + pub(super) folder: bool, /// A statement may start at the token ([`crate::lex::Token::stmt`]). pub(super) stmt: bool, /// An expression may start at the token ([`crate::lex::Token::expr`]). @@ -25,7 +28,7 @@ pub(super) struct Sig<'s> { impl<'s> Sig<'s> { /// The significant token `t`, after a line break when `nl` is set. pub(super) fn of(t: &Token<'s>, nl: bool) -> Self { - Sig { kind: t.kind, text: t.text, line: t.line, nl, file: false, stmt: t.stmt, expr: t.expr, start: t.start } + Sig { kind: t.kind, text: t.text, line: t.line, nl, file: false, folder: false, stmt: t.stmt, expr: t.expr, start: t.start } } pub(super) fn is(&self, punct: &str) -> bool { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6f25fe6df3..0045c764f2 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -40,6 +40,8 @@ pub(crate) const FOLDER_DIALOGS: &[&str] = &["selectDialog"]; pub(crate) const INSTANCE_DIALOGS: &[&str] = &["openDlg", "saveDlg", "selectDlg"]; pub(crate) const FOLDER_PLACES: &[&str] = &["appData", "appPackage", "commonFiles", "current", "desktop", "myDocuments", "startup", "system", "temp", "trash", "userData"]; +/// The `Folder` place a script can assign. +pub(crate) const FOLDER_CURRENT: &str = "current"; pub(crate) const EXECUTE: &str = "execute"; pub(crate) const OPEN: &str = "open"; /// The open modes that write: write, append and edit. diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index cf71cefc0f..b771cc6417 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -564,6 +564,95 @@ fn setting_a_files_length_or_flags_writes_it() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 4, 5, 6, 7, 8, 10, 12][..])); } +/// `new Folder(…)` and the `Folder` places always give a Folder object, which has no `length`, +/// `hidden` or `readonly` setter. `Folder(…)` gives a File object when the path names a file, +/// `Folder.selectDialog()` gives a File or Folder object, and a variable assigned another variable +/// may hold either, so setting those writes. Removing a folder still writes. +#[test] +fn setting_a_folders_length_or_flags_does_not_write() { + let r = report(concat!( + "var d = new Folder(p);\n", + "d.length = 0;\n", + "d.hidden = true;\n", + "Folder.temp.length = 0;\n", + "(new Folder(q)).length = 0;\n", + "(Folder.desktop)['readonly'] = true;\n", + "Folder(p).readonly = true;\n", + "var e = Folder.selectDialog();\n", + "e.length = 0;\n", + "var g = (d);\n", + "g['length'] = 0;\n", + "var h = Folder(p);\n", + "h.hidden = true;\n", + "(Folder(p)).length = 0;\n", + "d.remove();\n", + "Folder.current.hidden = true;\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[7, 9, 11, 13, 14, 15, 16][..])]); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[7, 9, 11, 13, 14, 15, 16][..])); +} + +/// A File object assigned to a function's own variable, its parameter or a `catch` block's +/// parameter ends with them; one assigned to an outer variable stays. Such a variable or parameter +/// starts without what the outer variable of the same name was assigned. +#[test] +fn a_file_in_a_local_variable_leaves_an_outer_folder_alone() { + let r = report(concat!( + "var d = new Folder(p);\n", + "function f(e) { var d = new File(q); e = new File(q); d.length = 0; }\n", + "var e = new Folder(p);\n", + "try { x(); } catch (d) { d = new File(q); }\n", + "d.length = 0; e.hidden = true;\n", + "var g = new Folder(p);\n", + "function h() { g = y(); g = new File(q); }\n", + "g.length = 0;\n", + "var k = new File(q);\n", + "function m(n) { var k = new Folder(p); k.length = 0; n = new Folder(p); n.hidden = true; }\n", + "try { x(); } catch (k) { k = new Folder(p); k.readonly = true; }\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[2, 8][..])]); +} + +/// The check reads branches and function bodies in order, so a variable that any assignment gives an +/// object that may be a File object keeps counting as one, in the same file, in a function the code +/// after it assigns, and across included files. +#[test] +fn a_variable_that_may_hold_a_file_counts_as_one() { + let r = report(concat!( + "var d;\n", + "if (c) { d = new File(p); } else { d = new Folder(p); }\n", + "d.length = 0;\n", + "function w() { h.hidden = true; }\n", + "var h = new Folder(q);\n", + "if (c) h = File(p);\n", + "var k = new Folder(q);\n", + "k.length = 0;\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[3, 4][..])]); + for lib in ["d = new File(q);\n", "d = Folder.selectDialog();\n", "var x = new File(q); d = x;\n"] { + let mut m = mem(&[("lib.jsxinc", lib)]); + let r = check("main.jsx", b"#include 'lib.jsxinc'\nvar d = new Folder(p);\nd.length = 0;\n", Some(&mut m), &Limits::default()); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[3][..])], "{lib}"); + } + // The function that may give `d` a File object only does so once `e` holds one, which the + // second scan learns. + let r = report(concat!( + "var d = new Folder(p);\n", + "function write() { d.length = 0; }\n", + "function assign() { d = e; }\n", + "var e = new File(q);\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[2][..])]); + let mut m = mem(&[("lib.jsxinc", "d = Folder.temp;\n")]); + let r = check("main.jsx", b"#include 'lib.jsxinc'\nvar d = new Folder(p);\nd.length = 0;\n", Some(&mut m), &Limits::default()); + assert!(r.outside.is_empty(), "{:?}", r.outside); +} + #[test] fn a_function_after_a_line_that_ends_a_statement_is_a_declaration() { let r = report("var n = 1\nfunction File() {}\nFile('x');\nvar m = 2 /* a\n */ function Socket() {}\nnew Socket();\n"); diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..d120aa130c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2558,7 +2558,8 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a - File object's `length`, `hidden` or `readonly` counts too), `filesOpened` (files opened in other apps), `network`, + File object's `length`, `hidden` or `readonly` counts too, on any object that may be a File object; only + `new Folder(…)` and the `Folder` places such as `Folder.temp`, other than `Folder.current`, are left out), `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..4a1a91589d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1071,7 +1071,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). - File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files. - Check Script reads names by the same identifier rule as `vectorcraft-js`: Unicode 17.0 `ID_Start` characters, `$` and `_` start a name, and `ID_Continue` characters and `$` continue it (https://www.unicode.org/reports/tr31/, https://tc39.es/ecma262/#sec-names-and-keywords). U+2118, U+203F, U+00B7 and the zero width non-joiner and joiner are name characters, and U+00B2 and U+2E2F are not. Of the characters Unicode 17.0 assigned, U+088F starts a name and U+1ACF may follow its first character. A `\uXXXX` escape is read as its character only where a name may hold it, so `\u0030abc` does not become a name that starts with a digit; a `\u{…}` escape takes any number of hexadecimal digits up to U+10FFFF, and one that is empty, unclosed, out of range or a surrogate is not part of a name. Each `\u{…}` escape read in a name is reported as syntax newer than ES3, which has only the four-digit form (https://ecma-international.org/wp-content/uploads/ECMA-262_3rd_edition_december_1999.pdf, section 7.6). A private name may start with an escape (`this.#\u{61}pp` is the private name `#app`), and a private name at the start of a line inside braces is not read as a directive unless its name is a directive's. Tests: `crates/scriptcheck/src/tests.rs` (`names_are_made_of_the_unicode_identifier_characters`, `an_escape_stands_for_a_character_only_where_a_name_may_hold_it`, `braced_escapes_in_names_are_read_by_their_value`, `braced_name_escape_reports_later_syntax_and_member`, `private_names_with_escaped_starts_are_single_tokens`, `private_name_at_line_start_is_not_a_directive`), `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs` (`both_lexers_take_the_same_characters_into_names`). - - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). + - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. It leaves out only objects that are always Folder objects, `new Folder(…)` and the `Folder` places such as `Folder.temp` other than `Folder.current`, which a script can assign; `Folder(…)` gives a File object when the path names a file and `Folder.selectDialog()` gives a File or Folder object (https://extendscript.docsforadobe.dev/file-system-access/folder-object/), so setting those counts, as it does on a variable that any assignment, in any branch or included file, gives such an object (`setting_a_folders_length_or_flags_does_not_write`, `a_variable_that_may_hold_a_file_counts_as_one`, `a_file_in_a_local_variable_leaves_an_outer_folder_alone`). A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`.