colgrep 1.5.1

Semantic code search powered by ColBERT
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! Code unit extraction from AST nodes.

use super::analysis::{
    extract_control_flow, extract_docstring, extract_function_calls, extract_parameters,
    extract_parent_class, extract_return_type, extract_used_modules, extract_variables,
};
use super::ast::{find_start_with_attributes, get_node_name};
use super::types::{CodeUnit, Language, UnitType};
use std::path::Path;
use tree_sitter::Node;

/// Extract a function or method from an AST node.
pub fn extract_function(
    node: Node,
    path: &Path,
    lines: &[&str],
    bytes: &[u8],
    lang: Language,
    parent_class: Option<&str>,
    file_imports: &[String],
) -> Option<CodeUnit> {
    let name = get_node_name(node, bytes, lang)?;
    let ast_start_line = node.start_position().row;
    let end_line = node.end_position().row;

    // Include preceding attributes/decorators in the line range
    let code_start = find_start_with_attributes(ast_start_line, lines, lang);
    let start_line = code_start;

    // Determine if this is a method based on parent class or language-specific patterns
    let (unit_type, effective_parent) = determine_function_type(node, bytes, lang, parent_class);

    let mut unit = CodeUnit::new(
        name,
        path.to_path_buf(),
        start_line + 1, // 1-indexed, includes attributes
        end_line + 1,
        lang,
        unit_type,
        effective_parent.as_deref().or(parent_class),
    );

    // Layer 1: AST
    unit.signature = lines
        .get(ast_start_line)
        .map(|s| s.trim().to_string())
        .unwrap_or_default();
    unit.docstring = extract_docstring(node, lines, lang);
    unit.parameters = extract_parameters(node, bytes, lang);
    unit.return_type = extract_return_type(node, bytes, lang);

    // Layer 2: Call Graph
    unit.calls = extract_function_calls(node, bytes, lang);

    // Layer 3: Control Flow
    let (complexity, has_loops, has_branches, has_error_handling) =
        extract_control_flow(node, lang);
    unit.complexity = complexity;
    unit.has_loops = has_loops;
    unit.has_branches = has_branches;
    unit.has_error_handling = has_error_handling;

    // Layer 4: Data Flow
    unit.variables = extract_variables(node, bytes, lang);

    // Layer 5: Dependencies
    // Get modules used via attribute access (e.g., `json` from `json.loads()`)
    let used_modules = extract_used_modules(node, bytes, lang);
    // Filter to only modules that are actually imported (case-insensitive for Ruby, etc.)
    unit.imports = file_imports
        .iter()
        .filter(|import| {
            used_modules
                .iter()
                .any(|m| m.to_lowercase() == import.to_lowercase())
                || unit.calls.iter().any(|call| {
                    call.to_lowercase().contains(&import.to_lowercase())
                        || import.to_lowercase().contains(&call.to_lowercase())
                })
        })
        .cloned()
        .collect();

    // Full source content
    let content_end = (end_line + 1).min(lines.len());
    unit.code = lines[code_start..content_end].join("\n");

    Some(unit)
}

/// Extract a class, struct, or similar type definition from an AST node.
pub fn extract_class(
    node: Node,
    path: &Path,
    lines: &[&str],
    bytes: &[u8],
    lang: Language,
    file_imports: &[String],
) -> Option<CodeUnit> {
    let name = get_node_name(node, bytes, lang)?;
    let ast_start_line = node.start_position().row;
    let end_line = node.end_position().row;

    // Include preceding attributes/decorators in the line range
    let code_start = find_start_with_attributes(ast_start_line, lines, lang);
    let start_line = code_start;

    let mut unit = CodeUnit::new(
        name,
        path.to_path_buf(),
        start_line + 1,
        end_line + 1,
        lang,
        UnitType::Class,
        None,
    );

    // Layer 1: AST
    unit.signature = lines
        .get(ast_start_line)
        .map(|s| s.trim().to_string())
        .unwrap_or_default();
    unit.docstring = extract_docstring(node, lines, lang);
    unit.extends = extract_parent_class(node, bytes, lang, super::max_recursion_depth());

    // Layer 1: Type parameters (generics like <T, U>)
    unit.parameters = extract_class_type_parameters(node, bytes, lang);

    // Layer 2: Call Graph (classes can have calls in method bodies and initializers)
    unit.calls = extract_function_calls(node, bytes, lang);

    // Layer 4: Data Flow - extract class attributes/variables (deduplicated)
    unit.variables = extract_variables(node, bytes, lang);

    // Layer 5: Dependencies
    // Get modules used via attribute access (e.g., `json` from `json.loads()`)
    let used_modules = extract_used_modules(node, bytes, lang);
    // Filter to only modules that are actually imported (case-insensitive)
    unit.imports = file_imports
        .iter()
        .filter(|import| {
            used_modules
                .iter()
                .any(|m| m.to_lowercase() == import.to_lowercase())
                || unit.calls.iter().any(|call| {
                    call.to_lowercase().contains(&import.to_lowercase())
                        || import.to_lowercase().contains(&call.to_lowercase())
                })
        })
        .cloned()
        .collect();

    // Full source content
    let content_end = (end_line + 1).min(lines.len());
    unit.code = lines[code_start..content_end].join("\n");

    Some(unit)
}

