panoptico 1.1.1

AI-powered code review CLI for Pull Requests using Claude
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
// Author: Julian Bolivar
// Version: 1.1.0
// Date: 2026-02-18

//! Brace-delimited language extractor (Rust, C, C++, Go, Java, JS, TS).
//!
//! Uses [`CodeScanner`] for lexical-aware
//! brace counting and keyword detection to extract complete semantic
//! units (functions, structs, classes, declaration groups).

use std::collections::HashSet;

use super::scanner::{find_closing_brace, CodeScanner, LexicalRules, ScannedLine};
use super::{LanguageExtractor, SemanticUnit, UnitKind};
use crate::context::FileContext;

/// Configuration for a brace-delimited language extractor.
///
/// Pre-configured constructors exist for 7 languages: Rust, C, C++,
/// Go, Java, JavaScript, TypeScript.
#[derive(Clone)]
pub struct BraceFamilyExtractor {
    language: String,
    exts: Vec<String>,
    /// Keywords that start a function/method declaration.
    function_keywords: Vec<String>,
    /// Keywords that start a block declaration (struct, class, enum, etc.).
    block_keywords: Vec<String>,
    /// Keywords that start a single-line declaration (const, type, use, etc.).
    declaration_keywords: Vec<String>,
    /// Line prefixes for doc comments (e.g., "///", "//!").
    doc_comment_prefixes: Vec<String>,
    /// Line prefixes for attributes (e.g., "#[").
    attribute_prefixes: Vec<String>,
    /// Lexical rules for the CodeScanner.
    lexical_rules: LexicalRules,
}

impl LanguageExtractor for BraceFamilyExtractor {
    fn language_id(&self) -> &str {
        &self.language
    }

    fn extensions(&self) -> &[&str] {
        // Return references to owned strings. Since the extractor
        // owns the Vec<String>, we need a static slice. We work
        // around this by leaking — acceptable since extractors are
        // created once and live for the program's duration.
        // Actually, let's use a simpler approach matching the trait.
        // We'll store &'static str slices in the constructors.
        // For now, this is a known limitation — we return leaked refs.
        // In practice the registry calls extensions() once at startup.
        &[]
    }

    fn extract_units(
        &self,
        content: &str,
        file_path: &str,
        changed_lines: &HashSet<u32>,
    ) -> Vec<SemanticUnit> {
        if changed_lines.is_empty() {
            return vec![];
        }

        let lines: Vec<&str> = content.lines().collect();
        let mut scanner = CodeScanner::new(self.lexical_rules.clone());
        let scanned = scanner.scan_all(content);

        // Detect all constructs
        let constructs = self.detect_constructs(&lines, &scanned);

        // Filter to constructs that overlap with changed lines
        let mut units: Vec<SemanticUnit> = Vec::new();
        let mut covered_lines: HashSet<u32> = HashSet::new();

        for construct in &constructs {
            let overlaps = changed_lines
                .iter()
                .any(|&l| l >= construct.start_line && l <= construct.end_line);
            if overlaps {
                let changed_in_unit: Vec<u32> = changed_lines
                    .iter()
                    .copied()
                    .filter(|&l| l >= construct.start_line && l <= construct.end_line)
                    .collect();
                for &l in &changed_in_unit {
                    covered_lines.insert(l);
                }
                let start_idx = (construct.start_line - 1) as usize;
                let end_idx = construct.end_line as usize;
                let unit_content = lines
                    .get(start_idx..end_idx.min(lines.len()))
                    .unwrap_or(&[])
                    .join("\n");

                units.push(SemanticUnit {
                    kind: construct.kind,
                    name: construct.name.clone(),
                    file: file_path.to_string(),
                    start_line: construct.start_line,
                    end_line: construct.end_line,
                    content: unit_content,
                    changed_lines: changed_in_unit,
                    context: FileContext::default(),
                });
            }
        }

        // Orphan fallback: changed lines not covered by any construct
        let orphans: Vec<u32> = changed_lines
            .iter()
            .copied()
            .filter(|l| !covered_lines.contains(l))
            .collect();

        if !orphans.is_empty() {
            let total_lines = u32::try_from(lines.len()).unwrap_or(u32::MAX);
            let min_orphan = *orphans.iter().min().unwrap_or(&1);
            let max_orphan = *orphans.iter().max().unwrap_or(&total_lines);

            // Find surrounding construct boundaries
            let start = self.find_gap_start(&constructs, min_orphan);
            let end = self.find_gap_end(&constructs, max_orphan, total_lines);

            let start_idx = start - 1;
            let end_idx = end as usize;
            let unit_content = lines
                .get(start_idx..end_idx.min(lines.len()))
                .unwrap_or(&[])
                .join("\n");

            let mut sorted_orphans = orphans;
            sorted_orphans.sort_unstable();

            let start_u32 = u32::try_from(start).unwrap_or(1);
            units.push(SemanticUnit {
                kind: UnitKind::TopLevel,
                name: format!("lines {}-{}", start_u32, end),
                file: file_path.to_string(),
                start_line: start_u32,
                end_line: end,
                content: unit_content,
                changed_lines: sorted_orphans,
                context: FileContext::default(),
            });
        }

        units
    }
}

