magellan 4.13.0

Deterministic codebase mapping tool for local development
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
//! Reference and call extraction from Rust source code
//!
//! Extracts factual, byte-accurate references and calls to symbols without semantic analysis.

use crate::common::safe_slice;
use crate::ingest::{SymbolFact, SymbolKind};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// A fact about a reference to a symbol
///
/// Pure data structure. No behavior. No semantic resolution.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ReferenceFact {
    /// File containing this reference
    pub file_path: PathBuf,
    /// Name of the symbol being referenced
    pub referenced_symbol: String,
    /// Byte offset where reference starts in file
    pub byte_start: usize,
    /// Byte offset where reference ends in file
    pub byte_end: usize,
    /// Line where reference starts (1-indexed)
    pub start_line: usize,
    /// Column where reference starts (0-indexed, bytes)
    pub start_col: usize,
    /// Line where reference ends (1-indexed)
    pub end_line: usize,
    /// Column where reference ends (0-indexed, bytes)
    pub end_col: usize,
}

/// A fact about a function call (forward call graph edge)
///
/// Represents: caller function → callee function
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CallFact {
    /// File containing this call
    pub file_path: PathBuf,
    /// Name of the calling function
    pub caller: String,
    /// Name of the function being called
    pub callee: String,
    /// Stable symbol ID of the caller (optional, for correlation)
    #[serde(default)]
    pub caller_symbol_id: Option<String>,
    /// Stable symbol ID of the callee (optional, for correlation)
    #[serde(default)]
    pub callee_symbol_id: Option<String>,
    /// Byte offset where call starts in file
    pub byte_start: usize,
    /// Byte offset where call ends in file
    pub byte_end: usize,
    /// Line where call starts (1-indexed)
    pub start_line: usize,
    /// Column where call starts (0-indexed, bytes)
    pub start_col: usize,
    /// Line where call ends (1-indexed)
    pub end_line: usize,
    /// Column where call ends (0-indexed, bytes)
    pub end_col: usize,
}

/// Reference extractor
pub struct ReferenceExtractor {
    parser: tree_sitter::Parser,
}

impl ReferenceExtractor {
    /// Create a new reference extractor
    pub fn new() -> anyhow::Result<Self> {
        let mut parser = tree_sitter::Parser::new();
        let language = tree_sitter_rust::LANGUAGE.into();
        parser.set_language(&language)?;

        Ok(Self { parser })
    }

    /// Extract reference facts from Rust source code
    ///
    /// # Arguments
    /// * `file_path` - Path to the file (for context only, not accessed)
    /// * `source` - Source code content as bytes
    /// * `symbols` - Symbols defined in this file (to match against and exclude)
    ///
    /// # Returns
    /// Vector of reference facts found in the source
    ///
    /// # Guarantees
    /// - Pure function: same input → same output
    /// - No side effects
    /// - No filesystem access
    /// - No semantic analysis (textual + position match only)
    pub fn extract_references(
        &mut self,
        file_path: PathBuf,
        source: &[u8],
        symbols: &[SymbolFact],
    ) -> Vec<ReferenceFact> {
        self.extract_references_with_fqn(file_path, source, symbols, None)
    }

    /// Extract reference facts with optional fully-qualified symbol map.
    ///
    /// The FQN map enables accurate cross-file resolution of qualified identifiers
    /// such as `math::add`, `pkg.Func`, or `Class::method`.
    pub fn extract_references_with_fqn(
        &mut self,
        file_path: PathBuf,
        source: &[u8],
        symbols: &[SymbolFact],
        fqn_to_symbol: Option<&HashMap<String, &SymbolFact>>,
    ) -> Vec<ReferenceFact> {
        let tree = match self.parser.parse(source, None) {
            Some(t) => t,
            None => return Vec::new(),
        };

        let root_node = tree.root_node();
        let mut references = Vec::new();

        self.walk_tree_for_references(
            &root_node,
            source,
            &file_path,
            symbols,
            fqn_to_symbol,
            &mut references,
        );

        references
    }

