codanna 0.9.19

Code Intelligence for Large Language Models
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Go-specific language behavior implementation

use crate::Visibility;
use crate::parsing::LanguageBehavior;
use crate::parsing::behavior_state::{BehaviorState, StatefulBehavior};
use crate::parsing::resolution::{InheritanceResolver, ResolutionScope};
use crate::types::FileId;
use std::path::{Path, PathBuf};
use tree_sitter::Language;

use super::resolution::{GoInheritanceResolver, GoResolutionContext};

/// Go language behavior implementation
#[derive(Clone)]
pub struct GoBehavior {
    state: BehaviorState,
}

impl GoBehavior {
    /// Create a new Go behavior instance
    pub fn new() -> Self {
        Self {
            state: BehaviorState::new(),
        }
    }
}

impl Default for GoBehavior {
    fn default() -> Self {
        Self::new()
    }
}

impl StatefulBehavior for GoBehavior {
    fn state(&self) -> &BehaviorState {
        &self.state
    }
}

impl LanguageBehavior for GoBehavior {
    fn language_id(&self) -> crate::parsing::registry::LanguageId {
        crate::parsing::registry::LanguageId::new("go")
    }

    fn format_module_path(&self, base_path: &str, _symbol_name: &str) -> String {
        // Go uses file paths as module paths, not including the symbol name
        // All symbols in the same file share the same module path for visibility
        base_path.to_string()
    }

