vera2-core 0.12.16-aristoddle.1

Core engine for Vera: parsing, indexing, retrieval, storage, and embedding
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
//! Extract call-site references from tree-sitter ASTs.
//!
//! Walks the AST looking for function/method call expressions and records
//! the callee name, source file, and line number. These lightweight edges
//! power `vera references`, `vera impact`, and `vera dead-code`.
//!
//! # Naming convention for dotted callees
//!
//! A callee is stored under its **rightmost segment**. `obj.method()` records
//! `method`, and JSX follows the same rule, so `<Icons.Arrow />` records
//! `Arrow` rather than `Icons.Arrow`.
//!
//! This is what makes a reference link to a definition. Definitions are
//! indexed under their bare declared name — a component reached as
//! `Icons.Arrow` is declared somewhere as `export function Arrow` — and
//! `find_callers` matches the callee against that name. Storing the full
//! member path would leave the reference matching no definition, which is the
//! invisibility that indexing JSX call sites exists to fix.
//!
//! A lowercase root does not change this: `<icons.Arrow />` is a member
//! expression, and a member expression is always a value lookup — the
//! intrinsic test never applies to one.
//!
//! For *bare* tags there are two intrinsic forms, not one: a name starting
//! with a lowercase ASCII letter (`<div />`), and any name containing a hyphen
//! whatever its case (`<My-element />`, `<my-element />`), which is the
//! custom-element form. Both are host elements and stay out of the call graph.
//! See `is_jsx_host_element`.
//!
//! The trade-off is deliberate: two components sharing a final segment
//! (`Icons.Arrow` and `Shapes.Arrow`) collapse onto one name. Separating them
//! needs import and module resolution, which this layer does not do — it reads
//! one file at a time with no cross-file symbol table.

use crate::types::Language;

/// A raw reference (call site) extracted from the AST.
#[derive(Debug, Clone)]
pub struct RawReference {
    /// Name of the called symbol (e.g., function or method name).
    pub callee: String,
    /// Name of the enclosing symbol that contains this call (if known).
    pub caller: Option<String>,
    /// Receiver the call was made through, when the call site is a member
    /// expression: `state.add_url_rule()` records `state`. Plain calls and
    /// receivers that are not simple identifier paths record `None`.
    ///
    /// This is the only evidence this layer has for telling two definitions of
    /// the same name apart, since it never resolves imports or types.
    pub qualifier: Option<String>,
    /// 1-based line number of the call site.
    pub line: u32,
}

/// Longest receiver text worth storing. Real receivers are short names or
/// short dotted paths; anything longer is an expression this layer cannot use.
const MAX_QUALIFIER_LEN: usize = 64;

/// Extract the receiver of a member call: the object part of `obj.method()`.
///
/// Returns `None` unless the receiver is an identifier or a dotted path of
/// identifiers, so `foo().bar()` and `items[0].bar()` record nothing rather
/// than a fragment that cannot be matched against anything.
fn extract_qualifier(node: &tree_sitter::Node, source: &[u8]) -> Option<String> {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        let receiver = match child.kind() {
            "field_expression"
            | "member_expression"
            | "attribute"
            | "selector_expression"
            | "member_access_expression"
            | "navigation_expression" => child
                .child_by_field_name("object")
                .or_else(|| child.child_by_field_name("value"))
                .or_else(|| child.child_by_field_name("operand"))
                .or_else(|| child.child(0)),
            "scoped_identifier" | "qualified_identifier" => child
                .child_by_field_name("path")
                .or_else(|| child.child_by_field_name("scope"))
                .or_else(|| child.child(0)),
            _ => None,
        };
        let Some(receiver) = receiver else { continue };
        let text = receiver.utf8_text(source).ok()?.trim();
        if text.is_empty() || text.len() > MAX_QUALIFIER_LEN {
            return None;
        }
        if text
            .chars()
            .all(|ch| ch.is_alphanumeric() || ch == '_' || ch == '.' || ch == ':' || ch == '$')
        {
            return Some(text.to_string());
        }
        return None;
    }
    None
}

