Merge main into feat/scripts-export-autocad

This commit is contained in:
dotCooCoo committed 2026-11-30 15:26:54 -08:00
commit 270ffca6ef
126 files changed
+8418 -666

No files matched your search

+66 -6
View File
@@ -535,6 +535,8 @@ impl Chain {
/// member chain or a File object assigned in it to an outer name stays.
struct Scope {
depth: usize,
/// The offset of the body's `{` in the text, which [`Declared::looped`] names it by.
start: usize,
saved: HashMap<String, Saved>,
/// The bracket depth of the `var` statement the body is in, if any: it goes on when the body
/// closes.
@@ -621,6 +623,8 @@ struct Analyzer<'s, 'a, 'l> {
file: Option<&'a str>,
/// The four significant tokens before this one, the latest first.
h: [Option<Sig<'s>>; 4],
/// The significant token before the four of [`Self::h`].
h4: Option<Sig<'s>>,
brackets: Brackets,
/// Nesting too deep to follow was reported: it is reported once.
deep: bool,
@@ -658,6 +662,12 @@ struct Analyzer<'s, 'a, 'l> {
index_receiver: u8,
/// The script includes another file ([`Known::others`]): no variable joins [`Analyzer::writers`].
others: bool,
/// The variables that may get another value when code read elsewhere runs: assigned inside a
/// function body that does not declare them, or as a property of `this` ([`Analyzer::reassigned_later`]).
/// None of them joins [`Analyzer::writers`].
later: HashSet<String>,
/// `later` ran out of room: no variable joins [`Analyzer::writers`].
later_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,
@@ -721,6 +731,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
acc,
file,
h: [None; 4],
h4: None,
brackets: Brackets::default(),
deep: false,
active: None,
@@ -739,6 +750,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
closed: None,
index_receiver: 0,
others: known.others || declared.includes,
later: HashSet::new(),
later_full: false,
unsure: known.unsure || declared.unsure,
own_names: HashSet::new(),
scopes: vec![],
@@ -850,6 +863,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.features(&t);
self.newer(&t);
self.module_check(&t);
self.h4 = self.h[3];
self.h = [Some(t), self.h[0], self.h[1], self.h[2]];
}
@@ -1233,7 +1247,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
if body {
let params = self.params.take().map(|(_, names)| names).unwrap_or_default();
if self.scopes.len() < self.acc.limits.nesting {
self.scopes.push(Scope { depth: self.depth(), saved: HashMap::new(), var_depth: self.var_depth.take() });
self.scopes.push(Scope { depth: self.depth(), start: t.start, saved: HashMap::new(), var_depth: self.var_depth.take() });
// 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);
@@ -1398,6 +1412,8 @@ 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))
// A line break after a label's `:` does not end the statement the label may be
// the body of (`if (c) l:` before the line).
|| (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 {
@@ -1429,9 +1445,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
// A name after `.`, `..`, `.@`, `::` or `@` is a property's or an attribute's; any other
// name before `=` is a variable, at the start of a statement or inside an expression.
if !member_mark(h1) && !is(h1, "@") {
if !self.scopes.is_empty() && !self.declared_in_body(name.text) {
self.reassigned_later(name.text);
}
self.assign = Some(Assign { name: name.text.to_string(), after_new: false });
}
}
if let Some((name, _)) = self.updated(t)
&& !self.scopes.is_empty()
&& !self.declared_in_body(name)
{
self.reassigned_later(name);
}
match self.updated(t) {
// The value on the right is read at this depth, and the name holds nothing the check
// follows once that value ends ([`Analyzer::settle_groups`]).
@@ -1445,11 +1470,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
/// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t`
/// closes a function body, so a literal given to the body's own variable stays inside the body.
/// No variable joins when code the scan does not follow at that point may give it another value:
/// a function body that assigns its name ([`Declared::body_assigned`]), a member assignment of a
/// property of that name, which may be the global object's ([`Declared::rebound`]), a function
/// body that assigns a `saveAs` or `exportFile` property of any object
/// ([`Declared::body_writer_assigned`]), code given as text or a `with` statement
/// ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]).
/// a function body that assigns its name ([`Declared::body_assigned`], [`Analyzer::later`]), a
/// member assignment of a property of that name, which may be the global object's
/// ([`Declared::rebound`]), a function body that assigns a `saveAs` or `exportFile` property of
/// any object ([`Declared::body_writer_assigned`]), code given as text or a `with` statement
/// ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). Calls inside a loop that
/// assigns the variable use [`Declared::looped`] to classify its methods.
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)))
@@ -1458,12 +1484,45 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
&& !self.declared.rebound.contains(&name)
&& !self.declared.body_assigned.contains(name.as_str())
&& !self.declared.body_writer_assigned
&& !self.later_full
&& !self.later.contains(&name)
&& !self.declared.looped_full
&& (self.writers.contains_key(&name) || self.acc.room(self.writers.len()))
{
self.writers.insert(name, bits);
}
}
/// `name` may get another value when code read elsewhere runs: a function body assigns it without
/// declaring it, and the function may be called before or after any line, or it is assigned as a
/// property of `this`. Its object literal's methods are no longer known, now or later.
fn reassigned_later(&mut self, name: &str) {
self.writers.remove(name);
if !self.later.contains(name) {
if self.acc.room(self.later.len()) {
self.later.insert(name.to_string());
} else {
self.later_full = true;
}
}
}
/// The global variable `name` is assigned as a property of `this`: as [`Self::reassigned_later`],
/// and when a function body's own variable hides it, the global's methods saved for the body's
/// end are no longer known either.
pub(super) fn reassigned_global(&mut self, name: &str) {
self.reassigned_later(name);
if let Some(saved) = self.scopes.iter_mut().find_map(|s| s.saved.get_mut(name)) {
saved.writer = 0;
}
}
/// Whether `name` is declared in the innermost function body (`var name`, `function
/// name`, a parameter).
fn declared_in_body(&self, name: &str) -> bool {
self.scopes.last().is_some_and(|s| s.saved.get(name).is_some_and(|v| v.local))
}
/// `t` in an object literal assigned to a variable, `before` the bracket depth before `t`: a single
/// function expression directly inside its braces as the whole value of a key that names a
/// document method writing a file (`{saveAs: function … {…}, …}`, `{'exportFile': function … {…}}`)
@@ -1711,6 +1770,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.var_depth = None;
self.conds.clear();
self.h = [None; 4];
self.h4 = None;
self.acc.steps = self.acc.steps.saturating_add(1);
let d = directives::parse(t.text);
let Some(name) = d.known else {
+319 -3
View File
@@ -1,6 +1,6 @@
//! The names declared, read before the analysis.
use std::collections::HashSet;
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,
@@ -17,10 +17,41 @@ const UNREAD_BINDINGS: &[&str] = &["with", "eval", "Function", catalog::DOLLAR_E
/// The property a function reaches `Function` through.
const CONSTRUCTOR: &str = "constructor";
/// The statements whose parentheses the rest of the statement follows, so a line break after them
/// does not end a loop's body without braces.
const HEADS: &[&str] = &["if", "while", "for", "with", "switch"];
/// 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;
#[cfg(not(test))]
type LoopSpans = Vec<(usize, usize)>;
#[cfg(test)]
#[derive(Default)]
pub(super) struct LoopSpans {
spans: Vec<(usize, usize)>,
reads: std::cell::Cell<usize>,
}
#[cfg(test)]
impl std::ops::Deref for LoopSpans {
type Target = Vec<(usize, usize)>;
fn deref(&self) -> &Self::Target {
self.reads.set(self.reads.get() + 1);
&self.spans
}
}
#[cfg(test)]
impl std::ops::DerefMut for LoopSpans {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.spans
}
}
/// 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
/// they declare the function's own before any statement in it runs, and the function declarations
@@ -52,6 +83,16 @@ pub(crate) struct Declared<'s> {
pub(super) body_writer_assigned: bool,
/// 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
/// offset of the `{` of the function body that declares it (`None`: the global code's), with the
/// outermost loops that assign it, entries of `loop_spans`.
pub(super) looped: HashMap<(Option<usize>, &'s str), Vec<usize>>,
/// For each outermost loop, the offsets in the text where it starts and ends (`usize::MAX`: at
/// the end of the text).
pub(super) loop_spans: LoopSpans,
/// `looped` or `loop_spans` ran out of room, or loops nest past [`crate::Limits::nesting`]: any
/// variable may be assigned in a loop.
pub(super) looped_full: bool,
/// 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
@@ -62,14 +103,23 @@ pub(crate) struct Declared<'s> {
pub(super) unsure: bool,
}
#[cfg(test)]
impl Declared<'_> {
pub(crate) fn loop_span_reads(&self) -> usize {
self.loop_spans.reads.get()
}
}
/// A function body [`Declarations`] is reading: the bracket depth inside it, its entry in
/// [`Declared::bodies`], the names it declares so far, and the bracket depth of the `var` statement
/// the body is in, which goes on when the body closes.
/// the body is in, which goes on when the body closes, and the names assigned in a loop inside it
/// so far, each with its loops ([`Declared::looped`]).
struct Body<'s> {
depth: usize,
index: usize,
names: HashSet<&'s str>,
var_depth: Option<usize>,
looped: HashMap<&'s str, Vec<usize>>,
}
/// A `[` [`Declarations`] is reading: the bracket depth inside it, whether a property's name in
@@ -103,9 +153,46 @@ struct Declarations<'s, 'a, 'l> {
untracked: Option<usize>,
/// The `[` brackets being read, the innermost last, up to [`crate::Limits::nesting`].
keys: Vec<Key>,
/// The loops being read, the innermost last, up to [`crate::Limits::nesting`].
loops: Vec<Loop>,
out: Declared<'s>,
}
/// A loop [`Declarations`] is reading: the bracket depth of its keyword, how far it has been read,
/// and, for a body without braces, whether the last `{` at that depth opened a block (not an object
/// literal), whether an `if`, `while`, `for` or `with` at that depth waits for its `)`, and whether
/// the last token was that `)`.
struct Loop {
depth: usize,
stage: Stage,
block: bool,
head: bool,
after_head: bool,
/// The loop starts with `do` and has a trailing condition.
do_loop: bool,
}
/// How far a [`Loop`] has been read.
#[derive(Clone, Copy, PartialEq)]
enum Stage {
/// The parentheses after `for` or `while`.
Head,
/// The parentheses after the `while` of a `do` loop.
DoHead,
/// The `)` of a `do` loop's `while` was read: the loop ends with the `;` after it, or before the
/// next token.
DoEnd,
/// The body's first token is next.
Start,
/// A body in braces.
Block,
/// A body that is one statement without braces.
Statement,
/// The statement of a body without braces has reached its end: the loop ends at the next token,
/// unless it is `else`, `catch` or `finally`, which go on with the statement.
Tail,
}
/// What `src` declares ([`Declared`]), read in one pass over its tokens.
pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
let mut lexer = Lexer::new(src, acc.limits.nesting);
@@ -119,6 +206,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
bodies: vec![],
untracked: None,
keys: vec![],
loops: vec![],
out: Declared::default(),
};
let mut breaks = LineBreaks::default();
@@ -129,7 +217,15 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
Read::Token(sig) => d.token(sig),
}
}
// A body the file does not close keeps its names assigned in a loop as well.
while let Some(body) = d.bodies.pop() {
d.settle_looped(body);
}
let mut out = d.out;
for ids in out.looped.values_mut() {
ids.sort_unstable();
ids.dedup();
}
out.unsure |= out.rebound.contains(catalog::FOLDER);
acc.steps = acc.steps.saturating_add(lexer.steps);
out
@@ -154,12 +250,22 @@ impl<'s> Declarations<'s, '_, '_> {
if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(h0) && !goes_on_with(&t) {
self.var_depth = None;
}
self.loop_start(&t);
if t.kind == T::Punct {
self.bracket(&t);
} else if t.kind == T::Ident {
self.declaration(&t);
}
let depth = self.depth();
self.loop_end(&t, depth);
if t.is("=")
&& !self.loops.is_empty()
&& !member_mark(h1)
&& !is(h1, "@")
&& let Some(name) = h0.filter(|s| s.kind == T::Ident)
{
self.looped(name.text);
}
if let Some(after_new) = self.assign.take() {
if t.word("new") && !after_new {
self.assign = Some(true);
@@ -217,6 +323,209 @@ impl<'s> Declarations<'s, '_, '_> {
}
}
/// `t`, a token before the brackets are followed past it: the body of the innermost loop starts
/// at it, and `for`, `while` and `do` start a loop. Past [`crate::Limits::nesting`] loops, any
/// variable may be assigned in one ([`Declared::looped_full`]).
fn loop_start(&mut self, t: &Sig<'s>) {
let [h0, h1, ..] = self.h;
let depth = self.depth();
while let Some(l) = self.loops.last_mut() {
let after_head = std::mem::take(&mut l.after_head);
match l.stage {
Stage::Start => {
l.stage = if t.is("{") { Stage::Block } else { Stage::Statement };
l.head = HEADS.iter().any(|w| t.word(w)) && !member_mark(h0);
break;
}
// A line break ends a body of one statement where the tokens on either side of it
// don't go on with it, as in [`Analyzer::token`], and it does not follow the
// parentheses of an `if` or another statement that the body goes on with.
Stage::Statement
if t.nl
&& depth == l.depth
&& !goes_on_after(h0)
&& !goes_on_with(t)
&& !after_head
&& !["else", "do", "catch", "finally"].iter().any(|w| word(h0, w) && !member_mark(h1)) =>
{
l.stage = Stage::Tail;
}
Stage::Statement => {
if depth == l.depth {
if t.is("{") {
l.block = t.stmt || after_head || word(h0, "else") || (word(h0, "finally") && !member_mark(h1));
} else if HEADS.iter().any(|w| t.word(w)) && !member_mark(h0) {
l.head = true;
}
}
break;
}
Stage::Tail if l.do_loop && t.word("while") => {
l.stage = Stage::DoHead;
return;
}
Stage::Tail if t.word("else") => {
l.stage = Stage::Statement;
break;
}
// The `catch` and `finally` of a `try` statement that is the body go on with it.
Stage::Tail if t.word("catch") || t.word("finally") => {
l.stage = Stage::Statement;
l.head = t.word("catch");
break;
}
Stage::DoEnd if t.is(";") && depth == l.depth => break,
Stage::Tail | Stage::DoEnd => {
self.pop_loop(t.start);
// A body of one statement that is this loop ends with it.
if let Some(outer) = self.loops.last_mut()
&& outer.stage == Stage::Statement
&& outer.depth == depth
{
outer.stage = Stage::Tail;
}
}
_ => break,
}
}
let stage = if (t.word("for") || t.word("while")) && !member_mark(h0) {
Stage::Head
} else if t.word("do") && !member_mark(h0) {
Stage::Start
} else {
return;
};
if self.loops.len() >= self.acc.limits.nesting || (self.loops.is_empty() && !self.acc.room(self.out.loop_spans.len())) {
self.out.looped_full = true;
} else {
if self.loops.is_empty() {
self.out.loop_spans.push((t.start, usize::MAX));
}
self.loops.push(Loop { depth, stage, block: false, head: false, after_head: false, do_loop: t.word("do") });
}
}
/// Ends the innermost loop at offset `at`, which ends the outermost one in
/// [`Declared::loop_spans`].
fn pop_loop(&mut self, at: usize) {
self.loops.pop();
if self.loops.is_empty()
&& let Some((_, end)) = self.out.loop_spans.last_mut()
{
*end = at;
}
}
/// `t`, after the brackets are followed past it to `depth`: the parentheses of a loop end at the
/// `)` back at its depth, and a body in braces at the `}` back at it. A body of one statement
/// reaches its end ([`Stage::Tail`]) at a `;` at the loop's depth, at a `}` there that closes a
/// block, or with a loop that is that statement. A bracket closing below a loop's depth ends it.
fn loop_end(&mut self, t: &Sig<'s>, depth: usize) {
let mut inner = false;
while let Some(l) = self.loops.last_mut() {
let ended = depth < l.depth
|| match l.stage {
Stage::Head => {
if t.is(")") && depth == l.depth {
l.stage = Stage::Start;
}
false
}
Stage::DoHead => {
if t.is(")") && depth == l.depth {
l.stage = Stage::DoEnd;
}
false
}
Stage::DoEnd => t.is(";") && depth == l.depth,
Stage::Block => {
if t.is("}") && depth == l.depth && l.do_loop {
l.stage = Stage::Tail;
false
} else {
t.is("}") && depth == l.depth
}
}
Stage::Statement => {
if depth == l.depth {
if t.is(";") || (t.is("}") && l.block) || inner {
l.stage = Stage::Tail;
} else if t.is(")") && l.head {
l.head = false;
l.after_head = true;
}
}
false
}
Stage::Start | Stage::Tail => false,
};
if !ended {
break;
}
self.pop_loop(t.start);
inner = true;
}
}
/// `name` is assigned in the loops being read: kept with the outermost one for the innermost
/// function body that declares it when that body closes ([`Self::settle_looped`]), or for the
/// global code.
fn looped(&mut self, name: &'s str) {
let id = self.out.loop_spans.len().saturating_sub(1);
match self.bodies.last_mut() {
Some(body) if body.looped.contains_key(name) || self.acc.room(body.looped.len()) => {
let ids = body.looped.entry(name).or_default();
if !ids.contains(&id) {
ids.push(id);
}
}
Some(_) => self.out.looped_full = true,
None => self.keep_looped(None, name, vec![id]),
}
}
/// The names assigned in a loop inside `body`, which is closing: the body's own are kept for it,
/// and the others go to the body around it, or to the global code.
fn settle_looped(&mut self, body: Body<'s>) {
let start = self.out.bodies.get(body.index).map(|(at, _)| *at);
for (name, ids) in body.looped {
if body.names.contains(name) {
self.keep_looped(start, name, ids);
} else if let Some(outer) = self.bodies.last_mut() {
if outer.looped.contains_key(name) || self.acc.room(outer.looped.len()) {
let kept = outer.looped.entry(name).or_default();
for id in ids {
if !kept.contains(&id) {
kept.push(id);
}
}
} else {
self.out.looped_full = true;
}
} else {
self.keep_looped(None, name, ids);
}
}
}
/// Keeps `name` of `body` as assigned in outermost loops `ids`.
fn keep_looped(&mut self, body: Option<usize>, name: &'s str, ids: Vec<usize>) {
let len = self.out.looped.len();
match self.out.looped.get_mut(&(body, name)) {
Some(kept) => {
for id in ids {
if !kept.contains(&id) {
kept.push(id);
}
}
}
None if self.acc.room(len) => {
self.out.looped.insert((body, name), ids);
}
None => self.out.looped_full = true,
}
}
/// `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>) {
@@ -287,7 +596,13 @@ impl<'s> Declarations<'s, '_, '_> {
if self.bodies.len() < self.acc.limits.nesting {
let index = self.out.bodies.len();
self.out.bodies.push((t.start, vec![]));
self.bodies.push(Body { depth: self.depth(), index, names: HashSet::new(), var_depth: self.var_depth.take() });
self.bodies.push(Body {
depth: self.depth(),
index,
names: HashSet::new(),
var_depth: self.var_depth.take(),
looped: HashMap::new(),
});
} else if self.untracked.is_none() {
self.untracked = Some(self.depth());
}
@@ -314,6 +629,7 @@ impl<'s> Declarations<'s, '_, '_> {
}
while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) {
self.var_depth = body.var_depth;
self.settle_looped(body);
}
if self.untracked.is_some_and(|d| depth < d) {
self.untracked = None;
+49 -14
View File
@@ -208,7 +208,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
} else if of(catalog::FOLDER) && catalog::FOLDER_PLACES.contains(&n) {
self.acc.feature(FeatureId::FilePlaces, line);
}
if n == catalog::SAVE_CHANGES {
if n == catalog::SAVE_CHANGES && of(catalog::SAVE_OPTIONS) {
self.save_changes(line);
}
if n == catalog::ON_DRAW {
@@ -283,10 +283,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
"]" if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) => {
let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default();
self.setter(&name, h2, h3, line);
if name == catalog::SAVE_CHANGES
&& word(h2, catalog::SAVE_OPTIONS)
&& !member_mark(h3)
&& !self.own_names.contains(catalog::SAVE_OPTIONS)
{
self.save_changes(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.call(line),
"[" => self.index_receiver = self.writer_bits(h0, h1, Some(t.start)),
"(" => self.call(t, line),
// `Name.prototype["+"] = …` defines an operator.
"=" => {
let operator = || h1.filter(|s| s.kind == T::Str).is_some_and(|s| catalog::OPERATORS.contains(&unquote(s.text, 4).as_str()));
@@ -301,7 +308,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
/// `(` after a name: a call.
fn call(&mut self, line: Option<usize>) {
fn call(&mut self, t: &Sig<'s>, line: Option<usize>) {
let [h0, h1, h2, h3] = self.h;
// `doc['saveAs'](f)`: a document method named by a string literal in brackets.
if is(h0, "]")
@@ -335,7 +342,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) && !Self::defines(self.writer_bits(h2, h3, Some(t.start)), n))
{
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
@@ -362,9 +369,23 @@ 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.
fn writer_bits(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> u8 {
/// At call offset `at`, a variable assigned in a loop containing that offset may be a document.
fn writer_bits(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>, at: Option<usize>) -> u8 {
match receiver {
Some(r) if r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0),
Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => {
let Some(bits) = self.writers.get(r.text).copied() else { return 0 };
if at.is_some() && !self.scopes.is_empty() && !self.declared_in_body(r.text) {
return 0;
}
let looped = at.is_some_and(|at| {
self.declared.looped_full
|| 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())
})
});
if looped { 0 } else { bits }
}
_ => 0,
}
}
@@ -376,9 +397,25 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
/// `local[k] = w`, `delete local.saveAs`).
fn writer_use(&mut self, t: &Sig<'s>) {
let [h0, h1, h2, h3] = self.h;
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, ","));
// `this.local = …` or `this['local'] = …`: `this` is the global object in the global code and in a
// function called without a receiver (ECMA-262 3rd edition, sections 10.2.1 and 10.2.3), so the
// global variable of that name may get another value.
if changes {
// `this`, not a property named `this` (`holder.this.d`).
let global = if is(h1, ".") && word(h2, "this") && !member_mark(h3) {
h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string())
} else if is(h0, "]") && is(h2, "[") && word(h3, "this") && !member_mark(self.h4) {
h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 64))
} else {
None
};
if let Some(name) = global {
self.reassigned_global(&name);
}
}
let writer = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| s.filter(|s| self.writer_bits(Some(*s), before, None) != 0).map(|s| s.text);
let escaped = if word(h0, "delete") {
// `delete local…`
writer(Some(*t), h0)
@@ -395,8 +432,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
// `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)
// `local['saveAs'] = …`, not `other.local['saveAs'] = …`.
writer(h3, self.h4)
} else {
None
};
@@ -432,11 +469,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
if t.text.contains(catalog::ACTION_TEXT) {
self.acc.feature(FeatureId::Actions, line);
}
// `SaveOptions['SAVECHANGES']`, or the value written as the string `"SaveOptions.SAVECHANGES"`.
// The value written as the string `"SaveOptions.SAVECHANGES"`.
let value = unquote(t.text, 32);
if value == catalog::SAVE_CHANGES
|| value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES)
{
if value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES) {
self.save_changes(line);
}
let compares = h0.is_some_and(|s| s.kind == T::Punct && matches!(s.text, "==" | "===" | "!=" | "!=="));
+258 -6
View File
@@ -573,6 +573,19 @@ fn export_variables_in_brackets_writes_a_file() {
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
}
#[test]
fn evaluated_code_keeps_warnings_for_rebound_writer_receivers() {
for call in ["local.exportVariables(f);", "local['exportVariables'](f);", "local.saveAs(f);", "local['exportFile'](f);"] {
let r = report(&format!(
"var local = {{exportVariables: function () {{}}, saveAs: function () {{}}, exportFile: function () {{}}}};\n\
eval('local = app.activeDocument');\n{call}\n"
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]), "{call}");
let written = r.outside.iter().find(|o| o.id == "filesWritten");
assert_eq!(written.map(|o| o.lines.as_slice()), Some(&[3][..]), "{call}");
}
}
/// `SaveOptions.SAVECHANGES` makes a document's `close` save it to its own file, read directly, in
/// brackets, as a string or through a variable; closing without it, and the other save options,
/// write nothing.
@@ -592,6 +605,24 @@ fn closing_with_save_changes_writes_a_file() {
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[4, 5, 7][..])]);
}
#[test]
fn unrelated_save_changes_properties_and_strings_do_not_report_writes() {
let r = report(concat!(
"var a = other.SAVECHANGES;\n",
"var b = other['SAVECHANGES'];\n",
"app.activeDocument.close('SAVECHANGES');\n",
"var c = holder.SaveOptions.SAVECHANGES;\n",
"var d = holder.SaveOptions['SAVECHANGES'];\n",
"var e = 'SAVECHANGES';\n",
"var key = SaveOptions['SAVECHANGES' + suffix];\n",
"var f = SaveOptions.SAVECHANGES;\n",
"var g = SaveOptions['SAVECHANGES'];\n",
"var h = 'SaveOptions.SAVECHANGES';\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[8, 9, 10][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[8, 9, 10][..])]);
}
/// `saveAs` and `exportFile` called with their names as string literals in brackets write the file
/// too; reading the method without calling it does not.
#[test]
@@ -640,18 +671,16 @@ fn the_scripts_own_save_as_writes_no_file() {
fn a_changed_or_shared_own_save_as_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n",
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
"var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n",
"a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n",
"a.saveAs = app.activeDocument.saveAs;\n",
"b['saveAs'] = w;\n",
"c = app.activeDocument;\n",
"delete d.saveAs;\n",
"var h = e;\n",
"use(g);\n",
"a.saveAs(f);\n",
"b.saveAs(f);\n",
"c.saveAs(f);\n",
"d.saveAs(f);\n",
"e.saveAs(f);\n",
"g['saveAs'](f);\n",
@@ -662,10 +691,125 @@ fn a_changed_or_shared_own_save_as_writes_a_file() {
"q['saveAs'](f);\n",
"s.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19, 21, 22][..]));
// A computed key may name any property, a variable's on the global object included.
let r = report("var f = new File(p);\nvar c = {saveAs: function () {}};\nc[k] = w;\nc.saveAs(f);\n");
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 14, 16, 17, 19, 20][..]));
// A computed key may name any variable, so every `saveAs` in the script may write, the ones
// before the computed key included.
let r = report("var f = new File(p);\nvar c = {saveAs: function () {}};\nc.saveAs(f);\nc[k] = w;\nc.saveAs(f);\n");
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..]));
}
/// A variable assigned in a loop may hold a document when a later iteration calls its `saveAs`,
/// before the assignment in the text: the call writes a file. One assigned only after a loop does
/// not.
#[test]
fn an_own_save_as_reassigned_later_in_a_loop_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n",
"var d = {saveAs: function () {}};\n",
"for (var i = 0; i < 2; i++) { a.saveAs(f); a = app.activeDocument; }\n",
"while (n--) b.saveAs(f), b = app.activeDocument;\n",
"do { c.saveAs(f); } while ((c = next()));\n",
"for (;;) { d.saveAs(f); break; }\n",
"d = app.activeDocument;\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 6][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[4, 5, 6][..])]);
// The `else` of a body without braces is in the loop; a statement after a line break that ends
// such a body is not, and neither is a variable of the same name that a function declares.
let r = report(concat!(
"var f = new File(p);\n",
"var e = {saveAs: function () {}}; var g = {saveAs: function () {}}; var h = {saveAs: function () {}};\n",
"while (n--) if (n) e.saveAs(f); else e = app.activeDocument;\n",
"while (n--) g.saveAs(f), n\n",
"g = app.activeDocument\n",
"function k() { var h; for (;;) h = app.activeDocument; }\n",
"h.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
// An object literal's `}` does not end a body without braces, a call's `)` before a line break
// does, and a literal given after the last loop that assigns its variable is the script's own.
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
"while (n--) a.saveAs(f), t = {}, a = app.activeDocument;\n",
"b.saveAs(f);\n",
"while (n--) tick()\n",
"b = app.activeDocument\n",
"for (;;) { c = app.activeDocument; }\n",
"var c = {saveAs: function () {}};\n",
"c.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}};\n",
"while (n--) if (n)\n",
" a.saveAs(f), a = app.activeDocument;\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..]));
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
"a.saveAs(f); b['saveAs'](f);\n",
"while (n--) { a.saveAs(f); a = app.activeDocument; }\n",
"while (n--) { b['saveAs'](f); b = app.activeDocument; }\n",
"var a = {saveAs: function () {}};\n",
"a.saveAs(f);\n",
"while (n--) { a.saveAs(f); a = app.activeDocument; }\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 8][..]));
}
/// The `catch` and `finally` of a `try` body, and an `else` after a `do` loop inside a body without
/// braces, are in the loop; a statement after the whole loop is not.
#[test]
fn try_clauses_and_else_after_a_nested_do_loop_are_in_the_loop() {
let r = report(concat!(
"var f = new File(p);\n",
"var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n",
"var h = {saveAs: function () {}};\n",
"while (i++ < 2) try { d.saveAs(f); } finally { d = app.activeDocument; }\n",
"while (i++ < 2)\n",
" if (i === 2) do e.saveAs(f); while (false);\n",
" else e = app.activeDocument;\n",
"while (n--) do g.saveAs(f); while (false);\n",
"g = app.activeDocument;\n",
"while (n--) h.saveAs(f), holder.finally\n",
"h = app.activeDocument;\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 6][..]));
}
/// A literal after a label's line break may not run, a `this` assignment in a function whose own
/// variable hides the global one changes the global, and a property `d` of another object is not
/// the variable `d`. A member assignment of a property `g` (`holder.this.g = …`) may be the global
/// object's, so `g.saveAs` writes a file.
#[test]
fn labels_hidden_globals_and_other_objects_keep_writes_known() {
let r = report(concat!(
"var f = new File(p);\n",
"var a = app.activeDocument;\n",
"if (no) l:\n",
"var a = {saveAs: function () {}};\n",
"a.saveAs(f);\n",
"var b = {saveAs: function () {}};\n",
"function change() { var b; this.b = app.activeDocument; }\n",
"change(); b.saveAs(f);\n",
"var c = {saveAs: function () {}};\n",
"function keep() { var c; c = 1; }\n",
"keep(); c.saveAs(f);\n",
"var d = {saveAs: function () {}};\n",
"holder.d['saveAs'] = 1;\n",
"d.saveAs(f);\n",
"var e = {saveAs: function () {}};\n",
"e['saveAs'] = app.activeDocument.saveAs;\n",
"e.saveAs(f);\n",
"var g = {saveAs: function () {}};\n",
"function other() { var g; holder.this.g = app.activeDocument; holder.this['g'] = 1; }\n",
"other(); g.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17, 20][..]));
}
/// Only a `var` statement directly in a function body or the global code that gives its first name
@@ -752,6 +896,114 @@ fn a_save_as_other_code_may_replace_writes_a_file() {
}
}
#[test]
fn writer_calls_after_many_assignment_loops_have_bounded_work() {
for reinitialize in [false, true] {
let mut src = "var d = {saveAs: function () {}};\n".to_string();
for _ in 0..512 {
src.push_str("while (n--) { d = next(); }\n");
}
if reinitialize {
src.push_str("var d = {saveAs: function () {}};\n");
}
src.push_str("var local = {saveAs: function () {}};\n");
for _ in 0..2048 {
src.push_str("d.saveAs(f); local.saveAs(f);\n");
}
let limits = Limits::default();
let mut acc = report::Acc::new(&limits);
let declared = analyze::declarations(&src, &mut acc);
let before = declared.loop_span_reads();
analyze::scan(&src, &declared, &[], None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc);
let reads = declared.loop_span_reads() - before;
if reinitialize {
assert!(reads < 16 * 2048, "{reads} span accesses for 2048 calls on d");
} else {
assert_eq!(reads, 0);
}
}
}
/// A function body read before the literal that assigns its variable without declaring it may run
/// after the literal, so the literal's `saveAs` keeps reporting the write; a body that declares the
/// name assigns its own variable.
#[test]
fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() {
let r = report(concat!(
"var f = new File(p);\n",
"function choose() { d = app.activeDocument; }\n",
"var d = {saveAs: function () {}};\n",
"choose(); d.saveAs(f);\n",
"function bump() { e++; }\n",
"var e = {saveAs: function () {}};\n",
"e.saveAs(f);\n",
"function own() { var g; g = app.activeDocument; }\n",
"var g = {saveAs: function () {}};\n",
"g.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..]));
}
#[test]
fn captured_writer_receivers_can_change_before_each_call() {
for method in ["saveAs", "exportFile"] {
for call in [format!("d.{method}(f)"), format!("d['{method}'](f)")] {
for (prefix, suffix) in [("", ""), ("function outer() {\n", "}\nouter();\n")] {
let src = format!(
"{prefix}var d = {{{method}: function () {{}}}};\n\
function save(f) {{ {call}; }}\n\
d = app.activeDocument; save(f);\n{suffix}"
);
let r = report(&src);
let line = if prefix.is_empty() { 2 } else { 3 };
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[line][..]), "{src}");
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[line][..])], "{src}");
}
}
}
}
#[test]
fn captured_reassignments_keep_save_as_writing_after_a_later_initializer() {
let r = report(concat!(
"var f = new File(p);\n",
"function outer() {\n",
" function choose() { d = app.activeDocument; }\n",
" var d = {saveAs: function () {}};\n",
" choose(); d.saveAs(f);\n",
" function bump() { e++; }\n",
" var e = {saveAs: function () {}};\n",
" bump(); e.saveAs(f);\n",
" function own() { var g; g = app.activeDocument; }\n",
" var g = {saveAs: function () {}};\n",
" own(); g.saveAs(f);\n",
"}\n",
"outer();\n",
));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[5, 8][..])]);
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8][..]));
}
/// Assigning a property of `this`, the global object in the global code and in a function called
/// without a receiver, may give the global variable of that name another value, before or after
/// its literal.
#[test]
fn assigning_a_property_of_this_keeps_save_as_writing() {
let r = report(concat!(
"var f = new File(p);\n",
"var d = {saveAs: function () {}};\n",
"this.d = app.activeDocument;\n",
"d.saveAs(f);\n",
"function swap() { this['e'] = app.activeDocument; }\n",
"var e = {saveAs: function () {}};\n",
"swap(); e.saveAs(f);\n",
"var g = {saveAs: function () {}};\n",
"this.other = 1;\n",
"g.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..]));
}
/// A `saveAs` key's value is a method of the script's own only when the whole value is one function
/// expression: a value that goes on after the function's body, and a literal inside another, leave
/// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body