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
//! Special-form extractors for languages whose grammars need custom
//! handling (lisp defines, elixir do-blocks, go type specs, class methods).

use super::RawSymbol;
use super::classify::classify_node;
use super::names::extract_name;
use crate::types::{Language, SymbolType};

/// Extract a symbol from a Scheme `list` node if it starts with `define` or `define-syntax`.
///
/// Scheme AST: `list` → first child `symbol` "define" → second child is either
/// a `list` (procedure: name is its first `symbol`) or a `symbol` (variable definition).
pub(super) fn extract_scheme_define(
    node: &tree_sitter::Node<'_>,
    source: &[u8],
) -> Option<RawSymbol> {
    let mut cursor = node.walk();
    let children: Vec<_> = node.children(&mut cursor).collect();

    // Need at least: ( symbol <something> )
    // Find the first `symbol` child (skip parentheses)
    let first_sym = children.iter().find(|c| c.kind() == "symbol")?;
    let keyword = first_sym.utf8_text(source).ok()?;

    let sym_type = match keyword {
        "define" | "define-syntax" => SymbolType::Function,
        _ => return None,
    };

    // The name is in the next meaningful child after the keyword
    let after_keyword: Vec<_> = children
        .iter()
        .skip_while(|c| c.start_byte() <= first_sym.start_byte())
        .filter(|c| c.kind() != "(" && c.kind() != ")")
        .collect();

    let name = if let Some(next) = after_keyword.first() {
        if next.kind() == "list" {
            // (define (hello ...) ...) → name is first symbol in the inner list
            let mut inner_cursor = next.walk();
            next.children(&mut inner_cursor)
                .find(|c| c.kind() == "symbol")
                .and_then(|c| c.utf8_text(source).ok().map(|s| s.to_string()))
        } else if next.kind() == "symbol" {
            // (define x 42) → name is the symbol directly
            next.utf8_text(source).ok().map(|s| s.to_string())
        } else {
            None
        }
    } else {
        None
    };

    Some(RawSymbol::at(node, name, sym_type))
}

/// Extract a symbol from a Racket `list` node for define/module/struct forms.
pub(super) fn extract_racket_define(
    node: &tree_sitter::Node<'_>,
    source: &[u8],
) -> Option<RawSymbol> {
    let mut cursor = node.walk();
    let children: Vec<_> = node.children(&mut cursor).collect();

    let first_sym = children.iter().find(|c| c.kind() == "symbol")?;
    let keyword = first_sym.utf8_text(source).ok()?;

    let sym_type = match keyword {
        "define" | "define-syntax" => SymbolType::Function,
        "module" | "module*" | "module+" => SymbolType::Module,
        "struct" => SymbolType::Struct,
        _ => return None,
    };

    let after_keyword: Vec<_> = children
        .iter()
        .skip_while(|c| c.start_byte() <= first_sym.start_byte())
        .filter(|c| c.kind() != "(" && c.kind() != ")")
        .collect();

    let name = if let Some(next) = after_keyword.first() {
        if next.kind() == "list" {
            let mut inner_cursor = next.walk();
            next.children(&mut inner_cursor)
                .find(|c| c.kind() == "symbol")
                .and_then(|c| c.utf8_text(source).ok().map(|s| s.to_string()))
        } else if next.kind() == "symbol" {
            next.utf8_text(source).ok().map(|s| s.to_string())
        } else {
            None
        }
    } else {
        None
    };

    Some(RawSymbol::at(node, name, sym_type))
}

/// Keyword-to-symbol-type table for Clojure `list_lit` define forms.
pub(super) const CLOJURE_DEFINE_KINDS: &[(&[&str], SymbolType)] = &[
    (&["defn", "defmacro", "defn-"], SymbolType::Function),
    (&["ns"], SymbolType::Module),
    (&["def", "defonce"], SymbolType::Variable),
];

