mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 14:03:16 -05:00
The script checker kept a replacement of a variable's methods
(`give(local)`, `local.saveAs = w`) for the body that had declared the
name so far in the text. A `var` statement declares the name for the
whole body, and a parameter is the function's own variable, so the
replacement could count for the wrong variable:
- A function whose own later `var local` or parameter `local` declares
the name no longer ends the exemption of an outer `local`'s own
`saveAs` (`function h(a, local) { return local; }`).
- A replacement now counts for the innermost body around it that
declares the name anywhere in the body, found once every body's
names are known.
- When a body past the nesting limit or out of room for its names is
around the replacement, the declaring body is not known, and the
replacement counts for a variable of that name in every body.
- The call site looks the replacement up for the body that declares
the receiver, walking outward from the innermost body.
870 lines
39 KiB
Rust
870 lines
39 KiB
Rust
//! The names declared, read before the analysis.
|
|
|
|
use std::collections::{HashMap, HashSet};
|
|
|
|
use super::{
|
|
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
|
|
/// 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 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
|
|
/// directly in the global code do the same for the whole file (ECMA-262 3rd edition, section
|
|
/// 10.1.3). A `var` statement in the global code does not change a property the global object
|
|
/// already has, such as the host's `alert` (sections 10.1.3, 10.1.5 and 10.2.1). The global code's
|
|
/// `var` statements are not read here. A function declaration inside a block, which ECMAScript 3
|
|
/// does not allow (sections 12.1 and 14), makes its name the script's own from where it stands.
|
|
#[derive(Default)]
|
|
pub(crate) struct Declared<'s> {
|
|
/// For each function body, by the offset of its `{` in the text, the names it declares, in the
|
|
/// order the bodies start.
|
|
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<String>,
|
|
/// The names a function body assigns by name (`d = …`, `d += …`, `d++`, `for (d in …)`) other than
|
|
/// in a `var` statement's declarations, unless a body around the assignment declared the name with
|
|
/// `var` 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, 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 may replace (`local.saveAs = …`,
|
|
/// `local['saveAs'] += …`, `local[k] = …`, `var y = local`), unless the body declared the name
|
|
/// before it, each by the offset of the `{` of the function body that declares it anywhere in
|
|
/// the body (`None`: the global code's). 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<(Option<usize>, &'s str)>,
|
|
/// The variables of [`Declared::method_replaced`] whose declaring body is not known, because a
|
|
/// body around the replacement is past [`crate::Limits::nesting`] or ran out of room for its
|
|
/// names: the replacement counts for a variable of that name in any body.
|
|
pub(super) method_replaced_any: 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
|
|
/// 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
|
|
/// (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,
|
|
}
|
|
|
|
#[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, 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
|
|
/// 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<T>,
|
|
}
|
|
|
|
/// 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 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.
|
|
var_depth: Option<usize>,
|
|
/// `name =` was read, and the first token of the value is next (`true`: after `new`). As in
|
|
/// [`Analyzer::assignment`], that token doesn't start or end a `var` statement.
|
|
assign: Option<bool>,
|
|
/// The function bodies being read, the innermost last, up to [`crate::Limits::nesting`].
|
|
bodies: Vec<Body<'s>>,
|
|
/// The bracket depth inside the outermost function body past that limit being read. The names
|
|
/// declared inside it are not kept.
|
|
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>,
|
|
/// The replacements of a variable's methods ([`Declared::method_replaced`]) read so far, each with
|
|
/// the entries of [`Declared::bodies`] around it, the outermost first. A `var` statement later in
|
|
/// a body declares the name for the whole body, so the body that declares the variable is found
|
|
/// once every body's names are known.
|
|
replaced: HashSet<(Vec<usize>, &'s str)>,
|
|
/// The entries of [`Declared::bodies`] whose names ran out of room: one of them may declare any
|
|
/// name.
|
|
names_full: HashSet<usize>,
|
|
/// The parameters of the function whose parentheses are being read: the bracket depth inside
|
|
/// them, the names so far, and whether they ran out of room.
|
|
params: Option<(usize, Vec<&'s str>, bool)>,
|
|
/// The parameters of each entry of [`Declared::bodies`], which are the body's own variables
|
|
/// (ECMA-262 3rd edition, section 10.1.3).
|
|
body_params: HashMap<usize, Vec<&'s str>>,
|
|
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);
|
|
let mut d = Declarations {
|
|
acc,
|
|
brackets: Brackets::default(),
|
|
h: [None; 3],
|
|
h3: None,
|
|
h4: None,
|
|
function: None,
|
|
var_depth: None,
|
|
assign: None,
|
|
bodies: vec![],
|
|
untracked: None,
|
|
keys: vec![],
|
|
loops: vec![],
|
|
replaced: HashSet::new(),
|
|
names_full: HashSet::new(),
|
|
params: None,
|
|
body_params: HashMap::new(),
|
|
out: Declared::default(),
|
|
};
|
|
let mut breaks = LineBreaks::default();
|
|
for t in lexer.by_ref() {
|
|
match breaks.read(&t) {
|
|
Read::Skip => {}
|
|
Read::Directive => d.directive(&t),
|
|
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);
|
|
}
|
|
d.settle_replaced();
|
|
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
|
|
}
|
|
|
|
impl<'s> Declarations<'s, '_, '_> {
|
|
fn depth(&self) -> usize {
|
|
self.brackets.depth()
|
|
}
|
|
|
|
fn token(&mut self, t: Sig<'s>) {
|
|
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) {
|
|
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();
|
|
if let Some((at, names, full)) = self.params.as_mut()
|
|
&& *at == depth
|
|
&& (is(h0, "(") || is(h0, ","))
|
|
{
|
|
if self.acc.room(names.len()) {
|
|
names.push(t.text);
|
|
} else {
|
|
*full = true;
|
|
}
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
// `o.local = …` or `o['local'] = …` in a loop: the object may be the global object
|
|
// ([`Declared::rebound`]), so the global variable of that name may get another value on each
|
|
// pass. A key with an escape may spell any name: any variable may be assigned in a loop.
|
|
if t.is("=") && !self.loops.is_empty() {
|
|
let property = if member_mark(h1) {
|
|
h0.filter(|s| s.kind == T::Ident).map(|s| s.text)
|
|
} else if is(h0, "]") && is(self.h[2], "[") {
|
|
let key = h1.filter(|s| s.kind == T::Str);
|
|
if key.is_some_and(|s| s.text.contains('\\')) {
|
|
self.out.looped_full = true;
|
|
}
|
|
key.filter(|s| s.text.len() >= 2 && !s.text.contains('\\')).and_then(|s| s.text.get(1..s.text.len() - 1))
|
|
} else {
|
|
None
|
|
};
|
|
if let Some(name) = property {
|
|
let id = self.out.loop_spans.len().saturating_sub(1);
|
|
self.keep_looped(None, name, vec![id]);
|
|
}
|
|
}
|
|
self.method_replacement(&t);
|
|
if let Some(after_new) = self.assign.take() {
|
|
if t.word("new") && !after_new {
|
|
self.assign = Some(true);
|
|
}
|
|
} else {
|
|
if t.word("var") {
|
|
self.var_depth = Some(depth);
|
|
}
|
|
if (t.is(";") || for_in(&t, h0, h1)) && self.var_depth == Some(depth) {
|
|
self.var_depth = None;
|
|
}
|
|
if t.is("=") && h0.is_some_and(|s| s.kind == T::Ident) && !member_mark(h1) && !is(h1, "@") {
|
|
self.assign = Some(false);
|
|
}
|
|
}
|
|
// `function` that isn't a property's name: its body's `{` comes after its name and
|
|
// parameters.
|
|
if t.word("function") && !member_mark(h0) && !word(h0, "function") {
|
|
self.function = Some(depth);
|
|
}
|
|
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];
|
|
}
|
|
|
|
/// `t` changes or shares a variable's methods, as [`Analyzer::writer_use`] reads it: `=`, a
|
|
/// compound operator, `++` or `--` on `local.saveAs` or `local['saveAs']` (one of the document
|
|
/// write methods), `++local.saveAs`, a key in brackets that is not one string literal
|
|
/// (`local[k]`, `local['sa' + 'veAs']`), `delete local`, or `local` used as a value
|
|
/// (`var y = local`, `f(local)`), where another name may hold its object. 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, t: &Sig<'s>) {
|
|
let [h0, h1, h2] = self.h;
|
|
let (h3, h4) = (self.h3, self.h4);
|
|
let ident = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| s.filter(|s| s.kind == T::Ident && !member_mark(before));
|
|
let write = |s: Option<Sig<'s>>| s.is_some_and(|s| s.kind == T::Ident && catalog::DOM_FILE_WRITES.contains(&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 receiver = if changes && is(h1, ".") && write(h0) {
|
|
ident(h2, h3)
|
|
} else if changes
|
|
&& 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()));
|
|
ident(h3, h4).filter(|_| writes)
|
|
} else if is(h0, ".") && (is(h2, "++") || is(h2, "--")) && write(Some(*t)) && (h2.is_some_and(|s| s.nl) || !h1.is_some_and(|s| s.nl)) {
|
|
// `++local.saveAs`, not `n++` ending the line before `local.saveAs`.
|
|
ident(h1, h2)
|
|
} else if word(h0, "delete") {
|
|
ident(Some(*t), h0)
|
|
} else if let Some(name) = ident(h0, h1).filter(|_| !t.is(".") && !t.is("[") && !t.is("=") && !key) {
|
|
// `local` used as a value, or changed by a compound or update operator.
|
|
Some(name)
|
|
} else if is(h0, "[") {
|
|
// `local[k]`: a key that is not one string or number literal may name any method.
|
|
ident(h1, h2).filter(|_| t.kind != T::Str && t.kind != T::Number)
|
|
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str || s.kind == T::Number) {
|
|
// `local['sa' + k]`
|
|
ident(h2, h3).filter(|_| !t.is("]"))
|
|
} 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) || self.body_params.get(&b.index).is_some_and(|p| p.contains(&name)));
|
|
if (!self.bodies.is_empty() || self.untracked.is_some()) && !own {
|
|
if self.untracked.is_some() {
|
|
// A body past the nesting limit keeps no names, so any body around may declare the
|
|
// variable.
|
|
if self.out.method_replaced_any.contains(name) || self.acc.room(self.out.method_replaced_any.len()) {
|
|
self.out.method_replaced_any.insert(name);
|
|
} else {
|
|
self.out.unsure = true;
|
|
}
|
|
} else {
|
|
let key = (self.bodies.iter().map(|b| b.index).collect::<Vec<_>>(), name);
|
|
if self.replaced.contains(&key) || self.acc.room(self.replaced.len()) {
|
|
self.replaced.insert(key);
|
|
} else {
|
|
self.out.unsure = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Keeps each replacement in [`Self::replaced`] for the innermost body around it that declares
|
|
/// the variable anywhere in the body, or as a parameter, or for the global code when none does.
|
|
/// A replacement of a variable of the innermost body itself is not kept, as when the body
|
|
/// declared it before the replacement. When a body around it ran out of room for its names, the
|
|
/// body that declares the variable is not known, and the replacement counts for the variable of
|
|
/// that name in every body ([`Declared::method_replaced_any`]).
|
|
fn settle_replaced(&mut self) {
|
|
for (around, name) in std::mem::take(&mut self.replaced) {
|
|
let mut owner = None;
|
|
let mut known = true;
|
|
for (i, &index) in around.iter().enumerate().rev() {
|
|
if self.out.bodies.get(index).is_some_and(|(_, names)| names.contains(&name))
|
|
|| self.body_params.get(&index).is_some_and(|p| p.contains(&name))
|
|
{
|
|
owner = self.out.bodies.get(index).map(|(at, _)| (*at, i + 1 == around.len()));
|
|
break;
|
|
}
|
|
if self.names_full.contains(&index) {
|
|
known = false;
|
|
break;
|
|
}
|
|
}
|
|
if !known {
|
|
if self.out.method_replaced_any.contains(name) || self.acc.room(self.out.method_replaced_any.len()) {
|
|
self.out.method_replaced_any.insert(name);
|
|
} else {
|
|
self.out.unsure = true;
|
|
}
|
|
continue;
|
|
}
|
|
if owner.is_some_and(|(_, innermost)| innermost) {
|
|
continue;
|
|
}
|
|
let key = (owner.map(|(at, _)| at), name);
|
|
if self.out.method_replaced.contains(&key) || self.acc.room(self.out.method_replaced.len()) {
|
|
self.out.method_replaced.insert(key);
|
|
} 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) {
|
|
let [h0, h1, _] = self.h;
|
|
let name = |s: Option<Sig<'s>>| s.filter(|s| s.kind == T::Ident).map(|s| s.text);
|
|
let declares = word(h1, "var") || (is(h1, ",") && self.var_depth == Some(depth));
|
|
let assigned = if t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")) {
|
|
// `d = …`, `d += …` and `d++`, not `o.d = …` (a member: [`Declared::rebound`]) or `var d = …`.
|
|
name(h0).filter(|_| !member_mark(h1) && !(t.text == "=" && declares))
|
|
} else if t.kind == T::Ident && (is(h0, "++") || is(h0, "--")) {
|
|
// `++d`.
|
|
Some(t.text)
|
|
} else if t.word("in") && (is(h1, "(") || word(h1, "var")) {
|
|
// `for (d in …)`.
|
|
name(h0)
|
|
} else {
|
|
None
|
|
};
|
|
// A name the innermost body around `t` has declared with `var` before it is that body's own. A
|
|
// name only an outer body declared is that body's variable, which a nested function may assign
|
|
// before a call in the outer body runs.
|
|
let own = |name: &str| self.untracked.is_none() && self.bodies.last().is_some_and(|b| b.names.contains(name));
|
|
if let Some(name) = assigned.filter(|n| !own(n)) {
|
|
if self.out.body_assigned.contains(name) || self.acc.room(self.out.body_assigned.len()) {
|
|
self.out.body_assigned.insert(name);
|
|
} else {
|
|
self.out.unsure = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `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>) {
|
|
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
|
|
/// `function` at the depth of `function` opens the function's body.
|
|
fn bracket(&mut self, t: &Sig<'s>) {
|
|
match t.text {
|
|
"(" | "[" | "{" => {
|
|
let body = t.text == "{" && self.function.take() == Some(self.depth());
|
|
let params = t.text == "(" && self.function == Some(self.depth());
|
|
self.brackets.open(t, self.acc.limits.nesting);
|
|
if params {
|
|
self.params = Some((self.depth(), vec![], false));
|
|
}
|
|
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;
|
|
}
|
|
let params = self.params.take();
|
|
if self.bodies.len() < self.acc.limits.nesting {
|
|
let index = self.out.bodies.len();
|
|
if let Some((_, names, full)) = params {
|
|
if full {
|
|
self.names_full.insert(index);
|
|
}
|
|
if !names.is_empty() {
|
|
self.body_params.insert(index, names);
|
|
}
|
|
}
|
|
self.out.bodies.push((t.start, vec![]));
|
|
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());
|
|
}
|
|
}
|
|
")" | "]" | "}" => {
|
|
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;
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
/// The name `t`, when a `var` statement or a function declaration declares it: kept for the
|
|
/// innermost function body when the `var` statement is in that body or the declaration is
|
|
/// 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 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);
|
|
if !(var || function) || self.untracked.is_some() {
|
|
return;
|
|
}
|
|
if let Some(body) = self.bodies.last_mut() {
|
|
if (var || body.depth == depth) && !body.names.contains(t.text) {
|
|
if self.acc.room(body.names.len()) {
|
|
body.names.insert(t.text);
|
|
if let Some((_, names)) = self.out.bodies.get_mut(body.index) {
|
|
names.push(t.text);
|
|
}
|
|
} else {
|
|
self.names_full.insert(body.index);
|
|
}
|
|
}
|
|
} else if function && depth == 0 && !self.out.global.contains(t.text) && self.acc.room(self.out.global.len()) {
|
|
self.out.global.insert(t.text);
|
|
}
|
|
}
|
|
|
|
/// 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, t: &Token<'s>) {
|
|
if directives::parse(t.text).known == Some("include") {
|
|
self.out.includes = true;
|
|
}
|
|
if self.keys.iter().any(|k| k.member) {
|
|
self.out.unsure = true;
|
|
}
|
|
self.h = [None; 3];
|
|
self.var_depth = None;
|
|
self.assign = None;
|
|
}
|
|
}
|