git-prism 0.8.0

Agent-optimized git data MCP server — structured change manifests and full file snapshots for LLM agents
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
use super::{
    CallSite, Function, LanguageAnalyzer, MAX_RECURSION_DEPTH, body_hash_for_node, sha256_hex,
};
use tree_sitter::Parser;

pub struct CppAnalyzer;

fn create_parser() -> Parser {
    let mut parser = Parser::new();
    parser
        .set_language(&tree_sitter_cpp::LANGUAGE.into())
        .expect("Error loading C++ grammar");
    parser
}

fn signature_text(source: &[u8], node: &tree_sitter::Node) -> String {
    let start = node.start_byte();
    let body = node.child_by_field_name("body");
    let end = body.map_or(node.end_byte(), |b| b.start_byte());
    let raw = &source[start..end];
    String::from_utf8_lossy(raw).trim().to_string()
}

// Non-preprocessor nodes don't contain function/import children in the AST;
// unconditional recursion produces the same result.
fn is_preprocessor_container(kind: &str) -> bool {
    matches!(
        kind,
        "preproc_ifdef" | "preproc_if" | "preproc_else" | "preproc_elif"
    )
}

fn function_name_from_declarator(source: &[u8], declarator: &tree_sitter::Node) -> String {
    declarator
        .child_by_field_name("declarator")
        .and_then(|n| n.utf8_text(source).ok())
        .unwrap_or("")
        .to_string()
}