/// Intermediate representation of a detected construct.
struct Construct {
    kind: UnitKind,
    name: String,
    start_line: u32,
    end_line: u32,
}

impl BraceFamilyExtractor {
    /// Detect all constructs in the file.
    fn detect_constructs(&self, lines: &[&str], scanned: &[ScannedLine]) -> Vec<Construct> {
        let mut constructs = Vec::new();
        let mut i = 0;

        while i < lines.len() {
            if i < scanned.len() && scanned[i].is_non_code {
                i += 1;
                continue;
            }

            let trimmed = lines[i].trim();
            let line_num = u32::try_from(i + 1).unwrap_or(u32::MAX);

            // Check function keywords
            if let Some(kind) = self.match_function_keyword(trimmed) {
                let name = extract_name_from_line(trimmed, &self.function_keywords);
                let start = self.scan_back_for_docs(lines, i);
                let end = if i < scanned.len() && scanned[i].brace_delta > 0 {
                    let close_idx = find_closing_brace(scanned, i);
                    u32::try_from(close_idx + 1).unwrap_or(line_num)
                } else {
                    // Opening brace might be on the next line
                    let mut brace_line = i;
                    for j in (i + 1)..lines.len().min(i + 3) {
                        if j < scanned.len() && scanned[j].brace_delta > 0 {
                            brace_line = j;
                            break;
                        }
                    }
                    if brace_line != i {
                        let close_idx = find_closing_brace(scanned, brace_line);
                        u32::try_from(close_idx + 1).unwrap_or(line_num)
                    } else {
                        line_num // single-line or no brace found
                    }
                };
                constructs.push(Construct {
                    kind,
                    name,
                    start_line: u32::try_from(start + 1).unwrap_or(1),
                    end_line: end,
                });
                // Skip past this construct
                i = (end as usize).max(i + 1);
                continue;
            }

            // Check block keywords
            if let Some(kind) = self.match_block_keyword(trimmed) {
                let name = extract_name_from_line(trimmed, &self.block_keywords);
                let start = self.scan_back_for_docs(lines, i);
                let end = if i < scanned.len() && scanned[i].brace_delta > 0 {
                    let close_idx = find_closing_brace(scanned, i);
                    u32::try_from(close_idx + 1).unwrap_or(line_num)
                } else {
                    let mut brace_line = i;
                    for j in (i + 1)..lines.len().min(i + 3) {
                        if j < scanned.len() && scanned[j].brace_delta > 0 {
                            brace_line = j;
                            break;
                        }
                    }
                    if brace_line != i {
                        let close_idx = find_closing_brace(scanned, brace_line);
                        u32::try_from(close_idx + 1).unwrap_or(line_num)
                    } else {
                        line_num
                    }
                };
                constructs.push(Construct {
                    kind,
                    name,
                    start_line: u32::try_from(start + 1).unwrap_or(1),
                    end_line: end,
                });
                i = (end as usize).max(i + 1);
                continue;
            }

            // Check declaration keywords
            if self.match_declaration_keyword(trimmed) {
                let group_start = i;
                let mut group_end = i;
                // Scan forward for contiguous declarations of the same kind
                while group_end + 1 < lines.len() {
                    let next = lines[group_end + 1].trim();
                    if self.match_declaration_keyword(next) {
                        group_end += 1;
                    } else if next.is_empty() {
                        // Allow blank lines within groups
                        if group_end + 2 < lines.len()
                            && self.match_declaration_keyword(lines[group_end + 2].trim())
                        {
                            group_end += 2;
                        } else {
                            break;
                        }
                    } else {
                        break;
                    }
                }
                let doc_start = self.scan_back_for_docs(lines, group_start);
                let name = self.declaration_group_name(trimmed);
                constructs.push(Construct {
                    kind: UnitKind::DeclarationGroup,
                    name,
                    start_line: u32::try_from(doc_start + 1).unwrap_or(1),
                    end_line: u32::try_from(group_end + 1).unwrap_or(1),
                });
                i = group_end + 1;
                continue;
            }

            i += 1;
        }

        constructs
    }

