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
//! Rust-specific language behavior implementation

use super::resolution::{RustResolutionContext, RustTraitResolver};
use crate::FileId;
use crate::Visibility;
use crate::parsing::behavior_state::{BehaviorState, StatefulBehavior};
use crate::parsing::{InheritanceResolver, LanguageBehavior, ResolutionScope};
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use tree_sitter::Language;

/// Rust language behavior implementation
#[derive(Clone)]
pub struct RustBehavior {
    language: Language,
    state: BehaviorState,
    trait_resolver: Arc<RwLock<RustTraitResolver>>,
}

impl RustBehavior {
    /// Create a new Rust behavior instance
    pub fn new() -> Self {
        Self {
            language: tree_sitter_rust::LANGUAGE.into(),
            state: BehaviorState::new(),
            trait_resolver: Arc::new(RwLock::new(RustTraitResolver::new())),
        }
    }
}

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

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

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

    fn format_module_path(&self, base_path: &str, symbol_name: &str) -> String {
        format!("{base_path}::{symbol_name}")
    }

    fn parse_visibility(&self, signature: &str) -> Visibility {
        if signature.contains("pub(crate)") {
            Visibility::Crate
        } else if signature.contains("pub(super)") {
            Visibility::Module
        } else if signature.contains("pub ") || signature.starts_with("pub ") {
            Visibility::Public
        } else {
            Visibility::Private
        }
    }

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

    fn supports_traits(&self) -> bool {
        true
    }

    fn supports_inherent_methods(&self) -> bool {
        true
    }

    fn get_language(&self) -> Language {
        self.language.clone()
    }

    fn format_path_as_module(&self, components: &[&str]) -> Option<String> {
        // Handle empty path
        if components.is_empty() {
            return Some("crate".to_string());
        }

        // Handle mod.rs: ["foo", "mod"] -> ["foo"]
        let components: Vec<&str> = if components.last() == Some(&"mod") {
            components[..components.len() - 1].to_vec()
        } else {
            components.to_vec()
        };

        // Handle main.rs, lib.rs, or empty (after mod.rs stripping)
        if components.is_empty()
            || (components.len() == 1 && (components[0] == "main" || components[0] == "lib"))
        {
            return Some("crate".to_string());
        }

        // Normal case: join with :: and prepend crate::
        Some(format!("crate::{}", components.join("::")))
    }

    // Override resolution methods to use Rust-specific implementations

    fn create_resolution_context(&self, file_id: FileId) -> Box<dyn ResolutionScope> {
        Box::new(RustResolutionContext::new(file_id))
    }

    fn create_inheritance_resolver(&self) -> Box<dyn InheritanceResolver> {
        // Clone the current state of the trait resolver
        // This is a snapshot at this point in time
        let resolver = self.trait_resolver.read().unwrap();
        Box::new(resolver.clone())
    }

    fn is_resolvable_symbol(&self, symbol: &crate::Symbol) -> bool {
        use crate::SymbolKind;
        use crate::symbol::ScopeContext;

        // Check scope_context first if available
        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 { .. } => {
                    // Rust-specific: trait methods and impl methods should be resolvable
                    // even if they're private, for within-file resolution
                    matches!(symbol.kind, SymbolKind::Method)
                        || matches!(symbol.visibility, crate::Visibility::Public)
                }
            }
        } else {
            // Fallback to symbol kind for backward compatibility
            matches!(
                symbol.kind,
                SymbolKind::Function
                    | SymbolKind::Method
                    | SymbolKind::Struct
                    | SymbolKind::Trait
                    | SymbolKind::Interface
                    | SymbolKind::Class
                    | SymbolKind::TypeAlias
                    | SymbolKind::Enum
                    | SymbolKind::Constant
            )
        }
    }

    fn add_trait_impl(&self, type_name: String, trait_name: String, file_id: FileId) {
        // Activate the actual functionality from RustTraitResolver
        let mut resolver = self.trait_resolver.write().unwrap();
        resolver.add_trait_impl(type_name, trait_name, file_id);
    }

    fn add_inherent_methods(&self, type_name: String, methods: Vec<String>) {
        // Activate the actual functionality from RustTraitResolver
        let mut resolver = self.trait_resolver.write().unwrap();
        resolver.add_inherent_methods(type_name, methods);
    }

    fn add_trait_methods(&self, trait_name: String, methods: Vec<String>) {
        // Activate the actual functionality from RustTraitResolver
        let mut resolver = self.trait_resolver.write().unwrap();
        resolver.add_trait_methods(trait_name, methods);
    }

    fn resolve_method_trait(&self, _type_name: &str, _method: &str) -> Option<&str> {
        // Note: Due to the lifetime constraints of returning &str from a RwLock,
        // we can't implement this directly. The actual resolution happens through
        // create_inheritance_resolver() which returns a snapshot of the resolver.
        // This will be addressed when we change the API to return String instead of &str.
        None
    }

    fn format_method_call(&self, receiver: &str, method: &str) -> String {
        // Rust uses :: for associated functions and . for methods
        // Since we don't have context here, default to method syntax
        format!("{receiver}.{method}")
    }

    fn inheritance_relation_name(&self) -> &'static str {
        // Rust uses "implements" for traits
        "implements"
    }

    fn map_relationship(&self, language_specific: &str) -> crate::relationship::RelationKind {
        use crate::relationship::RelationKind;
        match language_specific {
            "implements" => RelationKind::Implements,
            "uses" => RelationKind::Uses,
            "calls" => RelationKind::Calls,
            "defines" => RelationKind::Defines,
            "references" => RelationKind::References,
            _ => 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)
    }

    // Override visibility check for Rust-specific semantics
    fn is_symbol_visible_from_file(&self, symbol: &crate::Symbol, from_file: FileId) -> bool {
        // Same file: always visible
        if symbol.file_id == from_file {
            return true;
        }

        // Different file: check visibility based on Rust rules
        match symbol.visibility {
            Visibility::Public => true,
            Visibility::Crate => {
                // pub(crate) is visible from anywhere in the same crate
                // For now, assume all files are in the same crate
                // TODO: In the future, check if files are in same crate based on Cargo.toml
                true
            }
            Visibility::Module => {
                // pub(super) is visible from parent module and siblings
                // This requires module hierarchy analysis
                // For now, be conservative and return false
                false
            }
            Visibility::Private => false,
        }
    }

    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 import_matches_symbol(
        &self,
        import_path: &str,
        symbol_module_path: &str,
        importing_module: Option<&str>,
    ) -> bool {
        // Case 1: Exact match (most common case, check first for performance)
        if import_path == symbol_module_path {
            return true;
        }

        // Case 1b: Handle crate:: prefix mismatch
        // Import might be "crate::foo::Bar" but symbol might be stored as "foo::Bar"
        if let Some(without_crate) = import_path.strip_prefix("crate::") {
            // Remove "crate::" prefix
            if without_crate == symbol_module_path {
                return true;
            }
        }

        // Case 1c: Reverse case - symbol has crate:: but import doesn't
        if symbol_module_path.starts_with("crate::") && !import_path.starts_with("crate::") {
            let symbol_without_crate = &symbol_module_path[7..];
            if import_path == symbol_without_crate {
                return true;
            }
        }

        // Case 1d: Common re-export pattern
        // Allow importing a re-exported name from a higher-level module:
        // import_path:  crate::parsing::Name
        // symbol_path:  crate::parsing::something::Name
        // Heuristic: same trailing name, symbol path starts with import prefix + '::'
        if let Some((import_prefix, import_name)) = import_path.rsplit_once("::") {
            // Only apply when both sides end with the same name
            if symbol_module_path.ends_with(&format!("::{import_name}")) {
                // Direct prefix check
                if symbol_module_path.starts_with(&format!("{import_prefix}::")) {
                    tracing::debug!(
                        "[rust] re-export heuristic matched (direct): import='{import_path}', symbol='{symbol_module_path}'"
                    );
                    return true;
                }

                // crate:: prefix normalization (import has crate::, symbol doesn't)
                if let Some(without_crate) = import_prefix.strip_prefix("crate::") {
                    if symbol_module_path.starts_with(&format!("{without_crate}::")) {
                        tracing::debug!(
                            "[rust] re-export heuristic matched (import had crate::): import='{import_path}', symbol='{symbol_module_path}'"
                        );
                        return true;
                    }
                }

                // crate:: prefix normalization (symbol has crate::, import doesn't)
                if symbol_module_path.starts_with("crate::")
                    && !import_prefix.starts_with("crate::")
                {
                    let symbol_without_crate = &symbol_module_path[7..];
                    if symbol_without_crate.starts_with(&format!("{import_prefix}::")) {
                        tracing::debug!(
                            "[rust] re-export heuristic matched (symbol had crate::): import='{import_path}', symbol='{symbol_module_path}'"
                        );
                        return true;
                    }
                }
            }
        }

        // Case 2: Handle super:: imports
        if import_path.starts_with("super::") {
            if let Some(importing_mod) = importing_module {
                let relative_path = import_path.strip_prefix("super::").unwrap(); // Safe: we checked starts_with

                // super:: means go up one level from the importing module
                // Example: In crate::parsing::rust, super::LanguageBehavior -> crate::parsing::LanguageBehavior
                if let Some(parent) = importing_mod.rsplit_once("::") {
                    let candidate = format!("{}::{}", parent.0, relative_path);
                    if candidate == symbol_module_path {
                        return true;
                    }

                    // Re-export heuristic for super:: imports:
                    // If the symbol lives deeper under the parent module but has the same tail name,
                    // consider it a match (common re-export pattern)
                    if symbol_module_path.ends_with(&format!("::{relative_path}"))
                        && (symbol_module_path.starts_with(&format!("{}::", parent.0))
                            || symbol_module_path == parent.0)
                    {
                        tracing::debug!(
                            "[rust] re-export heuristic matched (super): import='{import_path}', symbol='{symbol_module_path}'"
                        );
                        return true;
                    }
                }
            }
        }

        // Case 3: Only do complex matching if we have the importing module context
        if let Some(importing_mod) = importing_module {
            // Check if it's a relative import (doesn't start with crate:: or std libs)
            if !import_path.starts_with("crate::")
                && !import_path.starts_with("std::")
                && !import_path.starts_with("core::")
                && !import_path.starts_with("alloc::")
                && !import_path.starts_with("super::")
            {
                // Try as relative to importing module
                // Example: helpers::func in crate::module -> crate::module::helpers::func
                let candidate = format!("{importing_mod}::{import_path}");
                if candidate == symbol_module_path {
                    return true;
                }

                // Re-export heuristic for relative import under importing module
                if let Some((base, name)) = candidate.rsplit_once("::") {
                    if symbol_module_path.ends_with(&format!("::{name}"))
                        && (symbol_module_path.starts_with(&format!("{base}::"))
                            || symbol_module_path == base)
                    {
                        tracing::debug!(
                            "[rust] re-export heuristic matched (relative): import='{import_path}', symbol='{symbol_module_path}'"
                        );
                        return true;
                    }
                }

                // Try as sibling module (same parent)
                // Example: In crate::module::submodule, helpers::func -> crate::module::helpers::func
                if let Some(parent) = importing_mod.rsplit_once("::") {
                    let sibling = format!("{}::{}", parent.0, import_path);
                    if sibling == symbol_module_path {
                        return true;
                    }

                    // Re-export heuristic for sibling resolution
                    if let Some((base, name)) = sibling.rsplit_once("::") {
                        if symbol_module_path.ends_with(&format!("::{name}"))
                            && (symbol_module_path.starts_with(&format!("{base}::"))
                                || symbol_module_path == base)
                        {
                            tracing::debug!(
                                "[rust] re-export heuristic matched (sibling): import='{import_path}', symbol='{symbol_module_path}'"
                            );
                            return true;
                        }
                    }
                }
            }
        }

        false
    }

    fn disambiguate_symbol(
        &self,
        _name: &str,
        candidates: &[(crate::SymbolId, crate::SymbolKind)],
        rel_kind: crate::relationship::RelationKind,
        role: crate::parsing::RelationRole,
    ) -> Option<crate::SymbolId> {
        use crate::SymbolKind::*;
        use crate::parsing::RelationRole::*;
        use crate::relationship::RelationKind::*;

        // For Rust, determine preferred kinds based on relationship and role
        let preferred_kinds: &[crate::SymbolKind] = match (rel_kind, role) {
            // For Implements, the "from" should be Struct/Enum (implementors)
            (Implements, From) => &[Struct, Enum],
            // For Implements, the "to" should be Trait
            (Implements, To) => &[Trait],
            // For Calls, prefer Function/Method
            (Calls, From) | (Calls, To) => &[Function, Method],
            // For Extends (supertraits), prefer Trait
            (Extends, From) | (Extends, To) => &[Trait],
            // Default: accept first candidate
            _ => return candidates.first().map(|(id, _)| *id),
        };

        // Find first candidate matching preferred kinds, fall back to first
        candidates
            .iter()
            .find(|(_, kind)| preferred_kinds.contains(kind))
            .or_else(|| candidates.first())
            .map(|(id, _)| *id)
    }
}

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

    #[test]
    fn test_format_module_path() {
        let behavior = RustBehavior::new();
        assert_eq!(
            behavior.format_module_path("crate::module", "function"),
            "crate::module::function"
        );
    }

    #[test]
    fn test_import_matches_symbol_reexport_cases() {
        let behavior = RustBehavior::new();

        // Exact match
        assert!(behavior.import_matches_symbol(
            "crate::parsing::LanguageBehavior",
            "crate::parsing::LanguageBehavior",
            Some("crate::parsing::rust")
        ));

        // crate:: prefix mismatch (import has crate::, symbol doesn't)
        assert!(behavior.import_matches_symbol("crate::foo::Bar", "foo::Bar", Some("crate::foo")));

        // Reverse crate:: mismatch (symbol has crate::, import doesn't)
        assert!(behavior.import_matches_symbol("foo::Bar", "crate::foo::Bar", Some("crate::foo")));

        // Re-export under deeper module (direct heuristic)
        assert!(behavior.import_matches_symbol(
            "crate::parsing::LanguageBehavior",
            "crate::parsing::language_behavior::LanguageBehavior",
            Some("crate::parsing::rust")
        ));

        // super:: import resolves to parent; symbol lives deeper under parent
        assert!(behavior.import_matches_symbol(
            "super::TypeScriptBehavior",
            "crate::parsing::typescript::behavior::TypeScriptBehavior",
            Some("crate::parsing::typescript::parser")
        ));

        // Relative import from module; symbol under submodule
        assert!(behavior.import_matches_symbol(
            "LanguageBehavior",
            "crate::parsing::language_behavior::LanguageBehavior",
            Some("crate::parsing")
        ));

        // Sibling import pattern; symbol under deeper sibling
        assert!(behavior.import_matches_symbol(
            "LanguageBehavior",
            "crate::parsing::language_behavior::LanguageBehavior",
            Some("crate::parsing::rust")
        ));
    }

    #[test]
    fn test_import_matches_symbol_negative_cases() {
        let behavior = RustBehavior::new();

        // Different tail name should not match
        assert!(!behavior.import_matches_symbol(
            "crate::parsing::Foo",
            "crate::parsing::language_behavior::Bar",
            Some("crate::parsing::rust")
        ));

        // Prefix mismatch should not match (import prefix doesn't match symbol prefix)
        assert!(!behavior.import_matches_symbol(
            "crate::utils::Helper",
            "crate::parsing::utils::Helper",
            Some("crate::utils")
        ));

        // super:: import but symbol lives outside parent module
        assert!(!behavior.import_matches_symbol(
            "super::Foo",
            "crate::x::Foo",
            Some("crate::a::b::c")
        ));

        // Relative import from module; symbol under unrelated module
        assert!(!behavior.import_matches_symbol(
            "helpers::func",
            "crate::other::helpers::func",
            Some("crate::module")
        ));

        // crate:: mismatch with different path should not match
        assert!(!behavior.import_matches_symbol(
            "crate::foo::Bar",
            "crate::bar::Bar",
            Some("crate::foo")
        ));

        // Sibling heuristic should not over-match across unrelated bases
        assert!(!behavior.import_matches_symbol(
            "LanguageBehavior",
            "crate::other::language_behavior::LanguageBehavior",
            Some("crate::parsing::rust")
        ));
    }

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

        assert_eq!(
            behavior.parse_visibility("pub fn foo()"),
            Visibility::Public
        );
        assert_eq!(behavior.parse_visibility("fn foo()"), Visibility::Private);
        assert_eq!(
            behavior.parse_visibility("pub(crate) fn foo()"),
            Visibility::Crate
        );
        assert_eq!(
            behavior.parse_visibility("pub(super) fn foo()"),
            Visibility::Module
        );
    }

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

    #[test]
    fn test_supports_features() {
        let behavior = RustBehavior::new();
        assert!(behavior.supports_traits());
        assert!(behavior.supports_inherent_methods());
    }

    #[test]
    fn test_abi_version() {
        let behavior = RustBehavior::new();
        // Rust should be on ABI-15
        assert_eq!(behavior.get_abi_version(), 15);
    }

    #[test]
    fn test_validate_node_kinds() {
        let behavior = RustBehavior::new();

        // Valid Rust node kinds
        assert!(behavior.validate_node_kind("function_item"));
        assert!(behavior.validate_node_kind("struct_item"));
        assert!(behavior.validate_node_kind("impl_item"));
        assert!(behavior.validate_node_kind("trait_item"));

        // Invalid node kind
        assert!(!behavior.validate_node_kind("made_up_node"));
    }

    #[test]
    fn test_format_path_as_module() {
        let behavior = RustBehavior::new();

        // Empty path → crate
        assert_eq!(
            behavior.format_path_as_module(&[]),
            Some("crate".to_string())
        );

        // main.rs → crate
        assert_eq!(
            behavior.format_path_as_module(&["main"]),
            Some("crate".to_string())
        );

        // lib.rs → crate
        assert_eq!(
            behavior.format_path_as_module(&["lib"]),
            Some("crate".to_string())
        );

        // foo/bar.rs → crate::foo::bar
        assert_eq!(
            behavior.format_path_as_module(&["foo", "bar"]),
            Some("crate::foo::bar".to_string())
        );

        // foo/mod.rs → crate::foo (mod.rs stripped)
        assert_eq!(
            behavior.format_path_as_module(&["foo", "mod"]),
            Some("crate::foo".to_string())
        );

        // a/b/c.rs → crate::a::b::c
        assert_eq!(
            behavior.format_path_as_module(&["a", "b", "c"]),
            Some("crate::a::b::c".to_string())
        );

        // tests/integration.rs → crate::tests::integration
        assert_eq!(
            behavior.format_path_as_module(&["tests", "integration"]),
            Some("crate::tests::integration".to_string())
        );
    }
}