/// Extract type parameters from a class/struct declaration (generics like <T, U>).
fn extract_class_type_parameters(node: Node, bytes: &[u8], lang: Language) -> Vec<String> {
    let type_params_node = match lang {
        Language::Java | Language::Scala => node.child_by_field_name("type_parameters"),
        Language::TypeScript | Language::Vue | Language::Svelte => {
            node.child_by_field_name("type_parameters")
        }
        Language::Rust => node.child_by_field_name("type_parameters"),
        Language::CSharp => node.child_by_field_name("type_parameters"),
        Language::Kotlin => node.child_by_field_name("type_parameters"),
        Language::Swift => {
            // Swift uses generic_parameter_clause
            node.children(&mut node.walk())
                .find(|c| c.kind() == "generic_parameter_clause")
        }
        Language::Cpp => {
            // C++ templates: look for template_parameter_list in parent template_declaration
            if let Some(parent) = node.parent() {
                if parent.kind() == "template_declaration" {
                    return extract_cpp_template_params(parent, bytes);
                }
            }
            None
        }
        _ => None,
    };

    let Some(params) = type_params_node else {
        return Vec::new();
    };

    let mut result = Vec::new();
    extract_type_param_names(params, bytes, lang, &mut result);
    result
}

/// Recursively extract type parameter names from a type_parameters node.
fn extract_type_param_names(node: Node, bytes: &[u8], lang: Language, result: &mut Vec<String>) {
    let kind = node.kind();

    // Match type parameter identifier nodes based on language
    let is_type_param = match lang {
        Language::Java => kind == "type_identifier" || kind == "identifier",
        Language::TypeScript | Language::Vue | Language::Svelte => {
            kind == "type_identifier" || kind == "identifier"
        }
        Language::Rust => kind == "type_identifier" || kind == "identifier",
        Language::CSharp => kind == "identifier",
        Language::Kotlin => kind == "type_identifier" || kind == "simple_identifier",
        Language::Swift => kind == "type_identifier" || kind == "simple_identifier",
        Language::Scala => kind == "identifier" || kind == "type_identifier",
        _ => false,
    };

    if is_type_param {
        if let Ok(text) = node.utf8_text(bytes) {
            let name = text.trim();
            // Skip common keywords that might appear
            if !name.is_empty()
                && name != "extends"
                && name != "super"
                && name != "where"
                && !result.contains(&name.to_string())
            {
                result.push(name.to_string());
            }
        }
        return; // Don't recurse into type parameter identifiers
    }

    // Recurse into children
    for child in node.children(&mut node.walk()) {
        extract_type_param_names(child, bytes, lang, result);
    }
}

/// Extract template parameters from C++ template_declaration.
fn extract_cpp_template_params(node: Node, bytes: &[u8]) -> Vec<String> {
    let mut result = Vec::new();

    fn visit(node: Node, bytes: &[u8], result: &mut Vec<String>) {
        // Look for type_parameter_declaration or template_type_parameter
        if node.kind() == "type_parameter_declaration"
            || node.kind() == "template_type_parameter"
            || node.kind() == "type_identifier"
        {
            // Get the identifier
            if node.kind() == "type_identifier" {
                if let Ok(text) = node.utf8_text(bytes) {
                    let name = text.trim();
                    if !name.is_empty() && !result.contains(&name.to_string()) {
                        result.push(name.to_string());
                    }
                }
                return;
            }
            // For type_parameter_declaration, find the identifier child
            for child in node.children(&mut node.walk()) {
                if child.kind() == "type_identifier" || child.kind() == "identifier" {
                    if let Ok(text) = child.utf8_text(bytes) {
                        let name = text.trim();
                        if !name.is_empty() && !result.contains(&name.to_string()) {
                            result.push(name.to_string());
                        }
                    }
                }
            }
        }
        for child in node.children(&mut node.walk()) {
            visit(child, bytes, result);
        }
    }

    visit(node, bytes, &mut result);
    result
}

