Scripts: a hoisted function that changes or shares a variable, a captured variable and a labelled var end the own-method exemption

A function declared before the literal that assigns the variable's saveAs
or hands the variable on, a function that calls the method on a variable it
reads from outside, and a var statement after a label keep reporting the
file write.
This commit is contained in:
dotCooCoo committed 2026-11-25 23:06:58 -08:00
1 parent bee68ccd13
commit 210ba07347
3 files changed
+115 -22

No files matched your search

+12 -1
View File
@@ -637,6 +637,12 @@ struct Analyzer<'s, 'a, 'l> {
/// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit
/// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing.
writers: HashMap<String, u8>,
/// The variables a function body read before any literal gave them methods, in a way that
/// changes or shares them ([`Analyzer::writer_use`]): the body may run after the literal (a
/// hoisted declaration), so the literal's methods are not the script's own. Each name has the
/// most function bodies that were open where it was read; a literal in a body with that many
/// open or more is unaffected, since it gives a variable of its own.
shared_early: HashMap<String, usize>,
/// The object literals being assigned to a variable, the innermost last, up to
/// [`crate::Limits::nesting`] of them.
objects: Vec<ObjectValue>,
@@ -646,6 +652,8 @@ 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,
/// Whether that receiver's own methods hold at this place ([`Analyzer::stable`]).
index_stable: bool,
/// 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<usize>,
@@ -728,9 +736,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
maybe_files: known.files.difference(&known.folders).chain(declared.rebound.iter()).cloned().collect(),
maybe_files_full: false,
writers: HashMap::new(),
shared_early: HashMap::new(),
objects: vec![],
closed: None,
index_receiver: 0,
index_stable: false,
global_indexes: vec![],
global_index_closed: false,
unsure: known.unsure || declared.unsure,
@@ -1392,7 +1402,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
let body = self.scopes.last().map_or(0, |s| s.depth);
let starts = before.is_none()
|| [";", "{", "}"].iter().any(|p| is(before, p))
|| (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !word(before, "else") && !word(before, "do"));
|| (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !is(before, ":") && !word(before, "else") && !word(before, "do"));
let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body);
if self.objects.len() < self.acc.limits.nesting {
self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None });
@@ -1441,6 +1451,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
fn settle_literal(&mut self, t: &Sig<'s>) {
if let Some((name, bits)) = self.closed.take()
&& (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t)))
&& self.shared_early.get(&name).is_none_or(|&open| open <= self.scopes.len())
&& (self.writers.contains_key(&name) || self.acc.room(self.writers.len()))
{
self.writers.insert(name, bits);
+58 -21
View File
@@ -285,7 +285,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.setter(&name, h2, h3, line);
}
// `local['saveAs']`: what the object before the bracket defines, for a call that may follow.
"[" => self.index_receiver = self.writer_bits(h0, h1),
"[" => {
self.index_receiver = self.writer_bits(h0, h1);
self.index_stable = h0.is_some_and(|r| self.stable(r.text));
}
"(" => self.call(line),
// `Name.prototype["+"] = …` defines an operator.
"=" => {
@@ -308,7 +311,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
&& is(h2, "[")
&& let Some(method) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
&& catalog::DOM_FILE_WRITES.contains(&method.as_str())
&& !Self::defines(self.index_receiver, &method)
&& !(self.index_stable && Self::defines(self.index_receiver, &method))
{
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
@@ -335,7 +338,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
} else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) {
self.acc.feature(FeatureId::FileRead, line);
} else if (file && catalog::FILE_WRITES.contains(&n))
|| (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3), n))
|| (catalog::DOM_FILE_WRITES.contains(&n) && !(h2.is_some_and(|r| self.stable(r.text)) && Self::defines(self.writer_bits(h2, h3), n)))
{
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
@@ -362,6 +365,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
/// The methods that `receiver`, which `before` comes before, defines when it is a variable holding
/// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name;
/// 0 for anything else. A receiver the check does not follow may be a document.
/// Whether a call of `name`'s own method may be left out: the call is in the global code, or in a
/// function body that declares `name` itself. A body that reads `name` from outside may run
/// after the variable was given another value, so its calls are not known.
fn stable(&self, name: &str) -> bool {
self.scopes.last().is_none_or(|s| s.saved.contains_key(name))
}
fn writer_bits(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> u8 {
match receiver {
Some(r) if r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0),
@@ -395,30 +405,57 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
let writer = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| 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, ","));
let escaped = if word(h0, "delete") {
// `delete local…`
writer(Some(*t), h0)
} else if let Some(name) = writer(h0, h1) {
// `local` followed by anything but a member, its own assignment or an object key's `:`.
(!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name)
} else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) {
// `local.saveAs = …`
writer(h2, h3)
} else if is(h0, "[") {
// `local[k]` with a key that is not a string literal.
writer(h1, h2).filter(|_| t.kind != T::Str)
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) {
// `local['name' + k]`.
writer(h2, h3).filter(|_| !t.is("]"))
} else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) {
// `local['saveAs'] = …`
writer(h3, None)
let escape = |writer: &dyn Fn(Option<Sig<'s>>, Option<Sig<'s>>) -> Option<&'s str>| -> Option<&'s str> {
if word(h0, "delete") {
// `delete local…`
writer(Some(*t), h0)
} else if let Some(name) = writer(h0, h1) {
// `local` followed by anything but a member, its own assignment or an object key's `:`.
(!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name)
} else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) {
// `local.saveAs = …`
writer(h2, h3)
} else if is(h0, "[") {
// `local[k]` with a key that is not a string literal.
writer(h1, h2).filter(|_| t.kind != T::Str)
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) {
// `local['name' + k]`.
writer(h2, h3).filter(|_| !t.is("]"))
} else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) {
// `local['saveAs'] = …`
writer(h3, None)
} else {
None
}
};
let escaped = escape(&writer);
// A function body reads a variable of the enclosing code that no literal has given methods yet
// in a way that changes or shares it: the body may run after the literal, as a hoisted
// declaration does.
let early = if escaped.is_none() && !self.scopes.is_empty() {
let captured = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| {
s.filter(|s| {
s.kind == T::Ident
&& !member_mark(before)
&& !self.writers.contains_key(s.text)
&& self.scopes.last().is_some_and(|b| !b.saved.contains_key(s.text))
})
.map(|s| s.text)
};
escape(&captured)
} else {
None
};
if let Some(name) = escaped {
self.writers.remove(name);
}
if let Some(name) = early
&& (self.shared_early.contains_key(name) || self.acc.room(self.shared_early.len()))
{
let open = self.scopes.len();
let seen = self.shared_early.entry(name.to_string()).or_insert(open);
*seen = (*seen).max(open);
}
if changes {
let rebound = if is(h1, ".") {
h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string())
+45
View File
@@ -715,6 +715,51 @@ fn an_own_save_as_that_may_replace_itself_writes_a_file() {
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 6, 7][..]));
}
/// A function declared before the literal is hoisted, so it may change or share the variable before
/// the literal's later calls run: its calls then keep reporting the write. A function with a
/// variable of its own of the same name, and one that only calls the method, leave the method the
/// script's own.
#[test]
fn a_hoisted_function_that_changes_or_shares_the_variable_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"function a(w) { local.saveAs = w; }\n",
"var local = {saveAs: function () {}};\n",
"local.saveAs(f);\n",
"function b() { use(other); }\n",
"var other = {saveAs: function () {}};\n",
"other.saveAs(f);\n",
"function c() { var calm = app.activeDocument; use(calm); }\n",
"var calm = {saveAs: function () {}};\n",
"calm.saveAs(f);\n",
"function d() { quiet.saveAs(f); }\n",
"var quiet = {saveAs: function () {}};\n",
"quiet.saveAs(f);\n",
"function g1() { use(mine); }\n",
"function g2() { var mine = {saveAs: function () {}}; mine.saveAs(f); }\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 11][..]));
}
/// A function that reads the variable from outside runs after whatever the script gave it since, so
/// its calls keep reporting the write. A `var` after a label or a `case` is in a branch as well.
#[test]
fn a_captured_or_labelled_own_save_as_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"function run() { local.saveAs(f); }\n",
"function run2() { local['saveAs'](f); }\n",
"local = app.activeDocument;\n",
"run();\n",
"function own() { var inner = {saveAs: function () {}}; inner.saveAs(f); inner['saveAs'](f); }\n",
"if (flag) skip:\n",
"var lab = {saveAs: function () {}};\n",
"lab.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4, 10][..]));
}
/// 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