fn collect_functions(
    node: &tree_sitter::Node,
    source: &[u8],
    scope: &[String],
    functions: &mut Vec<Function>,
    depth: usize,
) {
    if depth >= MAX_RECURSION_DEPTH {
        tracing::warn!(
            depth_limit = MAX_RECURSION_DEPTH,
            language = "cpp",
            operation = "functions",
            "tree-sitter depth guard fired: recursive walk truncated; some functions may be missing"
        );
        return;
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "namespace_definition" => {
                let ns_name = child
                    .children(&mut child.walk())
                    .find(|c| c.kind() == "namespace_identifier")
                    .and_then(|n| n.utf8_text(source).ok())
                    .unwrap_or("")
                    .to_string();
                let mut new_scope = scope.to_vec();
                if !ns_name.is_empty() {
                    new_scope.push(ns_name);
                }
                if let Some(body) = child.child_by_field_name("body") {
                    collect_functions(&body, source, &new_scope, functions, depth + 1);
                }
            }
            "class_specifier" | "struct_specifier" => {
                let class_name = child
                    .children(&mut child.walk())
                    .find(|c| c.kind() == "type_identifier")
                    .and_then(|n| n.utf8_text(source).ok())
                    .unwrap_or("")
                    .to_string();
                let mut new_scope = scope.to_vec();
                if !class_name.is_empty() {
                    new_scope.push(class_name);
                }
                if let Some(body) = child.child_by_field_name("body") {
                    // cargo-mutants: skip -- equivalent mutant: `depth + 1` → `depth * 1`
                    // produces identical output for any shallow nested-class hierarchy
                    // a real codebase would contain. The overflow-guard pattern is
                    // already exercised by `it_completes_without_overflow_on_deeply_nested_namespaces`
                    // via the `namespace_definition` arm; the same `depth + 1`
                    // discipline applies here for nested classes.
                    collect_functions(&body, source, &new_scope, functions, depth + 1);
                }
            }
            "function_definition" => {
                let raw_name = child
                    .child_by_field_name("declarator")
                    .map(|d| function_name_from_declarator(source, &d))
                    .unwrap_or_default();
                let qualified = if scope.is_empty() {
                    raw_name
                } else {
                    format!("{}::{}", scope.join("::"), raw_name)
                };
                let sig = signature_text(source, &child);
                let body_hash = body_hash_for_node(source, child);
                functions.push(Function {
                    name: qualified,
                    signature: sig,
                    start_line: child.start_position().row + 1,
                    end_line: child.end_position().row + 1,
                    body_hash,
                });
            }
            "declaration" => {
                if let Some(declarator) = child.child_by_field_name("declarator")
                    && declarator.kind() == "function_declarator"
                {
                    let raw_name = function_name_from_declarator(source, &declarator);
                    let qualified = if scope.is_empty() {
                        raw_name
                    } else {
                        format!("{}::{}", scope.join("::"), raw_name)
                    };
                    let signature = child.utf8_text(source).unwrap_or("").trim().to_string();
                    let body_hash = sha256_hex(&source[child.start_byte()..child.end_byte()]);
                    functions.push(Function {
                        name: qualified,
                        signature,
                        start_line: child.start_position().row + 1,
                        end_line: child.end_position().row + 1,
                        body_hash,
                    });
                }
            }
            // linkage_specification body can be declaration_list (braced
            // `extern "C" { ... }`), function_definition (single-def form
            // `extern "C" void foo() {...}`), or declaration (forward-decl
            // form `extern "C" int foo(int);`). Recursing into the
            // linkage_specification itself walks its direct children; the
            // declaration_list arm below handles the braced case.
            "linkage_specification" => {
                // cargo-mutants: skip -- equivalent mutant: `depth + 1` → `depth * 1`
                // is observably identical here. `extern "C" { ... }` blocks do not nest
                // legally and tree-sitter-cpp does not error-recover into nested
                // `linkage_specification` nodes, so depth never reaches
                // MAX_RECURSION_DEPTH. The overflow-guard pattern is already covered
                // by `it_completes_without_overflow_on_deeply_nested_namespaces`.
                collect_functions(&child, source, scope, functions, depth + 1);
            }
            "declaration_list" => {
                // cargo-mutants: skip -- equivalent mutants: this arm is only entered
                // via `linkage_specification` (depth >= 1), so `depth - 1` does not
                // underflow, and `depth * 1` produces output indistinguishable from
                // `depth + 1` for shallow extern "C" blocks. Tree-sitter-cpp does not
                // produce nested declaration_list chains via valid syntax or error
                // recovery, so the depth cap is unreachable from this arm.
                collect_functions(&child, source, scope, functions, depth + 1);
            }
            kind if is_preprocessor_container(kind) => {
                // cargo-mutants: skip -- equivalent mutant: `depth + 1` → `depth * 1`
                // produces identical output for shallow real-world preprocessor nesting
                // (the depth never reaches MAX_RECURSION_DEPTH). The overflow-guard
                // pattern for preprocessor recursion is already covered in `c_lang.rs`
                // via `it_completes_without_overflow_on_deeply_nested_preproc_blocks`,
                // and the same `depth + 1` discipline applies here.
                collect_functions(&child, source, scope, functions, depth + 1);
            }
            _ => {}
        }
    }
}

fn collect_imports(
    node: &tree_sitter::Node,
    source: &[u8],
    imports: &mut Vec<String>,
    depth: usize,
) {
    if depth >= MAX_RECURSION_DEPTH {
        tracing::warn!(
            depth_limit = MAX_RECURSION_DEPTH,
            language = "cpp",
            operation = "imports",
            "tree-sitter depth guard fired: recursive walk truncated; some imports may be missing"
        );
        return;
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "preproc_include" => {
                let text = child.utf8_text(source).unwrap_or("").trim().to_string();
                imports.push(text);
            }
            kind if is_preprocessor_container(kind) => {
                collect_imports(&child, source, imports, depth + 1);
            }
            _ => {}
        }
    }
}

impl LanguageAnalyzer for CppAnalyzer {
    fn extract_functions(&self, source: &[u8]) -> anyhow::Result<Vec<Function>> {
        let mut parser = create_parser();
        let tree = parser
            .parse(source, None)
            .ok_or_else(|| anyhow::anyhow!("Failed to parse C++ source"))?;
        let mut functions = Vec::new();
        collect_functions(&tree.root_node(), source, &[], &mut functions, 0);
        Ok(functions)
    }