/// Extract a constant or static declaration from an AST node.
/// For JS/TS, if the value is an arrow function, extract as Function instead.
pub fn extract_constant(
    node: Node,
    path: &Path,
    lines: &[&str],
    bytes: &[u8],
    lang: Language,
    file_imports: &[String],
) -> Option<CodeUnit> {
    let ast_start_line = node.start_position().row;
    let end_line = node.end_position().row;

    // Get constant name based on language
    let name = get_constant_name(node, bytes, lang)?;

    // For Python, only capture UPPER_CASE names (convention for constants)
    if lang == Language::Python && !is_python_constant_name(&name) {
        return None;
    }

    // For JS/TS, check if this is an arrow function assigned to a const
    // If so, extract it as a Function instead of Constant
    if matches!(
        lang,
        Language::JavaScript | Language::TypeScript | Language::Vue | Language::Svelte
    ) {
        if let Some(unit) =
            extract_arrow_function_as_function(node, path, lines, bytes, lang, file_imports, &name)
        {
            return Some(unit);
        }
    }

    // Include preceding attributes in the line range
    let code_start = find_start_with_attributes(ast_start_line, lines, lang);
    let start_line = code_start;

    let mut unit = CodeUnit::new(
        name,
        path.to_path_buf(),
        start_line + 1,
        end_line + 1,
        lang,
        UnitType::Constant,
        None,
    );

    // Layer 1: AST
    unit.signature = lines
        .get(ast_start_line)
        .map(|s| s.trim().to_string())
        .unwrap_or_default();

    // Extract type annotation if available
    unit.return_type = get_constant_type(node, bytes, lang);

    // Layer 5: Dependencies
    unit.imports = file_imports.to_vec();

    // Full source content
    let content_end = (end_line + 1).min(lines.len());
    unit.code = lines[code_start..content_end].join("\n");

    Some(unit)
}