    /// Walk tree-sitter tree recursively and extract references
    fn walk_tree_for_references(
        &self,
        node: &tree_sitter::Node,
        source: &[u8],
        file_path: &PathBuf,
        symbols: &[SymbolFact],
        fqn_to_symbol: Option<&HashMap<String, &SymbolFact>>,
        references: &mut Vec<ReferenceFact>,
    ) {
        // Check if this node is a reference we care about
        if let Some(reference) =
            self.extract_reference(node, source, file_path, symbols, fqn_to_symbol)
        {
            references.push(reference);

            // Don't recurse into scoped_identifier - we've already handled it
            if node.kind() == "scoped_identifier" {
                return;
            }
        }

        // Recurse into children
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            self.walk_tree_for_references(
                &child,
                source,
                file_path,
                symbols,
                fqn_to_symbol,
                references,
            );
        }
    }

    /// Extract a reference fact from a tree-sitter node, if applicable
    fn extract_reference(
        &self,
        node: &tree_sitter::Node,
        source: &[u8],
        file_path: &PathBuf,
        symbols: &[SymbolFact],
        fqn_to_symbol: Option<&HashMap<String, &SymbolFact>>,
    ) -> Option<ReferenceFact> {
        let kind = node.kind();

        // Only process identifier and scoped_identifier nodes
        match kind {
            "identifier" => {}
            "scoped_identifier" => {}
            _ => return None,
        }

        // Get the text of this node
        let text_bytes = safe_slice(source, node.start_byte(), node.end_byte())?;
        let text = std::str::from_utf8(text_bytes).ok()?;

        // Resolve the referenced symbol. Prefer FQN-aware resolution for qualified identifiers.
        let referenced_symbol = if kind == "scoped_identifier" {
            let symbols_ref: Vec<&SymbolFact> = symbols.iter().collect();
            crate::ingest::resolve_qualified_symbol(
                text,
                kind,
                file_path,
                fqn_to_symbol.unwrap_or(&HashMap::new()),
                &symbols_ref,
            )
        } else {
            symbols
                .iter()
                .find(|s| s.name.as_ref().map(|n| n == text).unwrap_or(false))
                .map(|s| s as &SymbolFact)
        };

        let referenced_symbol = referenced_symbol?;
        let symbol_name = referenced_symbol.name.as_deref().unwrap_or(text);

        // Check if reference is OUTSIDE the symbol's defining span
        let ref_start = node.start_byte();
        let ref_end = node.end_byte();

        // Only apply span filter for same-file references (self-references)
        // Cross-file references should never be filtered by span
        if referenced_symbol.file_path == *file_path && ref_start < referenced_symbol.byte_end {
            return None; // Reference is within defining span (same file only)
        }

        Some(ReferenceFact {
            file_path: file_path.clone(),
            referenced_symbol: symbol_name.to_string(),
            byte_start: ref_start,
            byte_end: ref_end,
            start_line: node.start_position().row + 1,
            start_col: node.start_position().column,
            end_line: node.end_position().row + 1,
            end_col: node.end_position().column,
        })
    }
}

impl Default for ReferenceExtractor {
    fn default() -> Self {
        Self::new().expect("Failed to create reference extractor") // M-UNWRAP: tree-sitter language is a build-time invariant
    }
}

/// Extension to Parser for reference extraction (convenience wrapper)
impl crate::ingest::Parser {
    /// Extract reference facts using the inner parser
    pub fn extract_references(
        &mut self,
        file_path: PathBuf,
        source: &[u8],
        symbols: &[SymbolFact],
    ) -> Vec<ReferenceFact> {
        let mut extractor =
            ReferenceExtractor::new().expect("Failed to create reference extractor"); // M-UNWRAP: tree-sitter language is a build-time invariant
        extractor.extract_references(file_path, source, symbols)
    }

