agentis-ctx 0.3.3

Fast CLI tool that generates AI-ready context from your codebase, with built-in code intelligence
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
//! Rust-specific code parsing using tree-sitter.

use tree_sitter::{Node, Parser, Query, QueryCursor};

use crate::db::{Edge, EdgeKind, ModuleInfo, ParseResult, Symbol, SymbolKind, Visibility};
use crate::parser::{
    extract_brief, extract_call_edges, find_symbol_kind, is_def_capture, CallCapturePatterns,
    SymbolKindMapping,
};

/// Symbol kind mappings for Rust capture names.
const RUST_SYMBOL_MAPPINGS: &[SymbolKindMapping] = &[
    SymbolKindMapping::new("func", SymbolKind::Function),
    SymbolKindMapping::new("method", SymbolKind::Method),
    SymbolKindMapping::new("struct", SymbolKind::Struct),
    SymbolKindMapping::new("enum", SymbolKind::Enum),
    SymbolKindMapping::new("trait", SymbolKind::Trait),
    SymbolKindMapping::new("type", SymbolKind::Type),
    SymbolKindMapping::new("const", SymbolKind::Const),
    SymbolKindMapping::new("static", SymbolKind::Static),
    SymbolKindMapping::new("macro", SymbolKind::Macro),
    SymbolKindMapping::new("mod", SymbolKind::Module),
];

/// Rust-specific parser.
pub struct RustParser {
    parser: Parser,
    symbols_query: Query,
    calls_query: Query,
    impl_query: Query,
}

impl RustParser {
    /// Create a new Rust parser.
    pub fn new() -> Self {
        let mut parser = Parser::new();
        let language = tree_sitter_rust::language();
        parser
            .set_language(language)
            .expect("Failed to set Rust language");

        // Query for extracting trait implementations
        let impl_query = Query::new(
            language,
            r#"
            ; Trait implementations: impl Trait for Type
            (impl_item
                trait: (type_identifier) @trait.name
                type: (type_identifier) @type.name
            ) @impl.def
            "#,
        )
        .expect("Invalid impl query");

        // Query for extracting symbols (functions, structs, enums, etc.)
        // Note: We only match top-level functions (not inside impl blocks) and
        // methods inside impl blocks separately to avoid duplicate symbols.
        let symbols_query = Query::new(
            language,
            r#"
            ; Top-level functions only (not inside impl blocks)
            ; Using a negated pattern to exclude functions in impl blocks
            (source_file
                (function_item
                    name: (identifier) @func.name
                    parameters: (parameters) @func.params
                    return_type: (_)? @func.return
                ) @func.def
            )

            ; Functions inside mod blocks (but not impl blocks)
            (mod_item
                body: (declaration_list
                    (function_item
                        name: (identifier) @func.name
                        parameters: (parameters) @func.params
                        return_type: (_)? @func.return
                    ) @func.def
                )
            )

            ; Methods in impl blocks
            (impl_item
                type: (_) @impl.type
                body: (declaration_list
                    (function_item
                        name: (identifier) @method.name
                        parameters: (parameters) @method.params
                        return_type: (_)? @method.return
                    ) @method.def
                )
            ) @impl.def

            ; Structs
            (struct_item
                name: (type_identifier) @struct.name
            ) @struct.def

            ; Enums
            (enum_item
                name: (type_identifier) @enum.name
            ) @enum.def

            ; Traits
            (trait_item
                name: (type_identifier) @trait.name
            ) @trait.def

            ; Type aliases
            (type_item
                name: (type_identifier) @type.name
            ) @type.def

            ; Constants
            (const_item
                name: (identifier) @const.name
            ) @const.def

            ; Static items
            (static_item
                name: (identifier) @static.name
            ) @static.def

            ; Macro definitions
            (macro_definition
                name: (identifier) @macro.name
            ) @macro.def

            ; Module declarations
            (mod_item
                name: (identifier) @mod.name
            ) @mod.def

            ; Use statements (imports)
            (use_declaration
                argument: (_) @use.path
            ) @use.def
            "#,
        )
        .expect("Invalid symbols query");

        // Query for extracting function calls
        let calls_query = Query::new(
            language,
            r#"
            ; Function calls
            (call_expression
                function: (identifier) @call.name
            ) @call.expr

            ; Method calls
            (call_expression
                function: (field_expression
                    field: (field_identifier) @method_call.name
                )
            ) @method_call.expr

            ; Scoped calls (e.g., Type::method())
            (call_expression
                function: (scoped_identifier
                    name: (identifier) @scoped_call.name
                )
            ) @scoped_call.expr
            "#,
        )
        .expect("Invalid calls query");

        Self {
            parser,
            symbols_query,
            calls_query,
            impl_query,
        }
    }