/// Extract call-site references from a parsed tree.
///
/// Returns a list of `(callee_name, caller_name, line)` tuples representing
/// direct function/method calls found in the source. Does not attempt type
/// resolution or dynamic dispatch analysis.
pub fn extract_references(
    tree: &tree_sitter::Tree,
    source: &[u8],
    lang: Language,
) -> Vec<RawReference> {
    let symbols = super::extractor::extract_symbols(tree, source, lang);
    extract_references_with_symbols(tree, source, lang, &symbols)
}

/// Extract call-site references using pre-computed symbols.
///
/// Use this when symbols have already been extracted (e.g., during unified
/// parsing) to avoid redundant AST walks.
pub fn extract_references_with_symbols(
    tree: &tree_sitter::Tree,
    source: &[u8],
    lang: Language,
    symbols: &[super::extractor::RawSymbol],
) -> Vec<RawReference> {
    let mut refs = Vec::new();
    collect_calls(tree.root_node(), source, lang, symbols, &mut refs);
    refs
}

/// Node kinds that represent function/method calls per language.
fn is_call_node(lang: Language, kind: &str) -> bool {
    match lang {
        Language::Rust => matches!(kind, "call_expression" | "macro_invocation"),
        Language::TypeScript | Language::JavaScript => {
            matches!(kind, "call_expression" | "new_expression") || is_jsx_element_node(kind)
        }
        Language::Python => kind == "call",
        Language::Go => kind == "call_expression",
        Language::Java | Language::Kotlin | Language::CSharp => {
            matches!(
                kind,
                "method_invocation" | "object_creation_expression" | "invocation_expression"
            )
        }
        Language::C | Language::Cpp => kind == "call_expression",
        Language::Ruby => matches!(kind, "call" | "method_call"),
        Language::Swift => kind == "call_expression",
        Language::Php => matches!(kind, "function_call_expression" | "method_call_expression"),
        Language::Elixir => kind == "call",
        Language::Scala => matches!(kind, "call_expression" | "apply_expression"),
        Language::Lua | Language::Luau => kind == "function_call",
        Language::Dart => matches!(kind, "function_expression_invocation" | "method_invocation"),
        Language::Zig => kind == "call_expression",
        Language::Haskell => kind == "function_application",
        Language::Perl => kind == "function_call_expression",
        Language::Julia => kind == "call_expression",
        Language::OCaml => kind == "application_expression",
        Language::Groovy => matches!(kind, "method_call_expression" | "function_call"),
        Language::Erlang => matches!(kind, "call" | "function_call"),
        Language::FSharp => kind == "application_expression",
        Language::PowerShell => kind == "command_expression",
        Language::R => kind == "call",
        Language::DLang => kind == "call_expression",
        Language::Elm => kind == "function_call_expr",
        _ => false,
    }
}

/// Whether a node kind is a JSX element tag that names the component it renders.
///
/// `jsx_closing_element` is deliberately excluded so `<Foo></Foo>` records one
/// reference rather than two.
fn is_jsx_element_node(kind: &str) -> bool {
    matches!(kind, "jsx_opening_element" | "jsx_self_closing_element")
}

/// Whether a JSX tag names a host element rather than a component in scope.
///
/// JSX resolves a *bare* tag beginning with a lowercase ASCII letter, such as
/// `<div>`, to an intrinsic element string. Anything else is a value in scope,
/// and only those are call sites; recording host elements would add an edge per
/// HTML tag in the repository.
///
/// The rule mirrors TypeScript's `isIntrinsicJsxName`, which is
/// `first char in a..z || name contains '-'`. Both halves matter:
///
/// - the range is ASCII on purpose. A Unicode-aware lowercase test would call
///   `<éWidget />` a host element and drop a real component reference.
/// - a hyphen makes the tag intrinsic whatever its case, because that is the
///   custom-element form and TypeScript emits `<My-element />` as the string
///   `"My-element"` rather than a value lookup.
///
/// The decision has to come from the tag node, not from the extracted callee.
/// `extract_callee` returns the rightmost identifier, so `<Icons.arrow />` yields
/// `arrow`, and judging that name alone would discard a real component
/// reference. A dotted tag is a member expression on a value in scope whatever
/// the case of its property.
fn is_jsx_host_element(node: &tree_sitter::Node, source: &[u8]) -> bool {
    if !is_jsx_element_node(node.kind()) {
        return false;
    }
    let Some(name) = node.child_by_field_name("name") else {
        return false;
    };
    if name.kind() == "member_expression" {
        return false;
    }
    name.utf8_text(source).is_ok_and(|text| {
        text.starts_with(|ch: char| ch.is_ascii_lowercase()) || text.contains('-')
    })
}

