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

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

/// Swift language support.
pub struct Swift;

impl Swift {
    /// Find the first type_identifier in an inheritance_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 Swift {
    fn name(&self) -> &'static str {
        "Swift"
    }
    fn extensions(&self) -> &'static [&'static str] {
        &["swift"]
    }
    fn grammar_name(&self) -> &'static str {
        "swift"
    }

    fn as_symbols(&self) -> Option<&dyn LanguageSymbols> {
        Some(self)
    }

    fn signature_suffix(&self) -> &'static str {
        " {}"
    }

    fn refine_kind(
        &self,
        node: &Node,
        content: &str,
        tag_kind: crate::SymbolKind,
    ) -> crate::SymbolKind {
        // Swift uses class_declaration for class/struct/enum/actor,
        // distinguished by the declaration_kind field.
        if node.kind() == "class_declaration"
            && let Some(kind_node) = node.child_by_field_name("declaration_kind")
        {
            let kind_text = &content[kind_node.byte_range()];
            return match kind_text {
                "struct" => crate::SymbolKind::Struct,
                "enum" => crate::SymbolKind::Enum,
                "class" | "actor" => crate::SymbolKind::Class,
                _ => tag_kind,
            };
        }
        tag_kind
    }

    fn extract_docstring(&self, node: &Node, content: &str) -> Option<String> {
        // Swift doc comments use triple-slash `///` lines or `/** */` blocks.
        let mut doc_lines: Vec<String> = Vec::new();
        let mut prev = node.prev_sibling();

        while let Some(sibling) = prev {
            match sibling.kind() {
                "comment" => {
                    let text = &content[sibling.byte_range()];
                    if text.starts_with("///") {
                        let line = text.strip_prefix("///").unwrap_or("").trim().to_string();
                        doc_lines.push(line);
                    } else {
                        break;
                    }
                }
                "multiline_comment" => {
                    let text = &content[sibling.byte_range()];
                    if text.starts_with("/**") {
                        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 None;
                        }
                        return Some(lines.join(" "));
                    }
                    break;
                }
                "attribute" => {
                    // Skip attributes between doc comment and declaration
                }
                _ => break,
            }
            prev = sibling.prev_sibling();
        }

        if doc_lines.is_empty() {
            return None;
        }
        doc_lines.reverse();
        let joined = doc_lines.join(" ");
        let trimmed = joined.trim().to_string();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed)
        }
    }

    fn extract_attributes(&self, node: &Node, content: &str) -> Vec<String> {
        let mut attrs = Vec::new();
        if let Some(mods) = node.child_by_field_name("modifiers") {
            let mut cursor = mods.walk();
            for child in mods.children(&mut cursor) {
                if child.kind() == "attribute" {
                    let text = content[child.byte_range()].trim().to_string();
                    if !text.is_empty() {
                        attrs.push(text);
                    }
                }
            }
        }
        let mut prev = node.prev_sibling();
        while let Some(sibling) = prev {
            if sibling.kind() == "attribute" {
                let text = content[sibling.byte_range()].trim().to_string();
                if !text.is_empty() {
                    attrs.insert(0, text);
                }
                prev = sibling.prev_sibling();
            } else {
                break;
            }
        }
        attrs
    }

    fn extract_implements(&self, node: &Node, content: &str) -> crate::ImplementsInfo {
        let mut implements = Vec::new();
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "inheritance_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" => {
                let params = 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("return_type")
                    .map(|t| format!(" -> {}", content[t.byte_range()].trim()))
                    .unwrap_or_default();
                format!("func {}{}{}", name, params, return_type)
            }
            "class_declaration" => format!("class {}", name),
            "struct_declaration" => format!("struct {}", name),
            "protocol_declaration" => format!("protocol {}", name),
            "enum_declaration" => format!("enum {}", name),
            "extension_declaration" => format!("extension {}", name),
            "actor_declaration" => format!("actor {}", name),
            "typealias_declaration" => {
                let target = node
                    .child_by_field_name("value")
                    .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_declaration" {
            return Vec::new();
        }

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

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

        Vec::new()
    }

    fn format_import(&self, import: &Import, _names: Option<&[&str]>) -> String {
        // Swift: import Module
        format!("import {}", import.module)
    }

    fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
        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 get_visibility(&self, node: &Node, content: &str) -> Visibility {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "modifiers" || child.kind() == "modifier" {
                let mod_text = &content[child.byte_range()];
                if mod_text.contains("private") || mod_text.contains("fileprivate") {
                    return Visibility::Private;
                }
                if mod_text.contains("internal") {
                    return Visibility::Protected;
                }
                if mod_text.contains("public") || mod_text.contains("open") {
                    return Visibility::Public;
                }
            }
        }
        // Swift default is internal
        Visibility::Protected
    }

    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_"),
            crate::SymbolKind::Module => name == "tests" || name == "test",
            _ => false,
        }
    }

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

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

impl LanguageSymbols for Swift {}

// =============================================================================
// Swift Module Resolver
// =============================================================================