/// Keyword-to-symbol-type table for Common Lisp `list_lit` define forms.
pub(super) const COMMONLISP_DEFINE_KINDS: &[(&[&str], SymbolType)] = &[
    (&["defclass"], SymbolType::Class),
    (
        &["defvar", "defparameter", "defconstant"],
        SymbolType::Variable,
    ),
    (&["defpackage"], SymbolType::Module),
    (
        &["defmacro", "defgeneric", "defmethod"],
        SymbolType::Function,
    ),
];

/// Extract a symbol from a Lisp `list_lit` define form.
///
/// AST: `list_lit` → first `sym_lit` child text is the keyword → second
/// `sym_lit` is the name.
pub(super) fn extract_lisp_define(
    node: &tree_sitter::Node<'_>,
    source: &[u8],
    keyword_types: &[(&[&str], SymbolType)],
) -> Option<RawSymbol> {
    let mut cursor = node.walk();
    let sym_lits: Vec<_> = node
        .children(&mut cursor)
        .filter(|c| c.kind() == "sym_lit")
        .collect();

    if sym_lits.len() < 2 {
        return None;
    }

    let keyword = sym_lits[0].utf8_text(source).ok()?;
    let sym_type = keyword_types
        .iter()
        .find_map(|(keywords, ty)| keywords.contains(&keyword).then_some(*ty))?;

    let name = sym_lits[1].utf8_text(source).ok().map(|s| s.to_string());

    Some(RawSymbol::at(node, name, sym_type))
}

/// Extract a symbol from a Common Lisp `defun` node.
///
/// CL AST: `defun` → `defun_header` child → `sym_lit` child is the name.
pub(super) fn extract_commonlisp_defun(
    node: &tree_sitter::Node<'_>,
    source: &[u8],
) -> Option<RawSymbol> {
    let mut cursor = node.walk();
    let name = node
        .children(&mut cursor)
        .find(|c| c.kind() == "defun_header")
        .and_then(|header| {
            let mut hcursor = header.walk();
            header
                .children(&mut hcursor)
                .find(|c| c.kind() == "sym_lit")
                .and_then(|s| s.utf8_text(source).ok().map(|t| t.to_string()))
        });

    Some(RawSymbol::at(node, name, SymbolType::Function))
}

pub(super) fn extract_elixir_name(node: &tree_sitter::Node<'_>, source: &[u8]) -> Option<String> {
    let mut cursor = node.walk();
    let mut args = None;
    for child in node.children(&mut cursor) {
        if child.kind() == "arguments" {
            args = Some(child);
            break;
        }
    }

    if let Some(args_node) = args
        && args_node.named_child_count() > 0
        && let Some(first_arg) = args_node.named_child(0)
    {
        if first_arg.kind() == "call"
            && let Some(target) = first_arg.child_by_field_name("target")
        {
            return target.utf8_text(source).ok().map(|s| s.to_string());
        }
        let mut inner_cursor = first_arg.walk();
        for child in first_arg.children(&mut inner_cursor) {
            if child.kind() == "identifier" || child.kind() == "alias" {
                return child.utf8_text(source).ok().map(|s| s.to_string());
            }
        }
        return first_arg.utf8_text(source).ok().map(|s| s.to_string());
    }
    None
}

pub(super) fn get_elixir_do_block<'a>(
    node: &tree_sitter::Node<'a>,
) -> Option<tree_sitter::Node<'a>> {
    let mut cursor = node.walk();
    node.children(&mut cursor)
        .find(|child| child.kind() == "do_block")
}

