normalize-languages 0.3.2

Tree-sitter language support and dynamic grammar loading
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! TypeScript language support.

use std::path::{Path, PathBuf};

use crate::ecmascript;
use crate::{
    ContainerBody, Import, ImportSpec, Language, LanguageSymbols, ModuleId, ModuleResolver,
    Resolution, ResolverConfig, Visibility,
};
use tree_sitter::Node;

/// TypeScript language support.
pub struct TypeScript;

/// TSX language support (TypeScript + JSX).
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>> {
        // Try 'body' field first, then look for interface_body or class_body child
        if let Some(body) = node.child_by_field_name("body") {
            return Some(body);
        }
        // Fallback: find interface_body or class_body child
        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 {}

// TSX shares the same implementation as TypeScript, just with a different grammar
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>> {
        // Try 'body' field first, then look for interface_body or class_body child
        if let Some(body) = node.child_by_field_name("body") {
            return Some(body);
        }
        // Fallback: find interface_body or class_body child
        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)
    }
}

// =============================================================================
// TypeScript / TSX Module Resolver
// =============================================================================

/// Module resolver for TypeScript/TSX.
///
/// Handles:
/// - Relative imports (`./`, `../`)
/// - tsconfig.json `compilerOptions.paths` (alias mappings)
/// - tsconfig.json `compilerOptions.baseUrl` (search root)
/// - `.js` → `.ts` extension elision (TS compiles `.js` imports as `.ts`)
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();

        // Try to read tsconfig.json
        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");

            // Parse baseUrl
            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);
            }

            // Parse paths aliases
            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())
                    {
                        // Strip trailing /* from alias pattern and target
                        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();
        }

        // Derive module path relative to workspace root (or first search root)
        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);

        // Strip extension
        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;

        // Skip node_modules / bare node_modules imports
        if raw.starts_with("node_modules/") {
            return Resolution::NotFound;
        }

        // 1. Relative imports
        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);
        }

        // 2. Path alias (tsconfig paths)
        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;
                }
            }
        }

        // 3. baseUrl-relative bare imports
        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
    }
}

/// Try .ts, .tsx, /index.ts, /index.tsx candidates for a base path.
fn resolve_ts_file_candidates(base: &Path) -> Resolution {
    // Try as-is with ts extensions
    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
}

/// Resolve a relative specifier from a directory.
fn resolve_ts_relative(base_dir: &Path, raw: &str) -> Resolution {
    // Normalize the path
    let joined = base_dir.join(raw);
    let normalized = normalize_path(&joined);

    // Strip .js extension (TS compiles .js imports as .ts)
    let base = if normalized.extension().and_then(|e| e.to_str()) == Some("js") {
        normalized.with_extension("")
    } else {
        normalized.clone()
    };

    resolve_ts_file_candidates(&base)
}

/// Simple path normalization (handle `..` components).
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;

    /// Documents node kinds that exist in the TypeScript grammar but aren't used in trait methods.
    /// Run `cross_check_node_kinds` in registry.rs to see all potentially useful kinds.
    #[test]
    fn unused_node_kinds_audit() {
        #[rustfmt::skip]
        let documented_unused: &[&str] = &[
            // STRUCTURAL
            "class_body",              // class body block
            "class_heritage",          // extends clause
            "class_static_block",      // static { }
            "enum_assignment",         // enum value assignment
            "enum_body",               // enum body
            "formal_parameters",       // function params
            "identifier",              // too common
            "interface_body",          // interface body
            "nested_identifier",       // a.b.c path
            "nested_type_identifier",  // a.b.Type path
            "private_property_identifier", // #field
            "property_identifier",     // obj.prop
            "public_field_definition", // class field
            "shorthand_property_identifier", // { x } shorthand
            "shorthand_property_identifier_pattern", // destructuring
            "statement_block",         // { }
            "statement_identifier",    // label name
            "switch_body",             // switch cases

            // CLAUSE
            "default_type",            // default type param
            "else_clause",             // else branch
            "extends_clause",          // class extends
            "extends_type_clause",     // T extends U
            "finally_clause",          // finally block
            "implements_clause",       // implements X

            // EXPRESSION
            "as_expression",           // x as T
            "assignment_expression",   // x = y
            "augmented_assignment_expression", // x += y
            "await_expression",        // await foo
            "call_expression",         // foo()
            "function_expression",     // function() {}
            "instantiation_expression",// generic call
            "member_expression",       // foo.bar          // new Foo()
            "non_null_expression",     // x!
            "parenthesized_expression",// (expr)
            "satisfies_expression",    // x satisfies T
            "sequence_expression",     // a, b
            "subscript_expression",    // arr[i]
            "unary_expression",        // -x, !x
            "update_expression",       // x++
            "yield_expression",        // yield x

            // TYPE NODES
            "adding_type_annotation",  // : T
            "array_type",              // T[]
            "conditional_type",        // T extends U ? V : W
            "construct_signature",     // new(): T
            "constructor_type",        // new (x: T) => U
            "existential_type",        // *
            "flow_maybe_type",         // ?T      // function sig
            "function_type",           // (x: T) => U
            "generic_type",            // T<U>
            "index_type_query",        // keyof T
            "infer_type",              // infer T
            "intersection_type",       // T & U
            "literal_type",            // "foo" type
            "lookup_type",             // T[K]
            "mapped_type_clause",      // [K in T]
            "object_type",             // { x: T }
            "omitting_type_annotation",// omit annotation
            "opting_type_annotation",  // optional annotation
            "optional_type",           // T?
            "override_modifier",       // override
            "parenthesized_type",      // (T)
            "predefined_type",         // string, number
            "readonly_type",           // readonly T
            "rest_type",               // ...T
            "template_literal_type",   // `${T}`
            "template_type",           // template type
            "this_type",               // this
            "tuple_type",              // [T, U]         // : T
            "type_arguments",          // <T, U>
            "type_assertion",          // <T>x         // type name
            "type_parameter",          // T
            "type_parameters",         // <T, U>
            "type_predicate",          // x is T
            "type_predicate_annotation", // : x is T
            "type_query",              // typeof x
            "union_type",              // T | U

            // IMPORT/EXPORT DETAILS
            "accessibility_modifier",  // public/private/protected
            "export_clause",           // export { a, b }
            "export_specifier",        // export { a as b }
            "import",                  // import keyword
            "import_alias",            // import X = Y
            "import_attribute",        // import attributes
            "import_clause",           // import clause
            "import_require_clause",   // require()
            "import_specifier",        // import { a }
            "named_imports",           // { a, b }
            "namespace_export",        // export * as ns
            "namespace_import",        // import * as ns

            // DECLARATION // abstract class // abstract method
            "ambient_declaration",     // declare
            "debugger_statement",      // debugger;
            "empty_statement",         // ;
            "expression_statement",    // expr;
            "generator_function",      // function* foo
            "generator_function_declaration", // function* declaration
            "internal_module",         // namespace/module
            "labeled_statement",       // label: stmt
            "lexical_declaration",     // let/const                  // module keyword
            "using_declaration",       // using x = ...
            "variable_declaration",    // var x
            "with_statement",          // with (obj) - deprecated
            // control flow — not extracted as symbols
            "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");
    }
}