/// Get the name of a constant declaration.
fn get_constant_name(node: Node, bytes: &[u8], lang: Language) -> Option<String> {
    match lang {
        Language::Rust => node
            .child_by_field_name("name")
            .and_then(|n| n.utf8_text(bytes).ok())
            .map(|s| s.to_string()),
        Language::TypeScript | Language::JavaScript | Language::Vue | Language::Svelte => {
            for child in node.children(&mut node.walk()) {
                if child.kind() == "variable_declarator" {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        if let Ok(text) = name_node.utf8_text(bytes) {
                            return Some(text.to_string());
                        }
                    }
                }
            }
            None
        }
        Language::Go => {
            for child in node.children(&mut node.walk()) {
                if child.kind() == "const_spec" || child.kind() == "var_spec" {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        if let Ok(text) = name_node.utf8_text(bytes) {
                            return Some(text.to_string());
                        }
                    }
                    for spec_child in child.children(&mut child.walk()) {
                        if spec_child.kind() == "identifier" {
                            if let Ok(text) = spec_child.utf8_text(bytes) {
                                return Some(text.to_string());
                            }
                        }
                    }
                }
            }
            None
        }
        Language::Python => {
            let assignment = node.child(0)?;
            if assignment.kind() == "assignment" {
                let left = assignment.child_by_field_name("left")?;
                return left.utf8_text(bytes).ok().map(|s| s.to_string());
            }
            None
        }
        Language::C | Language::Cpp => {
            for child in node.children(&mut node.walk()) {
                if child.kind() == "init_declarator" || child.kind() == "declarator" {
                    if let Some(name_node) = child.child_by_field_name("declarator") {
                        if let Ok(text) = name_node.utf8_text(bytes) {
                            return Some(text.to_string());
                        }
                    }
                    if child.kind() == "identifier" {
                        if let Ok(text) = child.utf8_text(bytes) {
                            return Some(text.to_string());
                        }
                    }
                }
            }
            for child in node.children(&mut node.walk()) {
                if child.kind() == "identifier" {
                    if let Ok(text) = child.utf8_text(bytes) {
                        return Some(text.to_string());
                    }
                }
            }
            None
        }
        Language::Kotlin => node
            .child_by_field_name("name")
            .or_else(|| {
                for child in node.children(&mut node.walk()) {
                    if child.kind() == "variable_declaration" {
                        for subchild in child.children(&mut child.walk()) {
                            if subchild.kind() == "simple_identifier" {
                                return Some(subchild);
                            }
                        }
                    }
                }
                None
            })
            .and_then(|n| n.utf8_text(bytes).ok())
            .map(|s| s.to_string()),
        Language::Swift => {
            for child in node.children(&mut node.walk()) {
                if child.kind() == "pattern_initializer" {
                    for subchild in child.children(&mut child.walk()) {
                        if subchild.kind() == "identifier_pattern"
                            || subchild.kind() == "simple_identifier"
                        {
                            if let Ok(text) = subchild.utf8_text(bytes) {
                                return Some(text.to_string());
                            }
                        }
                    }
                }
            }
            None
        }
        Language::Scala => node
            .child_by_field_name("pattern")
            .and_then(|n| n.utf8_text(bytes).ok())
            .map(|s| s.to_string()),
        Language::Php => {
            for child in node.children(&mut node.walk()) {
                if child.kind() == "const_element" {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        if let Ok(text) = name_node.utf8_text(bytes) {
                            return Some(text.to_string());
                        }
                    }
                }
            }
            None
        }
        Language::Elixir => {
            for child in node.children(&mut node.walk()) {
                if child.kind() == "call" {
                    if let Some(target) = child.child_by_field_name("target") {
                        if let Ok(text) = target.utf8_text(bytes) {
                            return Some(format!("@{}", text));
                        }
                    }
                }
            }
            None
        }
        Language::Haskell | Language::Ocaml => node
            .child_by_field_name("name")
            .or_else(|| node.child_by_field_name("pattern"))
            .and_then(|n| n.utf8_text(bytes).ok())
            .map(|s| s.to_string()),
        // CSS at-rules ( @import / @charset / @namespace ): the unit name
        // is the at-keyword, produced by the same helper that names
        // rule_set / @media / @keyframes elsewhere in the parser.
        Language::Css => super::ast::get_node_name(node, bytes, lang),
        _ => None,
    }
}

/// Check if a Python name follows the constant naming convention (UPPER_CASE).
fn is_python_constant_name(name: &str) -> bool {
    if !name.chars().any(|c| c.is_ascii_alphabetic()) {
        return false;
    }
    name.chars()
        .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
}

/// Get the type annotation of a constant if available.
fn get_constant_type(node: Node, bytes: &[u8], lang: Language) -> Option<String> {
    match lang {
        Language::Rust => node
            .child_by_field_name("type")
            .and_then(|n| n.utf8_text(bytes).ok())
            .map(|s| s.to_string()),
        Language::TypeScript | Language::Vue | Language::Svelte => {
            for child in node.children(&mut node.walk()) {
                if child.kind() == "variable_declarator" {
                    if let Some(type_node) = child.child_by_field_name("type") {
                        return type_node.utf8_text(bytes).ok().map(|s| s.to_string());
                    }
                }
            }
            None
        }
        Language::Go => {
            for child in node.children(&mut node.walk()) {
                if child.kind() == "const_spec" || child.kind() == "var_spec" {
                    if let Some(type_node) = child.child_by_field_name("type") {
                        return type_node.utf8_text(bytes).ok().map(|s| s.to_string());
                    }
                }
            }
            None
        }
        Language::Python => {
            let assignment = node.child(0)?;
            if assignment.kind() == "assignment" {
                if let Some(type_node) = assignment.child_by_field_name("type") {
                    return type_node.utf8_text(bytes).ok().map(|s| s.to_string());
                }
            }
            None
        }
        _ => None,
    }
}

