mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 21:42:59 -05:00
- Document.exportForScreens throws a TypeError for null in place of the
options, itemToExport or fileNamePrefix, as exportFile does for null
options, instead of taking the defaults.
- The script checker counts a variable read just before the `}` that
closes a function body (`function get() { return $.global['local'] }`)
as read in that body, so a later literal's saveAs is no longer exempt.
885 lines
43 KiB
Rust
885 lines
43 KiB
Rust
//! The platform features, menu commands and later syntax the analysis recognises.
|
|
|
|
use super::{
|
|
Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, exact_unquote, is, member_mark, newer_number, report, unquote, word,
|
|
};
|
|
|
|
/// Words that start or continue a statement or an expression, never a variable's name.
|
|
const RESERVED: [&str; 24] = [
|
|
"var",
|
|
"function",
|
|
"if",
|
|
"else",
|
|
"for",
|
|
"while",
|
|
"do",
|
|
"return",
|
|
"new",
|
|
"typeof",
|
|
"delete",
|
|
"in",
|
|
"instanceof",
|
|
"this",
|
|
"with",
|
|
"switch",
|
|
"case",
|
|
"try",
|
|
"catch",
|
|
"finally",
|
|
"throw",
|
|
"break",
|
|
"continue",
|
|
"void",
|
|
];
|
|
|
|
/// A global name of the platform the report looks for (`$`, `File`, `Socket`, `alert`, `eval`…).
|
|
pub(super) fn platform_name(n: &str) -> bool {
|
|
matches!(
|
|
n,
|
|
catalog::DOLLAR
|
|
| catalog::LOCALIZE
|
|
| catalog::UNIT_VALUE
|
|
| catalog::FILE
|
|
| catalog::FOLDER
|
|
| catalog::WINDOW
|
|
| catalog::BRIDGE_TALK
|
|
| catalog::SOCKET
|
|
| catalog::EXTERNAL_OBJECT
|
|
| "eval"
|
|
| "Function"
|
|
) || catalog::NOTIFY.contains(&n)
|
|
|| catalog::XMP.contains(&n)
|
|
|| catalog::XML.contains(&n)
|
|
}
|
|
|
|
/// The feature of a window of type `value` (`"dialog"`, or a resource string that starts with it).
|
|
pub(super) fn window_type(value: &str) -> FeatureId {
|
|
let word = value.trim_start().split(|c: char| c.is_whitespace() || c == '{').next().unwrap_or_default();
|
|
if word.eq_ignore_ascii_case("dialog") {
|
|
FeatureId::ScriptuiDialog
|
|
} else if word.eq_ignore_ascii_case("palette") {
|
|
FeatureId::ScriptuiPalette
|
|
} else {
|
|
FeatureId::ScriptuiWindow
|
|
}
|
|
}
|
|
|
|
impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
|
pub(super) fn features(&mut self, t: &Sig<'s>) {
|
|
let line = self.agg(t.line);
|
|
let mut pending = std::mem::take(&mut self.pending);
|
|
// A platform name that no `:` follows stands for the platform's object.
|
|
if let Pending::Name(n, l) = pending {
|
|
pending = Pending::None;
|
|
if !t.is(":") {
|
|
self.platform(n, l);
|
|
pending = std::mem::take(&mut self.pending);
|
|
}
|
|
}
|
|
match pending {
|
|
Pending::None | Pending::Name(..) => {}
|
|
Pending::Window(l) => {
|
|
if t.is("(") {
|
|
self.pending = Pending::WindowType(l);
|
|
} else {
|
|
self.acc.feature(FeatureId::ScriptuiWindow, l);
|
|
}
|
|
}
|
|
Pending::WindowType(l) => {
|
|
let feature = if t.kind == T::Str { window_type(&unquote(t.text, 64)) } else { FeatureId::ScriptuiWindow };
|
|
self.acc.feature(feature, l);
|
|
}
|
|
Pending::Menu(l) => {
|
|
if t.kind == T::Str {
|
|
self.pending = Pending::MenuString(l, t.text);
|
|
} else {
|
|
self.menu(None, l);
|
|
}
|
|
}
|
|
Pending::MenuString(l, s) if t.is(",") => self.pending = Pending::MenuStringComma(l, s),
|
|
Pending::MenuString(l, s) | Pending::MenuStringComma(l, s) => self.menu(t.is(")").then_some(s), l),
|
|
Pending::Open(l) => {
|
|
if t.kind == T::Str {
|
|
self.open_mode(&unquote(t.text, 2), l);
|
|
}
|
|
}
|
|
Pending::Setter(l, prefix) => {
|
|
let sets = if prefix {
|
|
!t.is(".") && !t.is("[") && !t.is("(")
|
|
} else {
|
|
// An update operator after a line break belongs to the next line's operand.
|
|
t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || (matches!(t.text, "++" | "--") && !t.nl))
|
|
};
|
|
if sets {
|
|
self.file_setter(l);
|
|
}
|
|
}
|
|
}
|
|
self.with_step(t);
|
|
self.writer_use(t);
|
|
match t.kind {
|
|
T::Ident => self.name(t, line),
|
|
T::Punct => self.punct(t, line),
|
|
T::Str => self.string(t, line),
|
|
T::Xml => self.acc.feature(FeatureId::E4x, line),
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
/// A menu command run with the string literal `literal`, or with another value.
|
|
fn menu(&mut self, literal: Option<&str>, line: Option<usize>) {
|
|
match literal {
|
|
Some(s) => {
|
|
let value = unquote(s, self.acc.limits.echo.saturating_add(1));
|
|
self.acc.menu_string(&value, line);
|
|
}
|
|
None => self.acc.menu_dynamic(),
|
|
}
|
|
self.acc.feature(FeatureId::MenuCommand, line);
|
|
}
|
|
|
|
fn open_mode(&mut self, mode: &str, line: Option<usize>) {
|
|
if mode.eq_ignore_ascii_case("r") {
|
|
self.acc.feature(FeatureId::FileRead, line);
|
|
} else if let Some(m) = catalog::WRITE_MODES.iter().copied().find(|m| m.eq_ignore_ascii_case(mode)) {
|
|
self.acc.feature(FeatureId::FileWrite, line);
|
|
self.acc.outside(OutsideId::FilesWritten, line, Some(m));
|
|
}
|
|
}
|
|
|
|
/// What a pending feature waits for that never came.
|
|
pub(super) fn settle_pending(&mut self) {
|
|
let mut pending = std::mem::take(&mut self.pending);
|
|
if let Pending::Name(n, l) = pending {
|
|
self.platform(n, l);
|
|
pending = std::mem::take(&mut self.pending);
|
|
}
|
|
match pending {
|
|
Pending::Window(l) | Pending::WindowType(l) => self.acc.feature(FeatureId::ScriptuiWindow, l),
|
|
Pending::Menu(l) | Pending::MenuString(l, _) | Pending::MenuStringComma(l, _) => self.menu(None, l),
|
|
Pending::Setter(l, true) => self.file_setter(l),
|
|
Pending::Open(_) | Pending::Setter(_, false) | Pending::Name(..) | Pending::None => {}
|
|
}
|
|
}
|
|
|
|
/// `SaveOptions.SAVECHANGES` read at `line`: a `Document.close` given it saves the document to
|
|
/// its own file, and the value may reach `close` through a variable or an argument.
|
|
fn save_changes(&mut self, line: Option<usize>) {
|
|
self.acc.feature(FeatureId::FileWrite, line);
|
|
self.acc.outside(OutsideId::FilesWritten, line, None);
|
|
}
|
|
|
|
/// A File object's `length`, `hidden` or `readonly` set at `line`: the file changes.
|
|
fn file_setter(&mut self, line: Option<usize>) {
|
|
self.acc.feature(FeatureId::FileWrite, line);
|
|
self.acc.outside(OutsideId::FilesWritten, line, None);
|
|
}
|
|
|
|
/// `name`, a property of `receiver` read with `.` or as a string literal in brackets, `before`
|
|
/// coming before the receiver: when it is the setter of an object that may be a File object (not
|
|
/// of one that is a Folder object whatever the path names), the next token says whether it is set
|
|
/// ([`Pending::Setter`]). An update operator in `before` is a prefix
|
|
/// (`++f.length`) when the receiver is on its line, or when it starts a line or comes where an
|
|
/// expression may start; otherwise it ends the operand before it (`i++` and a line break, then
|
|
/// `f.length`).
|
|
fn setter(&mut self, name: &str, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>, line: Option<usize>) {
|
|
if catalog::FILE_SETTERS.contains(&name) && self.held_file(receiver, before) == Some(false) {
|
|
// Before a receiver that ends in `)` (`new File(i++).length`), the operator is inside the
|
|
// parentheses.
|
|
let update = before.filter(|b| (b.is("++") || b.is("--")) && receiver.is_some_and(|r| r.kind == T::Ident));
|
|
let prefix = update.is_some_and(|b| b.nl || b.expr || receiver.is_some_and(|r| !r.nl));
|
|
self.pending = Pending::Setter(line, prefix);
|
|
}
|
|
}
|
|
|
|
/// The platform name `n`, used at `line` (a tally's line): the feature it is, and what it does
|
|
/// outside the document.
|
|
fn platform(&mut self, n: &'s str, line: Option<usize>) {
|
|
match n {
|
|
catalog::UNIT_VALUE => self.acc.feature(FeatureId::UnitValue, line),
|
|
catalog::FILE | catalog::FOLDER => self.acc.feature(FeatureId::FileObjects, line),
|
|
catalog::BRIDGE_TALK => {
|
|
self.acc.feature(FeatureId::BridgeTalk, line);
|
|
self.acc.outside(OutsideId::OtherApps, line, None);
|
|
}
|
|
catalog::SOCKET => {
|
|
self.acc.feature(FeatureId::Socket, line);
|
|
self.acc.outside(OutsideId::Network, line, None);
|
|
}
|
|
catalog::EXTERNAL_OBJECT => {
|
|
self.acc.feature(FeatureId::ExternalObject, line);
|
|
self.acc.outside(OutsideId::NativeCode, line, None);
|
|
}
|
|
catalog::WINDOW => self.pending = Pending::Window(line),
|
|
_ if catalog::XMP.contains(&n) => self.acc.feature(FeatureId::Xmp, line),
|
|
_ if catalog::XML.contains(&n) => self.acc.feature(FeatureId::Xml, line),
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn name(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
|
let [h0, h1, h2, _] = self.h;
|
|
let n = t.text;
|
|
if is(h0, ".") {
|
|
// A member: of `$`, `File` or `Folder` when they come first and are the platform's.
|
|
let own = &self.own_names;
|
|
let of = |name: &str| word(h1, name) && !member_mark(h2) && !own.contains(name);
|
|
if of(catalog::DOLLAR) {
|
|
if catalog::DOLLAR_ENV.contains(&n) {
|
|
self.acc.feature(FeatureId::DollarEnv, line);
|
|
self.acc.outside(OutsideId::Environment, line, None);
|
|
} else if n == catalog::DOLLAR_EVAL_FILE {
|
|
self.acc.feature(FeatureId::DollarEvalFile, line);
|
|
self.acc.outside(OutsideId::UnseenCode, line, None);
|
|
} else {
|
|
self.acc.feature(FeatureId::Dollar, line);
|
|
}
|
|
} else if (of(catalog::FILE) && catalog::FILE_DIALOGS.contains(&n)) || (of(catalog::FOLDER) && catalog::FOLDER_DIALOGS.contains(&n)) {
|
|
self.acc.feature(FeatureId::FileDialog, line);
|
|
} else if of(catalog::FOLDER) && catalog::FOLDER_PLACES.contains(&n) {
|
|
self.acc.feature(FeatureId::FilePlaces, line);
|
|
}
|
|
if n == catalog::SAVE_CHANGES && of(catalog::SAVE_OPTIONS) {
|
|
self.save_changes(line);
|
|
}
|
|
if n == catalog::ON_DRAW {
|
|
self.acc.feature(FeatureId::ScriptuiDrawing, line);
|
|
}
|
|
if n == catalog::REFLECT {
|
|
self.acc.feature(FeatureId::Reflection, line);
|
|
}
|
|
self.setter(n, h1, h2, line);
|
|
return;
|
|
}
|
|
if member_mark(h0) {
|
|
return;
|
|
}
|
|
if word(h0, "function") {
|
|
self.acc.declared(n);
|
|
if h0.is_some_and(|f| f.stmt) {
|
|
// A function declaration's name is a variable where the function is declared. A
|
|
// declaration directly in a function body or in the global code makes it one from the
|
|
// body's `{` or from the start of the file ([`Declared`]), and any other declaration
|
|
// makes it one from here.
|
|
if !self.hoisted(n) {
|
|
self.keep_outer(n);
|
|
self.unbind(n);
|
|
}
|
|
} else {
|
|
// A function expression's name is a variable inside the function only.
|
|
self.expression_name = Some(n.to_string());
|
|
}
|
|
return;
|
|
}
|
|
if n == "catch" {
|
|
// Its block's `{` comes after its parameter's parentheses.
|
|
self.catch = Some((self.depth(), None));
|
|
}
|
|
if n == "function" {
|
|
// Its body's `{` comes after its name and parameters.
|
|
self.function = Some(self.depth());
|
|
self.expression_name = None;
|
|
// `name = function`: the script's own function too.
|
|
if is(h0, "=")
|
|
&& let Some(f) = h1.filter(|s| s.kind == T::Ident)
|
|
{
|
|
self.acc.declared(f.text);
|
|
}
|
|
}
|
|
if word(h0, "new") && n.starts_with(|c: char| c.is_ascii_uppercase()) && !catalog::CONSTRUCTORS.contains(&n) {
|
|
self.acc.type_name(n);
|
|
}
|
|
// A platform name stands for the platform's object, except where the script declares a
|
|
// variable, function or parameter of that name, and where it has a meaning of its own.
|
|
// Where a property key or a label may stand, the token after it decides.
|
|
if platform_name(n) && !self.declaring() && !self.own_names.contains(n) {
|
|
if h0.is_none() || [",", "{", ";", "}"].iter().any(|p| is(h0, p)) {
|
|
self.pending = Pending::Name(n, line);
|
|
} else {
|
|
self.platform(n, line);
|
|
}
|
|
}
|
|
match n {
|
|
// E4X: `default xml namespace = …` and `for each (…)`.
|
|
"namespace" if word(h0, "xml") && word(h1, "default") => self.acc.feature(FeatureId::E4x, line),
|
|
"each" if word(h0, "for") => self.acc.feature(FeatureId::E4x, line),
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn punct(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
|
let [h0, h1, h2, h3] = self.h;
|
|
match t.text {
|
|
// `f['length']`: a File object's setter may follow.
|
|
"]" 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, Some(t.start));
|
|
self.index_stable = h0.is_some_and(|r| self.stable(r.text));
|
|
}
|
|
"(" => 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()));
|
|
if is(h0, "]") && is(h2, "[") && word(h3, "prototype") && operator() {
|
|
self.acc.feature(FeatureId::OperatorOverloading, line);
|
|
}
|
|
}
|
|
// E4X: attributes (`x.@id`, `@*`), descendants (`x..item`) and qualified names (`ns::x`).
|
|
".@" | ".." | "::" | "@" => self.acc.feature(FeatureId::E4x, line),
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
/// Whether this `(` calls a document's `print`: the document-model member chain the `(` has just
|
|
/// set aside until its `)` is one of [`catalog::DOM_DOCUMENTS`] followed by `called`, the method
|
|
/// as the chain writes it (`.print()`, or `[]()` when brackets name it).
|
|
fn document_print(&self, called: &str) -> bool {
|
|
self.called_on(called).is_some_and(|receiver| catalog::DOM_DOCUMENTS.contains(&receiver))
|
|
}
|
|
|
|
/// Whether this `(` calls a method of the application object: `receiver`, which `before` comes
|
|
/// before, is the application object ([`Self::app_receiver`]), or the document-model member chain
|
|
/// the `(` has just set aside until its `)` is `app` followed by `called`. The chain starts at `app`
|
|
/// or at a variable that holds it, never at a property named `app` or at an `app` the script declared.
|
|
fn app_call(&self, called: &str, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> bool {
|
|
self.app_receiver(receiver, before) || self.called_on(called) == Some(catalog::DOM_ROOTS[0])
|
|
}
|
|
|
|
/// Whether the method `name`, which a string literal in brackets named, gives a document: the
|
|
/// member chain this `(` has just set aside, with `name` called on its receiver, is one of
|
|
/// [`catalog::DOM_DOCUMENTS`].
|
|
fn gives_document(&self, name: &str) -> bool {
|
|
let named =
|
|
|receiver: &str, d: &str| d.strip_prefix(receiver).and_then(|m| m.strip_prefix('.')).and_then(|m| m.strip_suffix("()")) == Some(name);
|
|
self.called_on("[]()").is_some_and(|receiver| catalog::DOM_DOCUMENTS.iter().any(|d| named(receiver, d)))
|
|
}
|
|
|
|
/// What the document-model member chain that this `(` has just set aside until its `)` holds before
|
|
/// `called`, when the chain ends with `called`.
|
|
fn called_on(&self, called: &str) -> Option<&str> {
|
|
let chain = self.suspended.last().filter(|c| c.wait.saturating_add(1) == self.depth());
|
|
chain.and_then(|c| c.path.strip_suffix(called))
|
|
}
|
|
|
|
/// What the call whose `(` is the current token reaches.
|
|
fn classify_call(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
|
let [h0, h1, h2, h3] = self.h;
|
|
// `doc['saveAs'](f)`, `doc['exportVariables'](f)` and `app['open'](f)`: a method named by a string literal in brackets.
|
|
if is(h0, "]")
|
|
&& is(h2, "[")
|
|
&& let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
|
|
{
|
|
if (catalog::DOM_FILE_WRITES.contains(&name.as_str()) && !(self.index_stable && Self::defines(self.index_receiver, &name)))
|
|
|| (name == catalog::DOM_PRINT && self.document_print("[]()"))
|
|
{
|
|
self.acc.feature(FeatureId::FileWrite, line);
|
|
self.acc.outside(OutsideId::FilesWritten, line, None);
|
|
} else if catalog::DOM_FILE_READS.contains(&name.as_str()) && self.app_call("[]()", h3, self.h4) {
|
|
self.acc.feature(FeatureId::FileRead, line);
|
|
}
|
|
// `app['open'](f)` and `app.documents['index'](0)` give a document, as `app.open(f)` and
|
|
// `app.documents.index(0)` do.
|
|
if self.gives_document(&name) {
|
|
let (depth, cap) = (self.depth(), self.chain_cap());
|
|
if let Some(c) = self.suspended.last_mut().filter(|c| c.wait.saturating_add(1) == depth) {
|
|
c.name_call(&name, cap);
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return };
|
|
let n = callee.text;
|
|
if is(h1, ".") {
|
|
let held = self.held_file(h2, h3);
|
|
// A Folder object whatever the path names has no File-only function: the call does not
|
|
// reach the file system.
|
|
if held == Some(true) && catalog::FILE_ONLY.contains(&n) {
|
|
return;
|
|
}
|
|
let file = held.is_some();
|
|
if n == catalog::MENU_COMMAND {
|
|
self.pending = Pending::Menu(line);
|
|
} else if n == catalog::OPEN && file {
|
|
self.pending = Pending::Open(line);
|
|
} else if catalog::DRAWING.contains(&n) {
|
|
self.acc.feature(FeatureId::ScriptuiDrawing, line);
|
|
} else if catalog::INSTANCE_DIALOGS.contains(&n) {
|
|
self.acc.feature(FeatureId::FileDialog, line);
|
|
} else if catalog::FOLDER_READS.contains(&n)
|
|
|| (file && catalog::FILE_READS.contains(&n))
|
|
|| (catalog::DOM_FILE_READS.contains(&n) && self.app_call(&format!(".{n}()"), h2, h3))
|
|
{
|
|
self.acc.feature(FeatureId::FileRead, line);
|
|
} else if (file && catalog::FILE_WRITES.contains(&n))
|
|
|| (catalog::DOM_FILE_WRITES.contains(&n)
|
|
&& !(h2.is_some_and(|r| self.stable(r.text)) && Self::defines(self.writer_bits(h2, h3, Some(t.start)), n)))
|
|
|| (n == catalog::DOM_PRINT && self.document_print(".print()"))
|
|
{
|
|
self.acc.feature(FeatureId::FileWrite, line);
|
|
self.acc.outside(OutsideId::FilesWritten, line, None);
|
|
} else if n == catalog::EXECUTE {
|
|
self.acc.feature(FeatureId::FileExecute, line);
|
|
self.acc.outside(OutsideId::FilesOpened, line, None);
|
|
} else if catalog::ACTIONS.contains(&n) {
|
|
self.acc.feature(FeatureId::Actions, line);
|
|
} else if n == catalog::SELECT_TOOL {
|
|
self.acc.feature(FeatureId::SelectTool, line);
|
|
}
|
|
} else if !member_mark(h1) && !word(h1, "function") && !self.own_names.contains(n) {
|
|
if catalog::NOTIFY.contains(&n) {
|
|
self.acc.feature(FeatureId::Notify, line);
|
|
} else if n == catalog::LOCALIZE {
|
|
self.acc.feature(FeatureId::Localize, line);
|
|
} else if matches!(n, "eval" | "Function") {
|
|
self.acc.feature(FeatureId::DynamicCode, line);
|
|
self.acc.outside(OutsideId::UnseenCode, line, None);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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. Inside the body of a
|
|
/// `with` statement the name may be a property of the statement's object, so no call is known
|
|
/// there ([`Analyzer::with_step`]).
|
|
fn stable(&self, name: &str) -> bool {
|
|
!self.withs_full && self.withs.is_empty() && self.scopes.last().is_none_or(|s| s.saved.contains_key(name))
|
|
}
|
|
|
|
/// Follows the `with` statements around `t`. A body in braces ends with its `}`; a body without
|
|
/// braces is taken to last until the block the statement is in closes.
|
|
fn with_step(&mut self, t: &Sig<'s>) {
|
|
let depth = self.depth();
|
|
self.withs.retain(|d| *d <= depth);
|
|
match self.with_head {
|
|
Some((d, false)) if t.is(")") && depth == d => self.with_head = Some((d, true)),
|
|
Some((d, true)) => {
|
|
self.with_head = None;
|
|
let body = if t.is("{") { depth } else { d };
|
|
if self.withs.len() < self.acc.limits.nesting {
|
|
self.withs.push(body);
|
|
} else {
|
|
self.withs_full = true;
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
if t.kind == T::Ident && t.text == "with" && !member_mark(self.h[0]) {
|
|
self.with_head = Some((depth, false));
|
|
}
|
|
}
|
|
|
|
/// `name` may have been given another value through the global object: neither the variable
|
|
/// nor the outer variables of that name that the open function bodies and `catch` blocks keep
|
|
/// to put back hold their literal's methods any longer.
|
|
fn forget_writer(&mut self, name: &str) {
|
|
self.writers.remove(name);
|
|
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;
|
|
}
|
|
}
|
|
|
|
/// 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) {
|
|
self.writers.clear();
|
|
for saved in self.scopes.iter_mut().flat_map(|s| s.saved.values_mut()) {
|
|
saved.writer = 0;
|
|
}
|
|
for c in &mut self.catches {
|
|
c.saved.writer = 0;
|
|
}
|
|
}
|
|
|
|
/// A function body uses `name`, which no literal has given methods and the body does not declare,
|
|
/// in a way that may change or share it ([`Analyzer::shared_early`]). With no room left for the
|
|
/// name, no literal's methods are the script's own from then on.
|
|
pub(super) fn share_early(&mut self, name: &str) {
|
|
self.share_early_as(name, false);
|
|
}
|
|
|
|
/// [`Analyzer::share_early`], and with `global` set, for the global variable `name` read through
|
|
/// the global object (`$.global.local`) even when the body declares a variable of that name.
|
|
fn share_early_as(&mut self, name: &str, global: bool) {
|
|
// A value read just before the `}` that closes a function body is read in that body.
|
|
let (open, declared) = match &self.closed_body {
|
|
Some((open, names)) => (*open, names.iter().any(|n| n == name)),
|
|
None => match self.scopes.last() {
|
|
Some(body) => (self.scopes.len(), body.saved.contains_key(name)),
|
|
None => return,
|
|
},
|
|
};
|
|
if (declared && !global) || self.writers.contains_key(name) {
|
|
return;
|
|
}
|
|
if self.shared_early.contains_key(name) || self.acc.room(self.shared_early.len()) {
|
|
let seen = self.shared_early.entry(name.to_string()).or_insert(open);
|
|
*seen = (*seen).max(open);
|
|
} else {
|
|
self.shared_full = true;
|
|
}
|
|
}
|
|
|
|
/// Whether `receiver`, which `before` comes before, is the application object: the name `app`
|
|
/// that no `.` comes before and that the script has not declared as its own.
|
|
fn app_receiver(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> bool {
|
|
word(receiver, catalog::DOM_ROOTS[0]) && !member_mark(before) && !self.shadowed.first().copied().unwrap_or(true)
|
|
}
|
|
|
|
/// 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.
|
|
/// 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 !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;
|
|
}
|
|
// A function body that replaces the method may run before the call, wherever it is in
|
|
// the text. The replacement is kept for the body that declares the variable: the
|
|
// innermost body around the call that declares it, or the global code.
|
|
let looped = at.is_some_and(|at| {
|
|
let owner = self.scopes.iter().rev().find(|s| s.saved.get(r.text).is_some_and(|v| v.local)).map(|s| s.start);
|
|
self.declared.looped_full
|
|
|| self.declared.method_replaced_any.contains(r.text)
|
|
|| self.declared.method_replaced.contains(&(owner, r.text))
|
|
|| self.declared.looped.get(&(owner, 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,
|
|
}
|
|
}
|
|
|
|
/// A variable of [`Analyzer::writers`] used before `t` in any way but a member (`local.name`,
|
|
/// `local['name']`) or an assignment to it ([`Analyzer::assignment`]), or whose `saveAs` or
|
|
/// `exportFile` is assigned: another name may hold its object, or its methods may change, so its
|
|
/// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`,
|
|
/// `local[k] = w`, `delete local.saveAs`). A property assignment whose name is such a variable's
|
|
/// (`this.local = d`, `$.global['local'] = d`) may give the variable a new value through the global
|
|
/// object, so its methods are no longer known either. An assignment to a property of the global
|
|
/// object under any other key (`$.global[key] = d`, `this['lo' + 'cal'] = d`) may give any such
|
|
/// variable a new value: no variable's methods are known after it.
|
|
fn writer_use(&mut self, t: &Sig<'s>) {
|
|
let [h0, h1, h2, h3] = self.h;
|
|
let global_index_closed = std::mem::take(&mut self.global_index_closed);
|
|
if t.kind == T::Ident
|
|
&& is(h0, ".")
|
|
&& ((word(h1, "global") && is(h2, ".") && word(h3, "$") && !member_mark(self.h4))
|
|
|| ((word(h1, "this") || word(h1, "globalThis")) && !member_mark(h2)))
|
|
{
|
|
self.global_member = Some(t.start);
|
|
}
|
|
if t.is("[") {
|
|
let global = (word(h0, "global") && is(h1, ".") && word(h2, "$") && !member_mark(h3))
|
|
|| ((word(h0, "this") || word(h0, "globalThis")) && !member_mark(h1));
|
|
if global && self.global_indexes.len() < self.acc.limits.nesting {
|
|
self.global_indexes.push(self.depth());
|
|
}
|
|
} else if t.is("]") {
|
|
let depth = self.depth();
|
|
self.global_index_closed = self.global_indexes.last() == Some(&(depth + 1));
|
|
self.global_indexes.retain(|d| *d <= depth);
|
|
// `$.global['local']` or `this['local']`: the `]` reads the global variable `local`.
|
|
if self.global_index_closed
|
|
&& is(h1, "[")
|
|
&& let Some(key) = h0.filter(|s| s.kind == T::Str)
|
|
{
|
|
self.global_bracket = Some((t.start, exact_unquote(key.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 h4 = self.h4;
|
|
// `$.global.local`, `globalThis.local` or `this.local`: `h2` names the global variable `local`.
|
|
let global_member = h2.is_some_and(|s| self.global_member == Some(s.start));
|
|
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 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 = …` or `$.global.local.saveAs = …`
|
|
writer(h2, if global_member { None } else { 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'] = …`, not `other.local['saveAs'] = …`.
|
|
writer(h3, h4)
|
|
} 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.share_early(name);
|
|
}
|
|
// `$.global['local']` or `this['local']` used as a value (`var alias = $.global['local']`,
|
|
// `f(this['local'])`): another name may hold the global variable's object.
|
|
if !changes
|
|
&& !t.is(".")
|
|
&& !t.is("[")
|
|
&& let Some((_, name)) = self.global_bracket.as_ref().filter(|(at, _)| h0.is_some_and(|s| s.start == *at))
|
|
{
|
|
match name.clone() {
|
|
Some(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 {
|
|
let write_key = |s: Option<Sig<'s>>| s.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str()));
|
|
let bracketed =
|
|
|s: Option<Sig<'s>>| s.and_then(|s| self.global_bracket.as_ref().filter(|(at, _)| *at == s.start).map(|(_, name)| name.clone()));
|
|
let global = if is(h1, ".") && h0.is_some_and(|m| m.kind == T::Ident) && write_key(h0) {
|
|
bracketed(h2)
|
|
} else if is(h0, "]") && is(h2, "[") && h1.is_some_and(|m| m.kind == T::Str) && write_key(h1) {
|
|
bracketed(h3).or_else(|| h3.filter(|s| s.kind == T::Ident && self.global_member == Some(s.start)).map(|s| Some(s.text.to_string())))
|
|
} else {
|
|
None
|
|
};
|
|
match global {
|
|
// The global variable's value may be saved under a body's or a `catch`'s own variable of
|
|
// that name, so forget every value of the name.
|
|
Some(Some(name)) => {
|
|
self.forget_writer(&name);
|
|
self.share_early_as(&name, true);
|
|
}
|
|
// A key that does not decode to one exact name may name any variable.
|
|
Some(None) => self.forget_writers(),
|
|
None => {}
|
|
}
|
|
}
|
|
// A name read in a function body that the body does not declare, as a receiver or otherwise. A
|
|
// receiver is settled once its member is read: assigning a property that is not one of the
|
|
// document methods that write a file (`d.n = 1`) leaves its methods as they are.
|
|
if let Some(r) = h0.filter(|r| r.kind == T::Ident && !member_mark(h1) && !RESERVED.contains(&r.text) && !t.is(".")) {
|
|
self.share_early(r.text);
|
|
}
|
|
if let Some(r) = h2.filter(|r| is(h1, ".") && r.kind == T::Ident && (!member_mark(h3) || global_member) && !RESERVED.contains(&r.text)) {
|
|
let own_property = t.is("=") && h0.is_some_and(|m| m.kind == T::Ident && !catalog::DOM_FILE_WRITES.contains(&m.text));
|
|
if !own_property {
|
|
self.share_early_as(r.text, global_member);
|
|
}
|
|
}
|
|
if changes {
|
|
// A member assignment of a property `local` (`o.local = …`, `o['local'] = …`): the object may
|
|
// be the global object (`this`, `globalThis`, `$.global`, or any object holding it, as
|
|
// `holder.this`), so the variable of that name may get another value.
|
|
let rebound = if is(h1, ".") {
|
|
h0.filter(|s| s.kind == T::Ident).map(|s| Some(s.text.to_string()))
|
|
} else if is(h0, "]") && is(h2, "[") && h1.is_some_and(|s| s.kind == T::Str) {
|
|
h1.filter(|s| s.kind == T::Str).map(|s| exact_unquote(s.text))
|
|
} else {
|
|
None
|
|
};
|
|
if let Some(Some(name)) = rebound {
|
|
// In a function body: the function may run after a later literal gives the name methods.
|
|
if !self.scopes.is_empty() {
|
|
self.reassigned_later(&name);
|
|
}
|
|
self.forget_writer(&name);
|
|
} else if global_index_closed || rebound.is_some() {
|
|
// `$.global[key] = …`, or a key that does not decode to one exact name: the key may
|
|
// name any of them.
|
|
self.forget_writers();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `(` after a name: a call ([`Self::classify_call`]). A call of a variable of
|
|
/// [`Analyzer::writers`]'s method other than the `saveAs` or `exportFile` its literal defines
|
|
/// (`local.install()`, `local['install']()`) may replace the object's methods through `this`, so
|
|
/// after the call they are no longer known.
|
|
fn call(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
|
let [h0, h1, h2, h3] = self.h;
|
|
let bits = self.writer_bits(h2, h3, None);
|
|
let receiver = if is(h1, ".") && bits != 0 && h0.is_some_and(|s| s.kind == T::Ident && !Self::defines(bits, s.text)) {
|
|
h2
|
|
} else if is(h0, "]")
|
|
&& is(h2, "[")
|
|
&& self.index_receiver != 0
|
|
&& h1.is_some_and(|s| s.kind == T::Str && !Self::defines(self.index_receiver, &unquote(s.text, 32)))
|
|
{
|
|
h3
|
|
} else {
|
|
None
|
|
};
|
|
self.classify_call(t, line);
|
|
if let Some(r) = receiver {
|
|
self.writers.remove(r.text);
|
|
}
|
|
}
|
|
|
|
/// Whether `bits` ([`Self::writer_bits`]) has `method`: the receiver's own `method` is called.
|
|
fn defines(bits: u8, method: &str) -> bool {
|
|
catalog::DOM_FILE_WRITES.iter().position(|m| *m == method).is_some_and(|i| bits & (1 << i) != 0)
|
|
}
|
|
|
|
/// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object
|
|
/// (not a property of the same name), or a File or Folder object made in place or held in
|
|
/// grouping parentheses ([`Sig::file`]): `Some(true)` for a Folder object whatever the path names
|
|
/// ([`Sig::folder`], [`Analyzer::folder`]), unless the file gives names values the analysis
|
|
/// doesn't read ([`Analyzer::unsure`]), `Some(false)` for an object that may be a File object, and
|
|
/// `None` for anything else.
|
|
fn held_file(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> Option<bool> {
|
|
let r = receiver?;
|
|
if r.file {
|
|
Some(r.folder && !self.unsure)
|
|
} else if r.kind == T::Ident && !member_mark(before) && self.alias(&r) {
|
|
Some(self.folder(r.text))
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
|
|
fn string(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
|
let [h0, h1, h2, _] = self.h;
|
|
if t.text.contains(catalog::ACTION_TEXT) {
|
|
self.acc.feature(FeatureId::Actions, line);
|
|
}
|
|
// The value written as the string `"SaveOptions.SAVECHANGES"`.
|
|
let value = unquote(t.text, 32);
|
|
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, "==" | "===" | "!=" | "!=="));
|
|
if compares && word(h1, "typename") && is(h2, ".") {
|
|
let name = unquote(t.text, self.acc.limits.echo.saturating_add(1));
|
|
self.acc.type_name(&name);
|
|
}
|
|
}
|
|
|
|
/// Syntax later than ECMAScript 3: reported once per construct and line.
|
|
pub(super) fn newer(&mut self, t: &Sig<'s>) {
|
|
let [h0, h1, ..] = self.h;
|
|
let construct: Option<&'s str> = match t.kind {
|
|
T::Template => Some("`"),
|
|
T::Punct if NEWER.contains(&t.text) => Some(t.text),
|
|
T::Number if newer_number(t.text) => Some(t.text),
|
|
T::Other if t.text.len() > 1 && t.text.starts_with('#') => Some(t.text),
|
|
T::Ident if word(h0, "class") && !member_mark(h1) => Some("class"),
|
|
// `let name` declares a variable. ES3 reads `let` as a variable's name in `let = 1`,
|
|
// `let.x` and `let in o`.
|
|
T::Ident if word(h0, "let") && !t.nl && !member_mark(h1) && !matches!(t.text, "in" | "instanceof") => Some("let"),
|
|
T::Ident if t.text == "function" && word(h0, "async") && !t.nl => Some("async"),
|
|
_ => None,
|
|
};
|
|
if let Some(c) = construct
|
|
&& self.last_newer != Some((t.line, c))
|
|
{
|
|
self.last_newer = Some((t.line, c));
|
|
self.acc.problem(report::NEWER_SYNTAX, Some(t.line), self.file, Some(c));
|
|
}
|
|
}
|
|
|
|
/// `import` or `export` starting a statement outside any bracket, unless a call, member or
|
|
/// property (`import(…)`, `export.x`, `import: 1`) follows: a module.
|
|
pub(super) fn module_check(&mut self, t: &Sig<'s>) {
|
|
if std::mem::take(&mut self.module_candidate) && !(t.kind == T::Punct && matches!(t.text, "(" | "." | "=" | ":" | "," | ")")) {
|
|
self.module = true;
|
|
}
|
|
let starts = self.h[0].is_none() || t.nl || is(self.h[0], ";") || is(self.h[0], "}");
|
|
if t.kind == T::Ident && matches!(t.text, "import" | "export") && self.depth() == 0 && !member_mark(self.h[0]) && starts {
|
|
self.module_candidate = true;
|
|
}
|
|
}
|
|
}
|