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
//! Kotlin language support.

use crate::traits::{ImportSpec, ModuleId, ModuleResolver, Resolution, ResolverConfig};
use crate::{ContainerBody, Import, Language, LanguageSymbols, Visibility};
use std::path::Path;
use tree_sitter::Node;

/// Kotlin language support.
pub struct Kotlin;

impl Kotlin {
    /// Find the first type_identifier in a delegation_specifier subtree.
    fn find_type_identifier(node: &Node, content: &str, out: &mut Vec<String>) {
        let before = out.len();
        if node.kind() == "type_identifier" {
            out.push(content[node.byte_range()].to_string());
            return;
        }
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            Self::find_type_identifier(&child, content, out);
            if out.len() > before {
                return;
            }
        }
    }
}

impl Language for Kotlin {
    fn name(&self) -> &'static str {
        "Kotlin"
    }
    fn extensions(&self) -> &'static [&'static str] {
        &["kt", "kts"]
    }
    fn grammar_name(&self) -> &'static str {
        "kotlin"
    }

    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> {
        extract_kdoc(node, content)
    }

    fn refine_kind(
        &self,
        node: &Node,
        _content: &str,
        tag_kind: crate::SymbolKind,
    ) -> crate::SymbolKind {
        if node.kind() == "class_declaration" {
            // Kotlin uses class_declaration for class, interface, enum class.
            // Distinguished by keyword children: "interface", "enum", "class".
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                match child.kind() {
                    "interface" => return crate::SymbolKind::Interface,
                    "enum" => return crate::SymbolKind::Enum,
                    // Stop before body/name to avoid scanning the entire tree
                    "type_identifier" | "class_body" | "enum_class_body" => break,
                    _ => {}
                }
            }
        }
        tag_kind
    }

    fn extract_implements(&self, node: &Node, content: &str) -> crate::ImplementsInfo {
        let mut implements = Vec::new();
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i as u32)
                && child.kind() == "delegation_specifier"
            {
                Self::find_type_identifier(&child, content, &mut implements);
            }
        }
        crate::ImplementsInfo {
            is_interface: false,
            implements,
        }
    }

    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();
            }
        };
        match node.kind() {
            "function_declaration" | "function_definition" => {
                let params = node
                    .child_by_field_name("value_parameters")
                    .or_else(|| node.child_by_field_name("parameters"))
                    .map(|p| content[p.byte_range()].to_string())
                    .unwrap_or_else(|| "()".to_string());
                let return_type = node
                    .child_by_field_name("type")
                    .map(|t| format!(": {}", content[t.byte_range()].trim()))
                    .unwrap_or_default();
                format!("fun {}{}{}", name, params, return_type)
            }
            "class_declaration" => format!("class {}", name),
            "object_declaration" => format!("object {}", name),
            "type_alias" => {
                let target = node
                    .child_by_field_name("type")
                    .map(|t| content[t.byte_range()].to_string())
                    .unwrap_or_default();
                format!("typealias {} = {}", name, target)
            }
            _ => {
                let text = &content[node.byte_range()];
                text.lines().next().unwrap_or(text).trim().to_string()
            }
        }
    }

    fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
        if node.kind() != "import_header" {
            return Vec::new();
        }

        let line = node.start_position().row + 1;

        // Get the import identifier
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "identifier" || child.kind() == "user_type" {
                let module = content[child.byte_range()].to_string();
                let is_wildcard = content[node.byte_range()].contains(".*");
                return vec![Import {
                    module,
                    names: Vec::new(),
                    alias: None,
                    is_wildcard,
                    is_relative: false,
                    line,
                }];
            }
        }

        Vec::new()
    }

    fn format_import(&self, import: &Import, _names: Option<&[&str]>) -> String {
        // Kotlin: import pkg.Class or import pkg.*
        if import.is_wildcard {
            format!("import {}.*", import.module)
        } else {
            format!("import {}", import.module)
        }
    }

    fn is_test_symbol(&self, symbol: &crate::Symbol) -> bool {
        let has_test_attr = symbol.attributes.iter().any(|a| a.contains("@Test"));
        if has_test_attr {
            return true;
        }
        match symbol.kind {
            crate::SymbolKind::Class => {
                symbol.name.starts_with("Test") || symbol.name.ends_with("Test")
            }
            _ => false,
        }
    }

    fn test_file_globs(&self) -> &'static [&'static str] {
        &[
            "**/src/test/**/*.kt",
            "**/Test*.kt",
            "**/*Test.kt",
            "**/*Tests.kt",
        ]
    }

    fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
        node.child_by_field_name("class_body")
            .or_else(|| node.child_by_field_name("body"))
    }

    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 node_name<'a>(&self, node: &Node, content: &'a str) -> Option<&'a str> {
        // Try "name" field first (most declarations)
        if let Some(name_node) = node.child_by_field_name("name") {
            return Some(&content[name_node.byte_range()]);
        }
        // Try first type_identifier (class/object declarations) or simple_identifier
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i as u32)
                && (child.kind() == "type_identifier" || child.kind() == "simple_identifier")
            {
                return Some(&content[child.byte_range()]);
            }
        }
        None
    }

    fn extract_attributes(&self, node: &Node, content: &str) -> Vec<String> {
        extract_kotlin_annotations(node, content)
    }

    fn get_visibility(&self, node: &Node, content: &str) -> Visibility {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "modifiers" {
                let mods = &content[child.byte_range()];
                if mods.contains("private") {
                    return Visibility::Private;
                }
                if mods.contains("protected") {
                    return Visibility::Protected;
                }
                if mods.contains("internal") {
                    return Visibility::Protected;
                } // internal ≈ protected for our purposes
                if mods.contains("public") {
                    return Visibility::Public;
                }
            }
            // Also check visibility_modifier directly
            if child.kind() == "visibility_modifier" {
                let vis = &content[child.byte_range()];
                if vis == "private" {
                    return Visibility::Private;
                }
                if vis == "protected" {
                    return Visibility::Protected;
                }
                if vis == "internal" {
                    return Visibility::Protected;
                }
                if vis == "public" {
                    return Visibility::Public;
                }
            }
        }
        // Kotlin default is public (unlike Java's package-private)
        Visibility::Public
    }

    fn module_resolver(&self) -> Option<&dyn ModuleResolver> {
        static RESOLVER: KotlinModuleResolver = KotlinModuleResolver;
        Some(&RESOLVER)
    }
}

