Scripts: a method replaced in a loop or a later function, and a global member used as a value, end the own-method exemption

- A loop that assigns `local.saveAs` or `local['saveAs']` marks `local` as assigned in that
  loop, so a call earlier in the loop writes a file.
- A function body that replaces a variable's write method, declared anywhere in the file,
  ends the exemption for that variable's calls. A variable the innermost body declares
  itself is left alone, and a key whose escapes do not decode counts as a write method.
- `$.global.local`, `this.local` and `globalThis.local` used as a value forget the variable's
  methods as `$.global['local']` does. A variable of the same name that the function body
  declares keeps its own.
- The test with two `a.saveAs(f)` calls puts them on separate lines and checks both.
This commit is contained in:
dotCooCoo committed 2026-12-04 00:49:56 -08:00
1 parent 644a4e6b8c
commit 904cf66f86
3 files changed
+159 -5

No files matched your search

+50 -2
View File
@@ -3,8 +3,8 @@
use std::collections::{HashMap, HashSet};
use super::{
Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark,
unquote, word,
Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, exact_unquote, 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
@@ -76,6 +76,10 @@ pub(crate) struct Declared<'s> {
/// also before its body in the text when it is a declaration, so a variable of that name may lose
/// the value an assignment the analysis read gave it.
pub(super) body_assigned: HashSet<&'s str>,
/// The variables whose document write method a function body replaces (`local.saveAs = …`,
/// `local['saveAs'] = …`), unless the body declared the name before it. The function may run at
/// any time after it is defined, also before its body in the text when it is a declaration.
pub(super) method_replaced: HashSet<&'s str>,
/// The file has an `#include` line: the included file's code may give its variables values.
pub(super) includes: bool,
/// The variables assigned inside a loop, its parentheses included (`name = …`), each by the
@@ -134,6 +138,9 @@ struct Declarations<'s, 'a, 'l> {
brackets: Brackets,
/// The three significant tokens before this one, the latest first.
h: [Option<Sig<'s>>; 3],
/// The two significant tokens before the three of `h`, the latest first.
h3: Option<Sig<'s>>,
h4: Option<Sig<'s>>,
/// `function` was read at this bracket depth, and its body's `{` is still to come.
function: Option<usize>,
/// The bracket depth of the `var` statement being read.
@@ -195,6 +202,8 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
acc,
brackets: Brackets::default(),
h: [None; 3],
h3: None,
h4: None,
function: None,
var_depth: None,
assign: None,
@@ -281,6 +290,9 @@ impl<'s> Declarations<'s, '_, '_> {
self.keep_looped(None, name, vec![id]);
}
}
if t.is("=") {
self.method_replacement();
}
if let Some(after_new) = self.assign.take() {
if t.word("new") && !after_new {
self.assign = Some(true);
@@ -304,9 +316,45 @@ impl<'s> Declarations<'s, '_, '_> {
if !self.bodies.is_empty() || self.untracked.is_some() {
self.body_assignment(&t, depth);
}
self.h4 = self.h3;
self.h3 = self.h[2];
self.h = [Some(t), h0, h1];
}
/// `=` after `local.saveAs` or `local['saveAs']`, one of the document write methods: in a loop,
/// `local` may hold another method when a call of it earlier in the loop runs again
/// ([`Declared::looped`]); in a function body that does not declare `local`, the function may
/// replace the method before any call of it runs ([`Declared::method_replaced`]).
fn method_replacement(&mut self) {
let [h0, h1, h2] = self.h;
let receiver = if is(h1, ".") && h0.is_some_and(|s| s.kind == T::Ident && catalog::DOM_FILE_WRITES.contains(&s.text)) {
h2.filter(|s| s.kind == T::Ident && !member_mark(self.h3))
} else if is(h0, "]")
&& is(h2, "[")
&& let Some(key) = h1.filter(|s| s.kind == T::Str)
{
// A key whose escapes do not decode to one exact name may spell any method's.
let writes = exact_unquote(key.text).is_none_or(|m| catalog::DOM_FILE_WRITES.contains(&m.as_str()));
self.h3.filter(|s| writes && s.kind == T::Ident && !member_mark(self.h4))
} else {
None
};
let Some(name) = receiver.map(|s| s.text) else { return };
if !self.loops.is_empty() {
self.looped(name);
}
// Only the innermost body's own variable is not the one a nested function may reach from
// outside before the call runs.
let own = self.untracked.is_none() && self.bodies.last().is_some_and(|b| b.names.contains(name));
if (!self.bodies.is_empty() || self.untracked.is_some()) && !own {
if self.out.method_replaced.contains(name) || self.acc.room(self.out.method_replaced.len()) {
self.out.method_replaced.insert(name);
} else {
self.out.unsure = true;
}
}
}
/// `t` inside a function body at bracket depth `depth`: the name it assigns, when it assigns one
/// by name outside a `var` statement's declarations, joins [`Declared::body_assigned`].
fn body_assignment(&mut self, t: &Sig<'s>, depth: usize) {
+33 -1
View File
@@ -495,6 +495,25 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
/// The global variable `name` read through the global object may be held under another name
/// ([`Self::forget_writer`]). A variable of that name that the innermost function body or a
/// `catch` block declares is another variable, and keeps its literal's methods.
fn forget_global_writer(&mut self, name: &str) {
let shadowed = self.scopes.last().is_some_and(|s| s.saved.contains_key(name)) || self.catches.iter().any(|c| c.name == name);
if !shadowed {
self.forget_writer(name);
return;
}
for s in &mut self.scopes {
if let Some(saved) = s.saved.get_mut(name) {
saved.writer = 0;
}
}
for c in self.catches.iter_mut().filter(|c| c.name == name) {
c.saved.writer = 0;
}
}
/// Any variable may have been given another value through the global object
/// ([`Self::forget_writer`] for every name).
fn forget_writers(&mut self) {
@@ -547,8 +566,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
if at.is_some() && !self.scopes.is_empty() && !self.declared_in_body(r.text) {
return 0;
}
// A function body that replaces the method may run before the call, wherever it is in
// the text.
let looped = at.is_some_and(|at| {
self.declared.looped_full
|| self.declared.method_replaced.contains(r.text)
|| self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| {
let next = self.declared.loop_spans.partition_point(|(start, _)| *start <= at);
next.checked_sub(1).is_some_and(|id| at < self.declared.loop_spans[id].1 && ids.binary_search(&id).is_ok())
@@ -675,12 +697,22 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
{
match name.clone() {
Some(name) => {
self.forget_writer(&name);
self.forget_global_writer(&name);
self.share_early_as(&name, true);
}
None => self.forget_writers(),
}
}
// `$.global.local`, `this.local` or `globalThis.local` used as a value (`var alias = this.local`),
// not `holder.local`: another name may hold the global variable's object.
if !changes
&& !t.is(".")
&& !t.is("[")
&& let Some(m) = h0.filter(|s| s.kind == T::Ident && self.global_member == Some(s.start))
{
self.forget_global_writer(m.text);
self.share_early_as(m.text, true);
}
// A document write method of a global variable replaced through a bracket form:
// `$.global['local'].saveAs = …`, `this['local']['saveAs'] = …` or `$.global.local['saveAs'] = …`.
if changes {
+76 -2
View File
@@ -999,11 +999,85 @@ fn an_own_save_as_that_may_replace_itself_writes_a_file() {
"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",
"a.saveAs(f);\n",
"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][..]));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 6, 7, 8][..]));
}
/// A loop that replaces a variable's `saveAs` (`local.saveAs = …`, `local['saveAs'] = …`) may run a
/// call of it before the replacement in the text on a later pass: the call writes a file. A loop
/// that only calls the method, or replaces it on another object, leaves it the script's own.
#[test]
fn an_own_save_as_replaced_later_in_a_loop_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"for (;;) { local.saveAs(f); local.saveAs = g; }\n",
"var other = {saveAs: function () {}};\n",
"while (n--) { other.saveAs(f); other['saveAs'] = g; }\n",
"var calm = {saveAs: function () {}};\n",
"for (;;) { calm.saveAs(f); holder.calm.saveAs = g; }\n",
"for (;;) { calm.saveAs(f); }\n",
"for (;;) { calm.saveAs(f); holder.calm['saveAs'] = g; }\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..]));
}
/// A function declared after a call is hoisted, so it may replace the variable's `saveAs` before the
/// call runs: the call writes a file. A function that only calls the method, or replaces it on a
/// variable of its own, leaves it the script's own.
#[test]
fn a_hoisted_function_declared_later_that_replaces_the_method_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}};\n",
"local.saveAs(f);\n",
"install();\n",
"function install() { local.saveAs = app.activeDocument.saveAs; }\n",
"var other = {saveAs: function () {}};\n",
"other.saveAs(f);\n",
"function swap(w) { other['saveAs'] = w; }\n",
"var calm = {saveAs: function () {}};\n",
"calm.saveAs(f);\n",
"function d() { calm.saveAs(f); }\n",
"function e() { var calm = {}; calm.saveAs = 1; }\n",
"var third = {saveAs: function () {}};\n",
"third.saveAs(f);\n",
"function h(w) { third['save\\x41s'] = w; }\n",
"function run() {\n",
" var mine = {saveAs: function () {}};\n",
" fix(); mine.saveAs(f);\n",
" function fix() { mine.saveAs = app.activeDocument.saveAs; }\n",
"}\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 7, 11, 14, 18][..]));
}
/// A global variable read through the global object as a value (`$.global.local`, `this.local`,
/// `globalThis.local`) may be held under another name, also by a hoisted function declared before
/// the literal: the variable's `saveAs` writes a file.
#[test]
fn a_global_member_used_as_a_value_ends_the_own_save_as() {
let r = report(concat!(
"var f = new File(p);\n",
"function a() { var alias = $.global.local; alias.saveAs = app.activeDocument.saveAs; }\n",
"var local = {saveAs: function () {}};\n",
"local.saveAs(f);\n",
"var other = {saveAs: function () {}};\n",
"var held = this.other;\n",
"other.saveAs(f);\n",
"function b() { use(globalThis.third); }\n",
"var third = {saveAs: function () {}};\n",
"third.saveAs(f);\n",
"var calm = {saveAs: function () {}};\n",
"use(holder.calm);\n",
"calm.saveAs(f);\n",
"function g() { var mine = {saveAs: function () {}}; var alias = $.global.mine; mine.saveAs(f); }\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 10][..]));
}
/// A function declared before the literal is hoisted, so it may change or share the variable before