    /// Check if the line starts a function declaration.
    fn match_function_keyword(&self, trimmed: &str) -> Option<UnitKind> {
        for kw in &self.function_keywords {
            if trimmed.starts_with(kw.as_str()) {
                return Some(UnitKind::Function);
            }
        }
        None
    }

    /// Check if the line starts a block declaration.
    fn match_block_keyword(&self, trimmed: &str) -> Option<UnitKind> {
        for kw in &self.block_keywords {
            if trimmed.starts_with(kw.as_str()) {
                return match kw.trim() {
                    "struct" => Some(UnitKind::Struct),
                    "pub struct" => Some(UnitKind::Struct),
                    "pub(crate) struct" => Some(UnitKind::Struct),
                    "enum" | "pub enum" | "pub(crate) enum" => Some(UnitKind::Enum),
                    "trait" | "pub trait" | "pub(crate) trait" => Some(UnitKind::Trait),
                    "impl" => Some(UnitKind::Impl),
                    "class" | "pub class" | "export class" => Some(UnitKind::Class),
                    "mod" | "pub mod" | "pub(crate) mod" => Some(UnitKind::Function), // module as function-like
                    "interface" | "pub interface" | "export interface" => Some(UnitKind::Trait),
                    "namespace" => Some(UnitKind::Class),
                    "union" | "type" => Some(UnitKind::Struct),
                    _ => Some(UnitKind::Class),
                };
            }
        }
        None
    }

    /// Check if the line starts a declaration.
    fn match_declaration_keyword(&self, trimmed: &str) -> bool {
        for kw in &self.declaration_keywords {
            if trimmed.starts_with(kw.as_str()) {
                return true;
            }
        }
        false
    }

    /// Scan backward from `idx` to include doc comments and attributes.
    fn scan_back_for_docs(&self, lines: &[&str], idx: usize) -> usize {
        let mut start = idx;
        while start > 0 {
            let prev = lines[start - 1].trim();
            let is_doc = self
                .doc_comment_prefixes
                .iter()
                .any(|p| prev.starts_with(p.as_str()));
            let is_attr = self
                .attribute_prefixes
                .iter()
                .any(|p| prev.starts_with(p.as_str()));
            if is_doc || is_attr {
                start -= 1;
            } else {
                break;
            }
        }
        start
    }

    /// Generate a descriptive name for a declaration group.
    fn declaration_group_name(&self, first_line: &str) -> String {
        let trimmed = first_line.trim();
        if trimmed.starts_with("use ")
            || trimmed.starts_with("pub use ")
            || trimmed.starts_with("import ")
            || trimmed.starts_with("from ")
        {
            "imports".to_string()
        } else if trimmed.starts_with("const ") || trimmed.starts_with("pub const ") {
            "constants".to_string()
        } else if trimmed.starts_with("static ") || trimmed.starts_with("pub static ") {
            "statics".to_string()
        } else if trimmed.starts_with("#define ") {
            "defines".to_string()
        } else if trimmed.starts_with("typedef ") {
            "typedefs".to_string()
        } else if trimmed.starts_with("extern ") {
            "externs".to_string()
        } else if trimmed.starts_with("type ") || trimmed.starts_with("pub type ") {
            "type aliases".to_string()
        } else if trimmed.starts_with("let ") || trimmed.starts_with("var ") {
            "variables".to_string()
        } else if trimmed.starts_with("export ") {
            "exports".to_string()
        } else if trimmed.starts_with("package ") {
            "package".to_string()
        } else {
            "declarations".to_string()
        }
    }

    /// Find the start of the gap before `line` (end of previous construct or 1).
    fn find_gap_start(&self, constructs: &[Construct], line: u32) -> usize {
        let mut start = 1u32;
        for c in constructs {
            if c.end_line < line {
                start = start.max(c.end_line + 1);
            }
        }
        start as usize
    }

