use std::path::{Path, PathBuf};
use rustc_hash::{FxHashMap, FxHashSet};
use fallow_types::extract::{ImportedName, ModuleInfo};
use crate::discover::FileId;
use crate::graph::{ModuleGraph, ModuleNode};
use super::{export_has_reachable_reference, export_name_str};
const DECLARATION_RUNTIME_PAIRS: &[(&str, &str)] =
&[(".d.ts", "js"), (".d.mts", "mjs"), (".d.cts", "cjs")];
pub(super) type DeclarationSiblingCredit = FxHashMap<FileId, FxHashSet<String>>;
pub(super) fn declaration_sibling_credit(
graph: &ModuleGraph,
modules: &[ModuleInfo],
infos_by_id: Option<&FxHashMap<FileId, &ModuleInfo>>,
) -> DeclarationSiblingCredit {
let pairs: Vec<(FileId, PathBuf)> = graph
.modules
.iter()
.filter_map(|module| runtime_sibling_path(&module.path).map(|path| (module.file_id, path)))
.collect();
if pairs.is_empty() {
return DeclarationSiblingCredit::default();
}
let by_path: FxHashMap<&Path, FileId> = graph
.modules
.iter()
.map(|module| (module.path.as_path(), module.file_id))
.collect();
let built: FxHashMap<FileId, &ModuleInfo>;
let infos = if let Some(infos) = infos_by_id {
infos
} else {
built = modules.iter().map(|info| (info.file_id, info)).collect();
&built
};
pairs
.into_iter()
.filter_map(|(declaration, sibling)| {
let runtime = *by_path.get(sibling.as_path())?;
let names = used_names_of(graph, infos, runtime);
(!names.is_empty()).then_some((declaration, names))
})
.collect()
}
pub(super) fn runtime_sibling_path(path: &Path) -> Option<PathBuf> {
let name = path.file_name()?.to_str()?;
DECLARATION_RUNTIME_PAIRS.iter().find_map(|(suffix, ext)| {
let stem = name.strip_suffix(suffix)?;
(!stem.is_empty()).then(|| path.with_file_name(format!("{stem}.{ext}")))
})
}
fn used_names_of(
graph: &ModuleGraph,
infos: &FxHashMap<FileId, &ModuleInfo>,
runtime: FileId,
) -> FxHashSet<String> {
let mut names = FxHashSet::default();
let mut seen_importers = FxHashSet::default();
for &importer in graph.importers_of(runtime) {
if !seen_importers.insert(importer) || !is_reachable_module(graph, importer) {
continue;
}
for (target, symbols) in graph.outgoing_symbol_edges(importer) {
if target != runtime {
continue;
}
for symbol in symbols {
match &symbol.imported_name {
ImportedName::Named(name) => {
names.insert(name.clone());
}
ImportedName::Default => {
names.insert("default".to_string());
}
ImportedName::Namespace => {
if let Some(info) = infos.get(&importer) {
names.extend(namespace_members_read(info, &symbol.local_name));
}
}
ImportedName::SideEffect => {}
}
}
}
}
if let Some(module) = graph.modules.get(runtime.0 as usize) {
names.extend(
module
.exports
.iter()
.filter(|export| export_has_reachable_reference(graph, module, export))
.map(|export| export_name_str(&export.name).to_string()),
);
}
names
}
fn namespace_members_read<'a>(
info: &'a ModuleInfo,
local: &'a str,
) -> impl Iterator<Item = String> + 'a {
info.member_accesses
.iter()
.filter(move |access| !local.is_empty() && access.object == local)
.map(|access| access.member.clone())
}
fn is_reachable_module(graph: &ModuleGraph, file_id: FileId) -> bool {
graph
.modules
.get(file_id.0 as usize)
.is_some_and(ModuleNode::is_reachable)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn runtime_sibling_path_pairs_each_declaration_suffix() {
for (declaration, runtime) in [
("src/lib.d.ts", "src/lib.js"),
("src/lib.d.mts", "src/lib.mjs"),
("src/lib.d.cts", "src/lib.cjs"),
] {
assert_eq!(
runtime_sibling_path(Path::new(declaration)),
Some(PathBuf::from(runtime)),
"{declaration}"
);
}
}
#[test]
fn runtime_sibling_path_ignores_other_files() {
for path in ["src/lib.ts", "src/lib.mjs", "src/.d.ts"] {
assert_eq!(runtime_sibling_path(Path::new(path)), None, "{path}");
}
}
}