/// Extract function-valued `const`, `let`, and `var` bindings as named function
/// symbols.
///
/// The name sits on the `variable_declarator`, not on the declaration itself,
/// so the generic name lookup finds nothing and the symbol is stored unnamed.
/// That is what makes function-valued bindings such as React components and
/// utilities unreachable from `structural definitions`.
///
/// `let` and `var` bindings are covered too: the reported symptom was about
/// `const` because that is the dominant style, but the missing name is a
/// property of the declarator, not of the keyword, so scoping this to `const`
/// would leave the same bug in place for the other two.
///
/// Returns `None` for anything else, including multi-declarator statements,
/// destructuring patterns and bindings to plain values, so those keep their
/// existing chunk shape.
///
/// The symbol spans the declaration node, which is what every other declaration
/// kind in this extractor does. `export` is part of the enclosing
/// `export_statement`, so it sits outside that span exactly as it already does
/// for `export`-ed functions, classes and interfaces. Chunk content is expanded
/// to whole lines afterwards, so a single-line `export const f = ...` still reads
/// with its `export`, while a declaration split across lines does not.
pub(super) fn extract_js_function_binding(
    node: &tree_sitter::Node<'_>,
    source: &[u8],
) -> Option<RawSymbol> {
    let mut cursor = node.walk();
    let mut declarators = node
        .children(&mut cursor)
        .filter(|child| child.kind() == "variable_declarator");
    let declarator = declarators.next()?;
    if declarators.next().is_some() {
        return None;
    }

    let value = declarator.child_by_field_name("value")?;
    if !matches!(
        value.kind(),
        "arrow_function" | "function_expression" | "generator_function"
    ) {
        return None;
    }

    let name = extract_name(&declarator, source)?;
    Some(RawSymbol::at(node, Some(name), SymbolType::Function))
}

/// Extract a Lua function-valued assignment as a named function symbol.
pub(super) fn extract_lua_function_binding(
    node: &tree_sitter::Node<'_>,
    source: &[u8],
) -> Option<RawSymbol> {
    let assignment = if node.kind() == "variable_declaration" {
        let mut cursor = node.walk();
        node.named_children(&mut cursor)
            .find(|child| child.kind() == "assignment_statement")?
    } else {
        *node
    };

    let mut cursor = assignment.walk();
    let children: Vec<_> = assignment.named_children(&mut cursor).collect();
    let [variable_list, expression_list] = children.as_slice() else {
        return None;
    };
    if variable_list.kind() != "variable_list" || expression_list.kind() != "expression_list" {
        return None;
    }

    let mut variable_cursor = variable_list.walk();
    let variables: Vec<_> = variable_list.named_children(&mut variable_cursor).collect();
    let [variable] = variables.as_slice() else {
        return None;
    };

    let mut value_cursor = expression_list.walk();
    let values: Vec<_> = expression_list.named_children(&mut value_cursor).collect();
    let [value] = values.as_slice() else {
        return None;
    };
    if value.kind() != "function_definition" {
        return None;
    }

    let name = match variable.kind() {
        "identifier" => variable.utf8_text(source).ok()?.to_string(),
        "dot_index_expression" => variable
            .child_by_field_name("field")?
            .utf8_text(source)
            .ok()?
            .to_string(),
        "method_index_expression" => variable
            .child_by_field_name("method")?
            .utf8_text(source)
            .ok()?
            .to_string(),
        _ => return None,
    };

    Some(RawSymbol::at(node, Some(name), SymbolType::Function))
}

/// Extract Bash `case` arms inside a function as named function symbols.
///
/// Bash dispatchers commonly put most of their useful behavior in a large
/// `case` statement. Keeping each arm as a child symbol gives those branches
/// their own names and spans while the enclosing function remains indexable.
pub(super) fn extract_bash_case_items(
    function_node: &tree_sitter::Node<'_>,
    source: &[u8],
    symbols: &mut Vec<RawSymbol>,
) {
    let function_name = extract_name(function_node, source);
    symbols.push(RawSymbol::at(
        function_node,
        function_name.clone(),
        SymbolType::Function,
    ));

    fn visit(
        node: tree_sitter::Node<'_>,
        source: &[u8],
        function_name: Option<&str>,
        symbols: &mut Vec<RawSymbol>,
    ) {
        if node.kind() == "case_statement" {
            let mut cursor = node.walk();
            for item in node
                .named_children(&mut cursor)
                .filter(|child| child.kind() == "case_item")
            {
                let mut value_cursor = item.walk();
                let Some(pattern) = item
                    .children_by_field_name("value", &mut value_cursor)
                    .next()
                    .and_then(|value| value.utf8_text(source).ok())
                    .and_then(bash_case_pattern_name)
                else {
                    continue;
                };

                let name = function_name
                    .map(|parent| format!("{parent} {pattern}"))
                    .unwrap_or(pattern);
                symbols.push(RawSymbol::at(&item, Some(name), SymbolType::Function));
            }
        }

        let mut cursor = node.walk();
        for child in node.named_children(&mut cursor) {
            // The generic extractor treats a function definition as a leaf;
            // do not attribute a nested function's case arms to its parent.
            if child.kind() != "function_definition" {
                visit(child, source, function_name, symbols);
            }
        }
    }

    let mut cursor = function_node.walk();
    for child in function_node.named_children(&mut cursor) {
        visit(child, source, function_name.as_deref(), symbols);
    }
}

