diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 08138a85ca..9fba907289 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -602,6 +602,10 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + /// Does a refusal by the file access name the refused file by its file name + /// ([`SaveJob::naming_refused_file`])? + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + names_refused_file: bool, } /// Writes the file at a path with what the filler it is given writes into it @@ -963,7 +967,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option Self { + self.names_refused_file = true; + self + } + /// The document when the job was made (what counts as saved once the file is written). pub(crate) fn snapshot(&self) -> &Arc { &self.snapshot @@ -1075,9 +1087,9 @@ impl SaveJob { // none of the files is written, also by a writer that does not check the file access. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some(e) = files.iter().find_map(|(p, _)| super::may_write(p).err()) + && let Some((p, e)) = files.iter().find_map(|(p, _)| super::may_write(p).err().map(|e| (p, e))) { - return Err(e); + return Err(if self.names_refused_file { super::access::naming_in_error(e, p) } else { e }); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { @@ -1239,9 +1251,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let job = save_job(s, plan)?; - let uid = s.doc()?.uid; let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + let job = save_job(s, plan)?; + let job = if given { job } else { job.naming_refused_file() }; + let uid = s.doc()?.uid; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 4eaebc96ca..dda0f3c1c5 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -646,6 +646,11 @@ struct Analyzer<'s, 'a, 'l> { /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, + /// The depths of the open `[` that index the global object (`$.global[`, `this[`, + /// `globalThis[`), the innermost last, up to [`crate::Limits::nesting`] of them. + global_indexes: Vec, + /// The last token was the `]` that closes an index of the global object. + global_index_closed: 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, @@ -726,6 +731,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { objects: vec![], closed: None, index_receiver: 0, + global_indexes: vec![], + global_index_closed: false, unsure: known.unsure || declared.unsure, own_names: HashSet::new(), scopes: vec![], @@ -1447,8 +1454,19 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `{saveAs: function () {} && d.saveAs}`) takes it out again ([`ObjectValue::step`]). A closing /// brace ends the literals it closes. The variable joins [`Analyzer::writers`] only after the /// literal ([`Analyzer::settle_literal`]), so a call inside the literal, and a value that goes on - /// (`{…} && d`), see the variable as it was. + /// (`{…} && d`), see the variable as it was. A `this` or the variable's own name inside the body + /// of such a function expression takes the method out as well: running it may replace the + /// object's methods (`{saveAs: function () { this.saveAs = d.saveAs; }}`). fn object_key(&mut self, t: &Sig<'s>, before: usize) { + if t.kind == T::Ident { + for o in self.objects.iter_mut().filter(|o| o.depth < before) { + if let Some((bit, Value::Body)) = o.value + && (t.text == "this" || t.text == o.name) + { + o.value = Some((bit, Value::Other)); + } + } + } if let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) { o.step(t); } diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index f6431ad2ba..70942a0986 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -375,9 +375,23 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`, /// `local[k] = w`, `delete local.saveAs`). A property assignment whose name is such a variable's /// (`this.local = d`, `$.global['local'] = d`) may give the variable a new value through the global - /// object, so its methods are no longer known either. + /// object, so its methods are no longer known either. An assignment to a property of the global + /// object under any other key (`$.global[key] = d`, `this['lo' + 'cal'] = d`) may give any such + /// variable a new value: no variable's methods are known after it. fn writer_use(&mut self, t: &Sig<'s>) { let [h0, h1, h2, h3] = self.h; + let global_index_closed = std::mem::take(&mut self.global_index_closed); + if t.is("[") { + let global = (word(h0, "global") && is(h1, ".") && word(h2, "$") && !member_mark(h3)) + || ((word(h0, "this") || word(h0, "globalThis")) && !member_mark(h1)); + if global && self.global_indexes.len() < self.acc.limits.nesting { + self.global_indexes.push(self.depth()); + } + } else if t.is("]") { + let depth = self.depth(); + self.global_index_closed = self.global_indexes.last() == Some(&(depth + 1)); + self.global_indexes.retain(|d| *d <= depth); + } let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")); let key = t.is(":") && (is(h1, "{") || is(h1, ",")); @@ -415,6 +429,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { }; if let Some(name) = rebound { self.writers.remove(&name); + } else if global_index_closed { + // `$.global[key] = …`: the key may name any of them. + self.writers.clear(); } } } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 0adc738db2..28aec12789 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -673,6 +673,48 @@ fn a_method_call_or_a_global_property_ends_the_own_save_as() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13][..])); } +/// An assignment to a property of the global object under a key that is not one string literal may +/// give any such variable another value: after it, their `saveAs` writes the file again. One under a +/// string literal ends only the variable it names, and an index of another object ends none. +#[test] +fn a_computed_global_property_ends_every_own_save_as() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", + "var rows = [];\n", + "rows[k] = 1; $.global['b'] = app.activeDocument;\n", + "a.saveAs(f);\n", + "$.global[key] = app.activeDocument;\n", + "a.saveAs(f);\n", + "var c = {saveAs: function () {}};\n", + "this['lo' + 'cal'] = app.activeDocument;\n", + "c.saveAs(f);\n", + "var h = {saveAs: function () {}};\n", + "globalThis[names[0]] = app.activeDocument;\n", + "h.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[7, 10, 13][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[7, 10, 13][..])]); +} + +/// A `saveAs` whose body uses `this` or the variable's own name may replace the object's methods +/// when it runs, so it is not the script's own and its calls write the file. A `this` in another +/// method's body leaves `saveAs` the script's own. +#[test] +fn an_own_save_as_that_may_replace_itself_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var doc = app.activeDocument;\n", + "var a = {saveAs: function () { this.saveAs = function (g) { doc.saveAs(g); }; }};\n", + "var b = {saveAs: function () { b.saveAs = w; }};\n", + "var c = {saveAs: function (g) { return g; }, install: function () { this.n = 1; }};\n", + "a.saveAs(f); a.saveAs(f);\n", + "b.saveAs(f);\n", + "c.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 6, 7][..])); +} + /// Only a `var` statement directly in a function body or the global code that gives its first name /// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the /// statement. A literal given in a branch, one the value goes on from, one given by an assignment