    /// Extract function call facts (forward call graph)
    ///
    /// # Arguments
    /// * `file_path` - Path to the file (for context only, not accessed)
    /// * `source` - Source code content as bytes
    /// * `symbols` - Symbols defined in this file (to match against)
    ///
    /// # Returns
    /// Vector of CallFact representing caller → callee relationships
    ///
    /// # Guarantees
    /// - Only function calls are extracted (not type references)
    /// - Calls are extracted when a function identifier within a function body
    ///   references another function symbol
    /// - No semantic analysis (AST-based only)
    pub fn extract_calls(
        &mut self,
        file_path: PathBuf,
        source: &[u8],
        symbols: &[SymbolFact],
    ) -> Vec<CallFact> {
        let mut extractor = CallExtractor::new().expect("Failed to create call extractor"); // M-UNWRAP: tree-sitter language is a build-time invariant
        extractor.extract_calls(file_path, source, symbols)
    }

    /// Extract function call facts with optional FQN-aware symbol map.
    ///
    /// The FQN map enables accurate resolution of qualified calls such as
    /// `math::add()` across files.
    pub fn extract_calls_with_fqn(
        &mut self,
        file_path: PathBuf,
        source: &[u8],
        symbols: &[SymbolFact],
        fqn_to_symbol: &HashMap<String, &SymbolFact>,
    ) -> Vec<CallFact> {
        let mut extractor = CallExtractor::new().expect("Failed to create call extractor"); // M-UNWRAP: tree-sitter language is a build-time invariant
        extractor.extract_calls_with_fqn(file_path, source, symbols, fqn_to_symbol)
    }

    /// Extract function call facts from a pre-parsed tree.
    ///
    /// Avoids redundant parsing when the tree is already available.
    pub fn extract_calls_from_tree(
        tree: &tree_sitter::Tree,
        file_path: PathBuf,
        source: &[u8],
        symbols: &[SymbolFact],
    ) -> Vec<CallFact> {
        let mut extractor = CallExtractor::new().expect("Failed to create call extractor"); // M-UNWRAP: tree-sitter language is a build-time invariant
        extractor.extract_calls_from_tree(tree, file_path, source, symbols)
    }

    /// Extract function call facts from a pre-parsed tree with FQN map.
    pub fn extract_calls_from_tree_with_fqn(
        tree: &tree_sitter::Tree,
        file_path: PathBuf,
        source: &[u8],
        symbols: &[SymbolFact],
        fqn_to_symbol: &HashMap<String, &SymbolFact>,
    ) -> Vec<CallFact> {
        let mut extractor = CallExtractor::new().expect("Failed to create call extractor"); // M-UNWRAP: tree-sitter language is a build-time invariant
        extractor.extract_calls_from_tree_with_fqn(tree, file_path, source, symbols, fqn_to_symbol)
    }
}

/// Call extractor for forward call graph
///
/// Extracts caller → callee relationships from function bodies
pub struct CallExtractor {
    parser: tree_sitter::Parser,
}

impl CallExtractor {
    /// Create a new call extractor
    pub fn new() -> anyhow::Result<Self> {
        let mut parser = tree_sitter::Parser::new();
        let language = tree_sitter_rust::LANGUAGE.into();
        parser.set_language(&language)?;

        Ok(Self { parser })
    }

    /// Extract function call facts from Rust source code
    ///
    /// # Behavior
    /// 1. Parse the source code
    /// 2. Find all function definitions
    /// 3. For each function, find identifier nodes that reference other functions
    /// 4. Create CallFact for each unique caller → callee relationship
    pub fn extract_calls(
        &mut self,
        file_path: PathBuf,
        source: &[u8],
        symbols: &[SymbolFact],
    ) -> Vec<CallFact> {
        let fqn_map = crate::ingest::build_fqn_map(symbols);
        self.extract_calls_with_fqn(file_path, source, symbols, &fqn_map)
    }

    /// Extract function call facts with an explicit FQN symbol map.
    pub fn extract_calls_with_fqn(
        &mut self,
        file_path: PathBuf,
        source: &[u8],
        symbols: &[SymbolFact],
        fqn_to_symbol: &HashMap<String, &SymbolFact>,
    ) -> Vec<CallFact> {
        let tree = match self.parser.parse(source, None) {
            Some(t) => t,
            None => return Vec::new(),
        };

        self.extract_calls_from_tree_with_fqn(&tree, file_path, source, symbols, fqn_to_symbol)
    }