/// Convert the first Bash case pattern into a readable symbol-name fragment.
fn bash_case_pattern_name(text: &str) -> Option<String> {
    let text = text.trim();
    if text.len() >= 2
        && matches!(
            (text.as_bytes().first(), text.as_bytes().last()),
            (Some(b'\''), Some(b'\'')) | (Some(b'"'), Some(b'"'))
        )
    {
        let text = &text[1..text.len() - 1];
        return (!text.is_empty()).then(|| text.to_string());
    }
    (!text.is_empty()).then(|| text.to_string())
}

/// Refine a Go type_spec into the correct SymbolType based on the type child.
pub(super) fn refine_go_type_spec(node: &tree_sitter::Node<'_>, source: &[u8]) -> SymbolType {
    if let Some(type_child) = node.child_by_field_name("type") {
        match type_child.kind() {
            "struct_type" => return SymbolType::Struct,
            "interface_type" => return SymbolType::Interface,
            _ => {}
        }
    }
    // Check the text for common patterns
    let text = node.utf8_text(source).unwrap_or("");
    if text.contains("struct") {
        SymbolType::Struct
    } else if text.contains("interface") {
        SymbolType::Interface
    } else {
        SymbolType::TypeAlias
    }
}

/// Extract individual methods from a Rust `impl` or `trait` block as separate
/// symbols, keeping the block itself indexable as `container_type`.
pub(super) fn extract_rust_block_methods(
    block_node: tree_sitter::Node<'_>,
    source: &[u8],
    lang: Language,
    symbols: &mut Vec<RawSymbol>,
    container_type: SymbolType,
) {
    let name = extract_name(&block_node, source);
    symbols.push(RawSymbol::at(&block_node, name, container_type));

    let mut cursor = block_node.walk();

    for child in block_node.children(&mut cursor) {
        if child.kind() == "declaration_list" {
            let mut inner_cursor = child.walk();
            for item in child.children(&mut inner_cursor) {
                if item.kind() == "function_item" {
                    let name = extract_name(&item, source);
                    symbols.push(RawSymbol::at(&item, name, SymbolType::Method));
                } else if let Some(sym_type) = classify_node(lang, item.kind()) {
                    let name = extract_name(&item, source);
                    symbols.push(RawSymbol::at(&item, name, sym_type));
                }
            }
        }
    }
}

/// Extract methods from a Python `class_definition` as separate symbols.
///
/// Similar to how Rust `impl` methods are extracted: the class body is
/// walked for `function_definition` nodes (methods) which become individual
/// [`Method`] chunks, while the class itself remains indexable as a full
/// [`Class`] symbol for definition-oriented queries.
pub(super) fn extract_python_class_methods(
    class_node: tree_sitter::Node<'_>,
    source: &[u8],
    symbols: &mut Vec<RawSymbol>,
) {
    let name = extract_name(&class_node, source);
    symbols.push(RawSymbol::at(&class_node, name, SymbolType::Class));

    // The class body is a `block` child.
    let mut cursor = class_node.walk();
    for child in class_node.children(&mut cursor) {
        if child.kind() == "block" {
            let mut inner_cursor = child.walk();
            for item in child.children(&mut inner_cursor) {
                // Direct function_definition in class body = method.
                if item.kind() == "function_definition" {
                    let name = extract_name(&item, source);
                    symbols.push(RawSymbol::at(&item, name, SymbolType::Method));
                }
                // Decorated methods: decorated_definition > function_definition
                else if item.kind() == "decorated_definition" {
                    let mut dec_cursor = item.walk();
                    for dec_child in item.children(&mut dec_cursor) {
                        if dec_child.kind() == "function_definition" {
                            let name = extract_name(&dec_child, source);
                            symbols.push(RawSymbol {
                                name,
                                symbol_type: SymbolType::Method,
                                // Use the decorated_definition range to include
                                // the decorator in the chunk.
                                start_byte: item.start_byte(),
                                end_byte: item.end_byte(),
                                start_row: item.start_position().row,
                                end_row: item.end_position().row,
                            });
                        }
                    }
                }
            }
        }
    }
}