/// Extract the callee name from a call node.
fn extract_callee(node: &tree_sitter::Node, source: &[u8]) -> Option<String> {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            // Direct function call: foo()
            "identifier" | "simple_identifier" => {
                return child.utf8_text(source).ok().map(|s| s.to_string());
            }
            // Method call: obj.method() — extract the method name
            "field_expression"
            | "member_expression"
            | "attribute"
            | "selector_expression"
            | "member_access_expression"
            | "navigation_expression" => {
                let mut inner = child.walk();
                for field_child in child.children(&mut inner) {
                    if matches!(
                        field_child.kind(),
                        "field_identifier"
                            | "property_identifier"
                            | "identifier"
                            | "simple_identifier"
                    ) {
                        // Take the last identifier (the method name)
                        if let Ok(text) = field_child.utf8_text(source) {
                            // Only return if this is the rightmost identifier
                            if field_child.end_byte() == child.end_byte()
                                || field_child.start_byte()
                                    > child.start_byte() + child.byte_range().len() / 2
                            {
                                return Some(text.to_string());
                            }
                        }
                    }
                }
                // Fallback: try named child "name" or "field"
                if let Some(name_node) = child.child_by_field_name("field") {
                    return name_node.utf8_text(source).ok().map(|s| s.to_string());
                }
                if let Some(name_node) = child.child_by_field_name("name") {
                    return name_node.utf8_text(source).ok().map(|s| s.to_string());
                }
            }
            // Scoped identifier: Foo::bar()
            "scoped_identifier" | "qualified_identifier" => {
                let mut inner = child.walk();
                let mut last_ident = None;
                for sc_child in child.children(&mut inner) {
                    if sc_child.kind() == "identifier" || sc_child.kind() == "type_identifier" {
                        last_ident = sc_child.utf8_text(source).ok().map(|s| s.to_string());
                    }
                }
                return last_ident;
            }
            _ => {}
        }
    }
    // Try the "function" or "name" field directly
    if let Some(func_node) = node.child_by_field_name("function") {
        if func_node.kind() == "identifier" || func_node.kind() == "simple_identifier" {
            return func_node.utf8_text(source).ok().map(|s| s.to_string());
        }
        // Nested field access
        if let Some(field) = func_node.child_by_field_name("field") {
            return field.utf8_text(source).ok().map(|s| s.to_string());
        }
        if let Some(name) = func_node.child_by_field_name("name") {
            return name.utf8_text(source).ok().map(|s| s.to_string());
        }
    }
    if let Some(name_node) = node.child_by_field_name("name") {
        return name_node.utf8_text(source).ok().map(|s| s.to_string());
    }
    if let Some(method_node) = node.child_by_field_name("method") {
        return method_node.utf8_text(source).ok().map(|s| s.to_string());
    }
    None
}

/// Find which symbol (from the extracted symbols list) encloses a given byte offset.
fn find_enclosing_symbol(
    symbols: &[super::extractor::RawSymbol],
    byte_offset: usize,
) -> Option<String> {
    symbols
        .iter()
        .filter(|s| s.start_byte <= byte_offset && byte_offset < s.end_byte)
        .min_by_key(|s| s.end_byte - s.start_byte)
        .and_then(|s| s.name.clone())
}