    fn get_language(&self) -> Language {
        tree_sitter_go::LANGUAGE.into()
    }
    fn module_separator(&self) -> &'static str {
        "/"
    }

    fn format_path_as_module(&self, components: &[&str]) -> Option<String> {
        if components.is_empty() {
            Some(".".to_string())
        } else {
            Some(components.join("/"))
        }
    }

    /// Get module path for a Go file using resolution rules from go.mod.
    ///
    /// Uses cached resolution rules from GoProvider to construct proper Go module paths.
    /// Falls back to directory-based path if no rules are available.
    fn module_path_from_file(
        &self,
        file_path: &Path,
        project_root: &Path,
        extensions: &[&str],
    ) -> Option<String> {
        use crate::parsing::paths::strip_extension;
        use crate::project_resolver::persist::ResolutionPersistence;
        use std::cell::RefCell;
        use std::time::{Duration, Instant};

        // Thread-local cache with 1-second TTL (per Python/TypeScript pattern)
        thread_local! {
            static RULES_CACHE: RefCell<Option<(Instant, crate::project_resolver::persist::ResolutionIndex)>> = const { RefCell::new(None) };
        }

        // Try cached resolution first
        let cached_result = RULES_CACHE.with(|cache| {
            let mut cache_ref = cache.borrow_mut();

            // Check if cache needs reload (>1 second old or empty)
            let needs_reload = cache_ref
                .as_ref()
                .map(|(ts, _)| ts.elapsed() >= Duration::from_secs(1))
                .unwrap_or(true);

            // Load from disk if needed
            if needs_reload {
                let persistence =
                    ResolutionPersistence::new(std::path::Path::new(crate::init::local_dir_name()));
                if let Ok(index) = persistence.load("go") {
                    *cache_ref = Some((Instant::now(), index));
                } else {
                    *cache_ref = None;
                }
            }

            // Get module path from cached rules
            if let Some((_, ref index)) = *cache_ref {
                // Canonicalize file path for matching
                if let Ok(canon_file) = file_path.canonicalize() {
                    // Find config that applies to this file
                    if let Some(config_path) = index.get_config_for_file(&canon_file) {
                        if let Some(rules) = index.rules.get(config_path) {
                            // Get baseUrl (Go module name from go.mod)
                            if let Some(ref base_url) = rules.base_url {
                                // Find matching source root
                                for root_path in rules.paths.keys() {
                                    let root = std::path::Path::new(root_path);
                                    let canon_root =
                                        root.canonicalize().unwrap_or_else(|_| root.to_path_buf());

                                    if let Ok(relative) = canon_file.strip_prefix(&canon_root) {
                                        // Get directory path (Go packages are directories)
                                        let relative_str = relative.to_str()?;
                                        let path_without_ext =
                                            strip_extension(relative_str, extensions);
                                        let dir_path = if let Some(parent) =
                                            Path::new(path_without_ext).parent()
                                        {
                                            parent.to_str().unwrap_or("")
                                        } else {
                                            ""
                                        };

                                        // Combine baseUrl with relative directory
                                        if dir_path.is_empty() {
                                            return Some(base_url.clone());
                                        } else {
                                            return Some(format!("{base_url}/{dir_path}"));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            None
        });

        // Return cached result if found
        if cached_result.is_some() {
            return cached_result;
        }

        // Fallback: directory-based path (original behavior)
        let relative_path = file_path
            .strip_prefix(project_root)
            .ok()
            .or_else(|| file_path.strip_prefix("./").ok())
            .unwrap_or(file_path);

        let path = relative_path.to_str()?;
        let path_clean = path.trim_start_matches("./");
        let module_path = strip_extension(path_clean, extensions);

        let dir_path = if let Some(parent) = Path::new(module_path).parent() {
            parent.to_str().unwrap_or("")
        } else {
            ""
        };

        if dir_path.is_empty() {
            Some(".".to_string())
        } else {
            Some(dir_path.to_string())
        }
    }

    /// Parse visibility from Go symbol signature using capitalization rules
    ///
    /// In Go, visibility is determined by the first character of the identifier:
    /// - Uppercase first letter = Public/Exported (accessible outside package)
    /// - Lowercase first letter = Private/Unexported (package-private)
    fn parse_visibility(&self, signature: &str) -> Visibility {
        // Go uses capitalization for visibility
        // Extract the symbol name from the signature and check if it starts with uppercase

        // Try to extract the symbol name from different signature patterns
        let symbol_name = if let Some(func_start) = signature.find("func ") {
            // Function signature: "func FunctionName(" or "func (receiver) MethodName("
            let after_func = &signature[func_start + 5..].trim_start();
            if after_func.starts_with('(') {
                // Method with receiver: "func (r *Type) MethodName("
                if let Some(receiver_end) = after_func.find(") ") {
                    let after_receiver = &after_func[receiver_end + 2..].trim_start();
                    after_receiver.split('(').next().unwrap_or("").trim()
                } else {
                    ""
                }
            } else {
                // Regular function: "func FunctionName("
                after_func.split('(').next().unwrap_or("").trim()
            }
        } else if let Some(type_start) = signature.find("type ") {
            // Type signature: "type TypeName struct" or "type TypeName interface"
            let after_type = &signature[type_start + 5..];
            after_type.split_whitespace().next().unwrap_or("")
        } else if let Some(var_start) = signature.find("var ") {
            // Variable signature: "var VariableName type"
            let after_var = &signature[var_start + 4..];
            after_var.split_whitespace().next().unwrap_or("")
        } else if let Some(const_start) = signature.find("const ") {
            // Constant signature: "const ConstantName = value"
            let after_const = &signature[const_start + 6..];
            after_const.split_whitespace().next().unwrap_or("")
        } else {
            // Fallback: take the first word that looks like an identifier
            signature
                .split_whitespace()
                .find(|word| word.chars().next().is_some_and(|c| c.is_alphabetic()))
                .unwrap_or("")
        };

        // Go visibility: uppercase first letter = public, lowercase = private
        if let Some(first_char) = symbol_name.chars().next() {
            if first_char.is_uppercase() {
                Visibility::Public
            } else {
                Visibility::Private
            }
        } else {
            Visibility::Private
        }
    }

    /// Go uses interfaces instead of traits
    ///
    /// Go's interface system provides similar functionality to traits
    /// but uses structural typing (duck typing) rather than explicit implementation.
    fn supports_traits(&self) -> bool {
        false // Go has interfaces, not traits (traits are a Rust concept)
    }

    /// Go supports methods on types (inherent methods)
    ///
    /// Methods can be defined on any named type using receiver syntax:
    /// `func (r ReceiverType) MethodName() {}`
    fn supports_inherent_methods(&self) -> bool {
        true // Go has methods on types
    }

    // Go-specific resolution overrides

    /// Create a Go-specific resolution context for symbol resolution
    ///
    /// Returns a GoResolutionContext that handles Go's package-based scoping,
    /// import resolution, and module system integration.
    fn create_resolution_context(&self, file_id: FileId) -> Box<dyn ResolutionScope> {
        Box::new(GoResolutionContext::new(file_id))
    }

    fn create_inheritance_resolver(&self) -> Box<dyn InheritanceResolver> {
        Box::new(GoInheritanceResolver::new())
    }

    fn inheritance_relation_name(&self) -> &'static str {
        // Go uses interface implementation (implicit)
        // There's no explicit "extends" or "implements" in Go
        "implements"
    }

    fn map_relationship(&self, language_specific: &str) -> crate::relationship::RelationKind {
        use crate::relationship::RelationKind;

        match language_specific {
            "extends" => RelationKind::Extends,
            "implements" => RelationKind::Implements,
            "uses" => RelationKind::Uses,
            "calls" => RelationKind::Calls,
            "defines" => RelationKind::Defines,
            _ => RelationKind::References,
        }
    }

    // Override import tracking methods to use state

    fn register_file(&self, path: PathBuf, file_id: FileId, module_path: String) {
        self.register_file_with_state(path, file_id, module_path);
    }

    fn add_import(&self, import: crate::parsing::Import) {
        self.add_import_with_state(import);
    }

    fn get_imports_for_file(&self, file_id: FileId) -> Vec<crate::parsing::Import> {
        self.get_imports_from_state(file_id)
    }

    // Go-specific: Symbol resolution rules
    fn is_resolvable_symbol(&self, symbol: &crate::Symbol) -> bool {
        use crate::SymbolKind;
        use crate::symbol::ScopeContext;

        // Go allows forward references for functions, types, and constants at package level
        let package_level_symbol = matches!(
            symbol.kind,
            SymbolKind::Function
                | SymbolKind::Struct
                | SymbolKind::Interface
                | SymbolKind::Constant
                | SymbolKind::TypeAlias
        );

        if package_level_symbol {
            return true;
        }

        // Methods are always resolvable within their file
        if matches!(symbol.kind, SymbolKind::Method) {
            return true;
        }

        // Check scope_context for other symbols
        if let Some(ref scope_context) = symbol.scope_context {
            match scope_context {
                ScopeContext::Module | ScopeContext::Global | ScopeContext::Package => true,
                ScopeContext::Local { .. } | ScopeContext::Parameter => false,
                ScopeContext::ClassMember { .. } => {
                    // Struct/interface members are resolvable if exported (uppercase)
                    matches!(symbol.visibility, Visibility::Public)
                }
            }
        } else {
            // Fallback for symbols without scope_context
            matches!(symbol.kind, SymbolKind::TypeAlias | SymbolKind::Variable)
        }
    }

    fn get_module_path_for_file(&self, file_id: FileId) -> Option<String> {
        // Use the BehaviorState to get module path (O(1) lookup)
        self.state.get_module_path(file_id)
    }

    fn configure_symbol(&self, symbol: &mut crate::Symbol, module_path: Option<&str>) {
        // Apply Go-specific module path formatting
        if let Some(path) = module_path {
            // Go uses package paths, not including symbol names
            symbol.module_path = Some(path.to_string().into());
        }

        // Apply Go visibility parsing based on capitalization
        if let Some(ref sig) = symbol.signature {
            symbol.visibility = self.parse_visibility(sig);
        }

        // Set Go-specific symbol properties
        // Go symbols are package-scoped by default
        if symbol.module_path.is_none() {
            symbol.module_path = Some(".".to_string().into()); // Current package
        }
    }

    fn import_matches_symbol(
        &self,
        import_path: &str,
        symbol_module_path: &str,
        importing_module: Option<&str>,
    ) -> bool {
        // Helper function to resolve relative path to absolute module path for Go
        fn resolve_relative_path(import_path: &str, importing_mod: &str) -> String {
            if import_path.starts_with("./") {
                // Same directory import
                let relative = import_path.trim_start_matches("./");

                if importing_mod.is_empty() || importing_mod == "." {
                    relative.to_string()
                } else {
                    format!("{importing_mod}/{relative}")
                }
            } else if import_path.starts_with("../") {
                // Parent directory import
                // Start with the importing module parts as owned strings
                let mut module_parts: Vec<String> =
                    importing_mod.split('/').map(|s| s.to_string()).collect();

                let mut path_remaining: &str = import_path;

                // Navigate up for each '../'
                while path_remaining.starts_with("../") {
                    if !module_parts.is_empty() {
                        module_parts.pop();
                    }
                    // If we've gone above the module root, we just continue
                    // This handles cases like ../../../some/path from a shallow module
                    path_remaining = &path_remaining[3..];
                }

                // Add the remaining path
                if !path_remaining.is_empty() {
                    module_parts.extend(
                        path_remaining
                            .split('/')
                            .filter(|s| !s.is_empty())
                            .map(|s| s.to_string()),
                    );
                }

                module_parts.join("/")
            } else {
                // Not a relative path, return as-is
                import_path.to_string()
            }
        }

        // Case 1: Exact match (most common case, check first for performance)
        if import_path == symbol_module_path {
            return true;
        }

        // Case 2: Only do complex matching if we have the importing module context
        if let Some(importing_mod) = importing_module {
            // Go import resolution:
            // - Relative imports start with './' or '../'
            // - Absolute imports are package paths like "fmt", "github.com/user/repo/package"

            if import_path.starts_with("./") || import_path.starts_with("../") {
                // Resolve relative path to absolute module path
                let resolved = resolve_relative_path(import_path, importing_mod);

                // Check if it matches exactly
                if resolved == symbol_module_path {
                    return true;
                }
            }
            // else: absolute package imports like "fmt", "github.com/user/repo"
            // These should match exactly (no complex resolution needed for Go packages)
        }

        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Visibility;
    use crate::parsing::registry::LanguageId;
    use std::path::Path;

    #[test]
    fn test_module_separator() {
        let behavior = GoBehavior::new();
        assert_eq!(behavior.module_separator(), "/");
    }

    #[test]
    fn test_module_path_from_file() {
        let behavior = GoBehavior::new();
        let project_root = Path::new("/home/user/project");
        let extensions = &["go"];

        // Test basic Go file
        let file_path = Path::new("/home/user/project/pkg/utils/helper.go");
        assert_eq!(
            behavior.module_path_from_file(file_path, project_root, extensions),
            Some("pkg/utils".to_string())
        );

        // Test root level file
        let file_path = Path::new("/home/user/project/main.go");
        assert_eq!(
            behavior.module_path_from_file(file_path, project_root, extensions),
            Some(".".to_string())
        );

        // Test nested package
        let file_path = Path::new("/home/user/project/internal/api/server.go");
        assert_eq!(
            behavior.module_path_from_file(file_path, project_root, extensions),
            Some("internal/api".to_string())
        );
    }

    #[test]
    fn test_format_module_path() {
        let behavior = GoBehavior::new();
        // Go doesn't append symbol names to module paths like Rust does
        assert_eq!(
            behavior.format_module_path("pkg/utils", "Helper"),
            "pkg/utils"
        );
    }

    #[test]
    fn test_parse_visibility() {
        let behavior = GoBehavior::new();

        // Test function signatures
        assert_eq!(
            behavior.parse_visibility("func PublicFunction() error"),
            Visibility::Public
        );
        assert_eq!(
            behavior.parse_visibility("func privateFunction() error"),
            Visibility::Private
        );

        // Test method signatures
        assert_eq!(
            behavior.parse_visibility("func (s *Server) HandleRequest() error"),
            Visibility::Public
        );
        assert_eq!(
            behavior.parse_visibility("func (s *Server) handleInternal() error"),
            Visibility::Private
        );

        // Test type signatures
        assert_eq!(
            behavior.parse_visibility("type PublicStruct struct"),
            Visibility::Public
        );
        assert_eq!(
            behavior.parse_visibility("type privateStruct struct"),
            Visibility::Private
        );

        // Test variable signatures
        assert_eq!(
            behavior.parse_visibility("var GlobalVar string"),
            Visibility::Public
        );
        assert_eq!(
            behavior.parse_visibility("var localVar string"),
            Visibility::Private
        );

        // Test constant signatures
        assert_eq!(
            behavior.parse_visibility("const MaxRetries = 3"),
            Visibility::Public
        );
        assert_eq!(
            behavior.parse_visibility("const timeout = 30"),
            Visibility::Private
        );
    }

    #[test]
    fn test_supports_traits() {
        let behavior = GoBehavior::new();
        assert!(!behavior.supports_traits()); // Go has interfaces, not traits
    }

    #[test]
    fn test_supports_inherent_methods() {
        let behavior = GoBehavior::new();
        assert!(behavior.supports_inherent_methods()); // Go has methods on types
    }

    #[test]
    fn test_import_matches_symbol() {
        let behavior = GoBehavior::new();

        // Test exact matches
        assert!(behavior.import_matches_symbol("fmt", "fmt", None));
        assert!(behavior.import_matches_symbol(
            "github.com/user/repo",
            "github.com/user/repo",
            None
        ));

        // Test relative imports
        assert!(behavior.import_matches_symbol("./utils", "pkg/utils", Some("pkg")));
        assert!(behavior.import_matches_symbol("../shared", "pkg/shared", Some("pkg/api")));

        // Test non-matches
        assert!(!behavior.import_matches_symbol("fmt", "strings", None));
        assert!(!behavior.import_matches_symbol("./utils", "pkg/other", Some("pkg")));
    }

    #[test]
    fn test_configure_symbol() {
        use crate::{FileId, Range, Symbol, SymbolId, SymbolKind, Visibility};

        let behavior = GoBehavior::new();

        // Test function with public signature
        let mut symbol = Symbol {
            id: SymbolId::new(1).unwrap(),
            name: "PublicFunction".into(),
            kind: SymbolKind::Function,
            signature: Some("func PublicFunction() error".into()),
            module_path: None,
            file_id: FileId::new(1).unwrap(),
            range: Range {
                start_line: 1,
                start_column: 1,
                end_line: 1,
                end_column: 10,
            },
            file_path: "<unknown>".into(),
            doc_comment: None,
            visibility: Visibility::Private, // Will be updated by configure_symbol
            scope_context: None,
            language_id: Some(LanguageId::new("go")),
        };

        behavior.configure_symbol(&mut symbol, Some("pkg/utils"));

        assert_eq!(
            symbol.module_path.as_ref().map(|s| s.as_ref()),
            Some("pkg/utils")
        );
        assert_eq!(symbol.visibility, Visibility::Public); // Should be public due to capitalization

        // Test variable with private signature
        let mut symbol = Symbol {
            id: SymbolId::new(2).unwrap(),
            name: "privateVar".into(),
            kind: SymbolKind::Variable,
            signature: Some("var privateVar string".into()),
            module_path: None,
            file_id: FileId::new(1).unwrap(),
            range: Range {
                start_line: 1,
                start_column: 1,
                end_line: 1,
                end_column: 10,
            },
            file_path: "<unknown>".into(),
            doc_comment: None,
            visibility: Visibility::Public, // Will be updated by configure_symbol
            scope_context: None,
            language_id: Some(LanguageId::new("go")),
        };

        behavior.configure_symbol(&mut symbol, None);

        assert_eq!(symbol.module_path.as_ref().map(|s| s.as_ref()), Some(".")); // Default to current package
        assert_eq!(symbol.visibility, Visibility::Private); // Should be private due to lowercase
    }
}