1use std::collections::{BTreeMap, BTreeSet};
51
52use crate::program::{
53 TsArrowBody, TsBindingName, TsDecl, TsExpr, TsObjectEntry, TsParam, TsProgram, TsStmt,
54 TsStmtKind, TsType, TsTypeMember,
55};
56
57const GLOBAL_TYPES: &[&str] = &[
60 "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 "const",
79 "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",
133];
134
135const 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
194pub fn unbound_names(program: &TsProgram) -> Vec<String> {
197 unbound_names_providing(program, |_| false)
198}
199
200pub 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
219pub 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 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
246pub 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
260pub fn raw_statement_texts(stmts: &[TsStmt]) -> Vec<String> {
266 let mut w = Walk::default();
267 w.stmts(stmts);
268 w.raw_texts
269}
270
271pub 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
295pub 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
315pub struct NamespaceMemberUse {
316 pub from: String,
318 pub member: String,
320}
321
322pub 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#[derive(Debug, Default, Clone, PartialEq, Eq)]
349pub struct ModuleExports {
350 pub names: BTreeSet<String>,
352 pub star_from: Vec<String>,
355}
356
357pub 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
401fn 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 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 used_declared: BTreeSet<String>,
455 scope: Vec<String>,
459 namespaces: BTreeMap<String, String>,
461 qualified: BTreeSet<(String, String)>,
463 type_only: BTreeSet<String>,
467 value_bound: BTreeSet<String>,
468 raw_texts: Vec<String>,
471 text_idents: BTreeSet<String>,
474}
475
476fn 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
485pub(crate) fn is_identifier_path(text: &str) -> bool {
488 text.split('.').all(is_identifier)
489}
490
491fn 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 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 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 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 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 fn in_scope(&self, name: &str) -> bool {
572 self.scope.iter().any(|n| n == name)
573 }
574
575 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 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 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 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 if word == "typeof" {
643 let operand = text[i..].trim_start();
644 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 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 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 fn opaque(&mut self, text: &str) {
763 self.bind_opaque(text);
764 self.use_opaque_generics(text);
765 }
766
767 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 let p = program_with(alias("Other", &[], TsType::named("K")));
1531 assert_eq!(unbound_names(&p), ["K"]);
1532 let p = program_with(TsStmt::expr_stmt(TsExpr::Ident("K".to_string()), None));
1534 assert_eq!(unbound_names(&p), ["K"]);
1535 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 #[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 let p = program(vec![generic_fn(&[])]);
1566 assert_eq!(unbound_names(&p), ["T"]);
1567 let p = program(vec![
1569 generic_fn(&["T"]),
1570 alias("Later", &[], TsType::named("T")),
1571 ]);
1572 assert_eq!(unbound_names(&p), ["T"]);
1573 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 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 #[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 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 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 let p = alias("Pair", &["A", "B extends Array<A>"], TsType::named("B"));
1617 assert!(unbound_names(&program(vec![p])).is_empty());
1618 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 #[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 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 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 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 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 #[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 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 assert_eq!(
1685 unbound_names(&over("{ F: (x: X) => Y; K: Z }")),
1686 ["X", "Y", "Z"]
1687 );
1688 }
1689
1690 #[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 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 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 #[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 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 #[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 #[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 #[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 let p = program(vec![raw(&["Option", "__bynkBytesToBase64"])]);
1816 assert_eq!(unbound_names(&p), ["Option", "__bynkBytesToBase64"]);
1817 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 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 let p = program(vec![TsStmt::raw("const x = Missing;\n", None), raw(&[])]);
1831 assert!(unbound_names(&p).is_empty(), "{:?}", unbound_names(&p));
1832 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 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 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 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 #[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 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 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 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 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 #[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 #[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 assert_eq!(unbound_names(&p), ["Missing", "src"]);
2313 }
2314
2315 #[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 let p = program(vec![imports, uses(&["isMiss"])]);
2337 assert_eq!(unbound_names(&p), ["isMiss"]);
2338 }
2339
2340 #[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 #[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 #[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}