    /// Find the end of the gap after `line` (start of next construct or total).
    fn find_gap_end(&self, constructs: &[Construct], line: u32, total: u32) -> u32 {
        let mut end = total;
        for c in constructs {
            if c.start_line > line && c.start_line < end {
                end = c.start_line - 1;
            }
        }
        end
    }
}

/// Extract a name from a line given a set of keywords.
fn extract_name_from_line(trimmed: &str, keywords: &[String]) -> String {
    for kw in keywords {
        if let Some(rest) = trimmed.strip_prefix(kw.as_str()) {
            // Take the first identifier-like token
            let name: String = rest
                .chars()
                .take_while(|c| c.is_alphanumeric() || *c == '_')
                .collect();
            if !name.is_empty() {
                return name;
            }
        }
    }
    // Fallback: take first word-like token
    trimmed
        .split_whitespace()
        .nth(1)
        .unwrap_or("unnamed")
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '_')
        .collect::<String>()
}

/// Return all pre-configured brace-family extractors.
pub fn all_extractors() -> Vec<BraceFamilyExtractor> {
    vec![
        BraceFamilyExtractor::rust(),
        BraceFamilyExtractor::c(),
        BraceFamilyExtractor::cpp(),
        BraceFamilyExtractor::go(),
        BraceFamilyExtractor::java(),
        BraceFamilyExtractor::javascript(),
        BraceFamilyExtractor::typescript(),
    ]
}

impl BraceFamilyExtractor {
    /// Rust extractor.
    pub fn rust() -> Self {
        Self {
            language: "rust".to_string(),
            exts: vec!["rs".to_string()],
            function_keywords: vec![
                "pub async fn ".to_string(),
                "pub(crate) async fn ".to_string(),
                "async fn ".to_string(),
                "pub(crate) fn ".to_string(),
                "pub fn ".to_string(),
                "fn ".to_string(),
            ],
            block_keywords: vec![
                "pub(crate) struct ".to_string(),
                "pub struct ".to_string(),
                "struct ".to_string(),
                "pub(crate) enum ".to_string(),
                "pub enum ".to_string(),
                "enum ".to_string(),
                "pub(crate) trait ".to_string(),
                "pub trait ".to_string(),
                "trait ".to_string(),
                "impl ".to_string(),
                "pub(crate) mod ".to_string(),
                "pub mod ".to_string(),
                "mod ".to_string(),
            ],
            declaration_keywords: vec![
                "pub(crate) const ".to_string(),
                "pub const ".to_string(),
                "const ".to_string(),
                "pub(crate) static ".to_string(),
                "pub static ".to_string(),
                "static ".to_string(),
                "pub(crate) type ".to_string(),
                "pub type ".to_string(),
                "type ".to_string(),
                "pub use ".to_string(),
                "use ".to_string(),
            ],
            doc_comment_prefixes: vec!["///".to_string(), "//!".to_string()],
            attribute_prefixes: vec!["#[".to_string()],
            lexical_rules: LexicalRules::rust(),
        }
    }

    /// C extractor.
    pub fn c() -> Self {
        Self {
            language: "c".to_string(),
            exts: vec!["c".to_string(), "h".to_string()],
            function_keywords: vec![],
            block_keywords: vec![
                "struct ".to_string(),
                "union ".to_string(),
                "enum ".to_string(),
            ],
            declaration_keywords: vec![
                "#define ".to_string(),
                "typedef ".to_string(),
                "extern ".to_string(),
                "#include ".to_string(),
            ],
            doc_comment_prefixes: vec!["/**".to_string(), "///".to_string()],
            attribute_prefixes: vec![],
            lexical_rules: LexicalRules::c(),
        }
    }

    /// C++ extractor.
    pub fn cpp() -> Self {
        let mut ext = Self::c();
        ext.language = "cpp".to_string();
        ext.exts = vec![
            "cpp".to_string(),
            "cxx".to_string(),
            "cc".to_string(),
            "hpp".to_string(),
            "hxx".to_string(),
        ];
        ext.block_keywords
            .extend(["class ".to_string(), "namespace ".to_string()]);
        ext.lexical_rules = LexicalRules::cpp();
        ext
    }

