diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 5d01cc8438..d718c88b30 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -53,19 +53,23 @@ pub(crate) struct Known { pub bound: HashMap, pub files: HashSet, pub folders: HashSet, + /// A file gives names values the analysis doesn't read ([`Declared::unsure`]): no object counts + /// as a Folder object whatever the path names. + pub unsure: bool, } impl 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().saturating_mul(2).saturating_sub(self.folders.len()) + self.bound.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) + usize::from(self.unsure) } /// What `other` adds, up to [`crate::Limits::entries`] names of each kind: a name already /// 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) { + self.unsure |= other.unsure; for (name, chain) in other.bound { if self.bound.len() < entries || self.bound.contains_key(&name) { self.bound.entry(name).or_insert(chain); @@ -566,6 +570,9 @@ struct Analyzer<'s, 'a, 'l> { maybe_files: HashSet, /// `maybe_files` ran out of room: no variable counts as holding a Folder object. maybe_files_full: bool, + /// This file or what the scan started with gives names values the analysis doesn't read + /// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names. + unsure: 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, @@ -635,8 +642,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { bound: known.bound.clone(), files: known.files.clone(), folders: known.folders.clone(), - maybe_files: known.files.difference(&known.folders).cloned().collect(), + // A variable of the same name as a property a member assignment writes may be that + // property of the global object. + maybe_files: known.files.difference(&known.folders).chain(declared.rebound.iter()).cloned().collect(), maybe_files_full: false, + unsure: known.unsure || declared.unsure, own_names: HashSet::new(), scopes: vec![], declared, @@ -865,10 +875,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// `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. + /// `name` holds a Folder object whatever the path names, no assignment the check read gave it a + /// value that may be a File object, and the file gives no name a value the analysis doesn't read. fn folder(&self, name: &str) -> bool { - !self.maybe_files_full && self.files.contains(name) && self.folders.contains(name) && !self.maybe_files.contains(name) + !self.maybe_files_full && !self.unsure && 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 @@ -1568,7 +1578,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } // 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 }; + let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders, unsure: self.unsure }; (std::mem::take(&mut self.includes), module, known) } } diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index d0e55cbb1f..48f071d2ac 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -2,7 +2,21 @@ use std::collections::HashSet; -use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, for_in, goes_on_after, goes_on_with, is, member_mark, word}; +use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word}; + +/// The names that give variables values the analysis doesn't read: a `with` statement makes an +/// object's properties stand for names in its body (ECMA-262 3rd edition, section 12.10), and `eval`, +/// `Function` and `$.evalFile` run code given as text. A string literal in brackets that names one +/// reaches it too (`this['eval']`), and so does a function's `constructor` property, which is +/// `Function` (section 15.3.4.1). +const UNREAD_BINDINGS: &[&str] = &["with", "eval", "Function", catalog::DOLLAR_EVAL_FILE]; + +/// The property a function reaches `Function` through. +const CONSTRUCTOR: &str = "constructor"; + +/// The longest property name, in characters, that [`Declared::rebound`] keeps. A string literal in +/// brackets that spells a longer one sets [`Declared::unsure`]. +const PROPERTY_CHARS: usize = 256; /// The names a file's function bodies and its global code declare, read before the analysis. A /// function's `var` statements and the function declarations directly in its body make the names @@ -19,6 +33,17 @@ pub(crate) struct Declared<'s> { pub(super) bodies: Vec<(usize, Vec<&'s str>)>, /// The names the function declarations directly in the global code declare. pub(super) global: HashSet<&'s str>, + /// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be + /// the global object, so a variable of that name may get a value the analysis doesn't read. + pub(super) rebound: HashSet, + /// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or + /// a `constructor` property used, a property read, called or assigned whose name in brackets is + /// not one string or number literal, which may be a variable's name on the global object + /// (ECMA-262 3rd edition, section 10.1.3) or one of [`UNREAD_BINDINGS`] whatever object the + /// brackets follow, a property assigned whose name is a string literal longer than + /// [`PROPERTY_CHARS`], or `Folder` assigned or declared), or `rebound` ran out of room: no + /// object counts as a Folder object whatever the path names. + pub(super) unsure: bool, } /// A function body [`Declarations`] is reading: the bracket depth inside it, its entry in @@ -31,13 +56,23 @@ struct Body<'s> { var_depth: Option, } +/// A `[` [`Declarations`] is reading: the bracket depth inside it, whether a property's name in +/// brackets starts at it (it comes after a value, where no array literal starts), and the tokens read +/// inside it so far: how many, and the kind of the first. +struct Key { + depth: usize, + member: bool, + tokens: usize, + first: Option, +} + /// The pass that finds [`Declared`]. It follows brackets, function bodies and `var` statements by /// the rules [`Analyzer`] follows them by, so that both passes find the same function bodies. struct Declarations<'s, 'a, 'l> { acc: &'a mut Acc<'l>, brackets: Brackets, - /// The two significant tokens before this one, the latest first. - h: [Option>; 2], + /// The three significant tokens before this one, the latest first. + h: [Option>; 3], /// `function` was read at this bracket depth, and its body's `{` is still to come. function: Option, /// The bracket depth of the `var` statement being read. @@ -50,6 +85,8 @@ struct Declarations<'s, 'a, 'l> { /// The bracket depth inside the outermost function body past that limit being read. The names /// declared inside it are not kept. untracked: Option, + /// The `[` brackets being read, the innermost last, up to [`crate::Limits::nesting`]. + keys: Vec, out: Declared<'s>, } @@ -59,12 +96,13 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { let mut d = Declarations { acc, brackets: Brackets::default(), - h: [None; 2], + h: [None; 3], function: None, var_depth: None, assign: None, bodies: vec![], untracked: None, + keys: vec![], out: Declared::default(), }; let mut breaks = LineBreaks::default(); @@ -75,7 +113,8 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { Read::Token(sig) => d.token(sig), } } - let out = d.out; + let mut out = d.out; + out.unsure |= out.rebound.contains(catalog::FOLDER); acc.steps = acc.steps.saturating_add(lexer.steps); out } @@ -86,7 +125,14 @@ impl<'s> Declarations<'s, '_, '_> { } fn token(&mut self, t: Sig<'s>) { - let [h0, h1] = self.h; + let [h0, h1, _] = self.h; + self.unread_binding(&t); + if !t.is("]") + && let Some(key) = self.keys.last_mut() + { + key.tokens = key.tokens.saturating_add(1); + key.first = key.first.or(Some(t.kind)); + } // As in [`Analyzer::token`], a line break ends a `var` statement when it is outside the // statement's brackets, and the tokens on either side of it don't go on with the expression. if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(h0) && !goes_on_with(&t) { @@ -118,7 +164,51 @@ impl<'s> Declarations<'s, '_, '_> { if t.word("function") && !member_mark(h0) && !word(h0, "function") { self.function = Some(depth); } - self.h = [Some(t), h0]; + self.h = [Some(t), h0, h1]; + } + + /// `t`, a token before the brackets are followed past it: notes in [`Declared::rebound`] and + /// [`Declared::unsure`] the ways the file gives names values the analysis doesn't read. + fn unread_binding(&mut self, t: &Sig<'s>) { + let [h0, h1, h2] = self.h; + if t.kind == T::Ident && (UNREAD_BINDINGS.contains(&t.text) || t.text == CONSTRUCTOR) { + self.out.unsure = true; + } + // `this['eval']`, `$['evalFile']` and `o['constructor']`. + if t.kind == T::Str && is(h0, "[") { + let name = unquote(t.text, PROPERTY_CHARS.saturating_add(1)); + if UNREAD_BINDINGS.contains(&name.as_str()) || name == CONSTRUCTOR { + self.out.unsure = true; + } + } + // `var Folder`, `function Folder` and `Folder = …`: `Folder` may stop being the platform's. + if (t.word(catalog::FOLDER) && (word(h0, "var") || word(h0, "function") || (is(h0, ",") && self.var_depth.is_some()))) + || (t.is("=") && word(h0, catalog::FOLDER)) + { + self.out.unsure = true; + } + if t.is("=") { + let literal = |kind: T| h1.is_some_and(|s| s.kind == kind) && is(h2, "["); + let property = if h0.is_some_and(|s| s.kind == T::Ident) && member_mark(h1) { + h0.map(|s| s.text.to_string()) + } else if is(h0, "]") && literal(T::Str) { + // The value spells a longer name than is kept: it may be any variable's. + h1.map(|s| unquote(s.text, PROPERTY_CHARS.saturating_add(1))).filter(|name| name.chars().count() <= PROPERTY_CHARS) + } else { + None + }; + if let Some(name) = property { + if self.out.rebound.contains(&name) || self.acc.room(self.out.rebound.len()) { + self.out.rebound.insert(name); + } else { + self.out.unsure = true; + } + } else if is(h0, "]") && !literal(T::Number) { + // `o[k] = …` with a computed name, or a string literal too long to keep. A number + // names no variable. + self.out.unsure = true; + } + } } /// An open or close bracket, by the rules of [`Analyzer::bracket`]: the first `{` after @@ -128,6 +218,16 @@ impl<'s> Declarations<'s, '_, '_> { "(" | "[" | "{" => { let body = t.text == "{" && self.function.take() == Some(self.depth()); self.brackets.open(t, self.acc.limits.nesting); + if t.text == "[" { + // After a value, `[` starts a property's name in brackets (ECMA-262 3rd + // edition, section 11.2.1); elsewhere it starts an array literal. + let member = !t.expr; + if self.keys.len() < self.acc.limits.nesting { + self.keys.push(Key { depth: self.depth(), member, tokens: 0, first: None }); + } else if member { + self.out.unsure = true; + } + } if !body { return; } @@ -140,10 +240,22 @@ impl<'s> Declarations<'s, '_, '_> { } } ")" | "]" | "}" => { + let inside = self.depth(); if !self.brackets.close(t) { return; } let depth = self.depth(); + // `o[k]`, `this['ev' + 'al']` and `o[('eval')]`, read, called or assigned: a name + // in brackets that isn't one string or number literal may be any variable's on the + // global object, or `eval`, `Function`, `evalFile` or `constructor`. + if t.text == "]" + && let Some(key) = self.keys.pop_if(|k| k.depth == inside) + && key.member + && !(key.tokens == 1 && matches!(key.first, Some(T::Str | T::Number))) + { + self.out.unsure = true; + } + while self.keys.pop_if(|k| depth < k.depth).is_some() {} if self.var_depth.is_some_and(|d| depth < d) { self.var_depth = None; } @@ -163,7 +275,7 @@ impl<'s> Declarations<'s, '_, '_> { /// directly in it, and for the global code when the declaration is directly in the global code. /// Each body keeps up to [`crate::Limits::entries`] names, and so does the global code. fn declaration(&mut self, t: &Sig<'s>) { - let [h0, _] = self.h; + let [h0, ..] = self.h; let depth = self.depth(); let var = word(h0, "var") || (is(h0, ",") && self.var_depth == Some(depth)); let function = word(h0, "function") && h0.is_some_and(|f| f.stmt); @@ -182,9 +294,14 @@ impl<'s> Declarations<'s, '_, '_> { } } - /// A preprocessor line ends the statement before it, as in [`Analyzer::directive`]. + /// A preprocessor line ends the statement before it, as in [`Analyzer::directive`]. Inside a + /// property's name in brackets it hides the tokens before the name (`this[`, a line, `'eval']`), + /// so the name may be any. fn directive(&mut self) { - self.h = [None; 2]; + if self.keys.iter().any(|k| k.member) { + self.out.unsure = true; + } + self.h = [None; 3]; self.var_depth = None; self.assign = None; } diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 19806fb9ad..5599d5b691 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -334,12 +334,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } /// 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. + /// ([`Sig::folder`], [`Analyzer::folder`]), unless the file gives names values the analysis + /// doesn't read ([`Analyzer::unsure`]), `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) + Some(r.folder && !self.unsure) } else if r.kind == T::Ident && !member_mark(before) && self.alias(&r) { Some(self.folder(r.text)) } else { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index b771cc6417..1f527349b4 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -653,6 +653,154 @@ fn a_variable_that_may_hold_a_file_counts_as_one() { assert!(r.outside.is_empty(), "{:?}", r.outside); } +/// A `with` statement, `eval`, `Function`, `$.evalFile`, a member assignment that may write the +/// global object's property of a variable's name, and a script's own `Folder` may give a name a +/// File object the check doesn't see, before or after the setter in the text, so the setter counts. +#[test] +fn a_folder_that_other_code_may_rebind_counts_as_a_file() { + let scripts: [(&str, usize); 11] = [ + ("var d = new Folder(p);\nwith (o) { d.length = 0; }\n", 2), + ("var d = new Folder(p);\nfunction w() { d.hidden = true; }\n$.global.d = new File(q);\n", 2), + ("var d = new Folder(p);\nfunction w() { d.hidden = true; }\nthis.d = new File(q);\n", 2), + ("var d = new Folder(p);\nfunction w() { d.hidden = true; }\nthis['d'] = new File(q);\n", 2), + ("var d = new Folder(p);\nfunction w() { d.hidden = true; }\n$.global[k] = new File(q);\n", 2), + ("eval(s);\nnew Folder(p).length = 0;\n", 2), + ("var d = new Folder(p);\nd.readonly = true;\n$.evalFile(f);\n", 2), + ("var d = new Folder(p);\nd.readonly = true;\nvar g = new Function(s);\n", 2), + ("$.global.Folder = File;\nnew Folder(p).length = 0;\n", 2), + ("function w() { new Folder(p).hidden = true; }\nFolder = File;\n", 1), + ("function w() { Folder.temp.hidden = true; }\nvar Folder = File;\n", 1), + ]; + let written = |r: &Report| r.outside.iter().find(|o| o.id == "filesWritten").map(|o| o.lines.clone()); + for (script, line) in scripts { + assert_eq!(written(&report(script)), Some(vec![line]), "{script}"); + } + // Another variable's name, or a number as the index, leaves the Folder alone. + let r = report("var d = new Folder(p);\no.e = new File(q);\na[0] = new File(q);\nd.length = 0;\n"); + assert_eq!(written(&r), None); + // A computed index may name the variable on any object that may be the global object. + let r = report("var d = new Folder(p);\na[k] = new File(q);\nd.length = 0;\n"); + assert_eq!(written(&r), Some(vec![3])); + // A `with` statement in an included file counts in the script too. + let mut m = mem(&[("lib.jsxinc", "with (o) { x = 1; }\n")]); + 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][..])]); +} + +/// An assignment to a computed property of any object, a string literal in brackets that names +/// `eval`, `Function` or `$.evalFile`, and any `constructor` property may give a name a File object +/// the check doesn't see, so no object counts as a Folder object. +#[test] +fn a_folder_that_unnamed_code_may_rebind_counts_as_a_file() { + let scripts: [(&str, usize); 13] = [ + ("var d = new Folder(p);\nvar g = this;\ng[k] = new File(q);\nd.length = 0;\n", 4), + ("var d = new Folder(p);\nvar g = $.global;\ng[k] = File;\nd.length = 0;\n", 4), + ("var d = new Folder(p);\n$['global'][k] = new File(q);\nd.length = 0;\n", 3), + ("var d = new Folder(p);\n$[\"global\"][k] = new File(q);\nd.length = 0;\n", 3), + ("var d = new Folder(p);\no[f(k)] = new File(q);\nd.length = 0;\n", 3), + ("var d = new Folder(p);\nd.length = 0;\n$['evalFile'](f);\n", 2), + ("var d = new Folder(p);\nd.length = 0;\nthis['eval'](s);\n", 2), + ("var d = new Folder(p);\nd.length = 0;\nthis['\\u0065val'](s);\n", 2), + ("var d = new Folder(p);\nd.length = 0;\nvar g = $.global['Function'];\n", 2), + ("var d = new Folder(p);\nd.length = 0;\n(function () {}).constructor(s)();\n", 2), + ("var d = new Folder(p);\nd.length = 0;\nvar c = o['constructor'];\n", 2), + ("new Folder(p).hidden = true;\nvar c = o.constructor;\n", 1), + ("var d = new Folder(p);\nd.length = 0;\nvar c = constructor;\n", 2), + ]; + let written = |r: &Report| r.outside.iter().find(|o| o.id == "filesWritten").map(|o| o.lines.clone()); + for (script, line) in scripts { + assert_eq!(written(&report(script)), Some(vec![line]), "{script}"); + } +} + +/// A string literal in brackets names the property its value spells, escapes undone, as a name +/// written with escapes is read as the name it spells. A literal longer than the check reads may +/// name any variable, so no object counts as a Folder object. +#[test] +fn a_bracketed_name_is_read_whole_or_counts_as_any_name() { + let long = "a".repeat(300); + let scripts = [ + format!("var {long} = new Folder(p);\nfunction w() {{ {long}.length = 0; }}\nthis['{long}'] = new File(q);\n"), + format!("var d = new Folder(p);\nfunction w() {{ d.length = 0; }}\nthis['{long}'] = new File(q);\n"), + "var d = new Folder(p);\nfunction w() { d.hidden = true; }\nthis['\\u0064'] = new File(q);\n".to_string(), + "var \\u0064 = new Folder(p);\nfunction w() { d.hidden = true; }\nthis['d'] = new File(q);\n".to_string(), + "var d = new Folder(p);\nfunction w() { \\u0064.hidden = true; }\nthis['\\x64'] = new File(q);\n".to_string(), + ]; + let written = |r: &Report| r.outside.iter().find(|o| o.id == "filesWritten").map(|o| o.lines.clone()); + for script in &scripts { + assert_eq!(written(&report(script)), Some(vec![2]), "{script}"); + } + // A short literal that names another variable leaves the Folder alone. + let r = report(&format!("var d = new Folder(p);\nfunction w() {{ d.length = 0; }}\nthis['{}'] = new File(q);\n", "a".repeat(200))); + assert_eq!(written(&r), None); +} + +/// The lines of `filesWritten` in the report on `script`. +fn files_written(script: &str) -> Option> { + report(script).outside.iter().find(|o| o.id == "filesWritten").map(|o| o.lines.clone()) +} + +/// A name in brackets held in a variable may be `eval`, so no object counts as a Folder object. +#[test] +fn a_bracketed_variable_read_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nvar k = 'eval';\nthis[k]('d = new File(q)');\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + +/// A name in brackets joined from strings may be `eval`, so no object counts as a Folder object. +#[test] +fn a_bracketed_joined_name_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nthis['ev' + 'al']('d = new File(q)');\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + +/// A string literal in grouping parentheses inside brackets is read as a computed name. +#[test] +fn a_bracketed_name_in_parentheses_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nthis[('eval')]('d = new File(q)');\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + +/// A comma expression in brackets names its last operand's value, which may be `eval`. +#[test] +fn a_bracketed_comma_expression_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nthis[0, 'eval']('d = new File(q)');\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + +/// A name in brackets held in a variable may be `evalFile`, called on `$`. +#[test] +fn a_bracketed_variable_call_on_dollar_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nvar k = 'evalFile';\n$[k](f);\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + +/// A name in brackets held in a variable may be `constructor`, which reaches `Function`. +#[test] +fn a_bracketed_variable_constructor_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nvar k = 'constructor';\n(function () {})[k](s)();\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + +/// One string or number literal in brackets names one property, and an array literal names none, +/// also with brackets inside brackets, so the Folder is left alone. A computed name inside another +/// name in brackets still counts as any name. +#[test] +fn a_literal_name_in_brackets_leaves_the_folder_alone() { + let script = "var d = new Folder(p);\nvar x = o['plain'];\nvar y = a[0][1];\na[0] = 1;\nvar z = [k, o['x'], a[0]];\nd.length = 0;\n"; + assert_eq!(files_written(script), None); + assert_eq!(files_written("var d = new Folder(p);\nd.length = 0;\nvar x = o[a[0]];\n"), Some(vec![2])); +} + +/// A preprocessor line inside a name in brackets hides the `[` before the name, so the name may be +/// `eval` and no object counts as a Folder object. +#[test] +fn a_directive_in_a_bracketed_name_counts_as_any_name() { + let script = "var d = new Folder(p);\nd.length = 0;\nthis[\n#target illustrator\n'eval']('d = new File(q)');\n"; + assert_eq!(files_written(script), Some(vec![2])); +} + #[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 0541cc2ebd..949d1c3952 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2566,7 +2566,15 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, 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, 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`, + `new Folder(…)` and the `Folder` places such as `Folder.temp`, other than `Folder.current`, are left out, and + nothing is left out in a check whose files use `with`, name `eval`, `Function`, `evalFile` or `constructor` as a + word or as a string literal in brackets, read, call or assign a property in brackets (a `[` after a value, not an + array literal) when the brackets hold anything but one number or string literal (`o[k]`, `this['ev' + 'al'](s)`, + `this[('eval')](s)`, `this[0, 'eval'](s)`, `o[a[0]]`, or a preprocessor line inside the brackets) or the `[` opens + while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256 + characters, assign properties of more than 1,000 different names on members (`o.d = …`, `o['d'] = …`), or + assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File + object), `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 e84ce63592..2b9293c9fb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1077,7 +1077,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. 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`). + - 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. Nothing counts as a Folder object in a check whose files use `with`, name `eval`, `Function`, `evalFile` or `constructor` as a word or as a string literal in brackets (`this['eval'](s)`, `(function () {}).constructor(s)`), read, call or assign a property in brackets on any object (a `[` after a value, not an array literal) when the brackets hold anything but one number or string literal (`g[k] = …`, `$['global'][k] = …`, `this[k](s)`, `this['ev' + 'al'](s)`, `this[('eval')](s)`, `this[0, 'eval'](s)`, `$[k](f)`, `(function () {})[k](s)`, or a preprocessor line inside the brackets) or the `[` opens while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256 characters, assign properties of more than 1,000 different names on members, or assign or declare `Folder`, and a variable whose name a member assignment writes (`$.global.d = …`, `this.d = …`, `this['d'] = …`, with the string's escapes undone) counts as one that may hold a File 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_folder_that_other_code_may_rebind_counts_as_a_file`, `a_folder_that_unnamed_code_may_rebind_counts_as_a_file`, `a_bracketed_name_is_read_whole_or_counts_as_any_name`, `a_bracketed_variable_read_counts_as_any_name`, `a_bracketed_joined_name_counts_as_any_name`, `a_bracketed_name_in_parentheses_counts_as_any_name`, `a_bracketed_comma_expression_counts_as_any_name`, `a_bracketed_variable_call_on_dollar_counts_as_any_name`, `a_bracketed_variable_constructor_counts_as_any_name`, `a_literal_name_in_brackets_leaves_the_folder_alone`, `a_directive_in_a_bracketed_name_counts_as_any_name`). 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`.