use std::path::{Path, PathBuf};
use crate::ecmascript;
use crate::{
ContainerBody, Import, ImportSpec, Language, LanguageSymbols, ModuleId, ModuleResolver,
Resolution, ResolverConfig, Visibility,
};
use tree_sitter::Node;
pub struct TypeScript;
pub struct Tsx;
impl Language for TypeScript {
fn name(&self) -> &'static str {
"TypeScript"
}
fn extensions(&self) -> &'static [&'static str] {
&["ts", "mts", "cts"]
}
fn grammar_name(&self) -> &'static str {
"typescript"
}
fn as_symbols(&self) -> Option<&dyn LanguageSymbols> {
Some(self)
}
fn signature_suffix(&self) -> &'static str {
" {}"
}
fn extract_docstring(&self, node: &Node, content: &str) -> Option<String> {
ecmascript::extract_jsdoc(node, content)
}
fn extract_implements(&self, node: &Node, content: &str) -> crate::ImplementsInfo {
ecmascript::extract_implements(node, content)
}
fn build_signature(&self, node: &Node, content: &str) -> String {
let name = match self.node_name(node, content) {
Some(n) => n,
None => {
return content[node.byte_range()]
.lines()
.next()
.unwrap_or("")
.trim()
.to_string();
}
};
ecmascript::build_signature(node, content, name)
}
fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
ecmascript::extract_imports(node, content)
}
fn format_import(&self, import: &Import, names: Option<&[&str]>) -> String {
ecmascript::format_import(import, names)
}
fn is_test_symbol(&self, symbol: &crate::Symbol) -> bool {
let name = symbol.name.as_str();
match symbol.kind {
crate::SymbolKind::Function | crate::SymbolKind::Method => {
name.starts_with("test_")
|| name.starts_with("Test")
|| name == "describe"
|| name == "it"
|| name == "test"
}
crate::SymbolKind::Module => name == "tests" || name == "test" || name == "__tests__",
_ => false,
}
}
fn test_file_globs(&self) -> &'static [&'static str] {
&[
"**/__tests__/**/*.ts",
"**/__mocks__/**/*.ts",
"**/*.test.ts",
"**/*.spec.ts",
"**/*.test.tsx",
"**/*.spec.tsx",
]
}
fn extract_attributes(&self, node: &Node, content: &str) -> Vec<String> {
ecmascript::extract_decorators(node, content)
}
fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
if let Some(body) = node.child_by_field_name("body") {
return Some(body);
}
for i in 0..node.child_count() as u32 {
if let Some(child) = node.child(i)
&& (child.kind() == "interface_body" || child.kind() == "class_body")
{
return Some(child);
}
}
None
}
fn analyze_container_body(
&self,
body_node: &Node,
content: &str,
inner_indent: &str,
) -> Option<ContainerBody> {
crate::body::analyze_brace_body(body_node, content, inner_indent)
}
fn get_visibility(&self, node: &Node, content: &str) -> Visibility {
ecmascript::get_visibility(node, content)
}
fn extract_module_doc(&self, src: &str) -> Option<String> {
ecmascript::extract_js_module_doc(src)
}
fn module_resolver(&self) -> Option<&dyn ModuleResolver> {
static RESOLVER: TsModuleResolver = TsModuleResolver;
Some(&RESOLVER)
}
}
impl LanguageSymbols for TypeScript {}
impl Language for Tsx {
fn name(&self) -> &'static str {
"TSX"
}
fn extensions(&self) -> &'static [&'static str] {
&["tsx"]
}
fn grammar_name(&self) -> &'static str {
"tsx"
}
fn signature_suffix(&self) -> &'static str {
" {}"
}
fn extract_docstring(&self, node: &Node, content: &str) -> Option<String> {
ecmascript::extract_jsdoc(node, content)
}
fn extract_implements(&self, node: &Node, content: &str) -> crate::ImplementsInfo {
ecmascript::extract_implements(node, content)
}
fn build_signature(&self, node: &Node, content: &str) -> String {
let name = match self.node_name(node, content) {
Some(n) => n,
None => {
return content[node.byte_range()]
.lines()
.next()
.unwrap_or("")
.trim()
.to_string();
}
};
ecmascript::build_signature(node, content, name)
}
fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
ecmascript::extract_imports(node, content)
}
fn format_import(&self, import: &Import, names: Option<&[&str]>) -> String {
ecmascript::format_import(import, names)
}
fn is_test_symbol(&self, symbol: &crate::Symbol) -> bool {
let name = symbol.name.as_str();
match symbol.kind {
crate::SymbolKind::Function | crate::SymbolKind::Method => {
name.starts_with("test_")
|| name.starts_with("Test")
|| name == "describe"
|| name == "it"
|| name == "test"
}
crate::SymbolKind::Module => name == "tests" || name == "test" || name == "__tests__",
_ => false,
}
}
fn test_file_globs(&self) -> &'static [&'static str] {
&[
"**/__tests__/**/*.ts",
"**/__mocks__/**/*.ts",
"**/*.test.ts",
"**/*.spec.ts",
"**/*.test.tsx",
"**/*.spec.tsx",
]
}
fn extract_attributes(&self, node: &Node, content: &str) -> Vec<String> {
ecmascript::extract_decorators(node, content)
}
fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
if let Some(body) = node.child_by_field_name("body") {
return Some(body);
}
for i in 0..node.child_count() as u32 {
if let Some(child) = node.child(i)
&& (child.kind() == "interface_body" || child.kind() == "class_body")
{
return Some(child);
}
}
None
}
fn analyze_container_body(
&self,
body_node: &Node,
content: &str,
inner_indent: &str,
) -> Option<ContainerBody> {
crate::body::analyze_brace_body(body_node, content, inner_indent)
}
fn get_visibility(&self, node: &Node, content: &str) -> Visibility {
ecmascript::get_visibility(node, content)
}
fn extract_module_doc(&self, src: &str) -> Option<String> {
ecmascript::extract_js_module_doc(src)
}
fn module_resolver(&self) -> Option<&dyn ModuleResolver> {
static RESOLVER: TsModuleResolver = TsModuleResolver;
Some(&RESOLVER)
}
}
pub struct TsModuleResolver;
impl ModuleResolver for TsModuleResolver {
fn workspace_config(&self, root: &Path) -> ResolverConfig {
let mut path_mappings: Vec<(String, PathBuf)> = Vec::new();
let mut search_roots: Vec<PathBuf> = Vec::new();
let tsconfig_path = root.join("tsconfig.json");
if let Ok(content) = std::fs::read_to_string(&tsconfig_path)
&& let Ok(tsconfig) = serde_json::from_str::<serde_json::Value>(&content)
{
let compiler_opts = tsconfig.get("compilerOptions");
if let Some(base_url) = compiler_opts
.and_then(|o| o.get("baseUrl"))
.and_then(|v| v.as_str())
{
let base = root.join(base_url);
search_roots.push(base);
}
if let Some(paths) = compiler_opts
.and_then(|o| o.get("paths"))
.and_then(|v| v.as_object())
{
for (alias, targets) in paths {
if let Some(first) = targets
.as_array()
.and_then(|arr| arr.first())
.and_then(|v| v.as_str())
{
let alias_key = alias.trim_end_matches("/*").to_string();
let target_path = root.join(first.trim_end_matches("/*"));
path_mappings.push((alias_key, target_path));
}
}
}
}
ResolverConfig {
workspace_root: root.to_path_buf(),
path_mappings,
search_roots,
}
}
fn module_of_file(&self, _root: &Path, file: &Path, cfg: &ResolverConfig) -> Vec<ModuleId> {
let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
if !matches!(ext, "ts" | "tsx" | "mts" | "cts") {
return Vec::new();
}
let base = cfg.search_roots.first().unwrap_or(&cfg.workspace_root);
let rel = file
.strip_prefix(base)
.or_else(|_| file.strip_prefix(&cfg.workspace_root))
.unwrap_or(file);
let stem = rel.with_extension("");
let module_path = stem
.components()
.filter_map(|c| {
if let std::path::Component::Normal(s) = c {
s.to_str()
} else {
None
}
})
.collect::<Vec<_>>()
.join("/");
if module_path.is_empty() {
return Vec::new();
}
vec![ModuleId {
canonical_path: module_path,
}]
}
fn resolve(&self, from_file: &Path, spec: &ImportSpec, cfg: &ResolverConfig) -> Resolution {
let ext = from_file.extension().and_then(|e| e.to_str()).unwrap_or("");
if !matches!(ext, "ts" | "tsx" | "mts" | "cts") {
return Resolution::NotApplicable;
}
let raw = &spec.raw;
if raw.starts_with("node_modules/") {
return Resolution::NotFound;
}
if spec.is_relative || raw.starts_with("./") || raw.starts_with("../") {
let base_dir = from_file.parent().unwrap_or(from_file);
return resolve_ts_relative(base_dir, raw);
}
for (alias, target_dir) in &cfg.path_mappings {
if raw == alias || raw.starts_with(&format!("{}/", alias)) {
let rest = raw.strip_prefix(alias).unwrap_or("");
let rest = rest.strip_prefix('/').unwrap_or(rest);
let candidate = if rest.is_empty() {
target_dir.clone()
} else {
target_dir.join(rest)
};
let result = resolve_ts_file_candidates(&candidate);
if !matches!(result, Resolution::NotFound) {
return result;
}
}
}
for search_root in &cfg.search_roots {
let candidate = search_root.join(raw);
let result = resolve_ts_file_candidates(&candidate);
if !matches!(result, Resolution::NotFound) {
return result;
}
}
Resolution::NotFound
}
}
fn resolve_ts_file_candidates(base: &Path) -> Resolution {
let candidates = [
base.with_extension("ts"),
base.with_extension("tsx"),
base.join("index.ts"),
base.join("index.tsx"),
];
for c in &candidates {
if c.exists() {
return Resolution::Resolved(c.clone(), String::new());
}
}
Resolution::NotFound
}
fn resolve_ts_relative(base_dir: &Path, raw: &str) -> Resolution {
let joined = base_dir.join(raw);
let normalized = normalize_path(&joined);
let base = if normalized.extension().and_then(|e| e.to_str()) == Some("js") {
normalized.with_extension("")
} else {
normalized.clone()
};
resolve_ts_file_candidates(&base)
}
fn normalize_path(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in path.components() {
match component {
std::path::Component::ParentDir => {
out.pop();
}
std::path::Component::CurDir => {}
c => out.push(c),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::validate_unused_kinds_audit;
#[test]
fn unused_node_kinds_audit() {
#[rustfmt::skip]
let documented_unused: &[&str] = &[
"class_body", "class_heritage", "class_static_block", "enum_assignment", "enum_body", "formal_parameters", "identifier", "interface_body", "nested_identifier", "nested_type_identifier", "private_property_identifier", "property_identifier", "public_field_definition", "shorthand_property_identifier", "shorthand_property_identifier_pattern", "statement_block", "statement_identifier", "switch_body",
"default_type", "else_clause", "extends_clause", "extends_type_clause", "finally_clause", "implements_clause",
"as_expression", "assignment_expression", "augmented_assignment_expression", "await_expression", "call_expression", "function_expression", "instantiation_expression", "member_expression", "non_null_expression", "parenthesized_expression", "satisfies_expression", "sequence_expression", "subscript_expression", "unary_expression", "update_expression", "yield_expression",
"adding_type_annotation", "array_type", "conditional_type", "construct_signature", "constructor_type", "existential_type", "flow_maybe_type", "function_type", "generic_type", "index_type_query", "infer_type", "intersection_type", "literal_type", "lookup_type", "mapped_type_clause", "object_type", "omitting_type_annotation", "opting_type_annotation", "optional_type", "override_modifier", "parenthesized_type", "predefined_type", "readonly_type", "rest_type", "template_literal_type", "template_type", "this_type", "tuple_type", "type_arguments", "type_assertion", "type_parameter", "type_parameters", "type_predicate", "type_predicate_annotation", "type_query", "union_type",
"accessibility_modifier", "export_clause", "export_specifier", "import", "import_alias", "import_attribute", "import_clause", "import_require_clause", "import_specifier", "named_imports", "namespace_export", "namespace_import",
"ambient_declaration", "debugger_statement", "empty_statement", "expression_statement", "generator_function", "generator_function_declaration", "internal_module", "labeled_statement", "lexical_declaration", "using_declaration", "variable_declaration", "with_statement", "for_in_statement",
"switch_case",
"continue_statement",
"do_statement",
"return_statement",
"class",
"switch_statement",
"binary_expression",
"while_statement",
"for_statement",
"if_statement",
"throw_statement",
"try_statement",
"break_statement",
"arrow_function",
"catch_clause",
"ternary_expression",
"import_statement",
"export_statement",
];
validate_unused_kinds_audit(&TypeScript, documented_unused)
.expect("TypeScript unused node kinds audit failed");
}
}