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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
//! Language-specific behavior abstraction
//!
//! This module provides the LanguageBehavior trait which encapsulates
//! all language-specific logic that was previously hardcoded in SimpleIndexer.
//! Each language implements this trait to define its specific conventions.
//!
//! # Architecture
//!
//! The LanguageBehavior trait is part of a larger refactoring to achieve true
//! language modularity in the codanna indexing system. It works in conjunction
//! with:
//!
//! - `LanguageParser`: Handles AST parsing for each language
//! - `ParserFactory`: Creates parser-behavior pairs
//! - `SimpleIndexer`: Uses behaviors to process symbols without language-specific code
//!
//! # Example Usage
//!
//! ```rust
//! use codanna::parsing::{ParserFactory, Language};
//! use codanna::types::{FileId, SymbolCounter};
//! use codanna::Settings;
//! use std::sync::Arc;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create settings
//! let settings = Arc::new(Settings::default());
//!
//! // Create factory and get parser-behavior pair
//! let factory = ParserFactory::new(settings);
//! let mut pair = factory.create_parser_with_behavior(Language::Rust)?;
//!
//! // Prepare parsing context
//! let code = "fn main() { println!(\"Hello\"); }";
//! let file_id = FileId::new(1).ok_or("Invalid file ID")?;
//! let mut counter = SymbolCounter::new();
//!
//! // Parse code with the parser
//! let mut symbols = pair.parser.parse(code, file_id, &mut counter);
//!
//! // Process symbols with the behavior
//! for symbol in &mut symbols {
//!     pair.behavior.configure_symbol(symbol, Some("crate::module"));
//! }
//!
//! println!("Parsed {} symbols", symbols.len());
//! # Ok(())
//! # }
//! ```
//!
//! # Implementing a New Language
//!
//! To add support for a new language:
//!
//! 1. Create a parser implementing `LanguageParser`
//! 2. Create a behavior implementing `LanguageBehavior`
//! 3. Register both in `ParserFactory`
//! 4. (Future) Register in the language registry for auto-discovery

use crate::parsing::MethodCall;
use crate::parsing::paths::{strip_extension, strip_source_root};
use crate::parsing::resolution::{
    GenericInheritanceResolver, GenericResolutionContext, ImportBinding, ImportOrigin,
    InheritanceResolver, PipelineSymbolCache, ResolutionScope, ScopeLevel,
};
use crate::relationship::RelationKind;
use crate::storage::DocumentIndex;
use crate::{FileId, Symbol, SymbolId, SymbolKind, Visibility};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tree_sitter::Language;

/// Role in a relationship (source or target)
///
/// Used during symbol disambiguation to indicate whether we're looking
/// for the "from" symbol (e.g., struct implementing) or the "to" symbol
/// (e.g., trait being implemented).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelationRole {
    /// The source symbol in a relationship
    From,
    /// The target symbol in a relationship
    To,
}

/// Trait for language-specific behavior and configuration
///
/// This trait extracts all language-specific logic from the indexer,
/// making the system truly language-agnostic. Each language parser
/// is paired with a behavior implementation that knows how to:
/// - Format module paths according to language conventions
/// - Parse visibility from signatures
/// - Validate node types using tree-sitter metadata
///
/// # Design Principles
///
/// 1. **Zero allocation where possible**: Methods return static strings or reuse inputs
/// 2. **Language agnostic core**: The indexer should never check language types
/// 3. **Extensible**: New languages can be added without modifying existing code
/// 4. **Type safe**: Use tree-sitter's ABI-15 for compile-time validation
pub trait LanguageBehavior: Send + Sync {
    /// Get the language ID for this behavior
    ///
    /// Used for filtering symbols to prevent cross-language resolution.
    fn language_id(&self) -> crate::parsing::registry::LanguageId;

    /// Format a module path according to language conventions
    ///
    /// # Examples
    /// - Rust: `"crate::module::submodule"`
    /// - Python: `"module.submodule"`
    /// - PHP: `"\\Namespace\\Subnamespace"`
    /// - Go: `"module/submodule"`
    fn format_module_path(&self, base_path: &str, symbol_name: &str) -> String;

    /// Parse visibility from a symbol's signature
    ///
    /// # Examples
    /// - Rust: `"pub fn foo()"` -> Public
    /// - Python: `"def _foo()"` -> Module (single underscore)
    /// - PHP: `"private function foo()"` -> Private
    /// - Go: `"func foo()"` -> Public
    fn parse_visibility(&self, signature: &str) -> Visibility;

    /// Get the module separator for this language
    ///
    /// # Examples
    /// - Rust: `"::"`
    /// - Python: `"."`
    /// - PHP: `"\\"`
    /// - Go: `"/"`
    fn module_separator(&self) -> &'static str;

