use std::path::Path;
use fallow_types::discover::FileId;
use fallow_types::extract::{ImportLoadKind, ImportedName, ModuleLoadMechanism, SemanticFact};
use rustc_hash::FxHashSet;
use super::types::ModuleNode;
use super::{EffectiveExportResolution, ExportNamespace, ImportedSymbol, ModuleGraph};
const TYPESCRIPT_EXTENSIONS: [&str; 4] = ["ts", "tsx", "mts", "cts"];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImportElision {
Keep(DecoratorMetadata),
RemoveUnread(DecoratorMetadata),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecoratorMetadata {
Off,
On {
strict_null_checks: bool,
},
}
impl ImportElision {
#[must_use]
pub const fn decorator_metadata(self) -> DecoratorMetadata {
match self {
Self::Keep(metadata) | Self::RemoveUnread(metadata) => metadata,
}
}
#[must_use]
pub(crate) const fn reads_decorator_metadata(self, emit: MetadataEmit) -> bool {
match self.decorator_metadata() {
DecoratorMetadata::On { strict_null_checks } => {
!strict_null_checks || matches!(emit, MetadataEmit::Always)
}
DecoratorMetadata::Off => false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MetadataEmit {
Always,
WithoutStrictNullChecks,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(super) enum BindingUse {
Value,
TypeOnly,
DecoratorMetadata(MetadataEmit),
Unread,
}
pub(super) struct BindingUses<'a> {
value: &'a [String],
type_only: &'a [String],
unread: &'a FxHashSet<String>,
metadata: &'a [SemanticFact],
}
impl<'a> BindingUses<'a> {
pub(super) fn of(module: &'a crate::resolve::ResolvedModule) -> Self {
Self {
value: &module.value_referenced_import_bindings,
type_only: &module.type_referenced_import_bindings,
unread: &module.unused_import_bindings,
metadata: &module.semantic_facts,
}
}
#[cfg(test)]
pub(super) fn unknown(unread: &'a FxHashSet<String>) -> Self {
Self {
value: &[],
type_only: &[],
unread,
metadata: &[],
}
}
pub(super) fn of_binding(&self, local: &str) -> BindingUse {
let in_sorted = |list: &[String]| {
list.binary_search_by(|name| name.as_str().cmp(local))
.is_ok()
};
if local.is_empty() || in_sorted(self.value) {
BindingUse::Value
} else if self.unread.contains(local) {
BindingUse::Unread
} else if in_sorted(self.type_only) {
self.metadata_emit(local)
.map_or(BindingUse::TypeOnly, BindingUse::DecoratorMetadata)
} else {
BindingUse::Value
}
}
}
impl BindingUses<'_> {
fn metadata_emit(&self, local: &str) -> Option<MetadataEmit> {
self.metadata.iter().find_map(|fact| match fact {
SemanticFact::DecoratorMetadataReference(fact) if fact.local == local => {
Some(if fact.without_strict_null_checks {
MetadataEmit::WithoutStrictNullChecks
} else {
MetadataEmit::Always
})
}
_ => None,
})
}
}
fn is_typescript_source(path: &Path) -> bool {
path.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| TYPESCRIPT_EXTENSIONS.contains(&extension))
}
pub(super) enum ImporterElision {
NotTypeScript,
Unknown,
Known(ImportElision),
}
impl ImporterElision {
pub(super) fn new(path: &Path) -> Self {
if is_typescript_source(path) {
Self::Unknown
} else {
Self::NotTypeScript
}
}
pub(super) fn get(
&mut self,
path: &Path,
elision_of: &mut dyn FnMut(&Path) -> ImportElision,
) -> ImportElision {
match *self {
Self::NotTypeScript => ImportElision::Keep(DecoratorMetadata::Off),
Self::Known(elision) => elision,
Self::Unknown => {
let elision = elision_of(path);
*self = Self::Known(elision);
elision
}
}
}
}
impl ModuleGraph {
pub(super) fn is_removed_import(
&self,
target: FileId,
symbol: &ImportedSymbol,
importer: &ModuleNode,
elision: ImportElision,
) -> bool {
if matches!(elision, ImportElision::Keep(_))
|| symbol.binding_use == BindingUse::Value
|| symbol.mechanism != ModuleLoadMechanism::EsModule
|| symbol.load_kind != ImportLoadKind::Static
{
return false;
}
let name = match &symbol.imported_name {
ImportedName::Named(name) => name.as_str(),
ImportedName::Default => "default",
ImportedName::Namespace | ImportedName::SideEffect => return false,
};
if self.names_only_a_type(target, name) {
return true;
}
let is_tsx = importer
.path
.extension()
.is_some_and(|extension| extension == "tsx");
let reads_metadata = symbol
.decorator_metadata()
.is_some_and(|emit| elision.reads_decorator_metadata(emit));
!is_tsx && !reads_metadata
}
fn names_only_a_type(&self, target: FileId, name: &str) -> bool {
matches!(
self.resolve_export(target, name, ExportNamespace::Value),
EffectiveExportResolution::Missing
) && !matches!(
self.resolve_export(target, name, ExportNamespace::Type),
EffectiveExportResolution::Missing
)
}
}