    /// Extract function call facts from a pre-parsed tree.
    pub fn extract_calls_from_tree(
        &mut self,
        tree: &tree_sitter::Tree,
        file_path: PathBuf,
        source: &[u8],
        symbols: &[SymbolFact],
    ) -> Vec<CallFact> {
        let fqn_map = crate::ingest::build_fqn_map(symbols);
        self.extract_calls_from_tree_with_fqn(tree, file_path, source, symbols, &fqn_map)
    }

    /// Extract function call facts from a pre-parsed tree with FQN map.
    pub fn extract_calls_from_tree_with_fqn(
        &mut self,
        tree: &tree_sitter::Tree,
        file_path: PathBuf,
        source: &[u8],
        symbols: &[SymbolFact],
        fqn_to_symbol: &HashMap<String, &SymbolFact>,
    ) -> Vec<CallFact> {
        let root_node = tree.root_node();
        let mut calls = Vec::new();

        // Build map: symbol name → symbol fact (for quick lookup)
        let symbol_map: HashMap<String, &SymbolFact> = symbols
            .iter()
            .filter_map(|s| s.name.as_ref().map(|name| (name.clone(), s)))
            .collect();

        // Filter to only functions (potential callers and callees)
        let functions: Vec<&SymbolFact> = symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Function)
            .collect();

        // Walk tree and find calls within function bodies
        Self::walk_tree_for_calls(
            &root_node,
            source,
            &file_path,
            &symbol_map,
            fqn_to_symbol,
            &functions,
            &mut calls,
        );