    /// Parse a Rust source file.
    pub fn parse(&mut self, file_path: &str, source: &str) -> Option<ParseResult> {
        let tree = self.parser.parse(source, None)?;
        let root = tree.root_node();

        let mut symbols = Vec::new();
        let mut edges = Vec::new();
        let mut imports = Vec::new();
        let mut exports = Vec::new();

        // Extract symbols
        self.extract_symbols(
            &root,
            file_path,
            source,
            &mut symbols,
            &mut imports,
            &mut exports,
        );

        // Extract edges (calls, uses)
        self.extract_edges(&root, file_path, source, &symbols, &mut edges);

        // Extract trait implementation edges
        self.extract_impl_edges(&root, file_path, source, &symbols, &mut edges);

        let module = ModuleInfo {
            file_path: file_path.to_string(),
            module_name: super::extract_module_name(file_path, &["mod", "lib", "main"]),
            exports,
            imports,
        };

        Some(ParseResult {
            file_path: file_path.to_string(),
            language: "rust".to_string(),
            symbols,
            edges,
            module: Some(module),
        })
    }

    /// Extract symbols from the AST.
    fn extract_symbols(
        &self,
        root: &Node,
        file_path: &str,
        source: &str,
        symbols: &mut Vec<Symbol>,
        imports: &mut Vec<crate::db::ImportInfo>,
        exports: &mut Vec<String>,
    ) {
        let mut cursor = QueryCursor::new();
        let matches = cursor.matches(&self.symbols_query, *root, source.as_bytes());

        for m in matches {
            let mut name: Option<&str> = None;
            let mut kind: Option<SymbolKind> = None;
            let mut def_node: Option<Node> = None;
            let mut signature_parts: Vec<&str> = Vec::new();
            let mut parent_type: Option<&str> = None;

            for capture in m.captures {
                let capture_name = &self.symbols_query.capture_names()[capture.index as usize];
                let capture_str = capture_name.as_str();
                let node = capture.node;
                let text = node.utf8_text(source.as_bytes()).unwrap_or("");

                // Try to match standard symbol patterns
                if let Some(k) = find_symbol_kind(capture_str, RUST_SYMBOL_MAPPINGS) {
                    name = Some(text);
                    kind = Some(k);
                } else {
                    // Handle special cases
                    match capture_str {
                        // Signature parts
                        "func.params" | "method.params" => signature_parts.push(text),
                        "func.return" | "method.return" => signature_parts.push(text),
                        // Parent type for methods
                        "impl.type" => parent_type = Some(text),
                        // Use statements
                        "use.path" => {
                            let import = parse_use_path(text);
                            imports.push(import);
                        }
                        // Generic .def captures
                        _ if is_def_capture(capture_str) => {
                            def_node = Some(node);
                        }
                        _ => {}
                    }
                }
            }

            // Create symbol if we have enough information
            if let (Some(name), Some(kind), Some(node)) = (name, kind, def_node) {
                let visibility = extract_visibility(&node, source);
                let docstring = extract_docstring(&node, source);
                let brief = docstring.as_ref().and_then(|d| extract_brief(d));

                let signature = build_signature(kind, name, &signature_parts, source, &node);

                let parent_id = parent_type.map(|p| Symbol::make_id(file_path, p, None));

                let symbol_source = node.utf8_text(source.as_bytes()).ok().map(String::from);

                let id = Symbol::make_id(file_path, name, parent_type);

                // Track exports (public symbols)
                if visibility == Visibility::Public {
                    exports.push(name.to_string());
                }

                symbols.push(Symbol {
                    id,
                    file_path: file_path.to_string(),
                    name: name.to_string(),
                    qualified_name: parent_type.map(|p| format!("{}::{}", p, name)),
                    kind,
                    visibility,
                    signature,
                    brief,
                    docstring,
                    line_start: node.start_position().row as u32 + 1,
                    line_end: node.end_position().row as u32 + 1,
                    col_start: node.start_position().column as u32,
                    col_end: node.end_position().column as u32,
                    parent_id,
                    source: symbol_source,
                });
            }
        }
    }