/// Collect call references using a single TreeCursor for the entire traversal.
fn collect_calls(
    root: tree_sitter::Node<'_>,
    source: &[u8],
    lang: Language,
    symbols: &[super::extractor::RawSymbol],
    refs: &mut Vec<RawReference>,
) {
    let mut cursor = root.walk();
    loop {
        let node = cursor.node();
        if is_call_node(lang, node.kind())
            && let Some(callee) = extract_callee(&node, source)
            && !is_jsx_host_element(&node, source)
        {
            let caller = find_enclosing_symbol(symbols, node.start_byte());
            refs.push(RawReference {
                callee,
                caller,
                qualifier: extract_qualifier(&node, source),
                line: node.start_position().row as u32 + 1,
            });
        }
        // Depth-first: try child, then sibling, then backtrack.
        if cursor.goto_first_child() {
            continue;
        }
        if cursor.goto_next_sibling() {
            continue;
        }
        loop {
            if !cursor.goto_parent() {
                return;
            }
            if cursor.goto_next_sibling() {
                break;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parsing::languages::tree_sitter_grammar_for_path;
    use tree_sitter::Parser;

    fn parse_and_extract(source: &str, lang: Language) -> Vec<RawReference> {
        // An extensionless path resolves to the plain per-language grammar.
        parse_and_extract_for_path(source, "source", lang)
    }

    fn parse_and_extract_for_path(source: &str, path: &str, lang: Language) -> Vec<RawReference> {
        let grammar = tree_sitter_grammar_for_path(lang, path).expect("grammar should exist");
        let mut parser = Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(source, None).unwrap();
        extract_references(&tree, source.as_bytes(), lang)
    }

    #[test]
    fn rust_function_calls() {
        let source = r#"
fn main() {
    foo();
    bar::baz();
    obj.method();
}

fn foo() {}
"#;
        let refs = parse_and_extract(source, Language::Rust);
        let callees: Vec<&str> = refs.iter().map(|r| r.callee.as_str()).collect();
        assert!(
            callees.contains(&"foo"),
            "should find foo call: {callees:?}"
        );
        assert!(
            refs.iter().any(|r| r.caller.as_deref() == Some("main")),
            "caller should be main"
        );
    }

    #[test]
    fn python_function_calls() {
        let source = r#"
def main():
    foo()
    bar.baz()

def foo():
    pass
"#;
        let refs = parse_and_extract(source, Language::Python);
        let callees: Vec<&str> = refs.iter().map(|r| r.callee.as_str()).collect();
        assert!(
            callees.contains(&"foo"),
            "should find foo call: {callees:?}"
        );
    }

    #[test]
    fn javascript_function_calls() {
        let source = r#"
function main() {
    foo();
    obj.method();
    new Bar();
}

function foo() {}
"#;
        let refs = parse_and_extract(source, Language::JavaScript);
        let callees: Vec<&str> = refs.iter().map(|r| r.callee.as_str()).collect();
        assert!(
            callees.contains(&"foo"),
            "should find foo call: {callees:?}"
        );
    }

    #[test]
    fn go_function_calls() {
        let source = r#"
package main

func main() {
    foo()
    fmt.Println("hello")
}

func foo() {}
"#;
        let refs = parse_and_extract(source, Language::Go);
        let callees: Vec<&str> = refs.iter().map(|r| r.callee.as_str()).collect();
        assert!(
            callees.contains(&"foo"),
            "should find foo call: {callees:?}"
        );
    }

    #[test]
    fn tsx_jsx_elements_are_call_sites() {
        let source = r#"
import { Hello } from "./jsx";

export function App() {
    return (
        <div className="wrap">
            <Hello name="world" />
            <Panel.Header title="hi"></Panel.Header>
            <Icons.arrow />
            <éWidget />
            <My-element />
        </div>
    );
}
"#;
        let refs = parse_and_extract_for_path(source, "src/app.tsx", Language::TypeScript);
        let callees: Vec<&str> = refs.iter().map(|r| r.callee.as_str()).collect();
        assert!(
            callees.contains(&"Hello"),
            "JSX element should be a call site: {callees:?}"
        );
        assert!(
            callees.contains(&"Header"),
            "dotted JSX element should be a call site: {callees:?}"
        );
        assert!(
            callees.contains(&"arrow"),
            "a dotted tag is a value in scope whatever the case of its \
             property, so <Icons.arrow /> is a call site: {callees:?}"
        );
        assert!(
            !callees.contains(&"div"),
            "host elements should not be call sites: {callees:?}"
        );
        assert!(
            callees.contains(&"éWidget"),
            "only ASCII a-z marks an intrinsic tag, so <éWidget /> is a \
             component reference: {callees:?}"
        );
        assert!(
            !callees.contains(&"My-element"),
            "a hyphen makes a tag intrinsic whatever its case, matching \
             TypeScript's isIntrinsicJsxName: {callees:?}"
        );
        assert_eq!(
            refs.iter().filter(|r| r.callee == "Header").count(),
            1,
            "paired tags should record one reference, not two"
        );
        assert!(
            refs.iter()
                .any(|r| r.callee == "Hello" && r.caller.as_deref() == Some("App")),
            "caller should be App: {refs:?}"
        );
    }

    #[test]
    fn jsx_in_javascript_is_a_call_site() {
        let source = "export function App() { return <Hello name=\"world\" />; }\n";
        let refs = parse_and_extract(source, Language::JavaScript);
        let callees: Vec<&str> = refs.iter().map(|r| r.callee.as_str()).collect();
        assert!(
            callees.contains(&"Hello"),
            "JSX element should be a call site: {callees:?}"
        );
    }

    #[test]
    fn empty_source_returns_no_refs() {
        let refs = parse_and_extract("", Language::Rust);
        assert!(refs.is_empty());
    }

    fn qualifier_of<'a>(refs: &'a [RawReference], callee: &str) -> Option<&'a str> {
        refs.iter()
            .find(|r| r.callee == callee)
            .and_then(|r| r.qualifier.as_deref())
    }

    #[test]
    fn python_records_the_call_receiver() {
        let source = "def register(app, state):\n    app.add_url_rule('/')\n    state.add_url_rule('/x')\n    helper()\n";
        let refs = parse_and_extract_for_path(source, "mod.py", Language::Python);
        let receivers: Vec<Option<&str>> = refs
            .iter()
            .filter(|r| r.callee == "add_url_rule")
            .map(|r| r.qualifier.as_deref())
            .collect();
        assert!(receivers.contains(&Some("app")), "{refs:?}");
        assert!(receivers.contains(&Some("state")), "{refs:?}");
        assert_eq!(qualifier_of(&refs, "helper"), None, "{refs:?}");
    }

    #[test]
    fn javascript_records_dotted_receivers() {
        let source = "function run(list) {\n  utils.forEach(list, fn);\n  list.forEach(fn);\n}\n";
        let refs = parse_and_extract_for_path(source, "mod.js", Language::JavaScript);
        let receivers: Vec<Option<&str>> = refs
            .iter()
            .filter(|r| r.callee == "forEach")
            .map(|r| r.qualifier.as_deref())
            .collect();
        assert!(receivers.contains(&Some("utils")), "{refs:?}");
        assert!(receivers.contains(&Some("list")), "{refs:?}");
    }

    #[test]
    fn rust_records_the_path_of_a_scoped_call() {
        let source = "fn main() {\n    helpers::build();\n    value.build();\n    build();\n}\n";
        let refs = parse_and_extract_for_path(source, "main.rs", Language::Rust);
        let receivers: Vec<Option<&str>> = refs
            .iter()
            .filter(|r| r.callee == "build")
            .map(|r| r.qualifier.as_deref())
            .collect();
        assert!(receivers.contains(&Some("helpers")), "{refs:?}");
        assert!(receivers.contains(&Some("value")), "{refs:?}");
        assert!(
            receivers.contains(&None),
            "a bare call has no receiver: {refs:?}"
        );
    }

    #[test]
    fn a_receiver_that_is_not_an_identifier_path_is_dropped() {
        // `build()` here is reached through a call and an index expression.
        // Recording a fragment of either would produce a receiver that can
        // never match a name the caller could pass.
        let source = "fn main() {\n    factory().build();\n    items[0].build();\n}\n";
        let refs = parse_and_extract_for_path(source, "main.rs", Language::Rust);
        for reference in refs.iter().filter(|r| r.callee == "build") {
            assert_eq!(reference.qualifier, None, "{refs:?}");
        }
    }

    #[test]
    fn go_records_the_package_or_variable_receiver() {
        let source =
            "package main\n\nfunc run(r Router) {\n\tfmt.Println(\"x\")\n\tr.Handle(\"/\")\n}\n";
        let refs = parse_and_extract_for_path(source, "main.go", Language::Go);
        assert_eq!(qualifier_of(&refs, "Println"), Some("fmt"), "{refs:?}");
        assert_eq!(qualifier_of(&refs, "Handle"), Some("r"), "{refs:?}");
    }
}