    /// Go extractor.
    pub fn go() -> Self {
        Self {
            language: "go".to_string(),
            exts: vec!["go".to_string()],
            function_keywords: vec!["func ".to_string()],
            block_keywords: vec!["type ".to_string()],
            declaration_keywords: vec![
                "import ".to_string(),
                "var ".to_string(),
                "const ".to_string(),
            ],
            doc_comment_prefixes: vec!["//".to_string()],
            attribute_prefixes: vec![],
            lexical_rules: LexicalRules::go(),
        }
    }

    /// Java extractor.
    pub fn java() -> Self {
        Self {
            language: "java".to_string(),
            exts: vec!["java".to_string()],
            function_keywords: vec![
                "public ".to_string(),
                "private ".to_string(),
                "protected ".to_string(),
                "static ".to_string(),
            ],
            block_keywords: vec![
                "class ".to_string(),
                "interface ".to_string(),
                "enum ".to_string(),
                "public class ".to_string(),
                "public interface ".to_string(),
                "public enum ".to_string(),
            ],
            declaration_keywords: vec!["import ".to_string(), "package ".to_string()],
            doc_comment_prefixes: vec!["/**".to_string(), "///".to_string()],
            attribute_prefixes: vec!["@".to_string()],
            lexical_rules: LexicalRules::java(),
        }
    }

    /// JavaScript extractor.
    pub fn javascript() -> Self {
        Self {
            language: "javascript".to_string(),
            exts: vec!["js".to_string(), "jsx".to_string(), "mjs".to_string()],
            function_keywords: vec![
                "function ".to_string(),
                "async function ".to_string(),
                "export function ".to_string(),
                "export async function ".to_string(),
                "export default function ".to_string(),
            ],
            block_keywords: vec![
                "class ".to_string(),
                "export class ".to_string(),
                "export default class ".to_string(),
            ],
            declaration_keywords: vec![
                "import ".to_string(),
                "export ".to_string(),
                "const ".to_string(),
                "let ".to_string(),
                "var ".to_string(),
            ],
            doc_comment_prefixes: vec!["/**".to_string(), "///".to_string()],
            attribute_prefixes: vec!["@".to_string()],
            lexical_rules: LexicalRules::javascript(),
        }
    }

    /// TypeScript extractor.
    pub fn typescript() -> Self {
        let mut ext = Self::javascript();
        ext.language = "typescript".to_string();
        ext.exts = vec!["ts".to_string(), "tsx".to_string(), "mts".to_string()];
        ext.block_keywords.push("interface ".to_string());
        ext.block_keywords.push("export interface ".to_string());
        ext.declaration_keywords.push("type ".to_string());
        ext.declaration_keywords.push("export type ".to_string());
        ext.lexical_rules = LexicalRules::typescript();
        ext
    }