    /// Extract edges (function calls) from the AST.
    fn extract_edges(
        &self,
        root: &Node,
        _file_path: &str,
        source: &str,
        symbols: &[Symbol],
        edges: &mut Vec<Edge>,
    ) {
        extract_call_edges(
            &self.calls_query,
            root,
            source,
            symbols,
            edges,
            &CallCapturePatterns::RUST,
        );
    }

    /// Extract trait implementation edges from the AST.
    fn extract_impl_edges(
        &self,
        root: &Node,
        _file_path: &str,
        source: &str,
        symbols: &[Symbol],
        edges: &mut Vec<Edge>,
    ) {
        let mut cursor = QueryCursor::new();
        let matches = cursor.matches(&self.impl_query, *root, source.as_bytes());

        for m in matches {
            let mut trait_name: Option<&str> = None;
            let mut type_name: Option<&str> = None;
            let mut def_node: Option<Node> = None;

            for capture in m.captures {
                let capture_name = &self.impl_query.capture_names()[capture.index as usize];
                let node = capture.node;
                let text = node.utf8_text(source.as_bytes()).unwrap_or("");

                match capture_name.as_str() {
                    "trait.name" => {
                        trait_name = Some(text);
                    }
                    "type.name" => {
                        type_name = Some(text);
                    }
                    "impl.def" => {
                        def_node = Some(node);
                    }
                    _ => {}
                }
            }

            if let (Some(trait_name), Some(type_name), Some(node)) =
                (trait_name, type_name, def_node)
            {
                let line = node.start_position().row as u32 + 1;
                let col = node.start_position().column as u32;

                // Find the type symbol - skip if not found (FK constraint requires valid source_id)
                let source_id = match symbols
                    .iter()
                    .find(|s| {
                        s.name == type_name
                            && matches!(s.kind, SymbolKind::Struct | SymbolKind::Enum)
                    })
                    .map(|s| s.id.clone())
                {
                    Some(id) => id,
                    None => continue, // Skip this edge if we can't find a valid source symbol
                };

                // Find the trait symbol
                let target_id = symbols
                    .iter()
                    .find(|s| s.name == trait_name && s.kind == SymbolKind::Trait)
                    .map(|s| s.id.clone());

                edges.push(Edge {
                    source_id,
                    target_id,
                    target_name: trait_name.to_string(),
                    kind: EdgeKind::Implements,
                    line: Some(line),
                    col: Some(col),
                    context: Some(format!("impl {} for {}", trait_name, type_name)),
                });
            }
        }
    }
}

/// Extract visibility from a node.
fn extract_visibility(node: &Node, source: &str) -> Visibility {
    // Look for visibility modifier as first child
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "visibility_modifier" {
            let text = child.utf8_text(source.as_bytes()).unwrap_or("");
            return match text {
                "pub" => Visibility::Public,
                "pub(crate)" => Visibility::Crate,
                "pub(super)" => Visibility::Super,
                _ if text.starts_with("pub(in") => Visibility::InPath,
                _ => Visibility::Private,
            };
        }
    }
    Visibility::Private
}