/// Module resolver for Swift (Swift Package Manager conventions).
///
/// Each target in `Sources/<TargetName>/` is a module.
/// `import TargetName` → `Sources/TargetName/` directory.
pub struct SwiftModuleResolver;

impl ModuleResolver for SwiftModuleResolver {
    fn workspace_config(&self, root: &Path) -> ResolverConfig {
        let mut path_mappings: Vec<(String, PathBuf)> = Vec::new();

        let package_swift = root.join("Package.swift");
        if let Ok(content) = std::fs::read_to_string(&package_swift) {
            // Parse `.target(name: "TargetName"` patterns
            let mut search_start = 0;
            while let Some(pos) = content[search_start..].find(".target(name:") {
                let abs_pos = search_start + pos;
                let after = &content[abs_pos + 13..]; // after ".target(name:"
                // Find the quoted name
                if let Some(q_start) = after.find('"') {
                    let rest = &after[q_start + 1..];
                    if let Some(q_end) = rest.find('"') {
                        let target_name = &rest[..q_end];
                        let target_dir = root.join("Sources").join(target_name);
                        path_mappings.push((target_name.to_string(), target_dir));
                    }
                }
                search_start = abs_pos + 13;
            }
        }

        // If no Package.swift or no targets found, scan Sources/ for directories
        if path_mappings.is_empty() {
            let sources_dir = root.join("Sources");
            if let Ok(entries) = std::fs::read_dir(&sources_dir) {
                for entry in entries.flatten() {
                    if entry.path().is_dir()
                        && let Some(name) = entry.file_name().to_str()
                    {
                        path_mappings.push((name.to_string(), entry.path()));
                    }
                }
            }
        }

        ResolverConfig {
            workspace_root: root.to_path_buf(),
            path_mappings,
            search_roots: vec![root.join("Sources")],
        }
    }

    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 != "swift" {
            return Vec::new();
        }
        for (target_name, target_dir) in &cfg.path_mappings {
            if file.starts_with(target_dir) {
                return vec![ModuleId {
                    canonical_path: target_name.clone(),
                }];
            }
        }
        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 != "swift" {
            return Resolution::NotApplicable;
        }
        let raw = &spec.raw;
        // Swift `import TargetName` → look in path_mappings
        for (target_name, target_dir) in &cfg.path_mappings {
            if target_name == raw {
                return Resolution::Resolved(target_dir.clone(), String::new());
            }
        }
        Resolution::NotFound
    }
}

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

    #[test]
    fn unused_node_kinds_audit() {
        #[rustfmt::skip]
        let documented_unused: &[&str] = &[
            // STRUCTURAL
            "as_operator", "associatedtype_declaration", "catch_keyword", "class_body",
            "computed_modify", "constructor_expression", "constructor_suffix", "custom_operator",
            "deinit_declaration", "deprecated_operator_declaration_body", "didset_clause",
            "else", "enum_class_body", "enum_entry", "enum_type_parameters",
            "existential_type", "external_macro_definition", "function_body", "function_modifier",
            "getter_specifier", "identifier", "inheritance_modifier", "inheritance_specifier",
            "interpolated_expression", "key_path_expression", "key_path_string_expression",
            "lambda_function_type", "lambda_function_type_parameters", "lambda_parameter",
            "macro_declaration", "macro_definition", "member_modifier", "metatype", "modifiers",
            "modify_specifier", "mutation_modifier", "opaque_type", "operator_declaration",
            "optional_type", "ownership_modifier", "parameter_modifier", "parameter_modifiers",
            "precedence_group_declaration", "property_behavior_modifier", "property_declaration",
            "property_modifier", "protocol_body", "protocol_composition_type",
            "protocol_function_declaration", "protocol_property_declaration", "self_expression",
            "setter_specifier", "simple_identifier", "statement_label", "statements",
            "super_expression", "switch_entry", "throw_keyword", "throws", "try_operator",
            "tuple_expression", "tuple_type", "tuple_type_item", "type_annotation",
            "type_arguments", "type_constraint", "type_constraints", "type_identifier",
            "type_modifiers", "type_pack_expansion", "type_parameter", "type_parameter_modifiers",
            "type_parameter_pack", "type_parameters", "user_type", "visibility_modifier",
            "where_clause", "willset_clause", "willset_didset_block",
            // EXPRESSION
            "additive_expression", "as_expression", "await_expression", "call_expression",
            "check_expression", "comparison_expression", "conjunction_expression",
            "directly_assignable_expression", "disjunction_expression", "equality_expression",
            "infix_expression", "multiplicative_expression", "navigation_expression",
            "open_end_range_expression", "open_start_range_expression", "postfix_expression",
            "prefix_expression", "range_expression", "selector_expression", "try_expression",
            // TYPE
            "array_type", "dictionary_type", "function_type",
            // covered by tags.scm
            "init_declaration",
            "repeat_while_statement",
            "while_statement",
            "import_declaration",
            "subscript_declaration",
            "lambda_literal",
            "for_statement",
            "if_statement",
            "nil_coalescing_expression",
            "do_statement",
            "ternary_expression",
            "catch_block",
            "control_transfer_statement",
            "switch_statement",
            "guard_statement",
        ];

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