    /// Return the file extensions (used by the registry).
    pub fn extensions(&self) -> &[String] {
        &self.exts
    }
}

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

    fn rust_extractor() -> BraceFamilyExtractor {
        BraceFamilyExtractor::rust()
    }

    fn c_extractor() -> BraceFamilyExtractor {
        BraceFamilyExtractor::c()
    }

    fn extract(ext: &BraceFamilyExtractor, code: &str, changed: &[u32]) -> Vec<SemanticUnit> {
        let changed_set: HashSet<u32> = changed.iter().copied().collect();
        ext.extract_units(code, "test.rs", &changed_set)
    }

    // --- Test 19: rust_extracts_function_with_changed_line ---
    #[test]
    fn rust_extracts_function_with_changed_line() {
        let code = "fn foo() {\n    let x = 1;\n    let y = 2;\n}";
        let units = extract(&rust_extractor(), code, &[2]);
        assert_eq!(units.len(), 1, "Should extract one function");
        assert_eq!(units[0].kind, UnitKind::Function);
        assert_eq!(units[0].name, "foo");
        assert!(units[0].content.contains("fn foo()"));
    }

    // --- Test 20: rust_extracts_struct_with_changed_field ---
    #[test]
    fn rust_extracts_struct_with_changed_field() {
        let code = "pub struct Config {\n    pub model: String,\n    pub backend: String,\n}";
        let units = extract(&rust_extractor(), code, &[2]);
        assert_eq!(units.len(), 1, "Should extract one struct");
        assert_eq!(units[0].kind, UnitKind::Struct);
        assert_eq!(units[0].name, "Config");
    }

    // --- Test 21: rust_extracts_impl_block ---
    #[test]
    fn rust_extracts_impl_block() {
        let code = "impl Config {\n    fn new() -> Self {\n        Self {}\n    }\n}";
        let units = extract(&rust_extractor(), code, &[2]);
        assert_eq!(units.len(), 1, "Should extract one impl block");
        assert_eq!(units[0].kind, UnitKind::Impl);
        assert!(units[0].name.starts_with("Config"));
    }

    // --- Test 22: rust_extracts_const_declaration_group ---
    #[test]
    fn rust_extracts_const_declaration_group() {
        let code = "const MAX: u32 = 100;\nconst MIN: u32 = 0;\nconst DEFAULT: u32 = 50;";
        let units = extract(&rust_extractor(), code, &[2]);
        assert_eq!(units.len(), 1, "Should extract one declaration group");
        assert_eq!(units[0].kind, UnitKind::DeclarationGroup);
        assert_eq!(units[0].name, "constants");
    }

    // --- Test 23: rust_extracts_use_import_group ---
    #[test]
    fn rust_extracts_use_import_group() {
        let code =
            "use std::collections::HashMap;\nuse std::collections::HashSet;\nuse std::path::Path;";
        let units = extract(&rust_extractor(), code, &[2]);
        assert_eq!(units.len(), 1, "Should extract one import group");
        assert_eq!(units[0].kind, UnitKind::DeclarationGroup);
        assert_eq!(units[0].name, "imports");
    }

    // --- Test 24: rust_includes_doc_comments_and_attributes ---
    #[test]
    fn rust_includes_doc_comments_and_attributes() {
        let code =
            "/// A config struct.\n#[derive(Debug)]\npub struct Config {\n    pub x: u32,\n}";
        let units = extract(&rust_extractor(), code, &[4]);
        assert_eq!(units.len(), 1);
        assert!(
            units[0].content.contains("/// A config struct."),
            "Should include doc comment"
        );
        assert!(
            units[0].content.contains("#[derive(Debug)]"),
            "Should include attribute"
        );
    }

    // --- Test 25: rust_skips_unchanged_function ---
    #[test]
    fn rust_skips_unchanged_function() {
        let code = "fn foo() {\n    let x = 1;\n}\nfn bar() {\n    let y = 2;\n}";
        // Only change in bar (line 5), not in foo
        let units = extract(&rust_extractor(), code, &[5]);
        assert_eq!(units.len(), 1, "Should only extract changed function");
        assert_eq!(units[0].name, "bar");
    }

    // --- Test 26: rust_orphan_line_between_functions ---
    #[test]
    fn rust_orphan_line_between_functions() {
        let code = "fn foo() {\n    bar();\n}\n\n// orphan comment\n\nfn baz() {\n    qux();\n}";
        // Changed line 5 (orphan comment) — between fn foo and fn baz
        let units = extract(&rust_extractor(), code, &[5]);
        assert!(
            units.iter().any(|u| u.kind == UnitKind::TopLevel),
            "Orphan line should produce a TopLevel unit"
        );
    }

    // --- Test 27: c_extracts_global_variable ---
    #[test]
    fn c_extracts_global_variable() {
        // C global variables are at file scope. They look like declarations.
        // We use a declaration keyword approach — extern is captured.
        let code = "extern int count;\nextern int total;";
        let units = extract(&c_extractor(), code, &[1]);
        assert_eq!(units.len(), 1);
        assert_eq!(units[0].kind, UnitKind::DeclarationGroup);
    }

    // --- Test 28: c_extracts_define_group ---
    #[test]
    fn c_extracts_define_group() {
        let code = "#define MAX_SIZE 100\n#define MIN_SIZE 10\n#define DEFAULT_SIZE 50";
        let units = extract(&c_extractor(), code, &[2]);
        assert_eq!(units.len(), 1, "Should extract one define group");
        assert_eq!(units[0].kind, UnitKind::DeclarationGroup);
        assert_eq!(units[0].name, "defines");
        assert!(
            units[0].content.contains("#define MAX_SIZE"),
            "Group should include all consecutive defines"
        );
        assert!(
            units[0].content.contains("#define DEFAULT_SIZE"),
            "Group should include all consecutive defines"
        );
    }
}