impl LanguageSymbols for Kotlin {}

// =============================================================================
// Kotlin Module Resolver
// =============================================================================

/// Module resolver for Kotlin (Maven/Gradle conventions).
///
/// Kotlin package = directory hierarchy. `com.example.Foo` lives at
/// `src/main/kotlin/com/example/Foo.kt` (or `src/test/kotlin/...`).
pub struct KotlinModuleResolver;

const KOTLIN_SRC_DIRS: &[&str] = &["src/main/kotlin", "src/test/kotlin", ""];

impl ModuleResolver for KotlinModuleResolver {
    fn workspace_config(&self, root: &Path) -> ResolverConfig {
        ResolverConfig {
            workspace_root: root.to_path_buf(),
            path_mappings: Vec::new(),
            search_roots: KOTLIN_SRC_DIRS.iter().map(|d| root.join(d)).collect(),
        }
    }

    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 ext != "kt" && ext != "kts" {
            return Vec::new();
        }
        for search_root in &cfg.search_roots {
            if let Ok(rel) = file.strip_prefix(search_root) {
                let rel_str = rel
                    .to_str()
                    .unwrap_or("")
                    .trim_end_matches(".kts")
                    .trim_end_matches(".kt")
                    .replace(['/', '\\'], ".");
                if !rel_str.is_empty() {
                    return vec![ModuleId {
                        canonical_path: rel_str,
                    }];
                }
            }
        }
        Vec::new()
    }

    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 ext != "kt" && ext != "kts" {
            return Resolution::NotApplicable;
        }
        let raw = &spec.raw;
        let path_part = raw.replace('.', "/");
        let exported_name = raw.rsplit('.').next().unwrap_or(raw).to_string();
        for search_root in &cfg.search_roots {
            let candidate = search_root.join(format!("{}.kt", path_part));
            if candidate.exists() {
                return Resolution::Resolved(candidate, exported_name.clone());
            }
            let candidate = search_root.join(format!("{}.kts", path_part));
            if candidate.exists() {
                return Resolution::Resolved(candidate, exported_name.clone());
            }
        }
        Resolution::NotFound
    }
}

/// Extract a KDoc comment (`/** ... */`) preceding a node.
///
/// Walks backwards through siblings looking for a `multiline_comment` starting with `/**`.
fn extract_kdoc(node: &Node, content: &str) -> Option<String> {
    let mut prev = node.prev_sibling();
    while let Some(sibling) = prev {
        match sibling.kind() {
            "multiline_comment" => {
                let text = &content[sibling.byte_range()];
                if text.starts_with("/**") {
                    // Strip /** and */ and leading *
                    let lines: Vec<&str> = text
                        .strip_prefix("/**")
                        .unwrap_or(text)
                        .strip_suffix("*/")
                        .unwrap_or(text)
                        .lines()
                        .map(|l| l.trim().strip_prefix("*").unwrap_or(l).trim())
                        .filter(|l| !l.is_empty())
                        .collect();
                    if !lines.is_empty() {
                        return Some(lines.join(" "));
                    }
                }
                return None;
            }
            "line_comment" => {
                // Skip single-line comments
            }
            _ => return None,
        }
        prev = sibling.prev_sibling();
    }
    None
}