    /// Get the source root directories for this language
    ///
    /// These directories are stripped when computing module paths.
    /// Default implementation returns common source directories.
    ///
    /// # Examples
    /// - Rust: `&["src"]`
    /// - Python: `&["src", "lib", "app"]`
    /// - PHP: `&["src", "app", "lib", "classes"]`
    fn source_roots(&self) -> &'static [&'static str] {
        &["src"]
    }

    /// Format path components as a module path
    ///
    /// Converts path segments into language-specific module path format.
    /// This is the core language-specific formatting logic.
    ///
    /// # Arguments
    /// * `components` - Path segments (e.g., `["foo", "bar", "baz"]`)
    ///
    /// # Examples
    /// - Rust: `["foo", "bar"]` → `"crate::foo::bar"`
    /// - Python: `["foo", "bar"]` → `"foo.bar"`
    /// - PHP: `["Foo", "Bar"]` → `"\\Foo\\Bar"`
    /// - Go: `["foo", "bar"]` → `"foo/bar"`
    fn format_path_as_module(&self, components: &[&str]) -> Option<String>;

    /// Check if this language supports trait/interface concepts
    fn supports_traits(&self) -> bool {
        false
    }

    /// Check if this language supports inherent methods
    /// (methods defined directly on types, not through traits)
    fn supports_inherent_methods(&self) -> bool {
        false
    }

    /// Get the tree-sitter Language for ABI-15 metadata access
    fn get_language(&self) -> Language;

    /// Validate that a node kind exists in this language's grammar
    /// Uses ABI-15 to check if the node type is valid
    fn validate_node_kind(&self, node_kind: &str) -> bool {
        self.get_language().id_for_node_kind(node_kind, true) != 0
    }

    /// Get the ABI version of the language grammar
    fn get_abi_version(&self) -> usize {
        self.get_language().abi_version()
    }

    /// Normalize a caller name before resolution.
    ///
    /// Default: return the name unchanged. Languages with synthetic caller
    /// markers (e.g., Python `"<module>"`) can map them to resolvable names
    /// (like the actual module path) based on file context.
    fn normalize_caller_name(&self, name: &str, _file_id: crate::FileId) -> String {
        name.to_string()
    }

    /// Configure a symbol with language-specific rules
    ///
    /// This is the main entry point for applying language-specific
    /// configuration to a symbol during indexing.
    fn configure_symbol(&self, symbol: &mut Symbol, module_path: Option<&str>) {
        // Apply module path formatting
        if let Some(path) = module_path {
            let full_path = self.format_module_path(path, &symbol.name);
            symbol.module_path = Some(full_path.into());
        }

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

    /// Calculate the module path from a file path according to language conventions
    ///
    /// This method converts a file system path to a language-specific module path.
    /// Each language has different conventions for how file paths map to module/namespace paths.
    ///
    /// # Examples
    /// - Rust: `"src/foo/bar.rs"` → `"crate::foo::bar"`
    /// - Python: `"src/package/module.py"` → `"package.module"`
    /// - PHP: `"src/Namespace/Class.php"` → `"\\Namespace\\Class"`
    /// - Go: `"src/module/submodule.go"` → `"module/submodule"`
    ///
    /// # Default Implementation
    /// Uses `source_roots()` and `format_path_as_module()` to compute the module path.
    /// Extensions are passed as a parameter to handle compound extensions like `.d.ts`, `.class.php`.
    ///
    /// # Arguments
    /// * `file_path` - Absolute path to the file
    /// * `workspace_root` - Root directory of the workspace
    /// * `extensions` - File extensions for this language (from LanguageDefinition)
    fn module_path_from_file(
        &self,
        file_path: &Path,
        workspace_root: &Path,
        extensions: &[&str],
    ) -> Option<String> {
        // Step 1: Get relative path from workspace root
        let relative_path = file_path.strip_prefix(workspace_root).ok()?;

        // Step 2: Strip source root directories (OS-agnostic)
        let path_without_src = strip_source_root(relative_path, self.source_roots());

        // Step 3: Strip extension using passed extensions list
        let path_str = path_without_src.to_str()?;
        let path_without_ext = strip_extension(path_str, extensions);

        // Step 4: Split into components using OS path separator
        let components: Vec<&str> = path_without_ext
            .split(std::path::MAIN_SEPARATOR)
            .filter(|s| !s.is_empty())
            .collect();

        // Step 5: Format using language-specific rules
        self.format_path_as_module(&components)
    }

    // ========== Resolution Methods ==========

    /// Create a language-specific resolution context
    ///
    /// Returns a resolution scope that implements the language's scoping rules.
    /// Default implementation returns a generic context that works for most languages.
    fn create_resolution_context(&self, file_id: FileId) -> Box<dyn ResolutionScope> {
        Box::new(GenericResolutionContext::new(file_id))
    }

    /// Create a language-specific inheritance resolver
    ///
    /// Returns an inheritance resolver that handles the language's inheritance model.
    /// Default implementation returns a generic resolver.
    fn create_inheritance_resolver(&self) -> Box<dyn InheritanceResolver> {
        Box::new(GenericInheritanceResolver::new())
    }

    /// Add an import to the language's import tracking
    ///
    /// Default implementation is a no-op. Languages should override to track imports.
    fn add_import(&self, _import: crate::parsing::Import) {
        // Default: no-op
    }

    /// Register a file with its module path
    ///
    /// Default implementation is a no-op. Languages should override to track files.
    fn register_file(&self, _path: PathBuf, _file_id: FileId, _module_path: String) {
        // Default: no-op
    }

    /// Add a trait/interface implementation
    ///
    /// Default implementation is a no-op. Languages with traits/interfaces should override.
    fn add_trait_impl(&self, _type_name: String, _trait_name: String, _file_id: FileId) {
        // Default: no-op for languages without traits
    }

    /// Add inherent methods for a type
    ///
    /// Default implementation is a no-op. Languages with inherent methods should override.
    fn add_inherent_methods(&self, _type_name: String, _methods: Vec<String>) {
        // Default: no-op for languages without inherent methods
    }

    /// Add methods that a trait/interface defines
    ///
    /// Default implementation is a no-op. Languages with traits/interfaces should override.
    fn add_trait_methods(&self, _trait_name: String, _methods: Vec<String>) {
        // Default: no-op
    }

    /// Resolve which trait/interface provides a method
    ///
    /// Returns the trait/interface name if the method comes from one, None if inherent.
    fn resolve_method_trait(&self, _type_name: &str, _method: &str) -> Option<&str> {
        None
    }

    /// Format a method call for this language
    ///
    /// Default uses the module separator (e.g., Type::method for Rust, Type.method for others)
    fn format_method_call(&self, receiver: &str, method: &str) -> String {
        format!("{}{}{}", receiver, self.module_separator(), method)
    }

    /// Resolve an instance method call to its symbol ID
    ///
    /// Given a type name and method name, find the symbol ID for the method.
    /// Uses the resolution context for import-aware type lookup, then queries
    /// the Defines relationship to find the method.
    ///
    /// # Arguments
    /// * `type_name` - The resolved type name (e.g., "Calculator")
    /// * `method_name` - The method being called (e.g., "add")
    /// * `context` - Resolution context with import information
    /// * `document_index` - For querying relationships
    ///
    /// # Returns
    /// The SymbolId of the method if found, None otherwise
    fn resolve_instance_method(
        &self,
        type_name: &str,
        method_name: &str,
        context: &dyn ResolutionScope,
        document_index: &DocumentIndex,
    ) -> Option<SymbolId> {
        // Step 1: Resolve type using context (import-aware)
        let type_id = match context.resolve(type_name) {
            Some(id) => {
                tracing::debug!("[resolve_instance_method] resolved type '{type_name}' to {id:?}");
                id
            }
            None => {
                tracing::debug!("[resolve_instance_method] failed to resolve type '{type_name}'");
                return None;
            }
        };

        // Step 2: Find method via Defines relationship from that specific type
        let defined_symbols =
            match document_index.get_relationships_from(type_id, RelationKind::Defines) {
                Ok(rels) => {
                    tracing::debug!(
                        "[resolve_instance_method] found {} Defines relationships from {type_id:?}",
                        rels.len()
                    );
                    rels
                }
                Err(e) => {
                    tracing::debug!(
                        "[resolve_instance_method] error getting Defines from {type_id:?}: {e}"
                    );
                    return None;
                }
            };

        // Step 3: Find the method with matching name
        for (_, to_id, _) in defined_symbols {
            if let Ok(Some(symbol)) = document_index.find_symbol_by_id(to_id) {
                tracing::debug!(
                    "[resolve_instance_method] checking defined symbol: '{}' vs '{method_name}'",
                    symbol.name.as_ref()
                );
                if symbol.name.as_ref() == method_name {
                    tracing::debug!(
                        "[resolve_instance_method] found method '{method_name}' at {to_id:?}"
                    );
                    return Some(to_id);
                }
            }
        }

        tracing::debug!(
            "[resolve_instance_method] method '{method_name}' not found in type '{type_name}'"
        );
        None
    }

    /// Resolve a method call to its symbol ID
    ///
    /// This is the unified API for resolving all types of method calls:
    /// - Static calls: `Type::method()` - resolved via context with qualified name
    /// - Instance calls: `receiver.method()` - type looked up, then Defines relationship queried
    /// - Self calls: `self.method()` - resolved via current type context
    ///
    /// # Arguments
    /// * `method_call` - The structured method call information
    /// * `receiver_types` - Map of variable names to their types (e.g., "calc" -> "Calculator")
    /// * `context` - Resolution context with import information
    /// * `document_index` - For querying symbols and relationships
    ///
    /// # Returns
    /// The SymbolId of the resolved method, or None if unresolved
    fn resolve_method_call(
        &self,
        method_call: &MethodCall,
        receiver_types: &HashMap<String, String>,
        context: &dyn ResolutionScope,
        document_index: &DocumentIndex,
    ) -> Option<SymbolId> {
        let method_name = &method_call.method_name;

        match (&method_call.receiver, method_call.is_static) {
            // Static call: Type::method()
            // Use module_separator for resolution (:: for Rust, . for most others)
            (Some(type_name), true) => {
                let qualified = format!("{type_name}{}{method_name}", self.module_separator());
                tracing::debug!("[resolve_method_call] static call: {qualified}");
                context.resolve(&qualified)
            }

            // Instance call: receiver.method()
            (Some(receiver), false) if receiver != "self" => {
                // Look up the receiver's type
                let type_name = match receiver_types.get(receiver) {
                    Some(t) => t,
                    None => {
                        tracing::debug!(
                            "[resolve_method_call] no type found for receiver '{receiver}'"
                        );
                        return None;
                    }
                };

                tracing::debug!(
                    "[resolve_method_call] instance call: {receiver}.{method_name} (type: {type_name})"
                );

                // Use resolve_instance_method to find via Defines relationship
                self.resolve_instance_method(type_name, method_name, context, document_index)
            }

            // Self call: self.method()
            (Some(receiver), false) if receiver == "self" => {
                // For self calls, try to resolve via context which should have current type info
                let self_method = format!("self.{method_name}");
                tracing::debug!("[resolve_method_call] self call: {self_method}");
                context.resolve(&self_method).or_else(|| {
                    // Fallback: just try the method name
                    context.resolve(method_name)
                })
            }

            // Plain function call (no receiver)
            (None, _) => {
                tracing::debug!("[resolve_method_call] plain function call: {method_name}");
                context.resolve(method_name)
            }

            // Catch-all (shouldn't happen)
            _ => {
                tracing::debug!("[resolve_method_call] unhandled case: {:?}", method_call);
                None
            }
        }
    }

    /// Get the inheritance relationship name for this language
    ///
    /// Returns "implements" for languages with interfaces, "extends" for inheritance.
    fn inheritance_relation_name(&self) -> &'static str {
        if self.supports_traits() {
            "implements"
        } else {
            "extends"
        }
    }

    /// Map language-specific relationship to generic RelationKind
    ///
    /// Allows languages to define how their concepts map to the generic relationship types.
    fn map_relationship(&self, language_specific: &str) -> RelationKind {
        match language_specific {
            "extends" => RelationKind::Extends,
            "implements" => RelationKind::Implements,
            "inherits" => RelationKind::Extends,
            "uses" => RelationKind::Uses,
            "calls" => RelationKind::Calls,
            "defines" => RelationKind::Defines,
            _ => RelationKind::References,
        }
    }

    /// Build resolution context for parallel pipeline (no Tantivy access).
    ///
    /// This method is used by the parallel indexing pipeline where all symbol
    /// data is already in the `PipelineSymbolCache`. Unlike `build_resolution_context_with_cache`,
    /// this version does NOT access DocumentIndex/Tantivy - all resolution uses cached data.
    ///
    /// # Arguments
    /// * `file_id` - The file being resolved
    /// * `imports` - Imports for this file (already extracted by CONTEXT stage)
    /// * `cache` - Symbol cache with full Symbol metadata
    /// * `extensions` - File extensions for this language (from settings.toml)
    ///
    /// # Returns
    /// A tuple of (ResolutionScope, enhanced_imports) where:
    /// - ResolutionScope: Language-specific context for resolution
    /// - enhanced_imports: Import paths normalized for module path matching
    fn build_resolution_context_with_pipeline_cache(
        &self,
        file_id: FileId,
        imports: &[crate::parsing::Import],
        cache: &dyn PipelineSymbolCache,
        extensions: &[&str],
    ) -> (Box<dyn ResolutionScope>, Vec<crate::parsing::Import>) {
        // Extensions available for language-specific implementations to strip from paths
        // Default implementation uses separator-based normalization only
        let _ = extensions;

        // Create language-specific resolution context
        let mut context = self.create_resolution_context(file_id);

        // 1. Build enhanced imports with normalized paths
        let importing_module = self.get_module_path_for_file(file_id);
        let separator = self.module_separator();

        let enhanced_imports: Vec<crate::parsing::Import> = imports
            .iter()
            .map(|import| {
                // Normalize path: "./foo/bar" → "foo.bar" (using module separator)
                let enhanced_path = if import.path.starts_with("./") {
                    import.path.trim_start_matches("./").replace('/', separator)
                } else if import.path.starts_with("../") {
                    // Relative parent - normalize without leading ../
                    import.path.replace('/', separator)
                } else {
                    // Absolute or external - normalize separators
                    import.path.replace('/', separator)
                };

                crate::parsing::Import {
                    path: enhanced_path,
                    file_id: import.file_id,
                    alias: import.alias.clone(),
                    is_glob: import.is_glob,
                    is_type_only: import.is_type_only,
                }
            })
            .collect();

        context.populate_imports(&enhanced_imports);

        // 2. Add imported symbols (HIGHEST PRIORITY)
        // Build CallerContext for resolution
        let caller = crate::parsing::CallerContext::from_file(file_id, self.language_id());

        for import in &enhanced_imports {
            let separator = self.module_separator();
            let symbol_name = import.path.split(separator).last().unwrap_or(&import.path);

            // Use PipelineSymbolCache.resolve() for multi-tier resolution
            let result = cache.resolve(
                symbol_name,
                &caller,
                None, // No specific range for imports
                imports,
            );

            let resolved_symbol = match result {
                crate::parsing::ResolveResult::Found(id) => Some(id),
                crate::parsing::ResolveResult::Ambiguous(ids) => ids.first().copied(),
                crate::parsing::ResolveResult::NotFound => None,
            };

            // Determine origin (simplified without Tantivy access)
            let origin = if let Some(id) = resolved_symbol {
                if let Some(sym) = cache.get(id) {
                    // Internal if same language and has matching module path
                    if sym.language_id.as_ref() == Some(&self.language_id()) {
                        if let Some(ref module_path) = sym.module_path {
                            if self.import_matches_symbol(
                                &import.path,
                                module_path.as_ref(),
                                importing_module.as_deref(),
                            ) {
                                ImportOrigin::Internal
                            } else {
                                ImportOrigin::External
                            }
                        } else {
                            ImportOrigin::Internal // Same language, assume internal
                        }
                    } else {
                        ImportOrigin::External
                    }
                } else {
                    ImportOrigin::Unknown
                }
            } else {
                ImportOrigin::External // Not found = likely external dependency
            };

            // Register bindings
            let mut binding_names: Vec<String> = Vec::new();
            if let Some(alias) = &import.alias {
                binding_names.push(alias.clone());
            }
            if !binding_names.contains(&symbol_name.to_string()) {
                binding_names.push(symbol_name.to_string());
            }

            let import_clone = import.clone();
            for name in &binding_names {
                context.register_import_binding(ImportBinding {
                    import: import_clone.clone(),
                    exposed_name: name.clone(),
                    origin,
                    resolved_symbol,
                });
            }

            if let (ImportOrigin::Internal, Some(symbol_id)) = (origin, resolved_symbol) {
                let primary_name = binding_names
                    .first()
                    .cloned()
                    .unwrap_or_else(|| symbol_name.to_string());
                context.add_symbol(primary_name, symbol_id, ScopeLevel::Module);
            }
        }

        // 2. Add file's local symbols (MEDIUM PRIORITY)
        for symbol_id in cache.symbols_in_file(file_id) {
            if let Some(symbol) = cache.get(symbol_id) {
                if self.is_resolvable_symbol(&symbol) {
                    context.add_symbol(symbol.name.to_string(), symbol.id, ScopeLevel::Module);

                    // Also add by module_path for fully qualified resolution
                    if let Some(module_path) = &symbol.module_path {
                        context.add_symbol(module_path.to_string(), symbol.id, ScopeLevel::Module);
                    }
                }
            }
        }

        // 3. Skip global symbol loading - cache.resolve() handles cross-file lookup
        // This is the key difference from build_resolution_context_with_cache:
        // We don't need to load all symbols upfront because PipelineSymbolCache
        // has them all and resolve() does multi-tier lookup on demand.

        self.initialize_resolution_context(context.as_mut(), file_id);
        (context, enhanced_imports)
    }

    /// Check if a symbol should be resolvable (added to resolution context)
    ///
    /// Languages override this to filter which symbols are available for resolution.
    /// For example, local variables might not be resolvable from other scopes.
    ///
    /// Default implementation includes common top-level symbols.
    fn is_resolvable_symbol(&self, symbol: &Symbol) -> bool {
        use crate::SymbolKind;

        // Check scope_context first if available
        if let Some(ref scope_context) = symbol.scope_context {
            use crate::symbol::ScopeContext;
            match scope_context {
                ScopeContext::Module | ScopeContext::Global | ScopeContext::Package => true,
                ScopeContext::Local { .. } | ScopeContext::Parameter => false,
                ScopeContext::ClassMember { .. } => {
                    // Class members might be resolvable depending on visibility
                    matches!(symbol.visibility, 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
            )
        }
    }

    /// Check if a symbol is visible from another file
    ///
    /// Languages implement their visibility rules here.
    /// For example, Rust checks pub, Python might check __all__, etc.
    ///
    /// Default implementation checks basic visibility.
    fn is_symbol_visible_from_file(&self, symbol: &Symbol, from_file: FileId) -> bool {
        // Same file: always visible
        if symbol.file_id == from_file {
            return true;
        }

        // Different file: check visibility
        matches!(symbol.visibility, Visibility::Public)
    }

    /// Get imports for a file
    ///
    /// Returns the list of imports that were registered for this file.
    /// Languages should track imports when add_import() is called.
    ///
    /// Default implementation returns empty (no imports).
    fn get_imports_for_file(&self, _file_id: FileId) -> Vec<crate::parsing::Import> {
        Vec::new()
    }

    /// Check if an import path matches a symbol's module path
    ///
    /// This allows each language to implement custom matching rules.
    /// For example, Rust needs to handle relative imports where
    /// "helpers::func" should match "crate::module::helpers::func"
    /// when imported from "crate::module".
    ///
    /// # Arguments
    /// * `import_path` - The import path as written in source
    /// * `symbol_module_path` - The full module path of the symbol
    /// * `importing_module` - The module doing the importing (if known)
    ///
    /// # Default Implementation
    /// Exact match only. Languages should override for relative imports.
    fn import_matches_symbol(
        &self,
        import_path: &str,
        symbol_module_path: &str,
        _importing_module: Option<&str>,
    ) -> bool {
        import_path == symbol_module_path
    }

    /// Get the module path for a file from behavior state
    ///
    /// Default implementation returns None. Languages with state tracking
    /// should override to return the module path.
    fn get_module_path_for_file(&self, _file_id: FileId) -> Option<String> {
        None
    }

    /// Get the file path for a FileId from behavior state
    ///
    /// Default implementation returns None. Languages with state tracking
    /// should override to return the file path.
    fn get_file_path(&self, _file_id: FileId) -> Option<PathBuf> {
        None
    }

    /// Load project resolution rules for a file from the persisted index
    ///
    /// Uses a thread-local cache to avoid repeated disk reads.
    /// Cache is invalidated after 1 second to pick up changes.
    ///
    /// This method works with the project resolver infrastructure:
    /// - TypeScript: tsconfig.json paths
    /// - JavaScript: jsconfig.json paths
    /// - Java: Maven/Gradle source roots
    /// - Swift: Package.swift source roots
    fn load_project_rules_for_file(
        &self,
        file_id: FileId,
    ) -> Option<crate::project_resolver::persist::ResolutionRules> {
        use crate::project_resolver::persist::ResolutionPersistence;
        use std::cell::RefCell;
        use std::time::{Duration, Instant};

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

        let language_id = self.language_id().as_str().to_string();

        RULES_CACHE.with(|cache| {
            let mut cache = cache.borrow_mut();

            // Check if cache is fresh (< 1 second old) and same language
            let needs_reload = if let Some((timestamp, cached_lang, _)) = &*cache {
                timestamp.elapsed() >= Duration::from_secs(1) || cached_lang != &language_id
            } else {
                true
            };

            // Load fresh from disk if needed
            if needs_reload {
                let persistence =
                    ResolutionPersistence::new(Path::new(crate::init::local_dir_name()));
                if let Ok(index) = persistence.load(&language_id) {
                    *cache = Some((Instant::now(), language_id.clone(), index));
                } else {
                    // No index file exists yet - that's OK
                    return None;
                }
            }

            // Get rules for the file
            if let Some((_, _, ref index)) = *cache {
                // Get the file path for this FileId from behavior state
                if let Some(file_path) = self.get_file_path(file_id) {
                    // Find the config that applies to this file
                    if let Some(config_path) = index.get_config_for_file(&file_path) {
                        return index.rules.get(config_path).cloned();
                    }
                }

                // Fallback: return any rules we have (for tests without proper file registration)
                index.rules.values().next().cloned()
            } else {
                None
            }
        })
    }

    /// Register expression-to-type mappings extracted during parsing
    ///
    /// Languages that need additional resolution metadata (e.g., Kotlin generic
    /// flow) can override this to persist data until resolution runs.
    fn register_expression_types(&self, _file_id: FileId, _entries: &[(String, String)]) {}

    /// Hook invoked after the base resolution context has been populated
    ///
    /// Allows languages to inject additional data (expression types, generic
    /// metadata, etc.) into their resolution contexts.
    fn initialize_resolution_context(&self, _context: &mut dyn ResolutionScope, _file_id: FileId) {}

    /// Check if a relationship between two symbol kinds is valid
    ///
    /// This delegates to the resolution context's implementation, which can be
    /// overridden per language. The default implementation in ResolutionScope
    /// provides universal rules, while language-specific contexts can override.
    ///
    /// # Parameters
    /// - `from_kind`: The kind of the source symbol
    /// - `to_kind`: The kind of the target symbol
    /// - `rel_kind`: The type of relationship
    /// - `file_id`: The file where the relationship originates
    ///
    /// # Returns
    /// true if the relationship is valid, false otherwise
    fn is_compatible_relationship(
        &self,
        from_kind: crate::SymbolKind,
        to_kind: crate::SymbolKind,
        rel_kind: crate::RelationKind,
        file_id: FileId,
    ) -> bool {
        // Create a resolution context for the file and delegate to it
        let context = self.create_resolution_context(file_id);
        context.is_compatible_relationship(from_kind, to_kind, rel_kind)
    }

    // ========== Relationship Resolution Methods ==========

    /// Disambiguate when multiple symbols share the same name
    ///
    /// Called when symbol lookup returns multiple candidates during relationship
    /// resolution. Each language can define how to pick the right candidate based
    /// on the relationship type and role.
    ///
    /// # Arguments
    /// * `name` - The symbol name being looked up
    /// * `candidates` - All symbols with this name: (id, kind)
    /// * `rel_kind` - The relationship type being resolved
    /// * `role` - Whether this is the From or To symbol in the relationship
    ///
    /// # Default Implementation
    /// Returns the first candidate. Languages should override for smarter selection.
    fn disambiguate_symbol(
        &self,
        _name: &str,
        candidates: &[(SymbolId, SymbolKind)],
        _rel_kind: RelationKind,
        _role: RelationRole,
    ) -> Option<SymbolId> {
        candidates.first().map(|(id, _)| *id)
    }

    /// Check if a relationship is valid for this language
    ///
    /// Called during relationship resolution to validate that the source and
    /// target symbol kinds are compatible for the given relationship type.
    /// Each language can define its own rules.
    ///
    /// # Arguments
    /// * `from_kind` - The source symbol's kind
    /// * `to_kind` - The target symbol's kind
    /// * `rel_kind` - The relationship type
    ///
    /// # Default Implementation
    /// Uses universal rules that work for most languages. Languages with
    /// different semantics should override.
    fn is_valid_relationship(
        &self,
        from_kind: SymbolKind,
        to_kind: SymbolKind,
        rel_kind: RelationKind,
    ) -> bool {
        default_relationship_compatibility(from_kind, to_kind, rel_kind)
    }
}

/// Default relationship compatibility rules (universal)
///
/// Provides reasonable defaults that work for most languages.
/// Called by the default `is_valid_relationship()` implementation.
/// Languages can call this from their override if they want to extend
/// rather than replace the default behavior.
pub fn default_relationship_compatibility(
    from_kind: SymbolKind,
    to_kind: SymbolKind,
    rel_kind: RelationKind,
) -> bool {
    use RelationKind::*;
    use SymbolKind::*;

    match rel_kind {
        Calls | CalledBy => {
            let caller = matches!(
                from_kind,
                Function | Method | Macro | Module | Constant | Variable
            );
            let callee = matches!(
                to_kind,
                Function | Method | Macro | Class | Constant | Variable
            );
            match rel_kind {
                Calls => caller && callee,
                CalledBy => callee && caller,
                _ => unreachable!(),
            }
        }
        Implements | ImplementedBy => {
            let implementor = matches!(from_kind, Struct | Enum | Class);
            let interface = matches!(to_kind, Trait | Interface);
            match rel_kind {
                Implements => implementor && interface,
                ImplementedBy => interface && implementor,
                _ => unreachable!(),
            }
        }
        Extends | ExtendedBy => {
            let extendable = matches!(from_kind, Class | Interface | Trait | Struct | Enum);
            let base = matches!(to_kind, Class | Interface | Trait | Struct | Enum);
            extendable && base
        }
        Uses | UsedBy => {
            // Most symbols can use/reference types and values
            true
        }
        Defines | DefinedIn => {
            let container = matches!(
                from_kind,
                Class | Struct | Enum | Trait | Interface | Module
            );
            let member = matches!(to_kind, Function | Method | Field | Constant | Variable);
            match rel_kind {
                Defines => container && member,
                DefinedIn => member && container,
                _ => unreachable!(),
            }
        }
        References | ReferencedBy => {
            // Very permissive - almost anything can reference anything
            true
        }
    }
}

/// Language metadata from ABI-15
#[derive(Debug, Clone)]
pub struct LanguageMetadata {
    pub abi_version: usize,
    pub node_kind_count: usize,
    pub field_count: usize,
}

impl LanguageMetadata {
    /// Create metadata from a tree-sitter Language
    pub fn from_language(language: Language) -> Self {
        Self {
            abi_version: language.abi_version(),
            node_kind_count: language.node_kind_count(),
            field_count: language.field_count(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{RelationKind, SymbolKind};

    /// Test struct that implements LanguageBehavior with default behavior
    struct TestBehavior;

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

        fn format_module_path(&self, base_path: &str, _symbol_name: &str) -> String {
            base_path.to_string()
        }

        fn parse_visibility(&self, _signature: &str) -> crate::Visibility {
            crate::Visibility::Public
        }

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

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

        fn get_language(&self) -> tree_sitter::Language {
            // Use a dummy language for testing
            tree_sitter_rust::LANGUAGE.into()
        }
    }

    #[test]
    fn test_default_compatibility_function_calls_function() {
        let behavior = TestBehavior;
        assert!(behavior.is_compatible_relationship(
            SymbolKind::Function,
            SymbolKind::Function,
            RelationKind::Calls,
            FileId::new(1).unwrap()
        ));
    }

    #[test]
    fn test_default_compatibility_function_calls_method() {
        let behavior = TestBehavior;
        assert!(behavior.is_compatible_relationship(
            SymbolKind::Function,
            SymbolKind::Method,
            RelationKind::Calls,
            FileId::new(1).unwrap()
        ));
    }

    #[test]
    fn test_default_compatibility_method_calls_function() {
        let behavior = TestBehavior;
        assert!(behavior.is_compatible_relationship(
            SymbolKind::Method,
            SymbolKind::Function,
            RelationKind::Calls,
            FileId::new(1).unwrap()
        ));
    }

    #[test]
    fn test_default_compatibility_function_calls_class() {
        let behavior = TestBehavior;
        // Functions can call classes (constructors)
        assert!(behavior.is_compatible_relationship(
            SymbolKind::Function,
            SymbolKind::Class,
            RelationKind::Calls,
            FileId::new(1).unwrap()
        ));
    }

    #[test]
    fn test_default_compatibility_function_cannot_call_constant() {
        let behavior = TestBehavior;
        // By default, constants are not callable
        assert!(!behavior.is_compatible_relationship(
            SymbolKind::Function,
            SymbolKind::Constant,
            RelationKind::Calls,
            FileId::new(1).unwrap()
        ));
    }

    #[test]
    fn test_default_compatibility_function_cannot_call_variable() {
        let behavior = TestBehavior;
        // By default, variables are not callable
        assert!(!behavior.is_compatible_relationship(
            SymbolKind::Function,
            SymbolKind::Variable,
            RelationKind::Calls,
            FileId::new(1).unwrap()
        ));
    }

    #[test]
    fn test_default_compatibility_macro_can_be_called() {
        let behavior = TestBehavior;
        assert!(behavior.is_compatible_relationship(
            SymbolKind::Function,
            SymbolKind::Macro,
            RelationKind::Calls,
            FileId::new(1).unwrap()
        ));
    }

    #[test]
    fn test_default_compatibility_class_extends_class() {
        let behavior = TestBehavior;
        assert!(behavior.is_compatible_relationship(
            SymbolKind::Class,
            SymbolKind::Class,
            RelationKind::Extends,
            FileId::new(1).unwrap()
        ));
    }

    #[test]
    fn test_default_compatibility_trait_extends_trait() {
        let behavior = TestBehavior;
        assert!(behavior.is_compatible_relationship(
            SymbolKind::Trait,
            SymbolKind::Trait,
            RelationKind::Extends,
            FileId::new(1).unwrap()
        ));
    }

    #[test]
    fn test_default_compatibility_class_implements_trait() {
        let behavior = TestBehavior;
        assert!(behavior.is_compatible_relationship(
            SymbolKind::Class,
            SymbolKind::Trait,
            RelationKind::Implements,
            FileId::new(1).unwrap()
        ));
    }

    #[test]
    fn test_default_compatibility_uses_always_valid() {
        let behavior = TestBehavior;
        // Uses relationship should always be valid (types can be used anywhere)
        assert!(behavior.is_compatible_relationship(
            SymbolKind::Function,
            SymbolKind::Struct,
            RelationKind::Uses,
            FileId::new(1).unwrap()
        ));
        assert!(behavior.is_compatible_relationship(
            SymbolKind::Method,
            SymbolKind::Enum,
            RelationKind::Uses,
            FileId::new(1).unwrap()
        ));
    }
}