fallow_graph/graph/import_elision.rs
1//! The imports that TypeScript removes from its output (issues #5262,
2//! #5309 and #5362).
3//!
4//! TypeScript removes a plain `import { X }` when the file never reads `X`
5//! as a value: `X` names only a type in the target, or the file uses `X`
6//! only in type positions, or not at all. Such an import does not load the
7//! target at runtime, so cycle detection must not count it. Some compiler
8//! options keep the import. The caller reads them per importer and gives an
9//! [`ImportElision`].
10//!
11//! Under `emitDecoratorMetadata`, the metadata of a decorated class member
12//! reads some of its type annotations at runtime. An import that such a
13//! position names stays, and its target export runs when the importer runs.
14
15use std::path::Path;
16
17use fallow_types::discover::FileId;
18use fallow_types::extract::{ImportLoadKind, ImportedName, ModuleLoadMechanism, SemanticFact};
19use rustc_hash::FxHashSet;
20
21use super::types::ModuleNode;
22use super::{EffectiveExportResolution, ExportNamespace, ImportedSymbol, ModuleGraph};
23
24/// The file extensions of the modules that TypeScript compiles.
25const TYPESCRIPT_EXTENSIONS: [&str; 4] = ["ts", "tsx", "mts", "cts"];
26
27/// Which plain imports TypeScript removes from the output of one importer,
28/// and whether its decorator metadata reads imports.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum ImportElision {
31 /// The compiler options keep each import: `verbatimModuleSyntax`,
32 /// `preserveValueImports`, or `importsNotUsedAsValues` with `preserve`
33 /// or `error`.
34 Keep(DecoratorMetadata),
35 /// TypeScript removes each import that the file never reads as a value,
36 /// except an import that the decorator metadata of the file reads.
37 RemoveUnread(DecoratorMetadata),
38}
39
40/// The `emitDecoratorMetadata` options of one importer.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum DecoratorMetadata {
43 /// No metadata, or the options are not known.
44 Off,
45 /// `emitDecoratorMetadata` is on.
46 On {
47 /// `strictNullChecks` is on, so a union with `null` or `undefined`
48 /// emits `Object` and reads no import.
49 strict_null_checks: bool,
50 },
51}
52
53impl ImportElision {
54 /// The [`DecoratorMetadata`] options of the importer.
55 #[must_use]
56 pub const fn decorator_metadata(self) -> DecoratorMetadata {
57 match self {
58 Self::Keep(metadata) | Self::RemoveUnread(metadata) => metadata,
59 }
60 }
61
62 /// Whether the decorator metadata of the importer reads a binding that
63 /// it emits as `emit`. The import of such a binding stays in the output,
64 /// and the importer reads the export when its class loads.
65 #[must_use]
66 pub(crate) const fn reads_decorator_metadata(self, emit: MetadataEmit) -> bool {
67 match self.decorator_metadata() {
68 DecoratorMetadata::On { strict_null_checks } => {
69 !strict_null_checks || matches!(emit, MetadataEmit::Always)
70 }
71 DecoratorMetadata::Off => false,
72 }
73 }
74}
75
76/// When TypeScript emits a binding in decorator metadata.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
78pub enum MetadataEmit {
79 /// With and without `strictNullChecks`.
80 Always,
81 /// Only without `strictNullChecks`: a union of the name with `null` or
82 /// `undefined`.
83 WithoutStrictNullChecks,
84}
85
86/// How the importer uses the local binding of an import.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
88pub(super) enum BindingUse {
89 /// The file reads the binding as a value, or the use is not known.
90 Value,
91 /// The file uses the binding only in type positions.
92 TypeOnly,
93 /// The file uses the binding only in type positions, and decorator
94 /// metadata emits it.
95 DecoratorMetadata(MetadataEmit),
96 /// The file never uses the binding.
97 Unread,
98}
99
100/// The binding use lists of one importer, as extraction records them.
101pub(super) struct BindingUses<'a> {
102 value: &'a [String],
103 type_only: &'a [String],
104 unread: &'a FxHashSet<String>,
105 metadata: &'a [SemanticFact],
106}
107
108impl<'a> BindingUses<'a> {
109 /// The lists of `module`. Extraction sorts the value and type lists.
110 pub(super) fn of(module: &'a crate::resolve::ResolvedModule) -> Self {
111 Self {
112 value: &module.value_referenced_import_bindings,
113 type_only: &module.type_referenced_import_bindings,
114 unread: &module.unused_import_bindings,
115 metadata: &module.semantic_facts,
116 }
117 }
118
119 /// No use facts, so each binding counts as a value.
120 #[cfg(test)]
121 pub(super) fn unknown(unread: &'a FxHashSet<String>) -> Self {
122 Self {
123 value: &[],
124 type_only: &[],
125 unread,
126 metadata: &[],
127 }
128 }
129
130 /// The use of `local`. A binding that no list names counts as a value
131 /// read, so a file without use facts keeps each import.
132 pub(super) fn of_binding(&self, local: &str) -> BindingUse {
133 let in_sorted = |list: &[String]| {
134 list.binary_search_by(|name| name.as_str().cmp(local))
135 .is_ok()
136 };
137 if local.is_empty() || in_sorted(self.value) {
138 BindingUse::Value
139 } else if self.unread.contains(local) {
140 BindingUse::Unread
141 } else if in_sorted(self.type_only) {
142 self.metadata_emit(local)
143 .map_or(BindingUse::TypeOnly, BindingUse::DecoratorMetadata)
144 } else {
145 BindingUse::Value
146 }
147 }
148}
149
150impl BindingUses<'_> {
151 /// How the decorator metadata of the file emits `local`, if it does.
152 fn metadata_emit(&self, local: &str) -> Option<MetadataEmit> {
153 self.metadata.iter().find_map(|fact| match fact {
154 SemanticFact::DecoratorMetadataReference(fact) if fact.local == local => {
155 Some(if fact.without_strict_null_checks {
156 MetadataEmit::WithoutStrictNullChecks
157 } else {
158 MetadataEmit::Always
159 })
160 }
161 _ => None,
162 })
163 }
164}
165
166/// Whether TypeScript compiles `path`. A JavaScript importer keeps each
167/// import, and a framework file (`.vue`, `.svelte`) compiles with rules of
168/// its own.
169fn is_typescript_source(path: &Path) -> bool {
170 path.extension()
171 .and_then(|extension| extension.to_str())
172 .is_some_and(|extension| TYPESCRIPT_EXTENSIONS.contains(&extension))
173}
174
175/// The [`ImportElision`] of one importer, read from the caller on first use.
176pub(super) enum ImporterElision {
177 NotTypeScript,
178 Unknown,
179 Known(ImportElision),
180}
181
182impl ImporterElision {
183 pub(super) fn new(path: &Path) -> Self {
184 if is_typescript_source(path) {
185 Self::Unknown
186 } else {
187 Self::NotTypeScript
188 }
189 }
190
191 pub(super) fn get(
192 &mut self,
193 path: &Path,
194 elision_of: &mut dyn FnMut(&Path) -> ImportElision,
195 ) -> ImportElision {
196 match *self {
197 Self::NotTypeScript => ImportElision::Keep(DecoratorMetadata::Off),
198 Self::Known(elision) => elision,
199 Self::Unknown => {
200 let elision = elision_of(path);
201 *self = Self::Known(elision);
202 elision
203 }
204 }
205 }
206}
207
208impl ModuleGraph {
209 /// Whether TypeScript removes `symbol`, an import of `target` in
210 /// `importer`, under `elision`.
211 ///
212 /// Only a static ES import of a named or default binding can go away. A
213 /// namespace or side-effect import, a re-export, a dynamic `import()`
214 /// and a `require()` stay in the output. A binding that the file reads as
215 /// a value stays. Then:
216 ///
217 /// - an import of a name that resolves in the type namespace of the
218 /// target and not in its value namespace goes away;
219 /// - an import that the file uses only in type positions or not at all
220 /// goes away, except in a `.tsx` file and when the decorator metadata
221 /// of the file reads it (see [`ImportElision::reads_decorator_metadata`]).
222 /// In a `.tsx` file the binding can be the JSX factory of the classic
223 /// runtime, which TypeScript keeps whatever the file does with it.
224 pub(super) fn is_removed_import(
225 &self,
226 target: FileId,
227 symbol: &ImportedSymbol,
228 importer: &ModuleNode,
229 elision: ImportElision,
230 ) -> bool {
231 if matches!(elision, ImportElision::Keep(_))
232 || symbol.binding_use == BindingUse::Value
233 || symbol.mechanism != ModuleLoadMechanism::EsModule
234 || symbol.load_kind != ImportLoadKind::Static
235 {
236 return false;
237 }
238 let name = match &symbol.imported_name {
239 ImportedName::Named(name) => name.as_str(),
240 ImportedName::Default => "default",
241 ImportedName::Namespace | ImportedName::SideEffect => return false,
242 };
243 if self.names_only_a_type(target, name) {
244 return true;
245 }
246 let is_tsx = importer
247 .path
248 .extension()
249 .is_some_and(|extension| extension == "tsx");
250 let reads_metadata = symbol
251 .decorator_metadata()
252 .is_some_and(|emit| elision.reads_decorator_metadata(emit));
253 !is_tsx && !reads_metadata
254 }
255
256 /// Whether `name` resolves in the type namespace of `target` and not in
257 /// its value namespace. A name that does not resolve at all does not: the
258 /// export can come from code that the graph cannot read.
259 fn names_only_a_type(&self, target: FileId, name: &str) -> bool {
260 matches!(
261 self.resolve_export(target, name, ExportNamespace::Value),
262 EffectiveExportResolution::Missing
263 ) && !matches!(
264 self.resolve_export(target, name, ExportNamespace::Type),
265 EffectiveExportResolution::Missing
266 )
267 }
268}