        calls
    }

    /// Walk tree-sitter tree and extract function calls
    fn walk_tree_for_calls(
        node: &tree_sitter::Node,
        source: &[u8],
        file_path: &PathBuf,
        symbol_map: &HashMap<String, &SymbolFact>,
        fqn_to_symbol: &HashMap<String, &SymbolFact>,
        _functions: &[&SymbolFact],
        calls: &mut Vec<CallFact>,
    ) {
        Self::walk_tree_for_calls_with_caller(
            node,
            source,
            file_path,
            symbol_map,
            fqn_to_symbol,
            None,
            calls,
        );
    }

    /// Walk tree-sitter tree and extract function calls, tracking current function
    fn walk_tree_for_calls_with_caller(
        node: &tree_sitter::Node,
        source: &[u8],
        file_path: &PathBuf,
        symbol_map: &HashMap<String, &SymbolFact>,
        fqn_to_symbol: &HashMap<String, &SymbolFact>,
        current_caller: Option<&SymbolFact>,
        calls: &mut Vec<CallFact>,
    ) {
        let kind = node.kind();

        // Track which function we're inside (if any)
        let caller: Option<&SymbolFact> = if kind == "function_item" {
            // Extract function name - this becomes the new caller for children
            Self::extract_function_name(node, source)
                .and_then(|name| symbol_map.get(&name).copied())
        } else {
            current_caller
        };

        // If we have a caller and this is a call_expression, extract the call
        if kind == "call_expression" {
            if let Some(caller_fact) = caller {
                Self::extract_calls_in_node(
                    node,
                    source,
                    file_path,
                    caller_fact,
                    symbol_map,
                    fqn_to_symbol,
                    calls,
                );
            }
        }

        // Recurse into children
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            Self::walk_tree_for_calls_with_caller(
                &child,
                source,
                file_path,
                symbol_map,
                fqn_to_symbol,
                caller,
                calls,
            );
        }
    }

    /// Extract function name from a function_item node
    fn extract_function_name(node: &tree_sitter::Node, source: &[u8]) -> Option<String> {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "identifier" || child.kind() == "type_identifier" {
                let name_bytes = safe_slice(source, child.start_byte(), child.end_byte())?;
                return std::str::from_utf8(name_bytes).ok().map(|s| s.to_string());
            }
        }
        None
    }

    /// Extract calls within a node (function body)
    fn extract_calls_in_node(
        node: &tree_sitter::Node,
        source: &[u8],
        file_path: &Path,
        caller: &SymbolFact,
        symbol_map: &HashMap<String, &SymbolFact>,
        fqn_to_symbol: &HashMap<String, &SymbolFact>,
        calls: &mut Vec<CallFact>,
    ) {
        // Look for call_expression nodes or identifier nodes
        let kind = node.kind();

        if kind == "call_expression" {
            // Extract the function being called
            if let Some((callee_text, callee_node_kind)) =
                Self::extract_callee_from_call(node, source)
            {
                // Resolve the callee. For qualified identifiers, use FQN-aware resolution.
                let all_symbols: Vec<&SymbolFact> = symbol_map.values().copied().collect();
                let resolved = if callee_node_kind == "scoped_identifier"
                    || callee_node_kind == "field_expression"
                    || callee_node_kind == "method_expression"
                {
                    crate::ingest::resolve_qualified_symbol(
                        &callee_text,
                        callee_node_kind,
                        file_path,
                        fqn_to_symbol,
                        &all_symbols,
                    )
                } else {
                    symbol_map.get(&callee_text).copied()
                };

                // Only create call if callee is a known function symbol
                if let Some(callee_fact) = resolved {
                    if callee_fact.kind == SymbolKind::Function {
                        let node_start = node.start_byte();
                        let node_end = node.end_byte();
                        let callee_name = callee_fact
                            .name
                            .as_ref()
                            .cloned()
                            .unwrap_or_else(|| callee_text.clone());
                        let call_fact = CallFact {
                            file_path: file_path.to_path_buf(),
                            caller: caller.name.clone().unwrap_or_default(),
                            callee: callee_name,
                            caller_symbol_id: None,
                            callee_symbol_id: None,
                            byte_start: node_start,
                            byte_end: node_end,
                            start_line: node.start_position().row + 1,
                            start_col: node.start_position().column,
                            end_line: node.end_position().row + 1,
                            end_col: node.end_position().column,
                        };
                        calls.push(call_fact);
                    }
                }
            }
        }
    }

    /// Extract callee text and node kind from a call_expression node.
    ///
    /// The node kind tells the caller whether the callee is a simple
    /// identifier or a qualified expression, so resolution can use the FQN map.
    fn extract_callee_from_call(
        node: &tree_sitter::Node,
        source: &[u8],
    ) -> Option<(String, &'static str)> {
        // The callee is typically the first child (identifier) or a scoped_identifier
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            let kind = child.kind();
            if kind == "identifier" {
                let name_bytes = safe_slice(source, child.start_byte(), child.end_byte())?;
                let name = std::str::from_utf8(name_bytes).ok()?.to_string();
                return Some((name, "identifier"));
            }
            // Handle qualified calls like math::add() and method calls like obj.method()
            if kind == "scoped_identifier" {
                let text_bytes = safe_slice(source, child.start_byte(), child.end_byte())?;
                let text = std::str::from_utf8(text_bytes).ok()?.to_string();
                return Some((text, "scoped_identifier"));
            }
            if kind == "field_expression" || kind == "method_expression" {
                // For a.b(), extract "b"
                let method_name = Self::extract_method_name(&child, source)?;
                return Some((method_name, kind));
            }
        }
        None
    }

    /// Extract method name from a field_expression or method_expression
    fn extract_method_name(node: &tree_sitter::Node, source: &[u8]) -> Option<String> {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            // Look for the field_identifier (method name in a.b())
            if child.kind() == "field_identifier" {
                let name_bytes = safe_slice(source, child.start_byte(), child.end_byte())?;
                return std::str::from_utf8(name_bytes).ok().map(|s| s.to_string());
            }
        }
        None
    }
}

impl Default for CallExtractor {
    fn default() -> Self {
        Self::new().expect("Failed to create call extractor") // M-UNWRAP: tree-sitter language is a build-time invariant
    }
}