/// Extract docstring from a node (looking for preceding comments).
fn extract_docstring(node: &Node, source: &str) -> Option<String> {
    let mut doc_lines = Vec::new();
    let mut prev = node.prev_sibling();

    // Collect consecutive doc comments before the node
    while let Some(sibling) = prev {
        match sibling.kind() {
            "line_comment" => {
                let text = sibling.utf8_text(source.as_bytes()).unwrap_or("");
                if text.starts_with("///") || text.starts_with("//!") {
                    let content = text
                        .trim_start_matches("///")
                        .trim_start_matches("//!")
                        .trim();
                    doc_lines.push(content.to_string());
                } else {
                    break;
                }
            }
            "block_comment" => {
                let text = sibling.utf8_text(source.as_bytes()).unwrap_or("");
                if text.starts_with("/**") || text.starts_with("/*!") {
                    doc_lines.push(super::parse_block_doc_comment(text));
                }
                break;
            }
            _ => break,
        }
        prev = sibling.prev_sibling();
    }

    if doc_lines.is_empty() {
        return None;
    }

    doc_lines.reverse();
    Some(doc_lines.join("\n"))
}

/// Build a signature string for a symbol.
fn build_signature(
    kind: SymbolKind,
    _name: &str,
    _parts: &[&str],
    source: &str,
    node: &Node,
) -> Option<String> {
    match kind {
        SymbolKind::Function | SymbolKind::Method => {
            // Get the function signature up to the body
            let text = node.utf8_text(source.as_bytes()).ok()?;
            // Find where the body starts (first '{')
            if let Some(idx) = text.find('{') {
                let sig = text[..idx].trim();
                Some(sig.to_string())
            } else {
                // No body, might be a trait method
                Some(text.lines().next()?.trim().to_string())
            }
        }
        SymbolKind::Struct | SymbolKind::Enum | SymbolKind::Trait => {
            // Get the first line
            let text = node.utf8_text(source.as_bytes()).ok()?;
            let first_line = text.lines().next()?.trim();
            Some(first_line.trim_end_matches('{').trim().to_string())
        }
        _ => None,
    }
}