    fn extract_calls(&self, source: &[u8]) -> anyhow::Result<Vec<CallSite>> {
        let mut parser = create_parser();
        let tree = parser
            .parse(source, None)
            .ok_or_else(|| anyhow::anyhow!("Failed to parse C++ source"))?;

        let mut calls = Vec::new();
        let mut stack = vec![tree.root_node()];
        while let Some(node) = stack.pop() {
            if node.kind() == "call_expression"
                && let Some(func) = node.child_by_field_name("function")
            {
                let callee = func.utf8_text(source).unwrap_or("").to_string();
                let (is_method_call, receiver) = match func.kind() {
                    "field_expression" => {
                        let recv = func
                            .child_by_field_name("argument")
                            .and_then(|n| n.utf8_text(source).ok())
                            .map(|s| s.to_string());
                        (true, recv)
                    }
                    _ => (false, None),
                };
                calls.push(CallSite {
                    callee,
                    line: node.start_position().row + 1,
                    is_method_call,
                    receiver,
                });
            }
            for i in (0..node.child_count()).rev() {
                if let Some(child) = node.child(i as u32) {
                    stack.push(child);
                }
            }
        }
        calls.sort_by_key(|c| c.line);
        Ok(calls)
    }

    fn extract_imports(&self, source: &[u8]) -> anyhow::Result<Vec<String>> {
        let mut parser = create_parser();
        let tree = parser
            .parse(source, None)
            .ok_or_else(|| anyhow::anyhow!("Failed to parse C++ source"))?;
        let mut imports = Vec::new();
        collect_imports(&tree.root_node(), source, &mut imports, 0);
        Ok(imports)
    }
}

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

    #[test]
    fn extracts_class_method() {
        let source = br#"class Calculator {
public:
    int add(int a, int b) {
        return a + b;
    }
};
"#;
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].name, "Calculator::add");
        assert_eq!(functions[0].signature, "int add(int a, int b)");
        assert_eq!(functions[0].start_line, 3);
        assert_eq!(functions[0].end_line, 5);
    }

    #[test]
    fn extracts_namespace_qualified_class_method() {
        let source = br#"namespace math {

class Calculator {
public:
    int add(int a, int b) {
        return a + b;
    }
};

}  // namespace math
"#;
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].name, "math::Calculator::add");
    }

    #[test]
    fn extracts_free_function() {
        let source = br#"void free_func(int x) {
    return;
}
"#;
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].name, "free_func");
        assert_eq!(functions[0].signature, "void free_func(int x)");
    }

    #[test]
    fn extracts_multiple_methods() {
        let source = br#"class Calc {
public:
    int add(int a, int b) { return a + b; }
    int sub(int a, int b) { return a - b; }
};
"#;
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 2);
        assert_eq!(functions[0].name, "Calc::add");
        assert_eq!(functions[1].name, "Calc::sub");
    }

    #[test]
    fn empty_file_returns_no_functions() {
        let source = b"";
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert!(functions.is_empty());
    }

    #[test]
    fn extracts_include_directives() {
        let source = br#"#include <iostream>
#include <string>
#include "myheader.h"
"#;
        let analyzer = CppAnalyzer;
        let imports = analyzer.extract_imports(source).unwrap();
        assert_eq!(imports.len(), 3);
        assert_eq!(imports[0], "#include <iostream>");
        assert_eq!(imports[1], "#include <string>");
        assert_eq!(imports[2], "#include \"myheader.h\"");
    }

    #[test]
    fn extracts_function_inside_ifdef() {
        let source = br#"#ifdef SOME_DEFINE
void guarded_func(int x) {
    return;
}
#endif
"#;
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].name, "guarded_func");
    }

    #[test]
    fn extracts_class_method_inside_preproc_if() {
        let source = br#"#if defined(PLATFORM_LINUX)
class LinuxImpl {
public:
    void init() {
        // linux init
    }
};
#endif
"#;
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].name, "LinuxImpl::init");
    }

    #[test]
    fn extracts_functions_from_nested_preproc_blocks() {
        let source = br#"#ifdef FEATURE_A
#ifdef FEATURE_B
void nested_func() {
    return;
}
#endif
#endif
"#;
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].name, "nested_func");
    }

    #[test]
    fn extracts_include_inside_ifdef() {
        let source = br#"#include <iostream>
#ifdef _WIN32
#include <windows.h>
#endif
"#;
        let analyzer = CppAnalyzer;
        let imports = analyzer.extract_imports(source).unwrap();
        assert_eq!(imports.len(), 2);
        assert_eq!(imports[0], "#include <iostream>");
        assert_eq!(imports[1], "#include <windows.h>");
    }

    #[test]
    fn extracts_include_inside_nested_preproc() {
        let source = br#"#ifdef PLATFORM
#ifdef USE_BOOST
#include <boost/shared_ptr.hpp>
#endif
#endif
"#;
        let analyzer = CppAnalyzer;
        let imports = analyzer.extract_imports(source).unwrap();
        assert_eq!(imports.len(), 1);
        assert_eq!(imports[0], "#include <boost/shared_ptr.hpp>");
    }

    #[test]
    fn no_imports_returns_empty() {
        let source = br#"void hello() {}
"#;
        let analyzer = CppAnalyzer;
        let imports = analyzer.extract_imports(source).unwrap();
        assert!(imports.is_empty());
    }

    // Kill line-offset mutants (+ with - or *) by checking exact line numbers.
    #[test]
    fn it_reports_correct_line_numbers_for_function_definition() {
        let source = b"// line 1
// line 2
// line 3
void compute(int x) {
    int y = x + 1;
    return;
}
";
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].start_line, 4);
        assert_eq!(functions[0].end_line, 7);
    }

    #[test]
    fn it_reports_correct_line_numbers_for_declaration() {
        let source = b"// line 1
// line 2
void compute(int x);
";
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].start_line, 3);
        assert_eq!(functions[0].end_line, 3);
    }

    // Kill "delete match arm declaration" mutant: ensure function declarations
    // (not definitions) are extracted.
    #[test]
    fn it_extracts_function_declaration_without_body() {
        let source = b"int add(int a, int b);
void greet(const char* name);
";
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 2);
        assert_eq!(functions[0].name, "add");
        assert_eq!(functions[0].signature, "int add(int a, int b);");
        assert_eq!(functions[1].name, "greet");
    }

    // Kill "replace == with != in collect_functions" for declarator.kind() == "function_declarator"
    #[test]
    fn it_only_extracts_function_declarators_not_variable_declarations() {
        let source = b"int x = 42;
void foo(int a);
";
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].name, "foo");
    }

    // Kill is_preprocessor_container -> true mutant
    #[test]
    fn it_extracts_standalone_function_not_in_preproc() {
        let source = b"void standalone() {
    return;
}
";
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].name, "standalone");
    }

    // Kill match guard with true for imports: ensure includes inside
    // preproc_else and preproc_elif are also found (tests more container kinds)
    #[test]
    fn it_extracts_include_inside_preproc_else() {
        let source = b"#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
";
        let analyzer = CppAnalyzer;
        let imports = analyzer.extract_imports(source).unwrap();
        assert_eq!(imports.len(), 2);
        assert_eq!(imports[0], "#include <windows.h>");
        assert_eq!(imports[1], "#include <unistd.h>");
    }

    // Kill match guard with true for functions in preproc containers
    #[test]
    fn it_extracts_function_inside_preproc_else() {
        let source = b"#ifdef _WIN32
void win_init() { return; }
#else
void unix_init() { return; }
#endif
";
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 2);
        assert_eq!(functions[0].name, "win_init");
        assert_eq!(functions[1].name, "unix_init");
    }

    #[test]
    fn extracts_function_and_method_calls() {
        let source = br#"void process() {
    int x = calculate(input);
    v.push_back(42);
    auto result = std::make_unique<Foo>(x);
}
"#;
        let analyzer = CppAnalyzer;
        let calls = analyzer.extract_calls(source).unwrap();
        let callees: Vec<&str> = calls.iter().map(|c| c.callee.as_str()).collect();
        assert!(callees.contains(&"calculate"));
        assert!(callees.contains(&"v.push_back"));
    }

    // Kill "delete match arm field_expression" mutant: assert that a method
    // call (field_expression form `obj.method()`) is reported with
    // is_method_call=true and a populated receiver. Without the field_expression
    // arm, both flags would default to (false, None).
    #[test]
    fn it_reports_method_call_with_receiver_for_field_expression() {
        let source = b"void process() {
    v.push_back(42);
}
";
        let analyzer = CppAnalyzer;
        let calls = analyzer.extract_calls(source).unwrap();
        let push_back = calls
            .iter()
            .find(|c| c.callee == "v.push_back")
            .expect("v.push_back call must be present");
        assert!(
            push_back.is_method_call,
            "field_expression call must be flagged as method call"
        );
        assert_eq!(push_back.receiver.as_deref(), Some("v"));
    }

    // Kill extract_calls line-offset mutants (+ with - or *). Calls on lines 2, 3, 4
    // distinguish `row + 1` (correct: 2, 3, 4) from `row * 1` (1, 2, 3) and
    // `row - 1` (0, 1, 2 or panic on usize underflow).
    #[test]
    fn it_reports_call_sites_on_correct_lines() {
        let source = b"void caller() {
    foo();
    bar();
    baz();
}
";
        let analyzer = CppAnalyzer;
        let calls = analyzer.extract_calls(source).unwrap();
        assert_eq!(calls.len(), 3);
        assert_eq!(calls[0].callee, "foo");
        assert_eq!(calls[0].line, 2);
        assert_eq!(calls[1].callee, "bar");
        assert_eq!(calls[1].line, 3);
        assert_eq!(calls[2].callee, "baz");
        assert_eq!(calls[2].line, 4);
    }

    #[test]
    fn empty_file_returns_no_calls() {
        let source = b"";
        let analyzer = CppAnalyzer;
        let calls = analyzer.extract_calls(source).unwrap();
        assert!(calls.is_empty());
    }

    /// Security regression: deeply-nested namespace declarations used to stack-overflow
    /// `collect_functions` because it recursed without a depth limit. An attacker committing
    /// a C++ file with thousands of nested namespaces could crash git-prism during
    /// `get_change_manifest`. The analyzer must now complete without crashing.
    ///
    /// Runs on a thread with a 2 MB stack: roomy enough for bounded recursion to
    /// `MAX_RECURSION_DEPTH` but far too small for unbounded recursion to 5000 frames.
    #[test]
    fn it_completes_without_overflow_on_deeply_nested_namespaces() {
        const GENERATED_NESTING_LEVELS: usize = 5000;
        const CONSTRAINED_THREAD_STACK_BYTES: usize = 2 * 1024 * 1024;

        let mut source = String::new();
        for i in 0..GENERATED_NESTING_LEVELS {
            source.push_str(&format!("namespace N{i} {{\n"));
        }
        for _ in 0..GENERATED_NESTING_LEVELS {
            source.push_str("}\n");
        }

        let handle = std::thread::Builder::new()
            .stack_size(CONSTRAINED_THREAD_STACK_BYTES)
            .spawn(move || {
                let analyzer = CppAnalyzer;
                analyzer.extract_functions(source.as_bytes())
            })
            .expect("spawn analyzer thread");

        let result = handle
            .join()
            .expect("analyzer thread must not stack-overflow on deeply-nested input");
        let functions = result.expect("analyzer must return Ok on deeply-nested input");
        // Namespaces contain no functions themselves — everything past the cap is guarded out.
        assert!(functions.is_empty());
    }

    /// Triangulation: 255 nested namespaces with a function at the innermost level.
    /// The guard fires at depth 256, so depth 255 must still allow extraction.
    #[test]
    fn it_extracts_functions_at_boundary_nesting_depth() {
        const GENERATED_NESTING_LEVELS: usize = 255;

        let mut source = String::new();
        for i in 0..GENERATED_NESTING_LEVELS {
            source.push_str(&format!("namespace N{i} {{\n"));
        }
        source.push_str("void leaf_fn() {}\n");
        for _ in 0..GENERATED_NESTING_LEVELS {
            source.push_str("}\n");
        }

        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source.as_bytes()).unwrap();
        assert_eq!(
            functions.len(),
            1,
            "function at depth 255 must be extracted"
        );
        assert!(functions[0].name.ends_with("leaf_fn"));
    }

    #[test]
    fn extracts_functions_inside_extern_c() {
        let source = br#"extern "C" {

void ffi_init() {
    printf("init\n");
}

void ffi_cleanup() {
    printf("cleanup\n");
}

}
"#;
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 2);
        assert_eq!(functions[0].name, "ffi_init");
        assert_eq!(functions[1].name, "ffi_cleanup");
    }

    // Single-declaration extern "C" (no braces) — linkage_specification wraps
    // a bare function_definition instead of a declaration_list with body field.
    #[test]
    fn extracts_function_inside_single_extern_c() {
        let source = br#"extern "C" int compute(int x) {
    return x + 1;
}
"#;
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].name, "compute");
    }

    #[test]
    fn extracts_functions_inside_nested_extern_c() {
        let source = br#"#ifdef __cplusplus
extern "C" {
#endif

void inner_fn() {
    return;
}

#ifdef __cplusplus
}
#endif
"#;
        let analyzer = CppAnalyzer;
        let functions = analyzer.extract_functions(source).unwrap();
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].name, "inner_fn");
    }

    /// Depth-guard warning: deeply-nested namespaces must emit the warning when truncated.
    #[test]
    #[traced_test]
    fn it_emits_depth_guard_warning_on_deeply_nested_namespaces() {
        const GENERATED_NESTING_LEVELS: usize = 300;

        let mut source = String::new();
        for i in 0..GENERATED_NESTING_LEVELS {
            source.push_str(&format!("namespace N{i} {{\n"));
        }
        for _ in 0..GENERATED_NESTING_LEVELS {
            source.push_str("}\n");
        }

        let analyzer = CppAnalyzer;
        let _ = analyzer.extract_functions(source.as_bytes());
        assert!(logs_contain("depth guard fired"));
        assert!(logs_contain("language=\"cpp\""));
        assert!(logs_contain("operation=\"functions\""));
    }

    /// Triangulation: shallow input must NOT emit the depth-guard warning.
    #[test]
    #[traced_test]
    fn it_does_not_emit_depth_guard_warning_on_shallow_functions() {
        let source = b"void foo() {}\nvoid bar() {}\n";
        let analyzer = CppAnalyzer;
        let _ = analyzer.extract_functions(source);
        assert!(!logs_contain("depth guard fired"));
    }

    /// Depth-guard warning: deeply-nested preprocessor blocks in collect_imports must emit warning.
    #[test]
    #[traced_test]
    fn it_emits_depth_guard_warning_on_deeply_nested_preproc_in_imports() {
        const GENERATED_NESTING_LEVELS: usize = 300;

        let mut source = String::new();
        for i in 0..GENERATED_NESTING_LEVELS {
            source.push_str(&format!("#ifdef MACRO_{i}\n"));
        }
        source.push_str("#include <deep.h>\n");
        for _ in 0..GENERATED_NESTING_LEVELS {
            source.push_str("#endif\n");
        }

        let analyzer = CppAnalyzer;
        let _ = analyzer.extract_imports(source.as_bytes());
        assert!(logs_contain("depth guard fired"));
        assert!(logs_contain("language=\"cpp\""));
        assert!(logs_contain("operation=\"imports\""));
    }

    /// Triangulation: shallow import input must NOT emit the depth-guard warning.
    #[test]
    #[traced_test]
    fn it_does_not_emit_depth_guard_warning_on_shallow_imports() {
        let source = b"#include <stdio.h>\n#include <stdlib.h>\n";
        let analyzer = CppAnalyzer;
        let _ = analyzer.extract_imports(source);
        assert!(!logs_contain("depth guard fired"));
    }
}