/// Extract an arrow function assigned to a const as a Function unit.
/// Returns Some(CodeUnit) if this is an arrow function, None otherwise.
fn extract_arrow_function_as_function(
    node: Node,
    path: &Path,
    lines: &[&str],
    bytes: &[u8],
    lang: Language,
    file_imports: &[String],
    name: &str,
) -> Option<CodeUnit> {
    use super::analysis::{
        extract_control_flow, extract_function_calls, extract_parameters, extract_return_type,
        extract_used_modules, extract_variables,
    };

    // Look for arrow_function in variable_declarator
    let arrow_node = find_arrow_function(node)?;

    let ast_start_line = node.start_position().row;
    let end_line = node.end_position().row;
    let code_start = find_start_with_attributes(ast_start_line, lines, lang);

    let mut unit = CodeUnit::new(
        name.to_string(),
        path.to_path_buf(),
        code_start + 1,
        end_line + 1,
        lang,
        UnitType::Function,
        None,
    );

    // Layer 1: AST
    unit.signature = lines
        .get(ast_start_line)
        .map(|s| s.trim().to_string())
        .unwrap_or_default();
    unit.docstring = super::analysis::extract_docstring(node, lines, lang);
    unit.parameters = extract_parameters(arrow_node, bytes, lang);
    unit.return_type = extract_return_type(arrow_node, bytes, lang);

    // Layer 2: Call Graph
    unit.calls = extract_function_calls(arrow_node, bytes, lang);

    // Layer 3: Control Flow
    let (complexity, has_loops, has_branches, has_error_handling) =
        extract_control_flow(arrow_node, lang);
    unit.complexity = complexity;
    unit.has_loops = has_loops;
    unit.has_branches = has_branches;
    unit.has_error_handling = has_error_handling;

    // Layer 4: Data Flow
    unit.variables = extract_variables(arrow_node, bytes, lang);

    // Layer 5: Dependencies
    // Get modules used via attribute access
    let used_modules = extract_used_modules(arrow_node, bytes, lang);
    // Filter to only modules that are actually imported (case-insensitive for Ruby, etc.)
    unit.imports = file_imports
        .iter()
        .filter(|import| {
            used_modules
                .iter()
                .any(|m| m.to_lowercase() == import.to_lowercase())
                || unit.calls.iter().any(|call| {
                    call.to_lowercase().contains(&import.to_lowercase())
                        || import.to_lowercase().contains(&call.to_lowercase())
                })
        })
        .cloned()
        .collect();

    // Full source content
    let content_end = (end_line + 1).min(lines.len());
    unit.code = lines[code_start..content_end].join("\n");

    Some(unit)
}

/// Find an arrow_function node within a variable declaration.
fn find_arrow_function(node: Node) -> Option<Node> {
    // Check children recursively for arrow_function
    fn find_recursive(node: Node) -> Option<Node> {
        if node.kind() == "arrow_function" {
            return Some(node);
        }
        for child in node.children(&mut node.walk()) {
            if let Some(found) = find_recursive(child) {
                return Some(found);
            }
        }
        None
    }
    find_recursive(node)
}

/// Determine if a function should be a Method based on language-specific patterns.
/// Returns (UnitType, Option<parent_class_name>)
fn determine_function_type(
    node: Node,
    bytes: &[u8],
    lang: Language,
    parent_class: Option<&str>,
) -> (UnitType, Option<String>) {
    // If already has a parent class, it's a method
    if parent_class.is_some() {
        return (UnitType::Method, None);
    }

    match lang {
        // Go: Check for method receiver (parameter_list before function name)
        Language::Go => {
            // In Go, method_declaration has a "receiver" field
            if node.kind() == "method_declaration" {
                if let Some(receiver) = node.child_by_field_name("receiver") {
                    // Extract receiver type name
                    if let Some(type_name) = extract_go_receiver_type(receiver, bytes) {
                        return (UnitType::Method, Some(type_name));
                    }
                }
            }
            (UnitType::Function, None)
        }
        // Rust: Check if function is inside an impl block by looking at parent
        Language::Rust => {
            // Walk up to check if parent is impl_item
            if let Some(parent) = node.parent() {
                if parent.kind() == "declaration_list" {
                    if let Some(grandparent) = parent.parent() {
                        if grandparent.kind() == "impl_item" {
                            // Extract impl type name
                            if let Some(type_name) = extract_rust_impl_type(grandparent, bytes) {
                                return (UnitType::Method, Some(type_name));
                            }
                        }
                    }
                }
            }
            (UnitType::Function, None)
        }
        _ => (UnitType::Function, None),
    }
}