/// Parse a use path into ImportInfo.
fn parse_use_path(path: &str) -> crate::db::ImportInfo {
    // Handle various use patterns:
    // - use foo::bar;
    // - use foo::bar::{baz, qux};
    // - use foo::bar::*;
    // - use foo::bar as alias;

    let path = path.trim();

    // Check for alias
    if let Some(idx) = path.rfind(" as ") {
        let (path_part, alias) = path.split_at(idx);
        let alias = alias.trim_start_matches(" as ").trim();
        return crate::db::ImportInfo {
            from: path_part.trim().to_string(),
            names: vec![alias.to_string()],
            alias: Some(alias.to_string()),
        };
    }

    // Check for group imports
    if path.contains('{') {
        if let Some(idx) = path.find('{') {
            let base = path[..idx].trim_end_matches(':').trim();
            let names_part = path[idx..].trim_matches(|c| c == '{' || c == '}');
            let names: Vec<String> = names_part
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            return crate::db::ImportInfo {
                from: base.to_string(),
                names,
                alias: None,
            };
        }
    }

    // Check for glob import
    if path.ends_with("::*") {
        let base = path.trim_end_matches("::*");
        return crate::db::ImportInfo {
            from: base.to_string(),
            names: vec!["*".to_string()],
            alias: None,
        };
    }

    // Simple import
    let parts: Vec<&str> = path.rsplitn(2, "::").collect();
    if parts.len() == 2 {
        crate::db::ImportInfo {
            from: parts[1].to_string(),
            names: vec![parts[0].to_string()],
            alias: None,
        }
    } else {
        crate::db::ImportInfo {
            from: path.to_string(),
            names: Vec::new(),
            alias: None,
        }
    }
}

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

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

    #[test]
    fn test_parse_simple_function() {
        let mut parser = RustParser::new();
        let source = r#"
/// This is a test function.
pub fn hello_world(name: &str) -> String {
    format!("Hello, {}!", name)
}
"#;

        let result = parser.parse("test.rs", source).unwrap();
        assert_eq!(result.symbols.len(), 1);

        let func = &result.symbols[0];
        assert_eq!(func.name, "hello_world");
        assert_eq!(func.kind, SymbolKind::Function);
        assert_eq!(func.visibility, Visibility::Public);
        assert!(func.signature.as_ref().unwrap().contains("fn hello_world"));
        assert_eq!(func.brief.as_ref().unwrap(), "This is a test function.");
    }

    #[test]
    fn test_parse_struct() {
        let mut parser = RustParser::new();
        let source = r#"
/// A point in 2D space.
pub struct Point {
    pub x: f64,
    pub y: f64,
}
"#;

        let result = parser.parse("test.rs", source).unwrap();
        assert_eq!(result.symbols.len(), 1);

        let s = &result.symbols[0];
        assert_eq!(s.name, "Point");
        assert_eq!(s.kind, SymbolKind::Struct);
        assert_eq!(s.visibility, Visibility::Public);
    }

    #[test]
    fn test_parse_impl_methods() {
        let mut parser = RustParser::new();
        let source = r#"
struct Foo;

impl Foo {
    pub fn new() -> Self {
        Foo
    }

    fn private_method(&self) {
    }
}
"#;

        let result = parser.parse("test.rs", source).unwrap();

        // Should have struct and 2 methods
        assert!(result.symbols.len() >= 2);

        let methods: Vec<_> = result
            .symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Method)
            .collect();
        assert_eq!(methods.len(), 2);

        let new_method = methods.iter().find(|m| m.name == "new").unwrap();
        assert_eq!(new_method.visibility, Visibility::Public);
        assert!(new_method
            .qualified_name
            .as_ref()
            .unwrap()
            .contains("Foo::new"));
    }

    #[test]
    fn test_extract_calls() {
        let mut parser = RustParser::new();
        let source = r#"
fn foo() {
    bar();
    baz();
}

fn bar() {}
fn baz() {}
"#;

        let result = parser.parse("test.rs", source).unwrap();

        let calls: Vec<_> = result
            .edges
            .iter()
            .filter(|e| e.kind == EdgeKind::Calls)
            .collect();

        assert_eq!(calls.len(), 2);
        assert!(calls.iter().any(|e| e.target_name == "bar"));
        assert!(calls.iter().any(|e| e.target_name == "baz"));
    }

    #[test]
    fn test_parse_use_path() {
        let import = parse_use_path("std::collections::HashMap");
        assert_eq!(import.from, "std::collections");
        assert_eq!(import.names, vec!["HashMap"]);

        let import = parse_use_path("std::io::{Read, Write}");
        assert_eq!(import.from, "std::io");
        assert_eq!(import.names, vec!["Read", "Write"]);

        let import = parse_use_path("std::prelude::*");
        assert_eq!(import.from, "std::prelude");
        assert_eq!(import.names, vec!["*"]);
    }

    #[test]
    fn test_extract_impl_edges() {
        let mut parser = RustParser::new();
        let source = r#"
trait Animal {
    fn speak(&self);
}

struct Dog {
    name: String,
}

struct Cat {
    name: String,
}

impl Animal for Dog {
    fn speak(&self) {
        println!("Woof!");
    }
}

impl Animal for Cat {
    fn speak(&self) {
        println!("Meow!");
    }
}
"#;

        let result = parser.parse("test.rs", source).unwrap();

        let impl_edges: Vec<_> = result
            .edges
            .iter()
            .filter(|e| e.kind == EdgeKind::Implements)
            .collect();

        // Dog implements Animal, Cat implements Animal
        assert_eq!(impl_edges.len(), 2);

        assert!(impl_edges
            .iter()
            .any(|e| { e.source_id.contains("Dog") && e.target_name == "Animal" }));

        assert!(impl_edges
            .iter()
            .any(|e| { e.source_id.contains("Cat") && e.target_name == "Animal" }));
    }

    #[test]
    fn test_imports_stored_in_module() {
        // NOTE: Import edges are now stored in module.imports rather than as edges
        // because edges require a source_id that references an existing symbol (FK constraint)
        let mut parser = RustParser::new();
        let source = r#"
use std::collections::HashMap;
use std::io::{Read, Write};
"#;

        let result = parser.parse("test.rs", source).unwrap();

        // Imports should be in module info, not as edges
        let module = result.module.unwrap();
        assert!(
            !module.imports.is_empty(),
            "Expected imports in module info"
        );

        // Check we captured the imports
        let all_imports: Vec<_> = module.imports.iter().flat_map(|i| i.names.iter()).collect();
        assert!(all_imports
            .iter()
            .any(|n| n.contains("HashMap") || n.contains("*")));
    }
}