/// Extract annotations from a Kotlin definition node.
/// Kotlin annotations live inside a `modifiers` child (e.g. `@JvmStatic`, `@Deprecated`).
fn extract_kotlin_annotations(node: &Node, content: &str) -> Vec<String> {
    let mut attrs = Vec::new();
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "modifiers" {
            let mut mod_cursor = child.walk();
            for mod_child in child.children(&mut mod_cursor) {
                if mod_child.kind() == "annotation" {
                    attrs.push(content[mod_child.byte_range()].to_string());
                }
            }
        }
    }
    attrs
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::validate_unused_kinds_audit;

    /// Documents node kinds that exist in the Kotlin 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
            "annotated_lambda",        // @Ann { }
            "class_body",              // class body
            "class_modifier",          // class modifiers
            "class_parameter",         // class param
            "constructor_delegation_call", // this(), super()  // constructor call
            "control_structure_body",  // control body
            "delegation_specifier",    // delegation              // enum value
            "function_body",           // function body
            "function_modifier",       // fun modifiers
            "function_type_parameters",// (T) -> U params
            "function_value_parameters", // fun params
            "identifier",              // too common
            "import_alias",            // import as
            "import_list",             // imports
            "inheritance_modifier",    // open, final
            "interpolated_expression", // ${expr}
            "interpolated_identifier", // $id
            "lambda_parameters",       // lambda params
            "member_modifier",         // member modifiers
            "modifiers",               // modifiers
            "multi_variable_declaration", // val (a, b)
            "parameter_modifier",      // param modifiers
            "parameter_modifiers",     // param modifiers list
            "parameter_with_optional_type", // optional type param
            "platform_modifier",       // expect, actual
            "primary_constructor",     // primary constructor    // property
            "property_modifier",       // property modifiers
            "reification_modifier",    // reified
            "secondary_constructor",   // secondary constructor       // simple id
            "statements",              // statement list
            "visibility_modifier",     // public, private

            // EXPRESSION
            "additive_expression",     // a + b
            "as_expression",           // x as T         // foo()
            "check_expression",        // is, !is
            "comparison_expression",   // a < b
            "directly_assignable_expression", // assignable
            "equality_expression",     // a == b
            "indexing_expression",     // arr[i]
            "infix_expression",        // a infix b
            "multiplicative_expression", // a * b   // a.b
            "parenthesized_expression",// (expr)
            "postfix_expression",      // x++
            "prefix_expression",       // ++x
            "range_expression",        // 0..10
            "spread_expression",       // *arr
            "super_expression",        // super
            "this_expression",         // this
            "wildcard_import",         // import.*

            // TYPE
            "function_type",           // (T) -> U
            "not_nullable_type",       // T & Any
            "nullable_type",           // T?
            "parenthesized_type",      // (T)
            "parenthesized_user_type", // (UserType)
            "receiver_type",           // T.
            "type_arguments",          // <T, U>
            "type_constraint",         // T : Bound
            "type_constraints",        // where clause         // type name
            "type_modifiers",          // type modifiers
            "type_parameter",          // T
            "type_parameter_modifiers",// type param mods
            "type_parameters",         // <T, U>
            "type_projection",         // out T, in T
            "type_projection_modifiers", // projection mods
            "type_test",               // is T               // user-defined type
            "variance_modifier",       // in, out

            // OTHER
            "finally_block",           // finally
            // property_declaration and variable_declaration are intentionally excluded from
            // tags.scm: the Kotlin grammar uses the same node kind for class-level properties
            // AND local val/var declarations inside function bodies. Including them in tags
            // causes collect_symbols_from_tags to fail because node_name() returns None for
            // property_declaration (name is nested inside variable_declaration, not a direct
            // "name" field), silently dropping all symbols in the file.
            "property_declaration",
            "variable_declaration",
            // control flow — not extracted as symbols
            "if_expression",
            "anonymous_function",
            "when_entry",
            "conjunction_expression",
            "disjunction_expression",
            "while_statement",
            "do_while_statement",
            "enum_class_body",
            "for_statement",
            "import_header",
            "elvis_expression",
            "jump_expression",
            "when_expression",
            "try_expression",
            "lambda_literal",
            "catch_block",
        ];

        validate_unused_kinds_audit(&Kotlin, documented_unused)
            .expect("Kotlin unused node kinds audit failed");
    }
}