Skip to main content

bynk_ts/
name_closure.rs

1//! Name closure: every name a module's tree uses is bound in that module
2//! (#1831).
3//!
4//! [`unbound_names`] walks a [`TsProgram`] and returns each name it uses that
5//! the module neither imports, declares, nor gets from TypeScript's, the
6//! Workers runtime's or Node's globals. Two positions are checked:
7//!
8//! - **type position**: a [`TsType::Named`], or the first segment of a
9//!   qualified `ns.T`;
10//! - **value position**: an identifier expression (`TsExpr::Ident`, first
11//!   segment of `a.b`), an object shorthand `{ x }`.
12//!
13//! A non-empty result is a `TS2304`/`TS2552` (`Cannot find name`) that `tsc`
14//! would report, found without `tsc`. That is the defect family of #1736,
15//! #1778, #1815, #1818, #1823 and #1829: the emitter names a type, or calls a
16//! codec, that the module never imports.
17//!
18//! **Scope is module-wide for values, node-local for type parameters.** A
19//! parameter or local declared anywhere in the module counts as bound
20//! everywhere in it, and a destructuring pattern binds every identifier in it.
21//! A type parameter (of a function, arrow, method, interface or alias) and a
22//! mapped type's key are bound only inside their own node (1A.36a): the same
23//! name used outside it is a use of something else. Each approximation can
24//! only hide a defect, never invent one.
25//!
26//! **Opaque text is mostly a blind spot.** `Raw` and `Verbatim` statements
27//! and `VerbatimExpr` expressions are pre-rendered TypeScript. A name they
28//! *declare* or *import* is found line by line (a line starting `import`,
29//! `type`, `interface`, `class`, `enum`, `function`, `const`, `let` or `var`).
30//! Of the names they *use*, only a generic type application (`Name<…>`) is
31//! checked (#1977: a kernel helper's parameter types are opaque text); any
32//! other use is not; a `TsStmt::raw_using` statement also declares the names its
33//! fixed text uses (1A.36a), and those are counted as uses. Measured over the positive corpus at #1831, opaque text was 0% of
34//! `index.ts`/`compose.ts`, about 14% of unit modules and about 26% of
35//! `handlers.ts` and test modules: chiefly service handler bodies, which
36//! `bynk-emit` still renders to text. That part of a module stays `tsc`'s
37//! job (#1823 lived there).
38//!
39//! **A type written as text is read.** A [`TsType::Named`] whose name carries
40//! its arguments or members as text (`Option<A>`, `Result<T, __BoundaryError>`,
41//! a union or function type) uses the names in that text, and a type
42//! parameter's constraint or default (`T extends Shape`) uses the names it
43//! holds (1A.36b-1). What is read is a type the emitter wrote itself, so the
44//! reading is narrow: capitalised words, not members, keys or string literals.
45//!
46//! **A global never hides a name the caller provides.** See
47//! [`unbound_names_providing`]: a module that imports a name sharing a
48//! global's (`Request`, `Response`) uses its import.
49
50use std::collections::{BTreeMap, BTreeSet};
51
52use crate::program::{
53    TsArrowBody, TsBindingName, TsDecl, TsExpr, TsObjectEntry, TsParam, TsProgram, TsStmt,
54    TsStmtKind, TsType, TsTypeMember,
55};
56
57/// Type names TypeScript, the Workers runtime or Node provide globally, plus
58/// the primitive keywords. A name here is never reported.
59const GLOBAL_TYPES: &[&str] = &[
60    // Keywords.
61    "string",
62    "number",
63    "boolean",
64    "bigint",
65    "symbol",
66    "object",
67    "unknown",
68    "never",
69    "void",
70    "undefined",
71    "null",
72    "any",
73    "this",
74    "true",
75    "false",
76    // `x as const`: the const assertion names no type (I4's generated client,
77    // #1970, asserts its `CONTRACTS` literal this way).
78    "const",
79    // ECMAScript / lib.dom globals the emitter names.
80    "Array",
81    "ReadonlyArray",
82    "Record",
83    "Partial",
84    "Readonly",
85    "Required",
86    "Pick",
87    "Omit",
88    "Exclude",
89    "Extract",
90    "NonNullable",
91    "ReturnType",
92    "Parameters",
93    "Awaited",
94    "BufferSource",
95    "Promise",
96    "PromiseLike",
97    "Map",
98    "ReadonlyMap",
99    "ReadonlySet",
100    "Set",
101    "ReadonlySet",
102    "WeakMap",
103    "Date",
104    "Error",
105    "RegExp",
106    "Uint8Array",
107    "ArrayBuffer",
108    "Iterable",
109    "IterableIterator",
110    "AsyncIterable",
111    "AsyncIterableIterator",
112    "AsyncGenerator",
113    "Generator",
114    "JSON",
115    "Response",
116    "Request",
117    "Headers",
118    "URL",
119    "URLSearchParams",
120    "ReadableStream",
121    "WritableStream",
122    "TextEncoder",
123    "TextDecoder",
124    "AbortSignal",
125    "WebSocket",
126    "MessageEvent",
127    "Blob",
128    "FormData",
129    "Function",
130    "PropertyKey",
131    // `globalThis.Response` and the like: the qualifier itself.
132    "globalThis",
133];
134
135/// Value names the ECMAScript, Workers and Node globals provide.
136const GLOBAL_VALUES: &[&str] = &[
137    "globalThis",
138    "undefined",
139    "NaN",
140    "Infinity",
141    "this",
142    "arguments",
143    "true",
144    "false",
145    "null",
146    "JSON",
147    "Object",
148    "Number",
149    "String",
150    "Boolean",
151    "Array",
152    "BufferSource",
153    "Promise",
154    "Math",
155    "Date",
156    "Error",
157    "TypeError",
158    "RangeError",
159    "SyntaxError",
160    "Symbol",
161    "BigInt",
162    "Map",
163    "Set",
164    "WeakMap",
165    "Reflect",
166    "Intl",
167    "Uint8Array",
168    "ArrayBuffer",
169    "TextEncoder",
170    "TextDecoder",
171    "URL",
172    "URLSearchParams",
173    "Response",
174    "Request",
175    "Headers",
176    "crypto",
177    "console",
178    "structuredClone",
179    "setTimeout",
180    "clearTimeout",
181    "queueMicrotask",
182    "atob",
183    "btoa",
184    "fetch",
185    "encodeURIComponent",
186    "decodeURIComponent",
187    "parseInt",
188    "parseFloat",
189    "isNaN",
190    "isFinite",
191    "AbortController",
192];
193
194/// Every name `program` uses, in type or value position, that it does not
195/// bind, sorted and deduplicated.
196pub fn unbound_names(program: &TsProgram) -> Vec<String> {
197    unbound_names_providing(program, |_| false)
198}
199
200/// [`unbound_names`] for a module whose imports `provided` knows: a name that
201/// `provided` accepts is never hidden by the global tables.
202///
203/// The global tables exist so that `Promise` or `URL`, which TypeScript and the
204/// Workers runtime provide, are not reported. They also hide a name the module
205/// imports that happens to share a global's name (a user type `Request` or
206/// `Response` of `bynk`, or a runtime export spelled like a global): the module
207/// uses its own import, not the global, and an import list derived from the
208/// tree has to see it. Emitted code spells every real global qualified
209/// (`globalThis.Promise`), so a bare use of such a name is a use of the import.
210/// `provided` answers for the names a caller can import: the runtime's exports
211/// when deriving a runtime header, the module's own imports when comparing.
212pub fn unbound_names_providing(
213    program: &TsProgram,
214    provided: impl Fn(&str) -> bool,
215) -> Vec<String> {
216    unbound_names_in(&program.stmts, provided)
217}
218
219/// [`unbound_names_providing`] over a module's statements as a slice, for a
220/// caller that holds them before it has a [`TsProgram`] (an emitter deriving a
221/// module's own header from the body it just built).
222pub fn unbound_names_in(stmts: &[TsStmt], provided: impl Fn(&str) -> bool) -> Vec<String> {
223    let mut w = Walk::default();
224    for s in stmts {
225        w.stmt(s);
226    }
227    let types = w
228        .used_types
229        .iter()
230        .filter(|n| !w.bound.contains(*n) && (provided(n) || !GLOBAL_TYPES.contains(&n.as_str())));
231    let values = w
232        .used_values
233        .iter()
234        .filter(|n| !w.bound.contains(*n) && (provided(n) || !GLOBAL_VALUES.contains(&n.as_str())));
235    // 1A.36a (Decision D): a name a `Raw` statement declares it uses may be a
236    // type or a value, so it is judged against both global tables.
237    let declared = w.used_declared.iter().filter(|n| {
238        !w.bound.contains(*n)
239            && (provided(n)
240                || (!GLOBAL_TYPES.contains(&n.as_str()) && !GLOBAL_VALUES.contains(&n.as_str())))
241    });
242    let all: BTreeSet<String> = types.chain(values).chain(declared).cloned().collect();
243    all.into_iter().collect()
244}
245
246/// 1A.39b (Decision D): every `TsExpr::Ident` of `program` that is not an identifier path
247/// (`[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*`) and every `TsBindingName::Ident` that is not an
248/// identifier, sorted and deduplicated. Such a text is expression text or a name built from it
249/// held in a variable-like node: it hides what it uses from [`unbound_names`] and from the
250/// printer's precedence. Member chains (`globalThis.Number`, `this.state`) pass: they print as
251/// they read and their head is what the closure sees.
252pub fn text_idents(program: &TsProgram) -> Vec<String> {
253    let mut w = Walk::default();
254    for s in &program.stmts {
255        w.stmt(s);
256    }
257    w.text_idents.into_iter().collect()
258}
259
260/// 1B.5e: the text of every opaque statement (`TsStmt::raw`, `raw_using`, a `Verbatim`) in
261/// `stmts`, **at any depth** — inside a function body, a `try`, a switch case or an object
262/// method, not only at the top level. A producer that reads a tree for the names it uses asks
263/// for this to check what the tree cannot see: a shallow `raw_text()` over the top-level
264/// statements alone misses a nested one.
265pub fn raw_statement_texts(stmts: &[TsStmt]) -> Vec<String> {
266    let mut w = Walk::default();
267    w.stmts(stmts);
268    w.raw_texts
269}
270
271/// #2045: each `(specifier, name)` a structured named import brings in as a
272/// value: every entry of an `import { … }` but its `type X` ones, none of an
273/// `import type { … }`. Namespace and opaque-text imports are not reported.
274pub fn value_imports(program: &TsProgram) -> Vec<(String, String)> {
275    let mut out = Vec::new();
276    for stmt in &program.stmts {
277        if let TsStmtKind::Decl(TsDecl::Import {
278            type_only: false,
279            names,
280            from,
281        }) = &stmt.kind
282        {
283            out.extend(
284                names
285                    .iter()
286                    .map(|n| n.trim())
287                    .filter(|n| !n.starts_with("type "))
288                    .map(|n| (from.clone(), n.to_string())),
289            );
290        }
291    }
292    out
293}
294
295/// #2045: every name `program` uses as a value that only a type-only import
296/// binds (`import { type Status }` then `Status.Active`): a `TS1361` (`cannot
297/// be used as a value because it was imported using 'import type'`). Opaque
298/// text is not searched for uses, as in [`unbound_names`].
299pub fn type_only_value_uses(program: &TsProgram) -> Vec<String> {
300    let mut w = Walk::default();
301    for s in &program.stmts {
302        w.stmt(s);
303    }
304    w.used_values
305        .iter()
306        .filter(|n| w.type_only.contains(*n) && !w.value_bound.contains(*n))
307        .cloned()
308        .collect()
309}
310
311/// #2036: a member a module names through one of its namespace imports:
312/// `handlers.Batch` in type position, `handlers.__deserialise_Batch(…)` in
313/// value position.
314#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
315pub struct NamespaceMemberUse {
316    /// The namespace import's specifier (`./handlers.js`).
317    pub from: String,
318    /// The member named (`Batch`).
319    pub member: String,
320}
321
322/// #2036: every member `program` names through a namespace import
323/// (`import * as ns`, `import type * as ns`), sorted and deduplicated. A
324/// member the target module does not export is a `TS2694`/`TS2339` that
325/// `tsc` would report (`Namespace 'handlers' has no exported member`), which
326/// [`unbound_names`] cannot see: the namespace itself is bound. Checking it
327/// needs the target module too, so a caller pairs this with
328/// [`module_exports`]. Opaque text is not searched for uses.
329pub fn namespace_member_uses(program: &TsProgram) -> Vec<NamespaceMemberUse> {
330    let mut w = Walk::default();
331    for s in &program.stmts {
332        w.stmt(s);
333    }
334    let uses: BTreeSet<NamespaceMemberUse> = w
335        .qualified
336        .iter()
337        .filter_map(|(head, member)| {
338            w.namespaces.get(head).map(|from| NamespaceMemberUse {
339                from: from.clone(),
340                member: member.clone(),
341            })
342        })
343        .collect();
344    uses.into_iter().collect()
345}
346
347/// #2036: what a module exports, for [`namespace_member_uses`]' members.
348#[derive(Debug, Default, Clone, PartialEq, Eq)]
349pub struct ModuleExports {
350    /// Every name exported directly or re-exported by name.
351    pub names: BTreeSet<String>,
352    /// The specifier of each `export * from "…"`, whose module's exports are
353    /// this one's too (a split context's `handlers.ts`, #1820).
354    pub star_from: Vec<String>,
355}
356
357/// #2036: the names `program` exports. Structured exports are read with
358/// [`TsStmt::exported_names`]; opaque text line by line, as [`unbound_names`]
359/// reads its declarations: a line starting `export` and then a declaration
360/// keyword or a `{ … }` list. Over-reporting an export can only hide a
361/// defect.
362pub fn module_exports(program: &TsProgram) -> ModuleExports {
363    let mut out = ModuleExports::default();
364    for stmt in &program.stmts {
365        match &stmt.kind {
366            TsStmtKind::Decl(TsDecl::ReExportAll { from }) => out.star_from.push(from.clone()),
367            TsStmtKind::Decl(_) => {
368                out.names
369                    .extend(stmt.exported_names().iter().map(|e| e.name.to_string()));
370            }
371            TsStmtKind::Raw(text, _) | TsStmtKind::Verbatim { text, .. } => {
372                opaque_exports(text, &mut out.names)
373            }
374            TsStmtKind::Const { .. }
375            | TsStmtKind::Let { .. }
376            | TsStmtKind::ExprStmt(_)
377            | TsStmtKind::Return(_)
378            | TsStmtKind::Throw(_)
379            | TsStmtKind::If { .. }
380            | TsStmtKind::ForOf { .. }
381            | TsStmtKind::For { .. }
382            | TsStmtKind::TryCatch { .. }
383            | TsStmtKind::Block(_)
384            | TsStmtKind::Continue(_)
385            | TsStmtKind::Break(_)
386            | TsStmtKind::While { .. }
387            | TsStmtKind::Labelled { .. }
388            | TsStmtKind::LetList(_)
389            | TsStmtKind::Assign { .. }
390            | TsStmtKind::Comment(_)
391            | TsStmtKind::DocComment(_)
392            | TsStmtKind::Blank
393            | TsStmtKind::Switch { .. }
394            | TsStmtKind::InlineBlock(_)
395            | TsStmtKind::Increment(_) => {}
396        }
397    }
398    out
399}
400
401/// The names opaque text exports, line by line (see [`module_exports`]).
402fn opaque_exports(text: &str, out: &mut BTreeSet<String>) {
403    for line in text.lines() {
404        let Some(rest) = line.trim_start().strip_prefix("export ") else {
405            continue;
406        };
407        let mut rest = rest.trim_start();
408        for prefix in ["declare ", "async "] {
409            rest = rest.strip_prefix(prefix).unwrap_or(rest).trim_start();
410        }
411        // `export type { A, B }` lists types, as `export { A, B }` lists names.
412        let list = rest
413            .strip_prefix("type ")
414            .map(str::trim_start)
415            .unwrap_or(rest)
416            .strip_prefix('{');
417        if let Some(list) = list {
418            let inner = list.split('}').next().unwrap_or("");
419            for spec in inner.split(',') {
420                let spec = spec.trim();
421                let spec = spec.strip_prefix("type ").unwrap_or(spec).trim();
422                if let Some(name) = leading_ident(spec.rsplit(" as ").next().unwrap_or(spec)) {
423                    out.insert(name.to_string());
424                }
425            }
426            continue;
427        }
428        for keyword in [
429            "function ",
430            "const ",
431            "let ",
432            "var ",
433            "class ",
434            "interface ",
435            "type ",
436            "enum ",
437        ] {
438            if let Some(after) = rest.strip_prefix(keyword)
439                && let Some(name) = leading_ident(after)
440            {
441                out.insert(name.to_string());
442            }
443        }
444    }
445}
446
447#[derive(Default)]
448struct Walk {
449    bound: BTreeSet<String>,
450    used_types: BTreeSet<String>,
451    used_values: BTreeSet<String>,
452    /// 1A.36a (Decision D): names a `TsStmt::raw_using` statement declares its
453    /// fixed text uses, in either position.
454    used_declared: BTreeSet<String>,
455    /// 1A.36a: type parameters and mapped-type keys currently in scope. Each is
456    /// bound only inside its own node (see [`Walk::scoped`]), so a use of the
457    /// name outside it is still a use of something else.
458    scope: Vec<String>,
459    /// #2036: each namespace import's alias and specifier.
460    namespaces: BTreeMap<String, String>,
461    /// #2036: every `head.member` named in type or value position.
462    qualified: BTreeSet<(String, String)>,
463    /// #2045: names bound only by a type-only import (`import { type X }`,
464    /// `import type { X }`, `import type * as ns`), and the names bound any
465    /// other way. A value use of the first and not the second is `TS1361`.
466    type_only: BTreeSet<String>,
467    value_bound: BTreeSet<String>,
468    /// 1B.5e: the text of every `Raw` or `Verbatim` statement met, at any depth, for
469    /// [`raw_statement_texts`].
470    raw_texts: Vec<String>,
471    /// 1A.39b (Decision D): each `TsExpr::Ident` or `TsBindingName::Ident` text that is not an
472    /// identifier path (see [`text_idents`]).
473    text_idents: BTreeSet<String>,
474}
475
476/// Whether `text` is an identifier (`[A-Za-z_$][\w$]*`).
477fn is_identifier(text: &str) -> bool {
478    let mut chars = text.chars();
479    chars
480        .next()
481        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
482        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
483}
484
485/// Whether `text` is an identifier path: identifiers joined by single dots (`this.state`,
486/// `globalThis.Number`).
487pub(crate) fn is_identifier_path(text: &str) -> bool {
488    text.split('.').all(is_identifier)
489}
490
491/// The identifier a piece of text starts with: `value` of `value.name`,
492/// `path` of `path: string = "$"`. `None` when the text does not start with
493/// one (a literal, a parenthesised expression).
494fn leading_ident(text: &str) -> Option<&str> {
495    let text = text.trim_start();
496    let end = text
497        .char_indices()
498        .find(|(_, c)| !(c.is_alphanumeric() || *c == '_' || *c == '$'))
499        .map_or(text.len(), |(i, _)| i);
500    let ident = &text[..end];
501    ident
502        .chars()
503        .next()
504        .filter(|c| c.is_alphabetic() || *c == '_' || *c == '$')
505        .map(|_| ident)
506}
507
508impl Walk {
509    /// Bind a declared name. A destructuring pattern (`[k, v]`, `{ a, b: c }`)
510    /// binds every identifier in it; over-binding can only hide a defect.
511    fn bind(&mut self, name: &str) {
512        let name = name.trim_start();
513        if name.starts_with('[') || name.starts_with('{') {
514            for word in name.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$')) {
515                if let Some(ident) = leading_ident(word) {
516                    self.bound.insert(ident.to_string());
517                    self.value_bound.insert(ident.to_string());
518                }
519            }
520        } else if let Some(ident) = leading_ident(name) {
521            self.bound.insert(ident.to_string());
522            self.value_bound.insert(ident.to_string());
523        }
524    }
525
526    /// #2045: bind a name a type-only import brings in.
527    fn bind_type_only(&mut self, name: &str) {
528        if let Some(ident) = leading_ident(name) {
529            self.bound.insert(ident.to_string());
530            self.type_only.insert(ident.to_string());
531        }
532    }
533
534    /// A destructuring pattern's names: `a`, `a: b` (binds `b`), `a = 1`.
535    fn bind_pattern(&mut self, names: &[String]) {
536        for n in names {
537            let local = n.split('=').next().unwrap_or(n);
538            let local = local.rsplit(':').next().unwrap_or(local);
539            self.bind(local);
540        }
541    }
542
543    fn binding(&mut self, name: &TsBindingName) {
544        match name {
545            TsBindingName::Ident(n) => {
546                if !is_identifier(n) {
547                    self.text_idents.insert(n.clone());
548                }
549                self.bind(n)
550            }
551            TsBindingName::ObjectPattern(names) => self.bind_pattern(names),
552            TsBindingName::ArrayPattern(names) => {
553                for n in names.iter().filter(|n| !n.is_empty()) {
554                    self.bind(n);
555                }
556            }
557        }
558    }
559
560    fn use_value(&mut self, text: &str) {
561        // A pre-rendered construction (`new globalThis.Map<K, V>()`, a state
562        // initialiser) uses the constructor, not the `new` keyword.
563        let text = text.trim_start();
564        let text = text.strip_prefix("new ").unwrap_or(text);
565        if let Some(ident) = leading_ident(text).filter(|i| !self.in_scope(i)) {
566            self.used_values.insert(ident.to_string());
567        }
568    }
569
570    /// Whether `name` is a type parameter or mapped key of an enclosing node.
571    fn in_scope(&self, name: &str) -> bool {
572        self.scope.iter().any(|n| n == name)
573    }
574
575    /// Run `f` with `names` (type parameters, a mapped key) bound for the
576    /// duration of one node only. They never reach the flat `bound` and
577    /// `value_bound` sets, so they bind nothing outside the node.
578    ///
579    /// A type parameter may be written with its constraint and default
580    /// (`T extends Shape = Circle`): the text after the name uses types, which
581    /// can name the parameters of the same list (1A.36b-1).
582    fn scoped(&mut self, names: &[String], f: impl FnOnce(&mut Self)) {
583        let depth = self.scope.len();
584        for n in names {
585            if let Some(ident) = leading_ident(n) {
586                self.scope.push(ident.to_string());
587            }
588        }
589        for n in names {
590            if let Some(ident) = leading_ident(n) {
591                self.use_type_text(&n.trim_start()[ident.len()..]);
592            }
593        }
594        f(self);
595        self.scope.truncate(depth);
596    }
597
598    /// The names a type written as text uses: every identifier that starts with
599    /// an upper-case letter or `_`, outside string literals and not a member
600    /// (`.name`) or a key (`name:`, `name?:`). A qualified head (`ns.T`) is the
601    /// use of a namespace and records the member, as for a structured name.
602    /// Lower-case words are keywords, primitives and parameters (a `typeof`
603    /// operand is a use of the value it names), none of them an import of a generated module.
604    fn use_type_text(&mut self, text: &str) {
605        let bytes = text.as_bytes();
606        let ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$';
607        // A mapped key (`[S in keyof T]`) and an `infer X` binder are bound by the
608        // text itself, wherever the text spells them.
609        let words: Vec<&str> = text
610            .split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
611            .filter(|w| !w.is_empty())
612            .collect();
613        let local: Vec<&str> = words
614            .windows(2)
615            .filter(|w| w[1] == "in" || w[0] == "infer")
616            .map(|w| if w[0] == "infer" { w[1] } else { w[0] })
617            .collect();
618        // The unmatched `{`, `(` and `[` before the cursor: a word followed by `:`
619        // is an object key only when the nearest of them is `{`. Elsewhere the
620        // colon belongs to a conditional type (`A extends B ? C : D`), a
621        // parameter or a tuple label.
622        let mut openers: Vec<u8> = Vec::new();
623        let mut i = 0;
624        while i < bytes.len() {
625            let b = bytes[i];
626            match b {
627                b'"' | b'\'' | b'`' => {
628                    i += 1;
629                    while i < bytes.len() && bytes[i] != b {
630                        i += if bytes[i] == b'\\' { 2 } else { 1 };
631                    }
632                    i += 1;
633                }
634                _ if ident(b) => {
635                    let start = i;
636                    while i < bytes.len() && ident(bytes[i]) {
637                        i += 1;
638                    }
639                    let word = &text[start..i];
640                    // `typeof x` uses the value `x` (a namespace, for
641                    // `typeof ns.__makeSurface`), never a type.
642                    if word == "typeof" {
643                        let operand = text[i..].trim_start();
644                        // `typeof import("./x")` names a module, not a value: `import`
645                        // is the keyword, so nothing is recorded.
646                        if let Some(name) = leading_ident(operand).filter(|n| *n != "import") {
647                            if !self.in_scope(name) {
648                                self.used_values.insert(name.to_string());
649                                if let Some(member) = operand[name.len()..]
650                                    .strip_prefix('.')
651                                    .and_then(leading_ident)
652                                {
653                                    self.qualified
654                                        .insert((name.to_string(), member.to_string()));
655                                }
656                            }
657                            i = text.len() - operand.len() + name.len();
658                        }
659                        continue;
660                    }
661                    let after_dot = start > 0 && bytes[start - 1] == b'.';
662                    let rest = text[i..].trim_start();
663                    let after_question = text[..start].trim_end().ends_with('?');
664                    let is_key = openers.last() == Some(&b'{')
665                        && !after_question
666                        && (rest.starts_with(':') || rest.starts_with("?:"));
667                    if after_dot || is_key || !(b.is_ascii_uppercase() || b == b'_') {
668                        continue;
669                    }
670                    if self.in_scope(word) || local.contains(&word) {
671                        continue;
672                    }
673                    self.used_types.insert(word.to_string());
674                    if let Some(member) = text[i..].strip_prefix('.').and_then(leading_ident) {
675                        self.qualified
676                            .insert((word.to_string(), member.to_string()));
677                    }
678                }
679                b'{' | b'(' | b'[' => {
680                    openers.push(b);
681                    i += 1;
682                }
683                b'}' | b')' | b']' => {
684                    openers.pop();
685                    i += 1;
686                }
687                _ => i += 1,
688            }
689        }
690    }
691
692    /// An import specifier: `X`, `type X`, `X as Y` or `type X as Y` binds
693    /// the local name.
694    fn bind_specifier(&mut self, spec: &str, decl_type_only: bool) {
695        let spec = spec.trim();
696        let (spec, type_only) = match spec.strip_prefix("type ") {
697            Some(rest) => (rest.trim(), true),
698            None => (spec, decl_type_only),
699        };
700        let local = spec.rsplit(" as ").next().unwrap_or(spec).trim();
701        if local.is_empty() {
702            return;
703        }
704        if type_only {
705            self.bind_type_only(local);
706        } else {
707            self.bind(local);
708        }
709    }
710
711    /// Lexical scan of opaque text for the names it declares or imports,
712    /// line by line: only a line that *starts* a declaration (`type`,
713    /// `interface`, `class`, `enum`, `function`, after any `export`/`declare`/
714    /// `default`/`async`) or an `import` counts, so a cast like `x as T` in a
715    /// function body is never mistaken for an import alias.
716    fn bind_opaque(&mut self, text: &str) {
717        for line in text.lines() {
718            let mut rest = line.trim_start();
719            for prefix in ["export ", "declare ", "default ", "async "] {
720                rest = rest.strip_prefix(prefix).unwrap_or(rest).trim_start();
721            }
722            if let Some(import) = rest.strip_prefix("import ") {
723                let head = import.split(" from ").next().unwrap_or("");
724                let braces = head
725                    .find('{')
726                    .and_then(|open| head[open..].find('}').map(|close| (open, open + close)));
727                if let Some((open, close)) = braces {
728                    for spec in head[open + 1..close].split(',') {
729                        self.bind_specifier(spec, false);
730                    }
731                } else if let Some(alias) = head.trim().strip_prefix("* as ") {
732                    self.bind(alias.trim());
733                }
734                continue;
735            }
736            for keyword in [
737                "type ",
738                "interface ",
739                "class ",
740                "enum ",
741                "function ",
742                "const ",
743                "let ",
744                "var ",
745            ] {
746                if let Some(after) = rest.strip_prefix(keyword) {
747                    let after = after.trim_start();
748                    if let Some(pattern) = after.strip_prefix('{') {
749                        let inner = pattern.split('}').next().unwrap_or("");
750                        let names: Vec<String> = inner.split(',').map(str::to_string).collect();
751                        self.bind_pattern(&names);
752                    } else {
753                        self.bind(after);
754                    }
755                }
756            }
757        }
758    }
759
760    /// Opaque text: the names it declares or imports, and the generic types
761    /// it applies.
762    fn opaque(&mut self, text: &str) {
763        self.bind_opaque(text);
764        self.use_opaque_generics(text);
765    }
766
767    /// #1977: the one *use* of a name opaque text is checked for — a generic
768    /// type application, a capitalised identifier immediately followed by `<`
769    /// (`MapEntry<string, number>` in a kernel helper's parameter types). That
770    /// shape is a type in every position the emitter writes it, and it never
771    /// collides with a comparison (`a < b` is spaced, its operands lower-case).
772    /// An identifier after a `.` is a member or the tail of a qualified or
773    /// inline-import spelling (`globalThis.Promise<T>`, `import("./m").T<U>`),
774    /// whose head, if any, is not this identifier; text inside string,
775    /// template and comment literals is skipped. Wider checks of opaque text
776    /// (an annotation `x: T`, a bare value use) collide with object keys,
777    /// locals and ternaries, so they stay `tsc`'s job.
778    fn use_opaque_generics(&mut self, text: &str) {
779        let bytes = text.as_bytes();
780        let ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$';
781        let mut i = 0;
782        while i < bytes.len() {
783            let b = bytes[i];
784            match b {
785                b'"' | b'\'' | b'`' => {
786                    i += 1;
787                    while i < bytes.len() && bytes[i] != b {
788                        i += if bytes[i] == b'\\' { 2 } else { 1 };
789                    }
790                    i += 1;
791                }
792                b'/' if bytes.get(i + 1) == Some(&b'/') => {
793                    while i < bytes.len() && bytes[i] != b'\n' {
794                        i += 1;
795                    }
796                }
797                b'/' if bytes.get(i + 1) == Some(&b'*') => {
798                    i += 2;
799                    while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
800                        i += 1;
801                    }
802                    i += 2;
803                }
804                _ if ident(b) => {
805                    let start = i;
806                    while i < bytes.len() && ident(bytes[i]) {
807                        i += 1;
808                    }
809                    let after_dot = start > 0 && bytes[start - 1] == b'.';
810                    if !after_dot
811                        && b.is_ascii_uppercase()
812                        && bytes.get(i) == Some(&b'<')
813                        && !self.in_scope(&text[start..i])
814                    {
815                        self.used_types.insert(text[start..i].to_string());
816                    }
817                }
818                _ => i += 1,
819            }
820        }
821    }
822
823    fn ty(&mut self, t: &TsType) {
824        match t {
825            TsType::Named { name, type_args } => {
826                let mut segments = name.splitn(2, '.');
827                let head = segments.next().unwrap_or(name).trim();
828                // A name may carry its arguments as text (`ns.T<number>`).
829                if let Some(member) = segments.next().and_then(leading_ident) {
830                    self.qualified
831                        .insert((head.to_string(), member.to_string()));
832                }
833                if head
834                    .chars()
835                    .next()
836                    .is_some_and(|c| c.is_alphabetic() || c == '_' || c == '$')
837                    && head
838                        .chars()
839                        .all(|c| c.is_alphanumeric() || c == '_' || c == '$')
840                    && !self.in_scope(head)
841                {
842                    self.used_types.insert(head.to_string());
843                }
844                for a in type_args {
845                    self.ty(a);
846                }
847                // A name that is more than an identifier carries a type as
848                // text: `Option<A>`, `Result<T, __BoundaryError>`, a union
849                // `A | B`, a function type. Its arguments and members use names
850                // too (1A.36b-1).
851                if name
852                    .chars()
853                    .any(|c| !(c.is_alphanumeric() || matches!(c, '_' | '$' | '.')))
854                {
855                    self.use_type_text(name);
856                }
857            }
858            TsType::Array { element, .. } => self.ty(element),
859            TsType::Object(members) => self.members(members),
860            TsType::Fn { params, ret, .. } => {
861                for p in params {
862                    self.ty(p);
863                }
864                self.ty(ret);
865            }
866            TsType::Union { members, .. } => {
867                for m in members {
868                    self.ty(m);
869                }
870            }
871            TsType::Intersection(members) => {
872                for m in members {
873                    self.ty(m);
874                }
875            }
876            // The key is the type's own binding, for its value.
877            TsType::Mapped {
878                key,
879                keys_of,
880                value,
881                ..
882            } => {
883                self.ty(keys_of);
884                self.scoped(std::slice::from_ref(key), |w| w.ty(value));
885            }
886            // `typeof x` uses the value `x`.
887            TsType::TypeOf(operand) => self.expr(operand),
888            TsType::Indexed { object, index } => {
889                self.ty(object);
890                self.ty(index);
891            }
892            TsType::StringLiteral(_) | TsType::NumberLiteral(_) => {}
893            TsType::Paren(inner) => self.ty(inner),
894        }
895    }
896
897    fn members(&mut self, members: &[TsTypeMember]) {
898        for m in members {
899            match m {
900                TsTypeMember::Prop { ty, .. } => self.ty(ty),
901                TsTypeMember::Method {
902                    generics,
903                    params,
904                    ret,
905                    ..
906                } => {
907                    self.scoped(generics, |w| {
908                        w.params(params);
909                        w.ty(ret);
910                    });
911                }
912                TsTypeMember::Index {
913                    key_ty, value_ty, ..
914                } => {
915                    self.ty(key_ty);
916                    self.ty(value_ty);
917                }
918            }
919        }
920    }
921
922    fn params(&mut self, params: &[TsParam]) {
923        for p in params {
924            match &p.array_pattern {
925                Some(names) => {
926                    for n in names.iter().filter(|n| !n.is_empty()) {
927                        self.bind(n);
928                    }
929                }
930                None => self.bind(&p.name),
931            }
932            if let Some(t) = &p.ty {
933                self.ty(t);
934            }
935            if let Some(d) = &p.default {
936                self.expr(d);
937            }
938        }
939    }
940
941    fn opt_ty(&mut self, t: &Option<TsType>) {
942        if let Some(t) = t {
943            self.ty(t);
944        }
945    }
946
947    fn stmts(&mut self, stmts: &[TsStmt]) {
948        for s in stmts {
949            self.stmt(s);
950        }
951    }
952
953    fn stmt(&mut self, stmt: &TsStmt) {
954        match &stmt.kind {
955            TsStmtKind::Verbatim { text, .. } => {
956                self.raw_texts.push(text.clone());
957                self.opaque(text)
958            }
959            TsStmtKind::Raw(text, uses) => {
960                self.raw_texts.push(text.clone());
961                self.opaque(text);
962                for n in uses {
963                    if !self.in_scope(n) {
964                        self.used_declared.insert(n.clone());
965                    }
966                }
967            }
968            TsStmtKind::Decl(decl) => self.decl(decl),
969            TsStmtKind::Const { name, ty, init } => {
970                self.binding(name);
971                self.opt_ty(ty);
972                self.expr(init);
973            }
974            TsStmtKind::Let { name, ty, init, .. } => {
975                self.binding(name);
976                self.opt_ty(ty);
977                if let Some(e) = init {
978                    self.expr(e);
979                }
980            }
981            TsStmtKind::ExprStmt(e) | TsStmtKind::Throw(e) | TsStmtKind::Increment(e) => {
982                self.expr(e)
983            }
984            TsStmtKind::Return(e) => {
985                if let Some(e) = e {
986                    self.expr(e);
987                }
988            }
989            TsStmtKind::If {
990                cond,
991                then_branch,
992                else_branch,
993                same_line_else: _,
994            } => {
995                self.expr(cond);
996                self.stmt(then_branch);
997                if let Some(e) = else_branch {
998                    self.stmt(e);
999                }
1000            }
1001            TsStmtKind::ForOf {
1002                binding,
1003                iter,
1004                body,
1005                is_await: _,
1006            } => {
1007                self.bind(binding);
1008                self.expr(iter);
1009                self.stmt(body);
1010            }
1011            TsStmtKind::While { cond, body } => {
1012                self.expr(cond);
1013                self.stmt(body);
1014            }
1015            TsStmtKind::Labelled { label: _, body } => self.stmt(body),
1016            TsStmtKind::LetList(decls) => {
1017                for d in decls {
1018                    self.bind(&d.name);
1019                    self.opt_ty(&d.ty);
1020                    if let Some(e) = &d.init {
1021                        self.expr(e);
1022                    }
1023                }
1024            }
1025            TsStmtKind::For {
1026                name,
1027                init,
1028                test,
1029                body,
1030            } => {
1031                self.bind(name);
1032                self.expr(init);
1033                self.expr(test);
1034                self.stmt(body);
1035            }
1036            TsStmtKind::TryCatch {
1037                try_block,
1038                catch_param,
1039                catch_block,
1040                finally_block,
1041            } => {
1042                if let Some(p) = catch_param {
1043                    self.bind(p);
1044                }
1045                self.stmt(try_block);
1046                if let Some(c) = catch_block {
1047                    self.stmt(c);
1048                }
1049                if let Some(f) = finally_block {
1050                    self.stmt(f);
1051                }
1052            }
1053            TsStmtKind::Block(stmts) | TsStmtKind::InlineBlock(stmts) => self.stmts(stmts),
1054            TsStmtKind::Assign { target, value } => {
1055                self.expr(target);
1056                self.expr(value);
1057            }
1058            TsStmtKind::Switch {
1059                discriminant,
1060                cases,
1061            } => {
1062                self.expr(discriminant);
1063                for case in cases {
1064                    for t in &case.labels {
1065                        self.expr(t);
1066                    }
1067                    self.stmts(&case.body);
1068                }
1069            }
1070            TsStmtKind::Continue(_)
1071            | TsStmtKind::Break(_)
1072            | TsStmtKind::Comment(_)
1073            | TsStmtKind::DocComment(_)
1074            | TsStmtKind::Blank => {}
1075        }
1076    }
1077
1078    fn decl(&mut self, decl: &TsDecl) {
1079        match decl {
1080            TsDecl::Import {
1081                names, type_only, ..
1082            } => {
1083                for n in names {
1084                    self.bind_specifier(n, *type_only);
1085                }
1086            }
1087            TsDecl::ImportNamespace {
1088                alias,
1089                from,
1090                type_only,
1091            } => {
1092                self.namespaces.insert(alias.clone(), from.clone());
1093                if *type_only {
1094                    self.bind_type_only(alias)
1095                } else {
1096                    self.bind(alias)
1097                }
1098            }
1099            TsDecl::ImportDefault { alias, named, .. } => {
1100                self.bind(alias);
1101                for n in named {
1102                    self.bind_specifier(n, false);
1103                }
1104            }
1105            TsDecl::ReExport { .. } | TsDecl::ReExportAll { .. } => {}
1106            // `export { a, b };` exports names this module binds (#1852),
1107            // so each is a use: one never imported or declared is unbound.
1108            // A `type X` entry (#2036) uses `X`, and `X as Y` uses `X`.
1109            TsDecl::ExportNames { names } => {
1110                for n in names {
1111                    let n = n.trim();
1112                    match n.strip_prefix("type ") {
1113                        Some(t) => {
1114                            if let Some(ident) = leading_ident(t).filter(|i| !self.in_scope(i)) {
1115                                self.used_types.insert(ident.to_string());
1116                            }
1117                        }
1118                        None => self.use_value(n),
1119                    }
1120                }
1121            }
1122            TsDecl::Export(inner) => self.decl(inner),
1123            TsDecl::Interface {
1124                name,
1125                type_params,
1126                members,
1127            } => {
1128                self.bind(name);
1129                self.scoped(type_params, |w| w.members(members));
1130            }
1131            TsDecl::TypeAlias {
1132                name,
1133                type_params,
1134                ty,
1135            } => {
1136                self.bind(name);
1137                self.scoped(type_params, |w| w.ty(ty));
1138            }
1139            TsDecl::ConstDecl { name, ty, init } => {
1140                self.bind(name);
1141                self.opt_ty(ty);
1142                self.expr(init);
1143            }
1144            TsDecl::DeclareConst { name, ty } => {
1145                self.bind(name);
1146                self.ty(ty);
1147            }
1148            TsDecl::Class {
1149                name,
1150                implements,
1151                fields,
1152                constructor,
1153                methods,
1154                ..
1155            } => {
1156                self.bind(name);
1157                for ty in implements {
1158                    self.ty(ty);
1159                }
1160                for f in fields {
1161                    self.opt_ty(&f.ty);
1162                    if let Some(init) = &f.init {
1163                        self.expr(init);
1164                    }
1165                }
1166                if let Some(ctor) = constructor {
1167                    self.params(&ctor.params);
1168                    self.stmts(&ctor.body);
1169                }
1170                for m in methods {
1171                    self.params(&m.params);
1172                    self.opt_ty(&m.return_type);
1173                    self.stmts(&m.body);
1174                }
1175            }
1176            TsDecl::Function {
1177                name,
1178                generics,
1179                params,
1180                return_type,
1181                body,
1182                ..
1183            } => {
1184                self.bind(name);
1185                self.scoped(generics, |w| {
1186                    w.params(params);
1187                    w.opt_ty(return_type);
1188                    w.stmts(body);
1189                });
1190            }
1191            TsDecl::ExportDefault(e) => self.expr(e),
1192        }
1193    }
1194
1195    fn expr(&mut self, expr: &TsExpr) {
1196        match expr {
1197            TsExpr::Ident(name) => {
1198                if !is_identifier_path(name) {
1199                    self.text_idents.insert(name.clone());
1200                }
1201                self.use_value(name)
1202            }
1203            TsExpr::Lit(_) => {}
1204            TsExpr::VerbatimExpr(text, _) => self.opaque(text),
1205            // Text the emitter printed from nodes, with the names it uses declared
1206            // beside it (1A.36b-1): counted as `raw_using`'s are.
1207            TsExpr::RawUsing(_, names) => {
1208                self.used_declared.extend(names.iter().cloned());
1209            }
1210            TsExpr::Member { object, property } | TsExpr::OptionalMember { object, property } => {
1211                if let TsExpr::Ident(head) = object.as_ref() {
1212                    self.qualified.insert((head.clone(), property.clone()));
1213                }
1214                self.expr(object)
1215            }
1216            TsExpr::Index { object, index } | TsExpr::OptionalIndex { object, index } => {
1217                self.expr(object);
1218                self.expr(index);
1219            }
1220            TsExpr::Arrow {
1221                params,
1222                generics,
1223                return_type,
1224                body,
1225                ..
1226            } => {
1227                self.scoped(generics, |w| {
1228                    w.params(params);
1229                    w.opt_ty(return_type);
1230                    match body.as_ref() {
1231                        TsArrowBody::Expr(e) => w.expr(e),
1232                        TsArrowBody::Block(stmts)
1233                        | TsArrowBody::Multiline(stmts)
1234                        | TsArrowBody::Flat(stmts) => w.stmts(stmts),
1235                    }
1236                });
1237            }
1238            // 1A.21: the default is read in the enclosing scope; the parameter is bound for the body.
1239            TsExpr::DefaultIife {
1240                name,
1241                default,
1242                return_type,
1243                body,
1244            } => {
1245                self.expr(default);
1246                self.bind(name);
1247                self.ty(return_type);
1248                self.stmts(body);
1249            }
1250            TsExpr::Call { callee, args } | TsExpr::New { callee, args } => {
1251                self.expr(callee);
1252                for a in args {
1253                    self.expr(a);
1254                }
1255            }
1256            // 1A.20: the names the type arguments mention are uses, as for `As`.
1257            TsExpr::TypeApp { callee, type_args } => {
1258                self.expr(callee);
1259                for t in type_args {
1260                    self.ty(t);
1261                }
1262            }
1263            TsExpr::Object { entries, .. } => {
1264                for e in entries {
1265                    match e {
1266                        TsObjectEntry::Prop { value: v, .. } | TsObjectEntry::Spread(v) => {
1267                            self.expr(v)
1268                        }
1269                        TsObjectEntry::Shorthand(name) => self.use_value(name),
1270                        TsObjectEntry::Method {
1271                            generics,
1272                            params,
1273                            return_type,
1274                            body,
1275                            ..
1276                        } => {
1277                            self.scoped(generics, |w| {
1278                                w.params(params);
1279                                w.opt_ty(return_type);
1280                                w.stmts(body);
1281                            });
1282                        }
1283                    }
1284                }
1285            }
1286            TsExpr::Array { items, .. } | TsExpr::LinesArray(items) => {
1287                for i in items {
1288                    self.expr(i);
1289                }
1290            }
1291            TsExpr::TemplateLit { exprs, .. } => {
1292                for e in exprs {
1293                    self.expr(e);
1294                }
1295            }
1296            TsExpr::Await(e)
1297            | TsExpr::Paren(e)
1298            | TsExpr::Spread(e)
1299            | TsExpr::NonNull(e)
1300            | TsExpr::Yield(e)
1301            | TsExpr::Unary { expr: e, .. } => self.expr(e),
1302            TsExpr::Sequence(items) => {
1303                for i in items {
1304                    self.expr(i);
1305                }
1306            }
1307            TsExpr::OptionalCall { callee, args } => {
1308                self.expr(callee);
1309                for a in args {
1310                    self.expr(a);
1311                }
1312            }
1313            TsExpr::Function {
1314                params,
1315                return_type,
1316                body,
1317                ..
1318            } => {
1319                self.params(params);
1320                self.opt_ty(return_type);
1321                self.stmts(body);
1322            }
1323            TsExpr::As { expr, ty } => {
1324                self.expr(expr);
1325                self.ty(ty);
1326            }
1327            TsExpr::AsConst(expr) => self.expr(expr),
1328            TsExpr::Assign { target, value }
1329            | TsExpr::AddAssign { target, value }
1330            | TsExpr::NullishAssign { target, value } => {
1331                self.expr(target);
1332                self.expr(value);
1333            }
1334            TsExpr::Binary { left, right, .. } => {
1335                self.expr(left);
1336                self.expr(right);
1337            }
1338            TsExpr::Conditional {
1339                test,
1340                consequent,
1341                alternate,
1342            }
1343            | TsExpr::MultilineConditional {
1344                test,
1345                consequent,
1346                alternate,
1347            } => {
1348                self.expr(test);
1349                self.expr(consequent);
1350                self.expr(alternate);
1351            }
1352        }
1353    }
1354}
1355
1356#[cfg(test)]
1357mod tests {
1358    use super::*;
1359    use crate::program::{TsArrowBody, TsDeclarator, VerbatimOrigin};
1360
1361    fn program(stmts: Vec<TsStmt>) -> TsProgram {
1362        TsProgram { stmts }
1363    }
1364
1365    fn import(names: &[&str]) -> TsStmt {
1366        TsStmt::decl(
1367            TsDecl::Import {
1368                type_only: false,
1369                names: names.iter().map(|n| n.to_string()).collect(),
1370                from: "./m.js".to_string(),
1371            },
1372            None,
1373        )
1374    }
1375
1376    /// `export function <name>(value: <param_ty>): __JsonValue { return <call>(value); }`
1377    fn codec(name: &str, param_ty: &str, call: &str) -> TsStmt {
1378        TsStmt::decl(
1379            TsDecl::Export(Box::new(TsDecl::Function {
1380                name: name.to_string(),
1381                generics: vec![],
1382                params: vec![TsParam::new(
1383                    "value".to_string(),
1384                    Some(TsType::named(param_ty)),
1385                )],
1386                return_type: Some(TsType::named("__JsonValue")),
1387                body: vec![TsStmt::return_stmt(
1388                    Some(TsExpr::Call {
1389                        callee: Box::new(TsExpr::Ident(call.to_string())),
1390                        args: vec![TsExpr::Ident("value".to_string())],
1391                    }),
1392                    None,
1393                )],
1394                is_async: false,
1395                inline: false,
1396            })),
1397            None,
1398        )
1399    }
1400
1401    #[test]
1402    fn a_type_named_but_never_imported_is_unbound() {
1403        // #1829's shape: a codec's parameter type the module never imports.
1404        let p = program(vec![
1405            import(&["type __JsonValue", "__serialise_Name"]),
1406            codec("__serialise_Note", "Note", "__serialise_Name"),
1407        ]);
1408        assert_eq!(unbound_names(&p), ["Note"]);
1409    }
1410
1411    /// A function over `s` whose parameter type is `ty` and whose body does nothing.
1412    fn function_over(ty: TsType) -> TsStmt {
1413        TsStmt::decl(
1414            TsDecl::Function {
1415                name: "f".to_string(),
1416                generics: vec![],
1417                params: vec![TsParam::new("s".to_string(), Some(ty))],
1418                return_type: None,
1419                body: vec![],
1420                is_async: false,
1421                inline: false,
1422            },
1423            None,
1424        )
1425    }
1426
1427    #[test]
1428    fn typeof_in_a_type_uses_the_value_it_names() {
1429        // `typeof s` names the parameter, so it is bound there and unbound outside.
1430        let p = program(vec![function_over(TsType::type_of(TsExpr::Ident(
1431            "s".to_string(),
1432        )))]);
1433        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1434        let p = program(vec![TsStmt::decl(
1435            TsDecl::TypeAlias {
1436                name: "T".to_string(),
1437                type_params: vec![],
1438                ty: TsType::type_of(TsExpr::Ident("missing".to_string())),
1439            },
1440            None,
1441        )]);
1442        assert_eq!(unbound_names(&p), ["missing"]);
1443        // The same operand inside type text: a namespace spelled only there.
1444        let over = |name: &str| program(vec![function_over(TsType::named(name))]);
1445        assert_eq!(
1446            unbound_names(&over(
1447                "globalThis.ReturnType<typeof commerce_payment.__makeSurface>"
1448            )),
1449            ["commerce_payment"]
1450        );
1451        let bound = program(vec![
1452            import(&["commerce_payment"]),
1453            function_over(TsType::named("Array<typeof commerce_payment.f>")),
1454        ]);
1455        assert!(unbound_names(&bound).is_empty());
1456    }
1457
1458    #[test]
1459    fn typeof_import_records_no_used_name() {
1460        // `import` after `typeof` is the keyword of an import type, not a value.
1461        let p = program(vec![function_over(TsType::named("typeof import(\"./x\")"))]);
1462        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1463    }
1464
1465    #[test]
1466    fn a_capitalised_tuple_label_or_parameter_name_reads_as_a_use() {
1467        // Pinned, conservative behaviour: `[First: A]` and `(Req: X) => Y` read `First` and
1468        // `Req` as uses, because only `{`-keys are recognised as labels. Over-reporting an
1469        // unbound name is the safe direction; a lower-case label is already ignored.
1470        let over = |name: &str| program(vec![function_over(TsType::named(name))]);
1471        assert_eq!(unbound_names(&over("[First: A]")), ["A", "First"]);
1472        assert_eq!(unbound_names(&over("(Req: X) => Y")), ["Req", "X", "Y"]);
1473    }
1474
1475    #[test]
1476    fn a_mapped_type_binds_its_key_and_uses_the_names_it_mentions() {
1477        let mapped = |source: &str| {
1478            TsType::mapped(
1479                "K",
1480                TsType::named(source),
1481                TsType::indexed(TsType::named(source), TsType::named("K")),
1482            )
1483        };
1484        // `K` is the mapped type's own, so only the source counts as a use.
1485        let p = program(vec![function_over(mapped("Shape"))]);
1486        assert_eq!(unbound_names(&p), ["Shape"]);
1487        let p = program(vec![
1488            import(&["type Shape"]),
1489            function_over(mapped("Shape")),
1490        ]);
1491        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1492    }
1493
1494    /// `type <name><params> = <ty>;`, exported nowhere: a declaration that binds only its own name.
1495    fn alias(name: &str, type_params: &[&str], ty: TsType) -> TsStmt {
1496        TsStmt::decl(
1497            TsDecl::TypeAlias {
1498                name: name.to_string(),
1499                type_params: type_params.iter().map(|p| p.to_string()).collect(),
1500                ty,
1501            },
1502            None,
1503        )
1504    }
1505
1506    /// 1A.36a: a mapped key is bound inside its own type and nowhere else. It used to enter
1507    /// the flat bound sets, so one mapped `K` made every `K` in the module, type or value,
1508    /// look bound.
1509    #[test]
1510    fn a_mapped_key_binds_only_inside_its_own_type() {
1511        let mapped = TsType::mapped(
1512            "K",
1513            TsType::named("Shape"),
1514            TsType::indexed(TsType::named("Shape"), TsType::named("K")),
1515        );
1516        let program_with = |outside: TsStmt| {
1517            program(vec![
1518                import(&["type Shape"]),
1519                alias("Mapped", &[], mapped.clone()),
1520                outside,
1521            ])
1522        };
1523        // Alone, the mapped type is closed.
1524        let p = program(vec![
1525            import(&["type Shape"]),
1526            alias("Mapped", &[], mapped.clone()),
1527        ]);
1528        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1529        // A type named `K` outside it is not the key.
1530        let p = program_with(alias("Other", &[], TsType::named("K")));
1531        assert_eq!(unbound_names(&p), ["K"]);
1532        // Nor is a value named `K`.
1533        let p = program_with(TsStmt::expr_stmt(TsExpr::Ident("K".to_string()), None));
1534        assert_eq!(unbound_names(&p), ["K"]);
1535        // The key is not in scope for the `keyof` operand: `[K in keyof K]` uses a `K` from outside.
1536        let p = program(vec![alias(
1537            "Self",
1538            &[],
1539            TsType::mapped("K", TsType::named("K"), TsType::named("string")),
1540        )]);
1541        assert_eq!(unbound_names(&p), ["K"]);
1542    }
1543
1544    /// 1A.36a: a type parameter is bound inside its own declaration, function, arrow or method
1545    /// and nowhere else.
1546    #[test]
1547    fn a_type_parameter_binds_only_inside_its_own_node() {
1548        let generic_fn = |generics: &[&str]| {
1549            TsStmt::decl(
1550                TsDecl::Function {
1551                    name: "id".to_string(),
1552                    generics: generics.iter().map(|g| g.to_string()).collect(),
1553                    params: vec![TsParam::new("x".to_string(), Some(TsType::named("T")))],
1554                    return_type: Some(TsType::named("T")),
1555                    body: vec![],
1556                    is_async: false,
1557                    inline: false,
1558                },
1559                None,
1560            )
1561        };
1562        let p = program(vec![generic_fn(&["T"])]);
1563        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1564        // Without the parameter, `T` is a use of an unbound name.
1565        let p = program(vec![generic_fn(&[])]);
1566        assert_eq!(unbound_names(&p), ["T"]);
1567        // The parameter of one function does not bind `T` in the next declaration.
1568        let p = program(vec![
1569            generic_fn(&["T"]),
1570            alias("Later", &[], TsType::named("T")),
1571        ]);
1572        assert_eq!(unbound_names(&p), ["T"]);
1573        // Nor does an alias's own parameter, or an arrow's, bind it outside.
1574        let p = program(vec![
1575            alias("Box", &["T"], TsType::named("T")),
1576            alias("Later", &[], TsType::named("T")),
1577        ]);
1578        assert_eq!(unbound_names(&p), ["T"]);
1579        let arrow = TsExpr::Arrow {
1580            params: vec![TsParam::new("x".to_string(), Some(TsType::named("T")))],
1581            return_type: None,
1582            generics: vec!["T".to_string()],
1583            body: Box::new(TsArrowBody::Expr(Box::new(TsExpr::Ident("x".to_string())))),
1584            is_async: false,
1585        };
1586        let p = program(vec![
1587            TsStmt::expr_stmt(arrow, None),
1588            alias("Later", &[], TsType::named("T")),
1589        ]);
1590        assert_eq!(unbound_names(&p), ["T"]);
1591        // A constraint (`T extends Shape`) binds `T`, not the whole text.
1592        let p = program(vec![
1593            import(&["type Shape"]),
1594            alias("Box", &["T extends Shape"], TsType::named("T")),
1595        ]);
1596        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1597    }
1598
1599    /// 1A.36b-1: a constraint or a default (`T extends Shape = Circle`) uses types, and can name
1600    /// the other parameters of its own list. A type named only there is unbound unless imported.
1601    #[test]
1602    fn a_type_parameter_constraint_and_default_use_the_names_they_hold() {
1603        let boxed = |param: &str| alias("Box", &[param], TsType::named("T"));
1604        // `Shape` appears nowhere else: only the constraint uses it.
1605        let p = program(vec![boxed("T extends Shape")]);
1606        assert_eq!(unbound_names(&p), ["Shape"]);
1607        let p = program(vec![import(&["type Shape"]), boxed("T extends Shape")]);
1608        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1609        // A default is a use too; an `extends` clause may use a generic type.
1610        let p = program(vec![boxed("T = Circle")]);
1611        assert_eq!(unbound_names(&p), ["Circle"]);
1612        let p = program(vec![boxed("T extends Readonly<Option<Shape>>")]);
1613        assert_eq!(unbound_names(&p), ["Option", "Shape"]);
1614        // A parameter of the same list is bound inside the constraint, and a
1615        // global is not reported.
1616        let p = alias("Pair", &["A", "B extends Array<A>"], TsType::named("B"));
1617        assert!(unbound_names(&program(vec![p])).is_empty());
1618        // A function's own list is read the same way.
1619        let f = TsStmt::decl(
1620            TsDecl::Function {
1621                name: "f".to_string(),
1622                generics: vec!["T extends Shape".to_string()],
1623                params: vec![],
1624                return_type: None,
1625                body: vec![],
1626                is_async: false,
1627                inline: false,
1628            },
1629            None,
1630        );
1631        assert_eq!(unbound_names(&program(vec![f])), ["Shape"]);
1632    }
1633
1634    /// 1A.36b-1: a `Named` type whose name carries its arguments as text uses the head and every
1635    /// name in the arguments, however it was spelled.
1636    #[test]
1637    fn a_named_type_that_carries_its_arguments_as_text_uses_them() {
1638        let over = |name: &str| program(vec![function_over(TsType::named(name))]);
1639        assert_eq!(unbound_names(&over("Option<A>")), ["A", "Option"]);
1640        assert_eq!(
1641            unbound_names(&over("Result<unknown, __BoundaryError>")),
1642            ["Result", "__BoundaryError"]
1643        );
1644        // A union, a function type and a global-qualified generic.
1645        assert_eq!(unbound_names(&over("Foo | Bar | null")), ["Bar", "Foo"]);
1646        assert_eq!(
1647            unbound_names(&over("(a: Req) => globalThis.Promise<Res>")),
1648            ["Req", "Res"]
1649        );
1650        // A mapped key and an `infer` binder are bound by the text.
1651        assert_eq!(
1652            unbound_names(&over("{ readonly [S in keyof Services]: Services[S] }")),
1653            ["Services"]
1654        );
1655        assert_eq!(unbound_names(&over("Box<infer U> | U")), ["Box"]);
1656        // Members, string literals, numbers, keys and lower-case words are not names.
1657        assert!(unbound_names(&over("\"Some\" | 200 | string")).is_empty());
1658        assert!(unbound_names(&over("{ Key: string }")).is_empty());
1659        assert_eq!(unbound_names(&over("ns.T<number>")), ["ns"]);
1660        // Imported, they are bound; a type parameter in scope is not a use.
1661        let p = program(vec![
1662            import(&["type Option", "type A"]),
1663            function_over(TsType::named("Option<A>")),
1664        ]);
1665        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1666    }
1667
1668    /// 1A.36b-2: a capitalised word before `:` is a key only inside `{ }`. In a conditional type
1669    /// the colon separates the branches, so the true branch is a use.
1670    #[test]
1671    fn a_conditional_type_branch_is_a_use_not_a_key() {
1672        let over = |name: &str| program(vec![function_over(TsType::named(name))]);
1673        assert_eq!(
1674            unbound_names(&over("A extends B ? C : D")),
1675            ["A", "B", "C", "D"]
1676        );
1677        // Inside an object type the same shape stays a key and a conditional value is a use.
1678        assert_eq!(
1679            unbound_names(&over("{ Key: A extends B ? C : D }")),
1680            ["A", "B", "C", "D"]
1681        );
1682        assert!(unbound_names(&over("{ Key?: string; Other: number }")).is_empty());
1683        // A key after a nested group closes is still a key.
1684        assert_eq!(
1685            unbound_names(&over("{ F: (x: X) => Y; K: Z }")),
1686            ["X", "Y", "Z"]
1687        );
1688    }
1689
1690    /// 1A.36b-1: the global tables hide a name the module imports that shares a global's name,
1691    /// unless the caller says it provides that name.
1692    #[test]
1693    fn a_provided_name_is_not_hidden_by_a_global() {
1694        let p = program(vec![function_over(TsType::named("Response"))]);
1695        assert!(unbound_names(&p).is_empty());
1696        let provided = |n: &str| n == "Response";
1697        assert_eq!(unbound_names_providing(&p, provided), ["Response"]);
1698        // Value position, and a name the caller does not provide, stay hidden.
1699        let call = TsStmt::expr_stmt(
1700            TsExpr::Call {
1701                callee: Box::new(TsExpr::Ident("Request".to_string())),
1702                args: vec![],
1703            },
1704            None,
1705        );
1706        let p = program(vec![call]);
1707        assert!(unbound_names_providing(&p, provided).is_empty());
1708        assert_eq!(unbound_names_providing(&p, |n| n == "Request"), ["Request"]);
1709        // Imported, the provided name is bound whatever it is called.
1710        let p = program(vec![
1711            import(&["Response"]),
1712            function_over(TsType::named("Response")),
1713        ]);
1714        assert!(unbound_names_providing(&p, provided).is_empty());
1715    }
1716
1717    /// 1A.36b-1: an expression's `raw_using` names are uses, as the statement's are, and the
1718    /// nodes the text was printed from are read the same way to find them.
1719    #[test]
1720    fn an_expression_that_declares_its_uses_counts_them() {
1721        let text = TsExpr::raw_using(
1722            "(__j: __JsonValue) => { return Ok(__j); }",
1723            vec!["Ok".to_string(), "__JsonValue".to_string()],
1724        );
1725        let p = program(vec![TsStmt::expr_stmt(text.clone(), None)]);
1726        assert_eq!(unbound_names(&p), ["Ok", "__JsonValue"]);
1727        let p = program(vec![
1728            import(&["Ok", "type __JsonValue"]),
1729            TsStmt::expr_stmt(text, None),
1730        ]);
1731        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1732        // The nodes it was printed from: parameters and locals bind, the rest is used.
1733        let arrow = TsExpr::Arrow {
1734            params: vec![TsParam::new(
1735                "__j".to_string(),
1736                Some(TsType::named("__JsonValue")),
1737            )],
1738            is_async: false,
1739            generics: vec![],
1740            return_type: None,
1741            body: Box::new(TsArrowBody::Block(vec![TsStmt::return_stmt(
1742                Some(TsExpr::Call {
1743                    callee: Box::new(TsExpr::Ident("Ok".to_string())),
1744                    args: vec![TsExpr::Ident("__j".to_string())],
1745                }),
1746                None,
1747            )])),
1748        };
1749        assert_eq!(
1750            unbound_names_in(&[TsStmt::expr_stmt(arrow, None)], |_| false),
1751            ["Ok", "__JsonValue"]
1752        );
1753    }
1754
1755    /// 1A.39a: a `Flat` body is read as the statements it holds, so what it declares binds and what
1756    /// it calls is a use (the witness decoder's body is exactly this).
1757    #[test]
1758    fn a_flat_arrow_body_is_read_like_a_block() {
1759        let arrow = TsExpr::Arrow {
1760            params: vec![TsParam::new("__j".to_string(), None)],
1761            is_async: false,
1762            generics: vec![],
1763            return_type: None,
1764            body: Box::new(TsArrowBody::Flat(vec![
1765                TsStmt::const_stmt(
1766                    TsBindingName::Ident("__v".to_string()),
1767                    None,
1768                    TsExpr::Ident("__j".to_string()),
1769                    None,
1770                ),
1771                TsStmt::return_stmt(
1772                    Some(TsExpr::Call {
1773                        callee: Box::new(TsExpr::Ident("Ok".to_string())),
1774                        args: vec![TsExpr::Ident("__v".to_string())],
1775                    }),
1776                    None,
1777                ),
1778            ])),
1779        };
1780        assert_eq!(
1781            unbound_names_in(&[TsStmt::expr_stmt(arrow, None)], |_| false),
1782            ["Ok"]
1783        );
1784    }
1785
1786    /// 1A.36b-1: `names_imported_from` reads what a module takes from one place.
1787    #[test]
1788    fn names_are_read_by_the_specifier_they_come_from() {
1789        let from = |spec: &str, names: &[&str]| {
1790            TsStmt::decl(
1791                TsDecl::Import {
1792                    type_only: false,
1793                    names: names.iter().map(|n| n.to_string()).collect(),
1794                    from: spec.to_string(),
1795                },
1796                None,
1797            )
1798        };
1799        let p = program(vec![
1800            from("./__bynk_runtime/result.js", &["Ok", "type Option"]),
1801            from("./other.js", &["Thing as Renamed"]),
1802        ]);
1803        let runtime = p.names_imported_from(|f| f.contains("__bynk_runtime/"));
1804        assert_eq!(runtime.into_iter().collect::<Vec<_>>(), ["Ok", "Option"]);
1805        let other = p.names_imported_from(|f| f == "./other.js");
1806        assert_eq!(other.into_iter().collect::<Vec<_>>(), ["Renamed"]);
1807    }
1808
1809    /// 1A.36a (Decision D): a `raw_using` statement's names are uses, in either position, and
1810    /// what the text declares is still bound. A plain `raw` carries no names.
1811    #[test]
1812    fn raw_using_counts_the_names_it_declares_as_uses() {
1813        let raw = |names: &[&str]| TsStmt::raw_using("export function f(): void {}\n", names);
1814        // A type and a value the module never binds are both unbound.
1815        let p = program(vec![raw(&["Option", "__bynkBytesToBase64"])]);
1816        assert_eq!(unbound_names(&p), ["Option", "__bynkBytesToBase64"]);
1817        // Imported, they are bound.
1818        let p = program(vec![
1819            import(&["type Option", "__bynkBytesToBase64"]),
1820            raw(&["Option", "__bynkBytesToBase64"]),
1821        ]);
1822        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1823        // A global of either table is not reported; a name the text declares is bound.
1824        let p = program(vec![TsStmt::raw_using(
1825            "interface Local {}\n",
1826            &["Local", "Record", "JSON"],
1827        )]);
1828        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1829        // No names: the text is a blind spot, as before.
1830        let p = program(vec![TsStmt::raw("const x = Missing;\n", None), raw(&[])]);
1831        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1832        // The names change nothing about printing.
1833        let with = raw(&["Option"]);
1834        let without = TsStmt::raw("export function f(): void {}\n", None);
1835        assert_eq!(crate::print_stmt(&with, 0), crate::print_stmt(&without, 0));
1836    }
1837
1838    #[test]
1839    fn a_parenthesised_type_uses_the_names_it_holds() {
1840        let thunk = |name: &str| {
1841            TsType::paren(TsType::Fn {
1842                rest: false,
1843                names: vec![],
1844                params: vec![],
1845                ret: Box::new(TsType::named(name)),
1846            })
1847        };
1848        let p = program(vec![function_over(thunk("Row"))]);
1849        assert_eq!(unbound_names(&p), ["Row"]);
1850        let p = program(vec![import(&["type Row"]), function_over(thunk("Row"))]);
1851        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1852    }
1853
1854    #[test]
1855    fn a_function_called_but_never_imported_is_unbound() {
1856        // #1815's shape: a codec helper called without its import.
1857        let p = program(vec![
1858            import(&["type __JsonValue", "type Amount"]),
1859            codec("__serialise_Quote", "Amount", "__serialise_Amount"),
1860        ]);
1861        assert_eq!(unbound_names(&p), ["__serialise_Amount"]);
1862    }
1863
1864    #[test]
1865    fn a_bare_export_list_uses_each_name_it_exports() {
1866        // #1852: a Workers context's `export { … };` of the commons codecs it
1867        // imports. A name exported without being imported is unbound.
1868        let p = program(vec![
1869            import(&["__serialise_Money"]),
1870            TsStmt::decl(
1871                TsDecl::ExportNames {
1872                    names: vec![
1873                        "__serialise_Money".to_string(),
1874                        "__deserialise_Money".to_string(),
1875                    ],
1876                },
1877                None,
1878            ),
1879        ]);
1880        assert_eq!(unbound_names(&p), ["__deserialise_Money"]);
1881    }
1882
1883    #[test]
1884    fn imports_bind_their_local_names_including_aliases_and_type_only() {
1885        let p = program(vec![
1886            import(&[
1887                "type __JsonValue",
1888                "Note as __CommonsNote",
1889                "__serialise_Base",
1890            ]),
1891            codec("__serialise_Note", "__CommonsNote", "__serialise_Base"),
1892        ]);
1893        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1894    }
1895
1896    #[test]
1897    fn a_namespace_import_binds_the_qualifier_of_a_qualified_name() {
1898        let p = program(vec![
1899            TsStmt::decl(
1900                TsDecl::ImportNamespace {
1901                    type_only: true,
1902                    alias: "handlers".to_string(),
1903                    from: "./handlers.js".to_string(),
1904                },
1905                None,
1906            ),
1907            TsStmt::let_stmt(
1908                TsBindingName::Ident("o".to_string()),
1909                Some(TsType::named("handlers.Order")),
1910                None,
1911                None,
1912            ),
1913            TsStmt::let_stmt(
1914                TsBindingName::Ident("p".to_string()),
1915                Some(TsType::named("other.Order")),
1916                None,
1917                None,
1918            ),
1919        ]);
1920        assert_eq!(unbound_names(&p), ["other"]);
1921    }
1922
1923    #[test]
1924    fn declarations_in_the_module_bind_their_names() {
1925        let p = program(vec![
1926            import(&["type __JsonValue"]),
1927            TsStmt::decl(
1928                TsDecl::TypeAlias {
1929                    name: "Note".to_string(),
1930                    type_params: vec![],
1931                    ty: TsType::named("string"),
1932                },
1933                None,
1934            ),
1935            codec("__serialise_Note", "Note", "__serialise_Note"),
1936        ]);
1937        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1938    }
1939
1940    #[test]
1941    fn parameters_locals_and_destructured_names_are_bound() {
1942        let p = program(vec![TsStmt::decl(
1943            TsDecl::Function {
1944                name: "f".to_string(),
1945                generics: vec!["T".to_string()],
1946                params: vec![TsParam::new(
1947                    "path: string = \"$\"".to_string(),
1948                    Some(TsType::named("T")),
1949                )],
1950                return_type: None,
1951                body: vec![
1952                    TsStmt::const_stmt(
1953                        TsBindingName::ObjectPattern(vec!["a".to_string(), "b: c".to_string()]),
1954                        None,
1955                        TsExpr::Ident("path".to_string()),
1956                        None,
1957                    ),
1958                    TsStmt::for_of(
1959                        "[k, v]",
1960                        TsExpr::Ident("c".to_string()),
1961                        TsStmt::block(
1962                            vec![
1963                                TsStmt::expr_stmt(TsExpr::Ident("k.length".to_string()), None),
1964                                TsStmt::expr_stmt(TsExpr::Ident("v".to_string()), None),
1965                                TsStmt::expr_stmt(TsExpr::Ident("a".to_string()), None),
1966                            ],
1967                            None,
1968                        ),
1969                        None,
1970                    ),
1971                ],
1972                is_async: false,
1973                inline: false,
1974            },
1975            None,
1976        )]);
1977        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1978    }
1979
1980    #[test]
1981    fn globals_and_literals_are_bound() {
1982        let p = program(vec![TsStmt::expr_stmt(
1983            TsExpr::Arrow {
1984                params: vec![],
1985                return_type: Some(TsType::named_with_args(
1986                    "Promise",
1987                    vec![TsType::named("globalThis.Response")],
1988                )),
1989                generics: vec![],
1990                body: Box::new(TsArrowBody::Expr(Box::new(TsExpr::Call {
1991                    callee: Box::new(TsExpr::Ident("JSON.stringify".to_string())),
1992                    args: vec![TsExpr::Ident("false".to_string())],
1993                }))),
1994                is_async: true,
1995            },
1996            None,
1997        )]);
1998        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1999    }
2000
2001    #[test]
2002    fn opaque_text_binds_what_it_declares_or_imports_line_by_line() {
2003        let p = program(vec![
2004            TsStmt::raw(
2005                "import { type __JsonValue, Amount as __A } from \"./m.js\";\n\
2006                 export const __serialise_Amount = (v: __A): __JsonValue => v;",
2007                None,
2008            ),
2009            TsStmt::verbatim(
2010                VerbatimOrigin::NotYetConverted,
2011                "export type Note = string;\nexport function __serialise_Note(n: Note) { return n; }",
2012                None,
2013            ),
2014            codec("__serialise_Quote", "Note", "__serialise_Amount"),
2015            codec("__serialise_Other", "__A", "__serialise_Note"),
2016        ]);
2017        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
2018    }
2019
2020    #[test]
2021    fn a_cast_in_opaque_text_is_not_mistaken_for_an_import_alias() {
2022        // The first version scanned for `import` anywhere and read `x as Note`
2023        // in a codec body as an alias, hiding #1829.
2024        let p = program(vec![
2025            import(&["type __JsonValue", "__serialise_Base"]),
2026            TsStmt::raw("// imports are below\nconst y = { z: x as Note };", None),
2027            codec("__serialise_Note", "Note", "__serialise_Base"),
2028        ]);
2029        assert_eq!(unbound_names(&p), ["Note"]);
2030    }
2031
2032    /// 1A.21: a `DefaultIife`'s default is a name use, so a name only the default uses is unbound
2033    /// when nothing declares it.
2034    #[test]
2035    fn a_default_iife_default_is_a_name_use() {
2036        let iife = |name: &str| TsExpr::DefaultIife {
2037            name: "p".to_string(),
2038            default: Box::new(TsExpr::Ident(name.to_string())),
2039            return_type: TsType::named("string"),
2040            body: vec![TsStmt::return_stmt(
2041                Some(TsExpr::Ident("p".to_string())),
2042                None,
2043            )],
2044        };
2045        let p = program(vec![TsStmt::expr_stmt(iife("missing"), None)]);
2046        assert_eq!(unbound_names(&p), ["missing"]);
2047        let p = program(vec![TsStmt::expr_stmt(iife("Err"), None), import(&["Err"])]);
2048        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
2049    }
2050
2051    #[test]
2052    fn a_generic_type_applied_in_opaque_text_must_be_bound() {
2053        // #1977's shape: a kernel helper typed with a generic record the
2054        // module never imports.
2055        let p = program(vec![TsStmt::raw(
2056            "return ((__xs: readonly MapEntry<string, number>[], __acc: number) => __acc)(all, 0);",
2057            None,
2058        )]);
2059        assert_eq!(unbound_names(&p), ["MapEntry"]);
2060    }
2061
2062    #[test]
2063    fn opaque_generics_skip_members_comparisons_globals_and_literals() {
2064        let p = program(vec![
2065            import(&["type Page"]),
2066            TsStmt::raw(
2067                "const a: globalThis.Promise<void> = f();\n\
2068                 const b: import(\"./m.js\").Note<string> = g();\n\
2069                 const c = __i < __xs.length && N < 3;\n\
2070                 const d: Record<string, Page<number>> = {};\n\
2071                 const e = \"Missing<T>\" + `Other<${x}>`; // Gone<T>\n\
2072                 /* Absent<T> */",
2073                None,
2074            ),
2075        ]);
2076        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
2077    }
2078
2079    #[test]
2080    fn a_name_used_only_inside_opaque_text_is_not_checked() {
2081        let p = program(vec![TsStmt::raw("return __serialise_Missing(x);", None)]);
2082        assert!(unbound_names(&p).is_empty());
2083    }
2084
2085    #[test]
2086    fn a_type_only_export_entry_uses_its_name() {
2087        // #2036: `export { type Batch };` of an imported consumed type.
2088        let export = |name: &str| {
2089            TsStmt::decl(
2090                TsDecl::ExportNames {
2091                    names: vec![format!("type {name}")],
2092                },
2093                None,
2094            )
2095        };
2096        let p = program(vec![import(&["Batch"]), export("Batch"), export("Missing")]);
2097        assert_eq!(unbound_names(&p), ["Missing"]);
2098    }
2099
2100    #[test]
2101    fn namespace_members_are_reported_with_their_specifier() {
2102        // #2036: `handlers.Batch` in type position and
2103        // `handlers.__deserialise_Batch(…)` in value position; a qualified
2104        // name whose head is no namespace import is not a member use.
2105        let p = program(vec![
2106            TsStmt::decl(
2107                TsDecl::ImportNamespace {
2108                    type_only: false,
2109                    alias: "handlers".to_string(),
2110                    from: "./handlers.js".to_string(),
2111                },
2112                None,
2113            ),
2114            TsStmt::let_stmt(
2115                TsBindingName::Ident("b".to_string()),
2116                Some(TsType::named("handlers.Batch<number>")),
2117                Some(TsExpr::Call {
2118                    callee: Box::new(TsExpr::Member {
2119                        object: Box::new(TsExpr::Ident("handlers".to_string())),
2120                        property: "__deserialise_Batch".to_string(),
2121                    }),
2122                    args: vec![],
2123                }),
2124                None,
2125            ),
2126            TsStmt::let_stmt(
2127                TsBindingName::Ident("c".to_string()),
2128                Some(TsType::named("globalThis.Response")),
2129                None,
2130                None,
2131            ),
2132        ]);
2133        let uses: Vec<(String, String)> = namespace_member_uses(&p)
2134            .into_iter()
2135            .map(|u| (u.from, u.member))
2136            .collect();
2137        assert_eq!(
2138            uses,
2139            [
2140                ("./handlers.js".to_string(), "Batch".to_string()),
2141                (
2142                    "./handlers.js".to_string(),
2143                    "__deserialise_Batch".to_string()
2144                ),
2145            ]
2146        );
2147    }
2148
2149    #[test]
2150    fn module_exports_reads_structured_and_opaque_exports_and_star_re_exports() {
2151        let p = program(vec![
2152            TsStmt::decl(
2153                TsDecl::ExportNames {
2154                    names: vec!["type Batch".to_string(), "a as b".to_string()],
2155                },
2156                None,
2157            ),
2158            codec("__serialise_Note", "Note", "__serialise_Name"),
2159            TsStmt::raw(
2160                "export async function run() {}\nexport { x, type Y };\nexport type { A, B as C };\nexport type D = number;\nconst hidden = 1;",
2161                None,
2162            ),
2163            TsStmt::decl(
2164                TsDecl::ReExportAll {
2165                    from: "./handlers/a.js".to_string(),
2166                },
2167                None,
2168            ),
2169        ]);
2170        let exports = module_exports(&p);
2171        let names: Vec<&str> = exports.names.iter().map(String::as_str).collect();
2172        assert_eq!(
2173            names,
2174            [
2175                "A",
2176                "Batch",
2177                "C",
2178                "D",
2179                "Y",
2180                "__serialise_Note",
2181                "b",
2182                "run",
2183                "x"
2184            ]
2185        );
2186        assert_eq!(exports.star_from, ["./handlers/a.js"]);
2187    }
2188
2189    #[test]
2190    fn a_type_only_import_used_as_a_value_is_reported() {
2191        // #2045: `import { type Status }` then `Status.Active` is TS1361; a
2192        // type position, or a name also bound as a value, is not.
2193        let member = |object: &str| TsExpr::Member {
2194            object: Box::new(TsExpr::Ident(object.to_string())),
2195            property: "Active".to_string(),
2196        };
2197        let p = program(vec![
2198            import(&["type Status", "type Batch", "Kept"]),
2199            TsStmt::let_stmt(
2200                TsBindingName::Ident("a".to_string()),
2201                Some(TsType::named("Batch")),
2202                Some(member("Status")),
2203                None,
2204            ),
2205            TsStmt::let_stmt(
2206                TsBindingName::Ident("b".to_string()),
2207                None,
2208                Some(member("Kept")),
2209                None,
2210            ),
2211        ]);
2212        assert_eq!(type_only_value_uses(&p), ["Status"]);
2213        assert!(unbound_names(&p).is_empty());
2214    }
2215
2216    /// 1A.20: a name that only a `TypeApp`'s type argument mentions is a use, so
2217    /// an import it needs is not reported as missing or dropped.
2218    #[test]
2219    fn a_type_application_argument_is_a_name_use() {
2220        let p = program(vec![
2221            import(&["type Batch"]),
2222            TsStmt::let_stmt(
2223                TsBindingName::Ident("a".to_string()),
2224                None,
2225                Some(TsExpr::Call {
2226                    callee: Box::new(TsExpr::TypeApp {
2227                        callee: Box::new(TsExpr::Ident("f".to_string())),
2228                        type_args: vec![TsType::named("Batch")],
2229                    }),
2230                    args: vec![],
2231                }),
2232                None,
2233            ),
2234        ]);
2235        assert_eq!(unbound_names(&p), ["f"]);
2236        assert!(type_only_value_uses(&p).is_empty());
2237    }
2238
2239    #[test]
2240    fn value_imports_skip_type_only_entries_and_declarations() {
2241        let p = program(vec![
2242            import(&["type Status", "Batch"]),
2243            TsStmt::decl(
2244                TsDecl::Import {
2245                    type_only: true,
2246                    names: vec!["Receipt".to_string()],
2247                    from: "./r.js".to_string(),
2248                },
2249                None,
2250            ),
2251        ]);
2252        assert_eq!(
2253            value_imports(&p),
2254            [("./m.js".to_string(), "Batch".to_string())]
2255        );
2256    }
2257
2258    /// 1A.35a part B: the new statements and expressions bind what they declare and use what
2259    /// they mention, so a program built from them reports only the genuinely unbound names.
2260    #[test]
2261    fn the_part_b_nodes_bind_and_use_their_names() {
2262        let id = |n: &str| TsExpr::Ident(n.to_string());
2263        let generator = TsExpr::Function {
2264            is_async: true,
2265            is_generator: true,
2266            params: vec![TsParam::array_pattern(
2267                vec!["k".to_string(), "v".to_string()],
2268                None,
2269            )],
2270            return_type: None,
2271            body: vec![
2272                TsStmt::let_list(
2273                    vec![
2274                        TsDeclarator::new("a"),
2275                        TsDeclarator::new("b").typed(TsType::named("Missing")),
2276                    ],
2277                    None,
2278                ),
2279                TsStmt::labelled(
2280                    "LOOP",
2281                    TsStmt::while_stmt(
2282                        id("a"),
2283                        TsStmt::block(
2284                            vec![
2285                                TsStmt::for_await_of(
2286                                    "e",
2287                                    id("src"),
2288                                    TsStmt::expr_stmt(
2289                                        TsExpr::Sequence(vec![
2290                                            TsExpr::Yield(Box::new(id("e"))),
2291                                            TsExpr::OptionalCall {
2292                                                callee: Box::new(id("k")),
2293                                                args: vec![id("v"), id("b")],
2294                                            },
2295                                        ]),
2296                                        None,
2297                                    ),
2298                                    None,
2299                                ),
2300                                TsStmt::continue_label_stmt("LOOP", None),
2301                            ],
2302                            None,
2303                        ),
2304                        None,
2305                    ),
2306                    None,
2307                ),
2308            ],
2309        };
2310        let p = program(vec![TsStmt::expr_stmt(generator, None)]);
2311        // `a`, `b`, `k`, `v` and `e` are bound inside; `src` and the type `Missing` are not.
2312        assert_eq!(unbound_names(&p), ["Missing", "src"]);
2313    }
2314
2315    /// 1A.38a: a default import with named imports binds the default alias and each
2316    /// named local, so a use of either is bound; a name it does not bring is not.
2317    #[test]
2318    fn a_default_import_with_named_imports_binds_all_of_them() {
2319        let imports = TsStmt::decl(
2320            TsDecl::ImportDefault {
2321                alias: "__entry0".to_string(),
2322                named: vec!["isMiss as __miss0".to_string()],
2323                from: "./a.js".to_string(),
2324            },
2325            None,
2326        );
2327        let uses = |names: &[&str]| {
2328            TsStmt::expr_stmt(
2329                TsExpr::array(names.iter().map(|n| TsExpr::Ident(n.to_string())).collect()),
2330                None,
2331            )
2332        };
2333        let p = program(vec![imports.clone(), uses(&["__entry0", "__miss0"])]);
2334        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
2335        // The imported name is `isMiss`; only its local alias is bound here.
2336        let p = program(vec![imports, uses(&["isMiss"])]);
2337        assert_eq!(unbound_names(&p), ["isMiss"]);
2338    }
2339
2340    /// 1A.38a: `MultilineConditional` is walked like `Conditional`: a name in its
2341    /// test, consequent or alternate is a use.
2342    #[test]
2343    fn a_multiline_conditional_uses_the_names_in_all_three_arms() {
2344        let id = |n: &str| TsExpr::Ident(n.to_string());
2345        let p = program(vec![TsStmt::expr_stmt(
2346            TsExpr::multiline_conditional(id("t"), id("c"), id("a")),
2347            None,
2348        )]);
2349        assert_eq!(unbound_names(&p), ["a", "c", "t"]);
2350        let p = program(vec![
2351            import(&["t", "c", "a"]),
2352            TsStmt::expr_stmt(
2353                TsExpr::multiline_conditional(id("t"), id("c"), id("a")),
2354                None,
2355            ),
2356        ]);
2357        assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
2358    }
2359
2360    /// 1A.38b: a parameter's default is a use of the names it mentions.
2361    #[test]
2362    fn a_name_in_a_parameter_default_is_unbound_unless_imported() {
2363        let f = || {
2364            TsStmt::decl(
2365                TsDecl::Function {
2366                    name: "f".to_string(),
2367                    generics: vec![],
2368                    params: vec![
2369                        TsParam::new("a", None).with_default(TsExpr::Ident("fallback".to_string())),
2370                    ],
2371                    return_type: None,
2372                    body: vec![],
2373                    is_async: false,
2374                    inline: false,
2375                },
2376                None,
2377            )
2378        };
2379        assert_eq!(unbound_names(&program(vec![f()])), ["fallback"]);
2380        assert!(unbound_names(&program(vec![import(&["fallback"]), f()])).is_empty());
2381    }
2382
2383    /// 1A.39b (Decision D): an identifier path passes; expression text held in an `Ident` is
2384    /// reported, as is a binding name that is not an identifier.
2385    #[test]
2386    fn text_idents_reports_expression_text_and_passes_identifier_paths() {
2387        let id = |n: &str| TsExpr::Ident(n.to_string());
2388        let p = program(vec![
2389            TsStmt::expr_stmt(id("globalThis.Number"), None),
2390            TsStmt::expr_stmt(id("this.state"), None),
2391            TsStmt::expr_stmt(id("f(a) as K"), None),
2392            TsStmt::expr_stmt(id("a..b"), None),
2393            TsStmt::const_stmt(
2394                TsBindingName::Ident("x y".to_string()),
2395                None,
2396                id("ok"),
2397                None,
2398            ),
2399        ]);
2400        assert_eq!(text_idents(&p), vec!["a..b", "f(a) as K", "x y"]);
2401    }
2402}