pub(super) fn extract_general_class_methods(
    class_node: tree_sitter::Node<'_>,
    source: &[u8],
    lang: Language,
    symbols: &mut Vec<RawSymbol>,
    class_sym_type: SymbolType,
) {
    // ALWAYS push the class/wrapper itself
    let name = extract_name(&class_node, source);
    symbols.push(RawSymbol::at(&class_node, name, class_sym_type));

    let mut cursor = class_node.walk();

    for child in class_node.children(&mut cursor) {
        let ckind = child.kind();
        if ckind.contains("body") || ckind.contains("block") || ckind == "declaration_list" {
            let mut inner_cursor = child.walk();
            for item in child.children(&mut inner_cursor) {
                if let Some(sym_type) = classify_node(lang, item.kind()) {
                    let mut end_byte = item.end_byte();
                    let mut end_row = item.end_position().row;

                    // Dart detached method body
                    if lang == Language::Dart
                        && item.kind() == "method_signature"
                        && let Some(next) = item.next_sibling()
                        && next.kind() == "function_body"
                    {
                        end_byte = next.end_byte();
                        end_row = next.end_position().row;
                    }

                    let name = extract_name(&item, source);
                    symbols.push(RawSymbol {
                        name,
                        symbol_type: sym_type,
                        start_byte: item.start_byte(),
                        end_byte,
                        start_row: item.start_position().row,
                        end_row,
                    });
                } else if lang == Language::Dart && item.kind() == "class_member" {
                    let mut cm_cursor = item.walk();
                    for cm_child in item.children(&mut cm_cursor) {
                        if let Some(sym_type) = classify_node(lang, cm_child.kind()) {
                            let mut end_byte = cm_child.end_byte();
                            let mut end_row = cm_child.end_position().row;

                            if cm_child.kind() == "method_signature"
                                && let Some(next) = cm_child.next_sibling()
                                && next.kind() == "function_body"
                            {
                                end_byte = next.end_byte();
                                end_row = next.end_position().row;
                            }

                            let name = extract_name(&cm_child, source);
                            symbols.push(RawSymbol {
                                name,
                                symbol_type: sym_type,
                                start_byte: cm_child.start_byte(),
                                end_byte,
                                start_row: cm_child.start_position().row,
                                end_row,
                            });
                        }
                    }
                } else if lang == Language::Java && class_sym_type == SymbolType::Enum {
                    // Java enum methods can be nested under enum_body_declarations
                    // wrappers instead of appearing as direct enum_body children.
                    let mut java_cursor = item.walk();
                    for java_child in item.children(&mut java_cursor) {
                        if let Some(sym_type) = classify_node(lang, java_child.kind()) {
                            let name = extract_name(&java_child, source);
                            symbols.push(RawSymbol::at(&java_child, name, sym_type));
                            continue;
                        }

                        let mut java_inner_cursor = java_child.walk();
                        for java_inner in java_child.children(&mut java_inner_cursor) {
                            if let Some(sym_type) = classify_node(lang, java_inner.kind()) {
                                let name = extract_name(&java_inner, source);
                                symbols.push(RawSymbol::at(&java_inner, name, sym_type));
                            }
                        }
                    }
                }
            }
        }
    }
}