/// Extract the receiver type name from a Go method receiver.
fn extract_go_receiver_type(receiver: Node, bytes: &[u8]) -> Option<String> {
    // receiver is a parameter_list containing one parameter with a type
    for child in receiver.children(&mut receiver.walk()) {
        if child.kind() == "parameter_declaration" {
            if let Some(type_node) = child.child_by_field_name("type") {
                // Handle pointer types (*Type)
                let type_text = type_node.utf8_text(bytes).ok()?;
                let type_name = type_text.trim_start_matches('*').trim();
                return Some(type_name.to_string());
            }
        }
    }
    None
}

/// Extract the type name from a Rust impl block.
fn extract_rust_impl_type(impl_node: Node, bytes: &[u8]) -> Option<String> {
    // impl_item has a "type" field for the implementing type
    if let Some(type_node) = impl_node.child_by_field_name("type") {
        return type_node.utf8_text(bytes).ok().map(|s| s.to_string());
    }
    None
}

/// Fill gaps between code units with RawCode units to achieve 100% file coverage.
/// Consecutive uncovered lines (including empty lines between them) are grouped into a single RawCode unit.
/// Only lines covered by existing code units split raw code blocks.
pub fn fill_raw_code_gaps(
    units: &mut Vec<CodeUnit>,
    path: &Path,
    lines: &[&str],
    lang: Language,
    file_imports: &[String],
) {
    if lines.is_empty() {
        return;
    }

    let total_lines = lines.len();

    // Build a set of covered lines (1-indexed, matching CodeUnit.line/end_line)
    let mut covered = vec![false; total_lines + 1];
    for unit in units.iter() {
        if unit.line <= total_lines {
            let end = unit.end_line.min(total_lines);
            covered[unit.line..=end].fill(true);
        }
    }

    // Find gaps (consecutive uncovered lines, including empty lines between non-empty ones)
    let mut raw_units = Vec::new();
    let mut gap_start: Option<usize> = None;
    let mut gap_end: Option<usize> = None;

    for (i, line_content) in lines.iter().enumerate() {
        let line_num = i + 1;
        let is_non_empty = !line_content.trim().is_empty();
        let is_covered = covered[line_num];

        if is_covered {
            // Hit a covered line - end the current gap if any
            if let (Some(start), Some(end)) = (gap_start, gap_end) {
                if let Some(unit) =
                    create_raw_code_unit(path, lines, start, end, lang, file_imports)
                {
                    raw_units.push(unit);
                }
            }
            gap_start = None;
            gap_end = None;
        } else if is_non_empty {
            // Uncovered non-empty line - start or extend the gap
            if gap_start.is_none() {
                gap_start = Some(line_num);
            }
            gap_end = Some(line_num);
        }
    }

    // Handle gap at end of file
    if let (Some(start), Some(end)) = (gap_start, gap_end) {
        if let Some(unit) = create_raw_code_unit(path, lines, start, end, lang, file_imports) {
            raw_units.push(unit);
        }
    }

    units.extend(raw_units);
}

/// Create a RawCode unit for a range of lines.
fn create_raw_code_unit(
    path: &Path,
    lines: &[&str],
    start_line: usize,
    end_line: usize,
    lang: Language,
    file_imports: &[String],
) -> Option<CodeUnit> {
    let content_lines: Vec<&str> = lines
        .get((start_line - 1)..end_line)
        .unwrap_or(&[])
        .to_vec();

    if content_lines.iter().all(|l| l.trim().is_empty()) {
        return None;
    }

    let name = format!("raw_code_{}", start_line);
    let qualified_name = format!("{}::raw_code_{}", path.display(), start_line);

    let signature = content_lines
        .iter()
        .find(|l| !l.trim().is_empty())
        .map(|l| l.trim().to_string())
        .unwrap_or_default();

    let code = content_lines.join("\n");

    Some(CodeUnit {
        name,
        qualified_name,
        file: path.to_path_buf(),
        line: start_line,
        end_line,
        language: lang,
        unit_type: UnitType::RawCode,
        signature,
        docstring: None,
        parameters: Vec::new(),
        return_type: None,
        extends: None,
        parent_class: None,
        calls: Vec::new(),
        called_by: Vec::new(),
        complexity: 1,
        has_loops: false,
        has_branches: false,
        has_error_handling: false,
        variables: Vec::new(),
        imports: file_imports.to_vec(),
        code,
    })
}