repotoire 0.8.2

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
//! C++ parser using tree-sitter
//!
//! Extracts functions, classes, methods, structs, namespaces, imports, and call relationships from C++ source code.

use crate::models::{Class, Function};
use crate::parsers::{ImportInfo, ParseResult};
use anyhow::{Context, Result};
use std::cell::RefCell;
use std::path::Path;
use std::sync::OnceLock;
use tree_sitter::{Node, Parser, Query, QueryCursor, StreamingIterator};

thread_local! {
    static CPP_PARSER: RefCell<Parser> = RefCell::new({
        let mut p = Parser::new();
        p.set_language(&tree_sitter_cpp::LANGUAGE.into()).expect("C++ language");
        p
    });
}

const CPP_FUNC_QUERY_STR: &str = r#"
    (function_definition
        type: (_) @return_type
        declarator: (function_declarator
            declarator: (_) @func_name
            parameters: (parameter_list) @params
        )
    ) @func
"#;

const CPP_CLASS_QUERY_STR: &str = r#"
    (class_specifier
        name: (type_identifier) @class_name
        body: (field_declaration_list) @body
    ) @class
"#;

const CPP_METHOD_QUERY_STR: &str = r#"
    (function_definition
        type: (_) @return_type
        declarator: (function_declarator
            declarator: (_) @method_name
            parameters: (parameter_list) @params
        )
    ) @method
"#;

const CPP_STRUCT_QUERY_STR: &str = r#"
    (struct_specifier
        name: (type_identifier) @struct_name
        body: (field_declaration_list)? @body
    ) @struct
"#;

const CPP_INCLUDE_QUERY_STR: &str = r#"
    (preproc_include
        path: [
            (string_literal) @path
            (system_lib_string) @system_path
        ]
    )
"#;

const CPP_CALL_QUERY_STR: &str = r#"
    (call_expression
        function: [
            (identifier) @func_name
            (field_expression
                field: (field_identifier) @method_name
            )
            (qualified_identifier) @qualified_name
        ]
    ) @call
"#;

static CPP_FUNC_QUERY: OnceLock<Query> = OnceLock::new();
static CPP_CLASS_QUERY: OnceLock<Query> = OnceLock::new();
static CPP_METHOD_QUERY: OnceLock<Query> = OnceLock::new();
static CPP_STRUCT_QUERY: OnceLock<Query> = OnceLock::new();
static CPP_INCLUDE_QUERY: OnceLock<Query> = OnceLock::new();
static CPP_CALL_QUERY: OnceLock<Query> = OnceLock::new();

/// Parse a C++ file and extract all code entities
#[allow(dead_code)]
pub fn parse(path: &Path) -> Result<ParseResult> {
    let source = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read file: {}", path.display()))?;

    parse_source(&source, path)
}

/// Parse C++ source code directly (useful for testing)
pub fn parse_source(source: &str, path: &Path) -> Result<ParseResult> {
    parse_source_with_tree(source, path).map(|(r, _)| r)
}

/// Parse C++ source code and return both the ParseResult and the tree-sitter Tree.
pub fn parse_source_with_tree(
    source: &str,
    path: &Path,
) -> Result<(ParseResult, tree_sitter::Tree)> {
    let tree = CPP_PARSER
        .with(|cell| cell.borrow_mut().parse(source, None))
        .context("Failed to parse C++ source")?;

    let root = tree.root_node();
    let extractor = CppExtractor::new(source.as_bytes(), path);
    let result = extractor.run(root)?;
    Ok((result, tree))
}

/// Stateful walker over a parsed C++ tree.
///
/// Holds the immutable inputs (source bytes, file path) and the mutable
/// `ParseResult` accumulator as fields, so visitor methods don't have
/// to thread a `(node, source, path, result)` tuple through every
/// recursion. Each `extract_*` method appends to `self.result`; the
/// caller drives the pipeline via [`Self::run`] and consumes the final
/// result.
struct CppExtractor<'a> {
    source: &'a [u8],
    path: &'a Path,
    result: ParseResult,
}

impl<'a> CppExtractor<'a> {
    fn new(source: &'a [u8], path: &'a Path) -> Self {
        Self {
            source,
            path,
            result: ParseResult::default(),
        }
    }

    /// Run the full extraction pipeline against the given tree root and
    /// return the accumulated [`ParseResult`].
    fn run(mut self, root: Node<'_>) -> Result<ParseResult> {
        self.extract_functions(&root)?;
        self.extract_classes(&root)?;
        self.extract_structs(&root)?;
        self.extract_includes(&root)?;
        self.extract_calls(&root)?;
        Ok(self.result)
    }
}

/// Check if a function definition has a specific storage class specifier (e.g., "extern", "static")
fn has_storage_class(func_node: &Node, source: &[u8], specifier: &str) -> bool {
    for child in func_node.children(&mut func_node.walk()) {
        if child.kind() == "storage_class_specifier" {
            if let Ok(text) = child.utf8_text(source) {
                if text == specifier {
                    return true;
                }
            }
        }
    }
    false
}

/// Check if a node is inside a class or struct body (field_declaration_list)
fn is_inside_class_body(node: &Node) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        if parent.kind() == "field_declaration_list" {
            return true;
        }
        current = parent.parent();
    }
    false
}

impl<'a> CppExtractor<'a> {
    /// Extract function definitions from the AST
    fn extract_functions(&mut self, root: &Node) -> Result<()> {
        let query = CPP_FUNC_QUERY.get_or_init(|| {
            Query::new(&tree_sitter_cpp::LANGUAGE.into(), CPP_FUNC_QUERY_STR)
                .expect("valid C++ function query")
        });

        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(query, *root, self.source);

        while let Some(m) = matches.next() {
            let mut func_node = None;
            let mut name = String::new();
            let mut params_node = None;
            let mut return_type_node = None;

            for capture in m.captures.iter() {
                let capture_name = query.capture_names()[capture.index as usize];
                match capture_name {
                    "func" => func_node = Some(capture.node),
                    "func_name" => {
                        let name_text = capture.node.utf8_text(self.source).unwrap_or("");
                        // Handle qualified names like ClassName::methodName
                        name = name_text.trim_start_matches('*').to_string();
                        if name.contains("::") {
                            // Skip class method definitions here, they're handled in extract_classes
                            continue;
                        }
                    }
                    "params" => params_node = Some(capture.node),
                    "return_type" => return_type_node = Some(capture.node),
                    _ => {}
                }
            }

            if name.is_empty() {
                continue;
            }

            if let Some(node) = func_node {
                // Skip methods inside class/struct bodies — handled by extract_class_methods
                if is_inside_class_body(&node) {
                    continue;
                }
                let parameters = extract_parameters(params_node, self.source);
                let return_type =
                    return_type_node.map(|n| n.utf8_text(self.source).unwrap_or("").to_string());

                let line_start = node.start_position().row as u32 + 1;
                let line_end = node.end_position().row as u32 + 1;
                let qualified_name = format!("{}::{}:{}", self.path.display(), name, line_start);

                let annotations = if has_storage_class(&node, self.source, "extern") {
                    vec!["exported".to_string()]
                } else {
                    vec![]
                };

                self.result.functions.push(Function {
                    name: name.clone(),
                    qualified_name,
                    file_path: self.path.to_path_buf(),
                    line_start,
                    line_end,
                    parameters,
                    return_type,
                    is_async: false,
                    complexity: Some(calculate_complexity(&node, self.source)),
                    max_nesting: None,
                    doc_comment: None,
                    annotations,
                });
            }
        }

        Ok(())
    }
}

impl<'a> CppExtractor<'a> {
    /// Extract C++ class definitions
    fn extract_classes(&mut self, root: &Node) -> Result<()> {
        let query = CPP_CLASS_QUERY.get_or_init(|| {
            Query::new(&tree_sitter_cpp::LANGUAGE.into(), CPP_CLASS_QUERY_STR)
                .expect("valid C++ class query")
        });

        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(query, *root, self.source);

        while let Some(m) = matches.next() {
            let mut class_node = None;
            let mut name = String::new();
            let mut body_node = None;

            for capture in m.captures.iter() {
                let capture_name = query.capture_names()[capture.index as usize];
                match capture_name {
                    "class" => class_node = Some(capture.node),
                    "class_name" => {
                        name = capture
                            .node
                            .utf8_text(self.source)
                            .unwrap_or("")
                            .to_string();
                    }
                    "body" => body_node = Some(capture.node),
                    _ => {}
                }
            }

            if let Some(node) = class_node {
                let line_start = node.start_position().row as u32 + 1;
                let line_end = node.end_position().row as u32 + 1;
                let qualified_name = format!("{}::{}", self.path.display(), name);

                // Extract base classes
                let bases = extract_base_classes(&node, self.source);

                // Extract methods from class body (class default = private)
                let methods = if let Some(body) = body_node {
                    self.extract_class_methods(&body, &name, "private")?
                } else {
                    vec![]
                };

                // Add methods to functions list
                for method in &methods {
                    self.result.functions.push(method.clone());
                }

                self.result.classes.push(Class {
                    name: name.clone(),
                    qualified_name,
                    file_path: self.path.to_path_buf(),
                    line_start,
                    line_end,
                    bases,
                    methods: methods.iter().map(|m| m.name.clone()).collect(),
                    field_count: 0,
                    doc_comment: None,
                    annotations: vec![],
                });
            }
        }

        Ok(())
    }
}

/// Extract base classes from a class/struct specifier node
fn extract_base_classes(class_node: &Node, source: &[u8]) -> Vec<String> {
    let mut bases = vec![];
    for child in class_node.children(&mut class_node.walk()) {
        if child.kind() == "base_class_clause" {
            // base_class_clause children include access specifiers and type identifiers
            for base_child in child.children(&mut child.walk()) {
                if base_child.kind() == "type_identifier"
                    || base_child.kind() == "qualified_identifier"
                {
                    if let Ok(text) = base_child.utf8_text(source) {
                        bases.push(text.to_string());
                    }
                }
            }
        }
    }
    bases
}

impl<'a> CppExtractor<'a> {
    /// Build a map from method start byte to its access level by walking the field_declaration_list
    fn build_access_map(
        &self,
        body: &Node,
        default_access: &str,
    ) -> std::collections::HashMap<usize, String> {
        let mut access_map = std::collections::HashMap::new();
        let mut current_access = default_access.to_string();

        for child in body.children(&mut body.walk()) {
            if child.kind() == "access_specifier" {
                // Text is e.g. "public:" — strip the colon
                if let Ok(text) = child.utf8_text(self.source) {
                    current_access = text.trim_end_matches(':').trim().to_string();
                }
            } else if child.kind() == "function_definition" || child.kind() == "declaration" {
                access_map.insert(child.start_byte(), current_access.clone());
            }
        }

        access_map
    }
}

impl<'a> CppExtractor<'a> {
    /// Extract methods from a class body
    fn extract_class_methods(
        &self,
        body: &Node,
        class_name: &str,
        default_access: &str,
    ) -> Result<Vec<Function>> {
        let mut methods = vec![];

        // Build access map by walking siblings sequentially
        let access_map = self.build_access_map(body, default_access);

        let query = CPP_METHOD_QUERY.get_or_init(|| {
            Query::new(&tree_sitter_cpp::LANGUAGE.into(), CPP_METHOD_QUERY_STR)
                .expect("valid C++ method query")
        });

        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(query, *body, self.source);

        while let Some(m) = matches.next() {
            let mut method_node = None;
            let mut name = String::new();
            let mut params_node = None;
            let mut return_type_node = None;

            for capture in m.captures.iter() {
                let capture_name = query.capture_names()[capture.index as usize];
                match capture_name {
                    "method" => method_node = Some(capture.node),
                    "method_name" => {
                        name = capture
                            .node
                            .utf8_text(self.source)
                            .unwrap_or("")
                            .to_string();
                    }
                    "params" => params_node = Some(capture.node),
                    "return_type" => return_type_node = Some(capture.node),
                    _ => {}
                }
            }

            if let Some(node) = method_node {
                let parameters = extract_parameters(params_node, self.source);
                let return_type =
                    return_type_node.map(|n| n.utf8_text(self.source).unwrap_or("").to_string());

                let line_start = node.start_position().row as u32 + 1;
                let line_end = node.end_position().row as u32 + 1;
                let qualified_name = format!(
                    "{}::{}::{}:{}",
                    self.path.display(),
                    class_name,
                    name,
                    line_start
                );

                // Determine access level from pre-built map
                let access = access_map
                    .get(&node.start_byte())
                    .map(|s| s.as_str())
                    .unwrap_or(default_access);

                let annotations = if access == "public" {
                    vec!["exported".to_string()]
                } else {
                    vec![]
                };

                methods.push(Function {
                    name: name.clone(),
                    qualified_name,
                    file_path: self.path.to_path_buf(),
                    line_start,
                    line_end,
                    parameters,
                    return_type,
                    is_async: false,
                    complexity: Some(calculate_complexity(&node, self.source)),
                    max_nesting: None,
                    doc_comment: None,
                    annotations,
                });
            }
        }

        Ok(methods)
    }
}

impl<'a> CppExtractor<'a> {
    /// Extract struct definitions (similar to classes in C++, but default access is public)
    fn extract_structs(&mut self, root: &Node) -> Result<()> {
        let query = CPP_STRUCT_QUERY.get_or_init(|| {
            Query::new(&tree_sitter_cpp::LANGUAGE.into(), CPP_STRUCT_QUERY_STR)
                .expect("valid C++ struct query")
        });

        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(query, *root, self.source);

        while let Some(m) = matches.next() {
            let mut struct_node = None;
            let mut name = String::new();
            let mut body_node = None;

            for capture in m.captures.iter() {
                let capture_name = query.capture_names()[capture.index as usize];
                match capture_name {
                    "struct" => struct_node = Some(capture.node),
                    "struct_name" => {
                        name = capture
                            .node
                            .utf8_text(self.source)
                            .unwrap_or("")
                            .to_string();
                    }
                    "body" => body_node = Some(capture.node),
                    _ => {}
                }
            }

            if let Some(node) = struct_node {
                let line_start = node.start_position().row as u32 + 1;
                let line_end = node.end_position().row as u32 + 1;
                let qualified_name = format!("{}::{}", self.path.display(), name);

                // Extract base classes
                let bases = extract_base_classes(&node, self.source);

                // Extract methods (struct default = public)
                let methods = if let Some(body) = body_node {
                    self.extract_class_methods(&body, &name, "public")?
                } else {
                    vec![]
                };

                // Add methods to functions list
                for method in &methods {
                    self.result.functions.push(method.clone());
                }

                self.result.classes.push(Class {
                    name: name.clone(),
                    qualified_name,
                    file_path: self.path.to_path_buf(),
                    line_start,
                    line_end,
                    bases,
                    methods: methods.iter().map(|m| m.name.clone()).collect(),
                    field_count: 0,
                    doc_comment: None,
                    annotations: vec![],
                });
            }
        }

        Ok(())
    }
}

impl<'a> CppExtractor<'a> {
    /// Extract #include statements
    fn extract_includes(&mut self, root: &Node) -> Result<()> {
        let query = CPP_INCLUDE_QUERY.get_or_init(|| {
            Query::new(&tree_sitter_cpp::LANGUAGE.into(), CPP_INCLUDE_QUERY_STR)
                .expect("valid C++ include query")
        });

        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(query, *root, self.source);

        while let Some(m) = matches.next() {
            for capture in m.captures.iter() {
                let path_text = capture.node.utf8_text(self.source).unwrap_or("");
                // Remove quotes or angle brackets
                let import_path = path_text
                    .trim_matches('"')
                    .trim_matches('<')
                    .trim_matches('>')
                    .to_string();
                self.result.imports.push(ImportInfo::runtime(import_path));
            }
        }

        Ok(())
    }
}

impl<'a> CppExtractor<'a> {
    /// Extract function calls
    fn extract_calls(&mut self, root: &Node) -> Result<()> {
        let query = CPP_CALL_QUERY.get_or_init(|| {
            Query::new(&tree_sitter_cpp::LANGUAGE.into(), CPP_CALL_QUERY_STR)
                .expect("valid C++ call query")
        });

        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(query, *root, self.source);

        while let Some(m) = matches.next() {
            let mut call_node = None;
            let mut callee_name = String::new();

            for capture in m.captures.iter() {
                let capture_name = query.capture_names()[capture.index as usize];
                match capture_name {
                    "call" => call_node = Some(capture.node),
                    "func_name" | "method_name" | "qualified_name" => {
                        callee_name = capture
                            .node
                            .utf8_text(self.source)
                            .unwrap_or("")
                            .to_string();
                    }
                    _ => {}
                }
            }

            if let Some(node) = call_node {
                // Find the enclosing function
                let caller = self.find_enclosing_function(&node);
                let _callee_line = node.start_position().row as u32 + 1;

                self.result.calls.push((
                    caller,
                    callee_name.clone(), // Use just the name, not path:name:line (#9)
                ));
            }
        }

        Ok(())
    }
}

impl<'a> CppExtractor<'a> {
    /// Find the enclosing function for a node
    fn find_enclosing_function(&self, node: &Node) -> String {
        let mut current = node.parent();
        while let Some(parent) = current {
            if parent.kind() == "function_definition" {
                // Get function name from declarator
                if let Some(declarator) = parent.child_by_field_name("declarator") {
                    if let Some(name_node) = declarator.child_by_field_name("declarator") {
                        let name = name_node.utf8_text(self.source).unwrap_or("unknown");
                        let line = parent.start_position().row as u32 + 1;
                        return format!("{}::{}:{}", self.path.display(), name, line);
                    }
                }
            }
            current = parent.parent();
        }
        format!("{}::<global>", self.path.display())
    }
}

/// Extract function parameters
fn extract_parameters(params_node: Option<Node>, source: &[u8]) -> Vec<String> {
    let Some(params) = params_node else {
        return vec![];
    };

    let mut parameters = vec![];
    let mut cursor = params.walk();

    for child in params.children(&mut cursor) {
        match child.kind() {
            "parameter_declaration" | "optional_parameter_declaration" => {
                // Try to get the parameter name
                if let Some(declarator) = child.child_by_field_name("declarator") {
                    let name = declarator.utf8_text(source).unwrap_or("");
                    let name = name.trim_start_matches('*').trim_start_matches('&');
                    if !name.is_empty() {
                        parameters.push(name.to_string());
                    }
                }
            }
            _ => {}
        }
    }

    parameters
}

/// Calculate cyclomatic complexity of a function
fn calculate_complexity(node: &Node, _source: &[u8]) -> u32 {
    // Keep logic consistent with other language parsers (#32)
    let mut complexity = 1u32;

    fn count_branches(node: &Node, complexity: &mut u32) {
        match node.kind() {
            "if_statement" | "for_statement" | "while_statement" | "do_statement" => {
                *complexity += 1;
            }
            "case_statement" | "default_statement" | "case_label" | "default_label" => {
                *complexity += 1;
            }
            "conditional_expression" | "catch_clause" => {
                *complexity += 1;
            }
            "binary_expression" => {
                for child in node.children(&mut node.walk()) {
                    if child.kind() == "&&" || child.kind() == "||" {
                        *complexity += 1;
                    }
                }
            }
            _ => {}
        }

        for child in node.children(&mut node.walk()) {
            count_branches(&child, complexity);
        }
    }

    count_branches(node, &mut complexity);
    complexity
}

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

    #[test]
    fn test_parse_simple_function() {
        let source = r#"
int add(int a, int b) {
    return a + b;
}
"#;
        let path = PathBuf::from("test.cpp");
        let result = parse_source(source, &path).expect("should parse C++ source");

        assert_eq!(result.functions.len(), 1);
        assert_eq!(result.functions[0].name, "add");
        assert_eq!(result.functions[0].parameters, vec!["a", "b"]);
    }

    #[test]
    fn test_parse_class() {
        let source = r#"
class Calculator {
public:
    int add(int a, int b) {
        return a + b;
    }

    int subtract(int a, int b) {
        return a - b;
    }
};
"#;
        let path = PathBuf::from("test.cpp");
        let result = parse_source(source, &path).expect("should parse C++ source");

        assert_eq!(result.classes.len(), 1);
        assert_eq!(result.classes[0].name, "Calculator");
    }

    #[test]
    fn test_parse_includes() {
        let source = r#"
#include <iostream>
#include <vector>
#include "myheader.h"

int main() {
    return 0;
}
"#;
        let path = PathBuf::from("test.cpp");
        let result = parse_source(source, &path).expect("should parse C++ source");

        assert!(result.imports.iter().any(|i| i.path == "iostream"));
        assert!(result.imports.iter().any(|i| i.path == "vector"));
        assert!(result.imports.iter().any(|i| i.path == "myheader.h"));
    }

    #[test]
    fn test_complexity_switch_counts_cases_not_switch() {
        let source = r#"
int classify(int x) {
    switch (x) {
        case 1: return 1;
        case 2: return 2;
        default: return 0;
    }
}
"#;
        let path = PathBuf::from("test.cpp");
        let result = parse_source(source, &path).expect("should parse C++ source");
        let c = result.functions[0].complexity.unwrap_or(0);
        // Base + switch branches should be counted (at least cases/default)
        assert!(
            c >= 3,
            "expected switch branches to increase complexity, got {c}"
        );
    }

    #[test]
    fn test_complexity() {
        let source = r#"
int complex(int x) {
    if (x > 0) {
        for (int i = 0; i < x; i++) {
            if (i % 2 == 0) {
                x++;
            }
        }
    } else if (x < 0) {
        while (x < 0) {
            x++;
        }
    }
    return x;
}
"#;
        let path = PathBuf::from("test.cpp");
        let result = parse_source(source, &path).expect("should parse C++ source");

        assert_eq!(result.functions.len(), 1);
        assert!(result.functions[0].complexity.unwrap_or(0) >= 5); // Multiple branches
    }

    #[test]
    fn test_public_methods_exported() {
        let source = r#"
class MyClass {
public:
    int public_method(int x) {
        return x;
    }

private:
    int private_method(int x) {
        return x;
    }

protected:
    int protected_method(int x) {
        return x;
    }
};
"#;
        let path = PathBuf::from("test.cpp");
        let result = parse_source(source, &path).expect("should parse C++ source");

        let public_fn = result
            .functions
            .iter()
            .find(|f| f.name == "public_method")
            .expect("should find public_method");
        assert!(
            public_fn.annotations.contains(&"exported".to_string()),
            "public method should be exported"
        );

        let private_fn = result
            .functions
            .iter()
            .find(|f| f.name == "private_method")
            .expect("should find private_method");
        assert!(
            private_fn.annotations.is_empty(),
            "private method should not be exported"
        );

        let protected_fn = result
            .functions
            .iter()
            .find(|f| f.name == "protected_method")
            .expect("should find protected_method");
        assert!(
            protected_fn.annotations.is_empty(),
            "protected method should not be exported"
        );
    }

    #[test]
    fn test_class_default_private() {
        let source = r#"
class Foo {
    int implicit_private(int x) {
        return x;
    }
};
"#;
        let path = PathBuf::from("test.cpp");
        let result = parse_source(source, &path).expect("should parse C++ source");

        let func = result
            .functions
            .iter()
            .find(|f| f.name == "implicit_private")
            .expect("should find implicit_private");
        assert!(
            func.annotations.is_empty(),
            "class methods without access specifier should default to private (not exported)"
        );
    }

    #[test]
    fn test_struct_methods_default_public() {
        let source = r#"
struct Bar {
    int implicit_public(int x) {
        return x;
    }

private:
    int explicit_private(int x) {
        return x;
    }
};
"#;
        let path = PathBuf::from("test.cpp");
        let result = parse_source(source, &path).expect("should parse C++ source");

        let public_fn = result
            .functions
            .iter()
            .find(|f| f.name == "implicit_public")
            .expect("should find implicit_public");
        assert!(
            public_fn.annotations.contains(&"exported".to_string()),
            "struct methods without access specifier should default to public (exported)"
        );

        let private_fn = result
            .functions
            .iter()
            .find(|f| f.name == "explicit_private")
            .expect("should find explicit_private");
        assert!(
            private_fn.annotations.is_empty(),
            "struct method after private: should not be exported"
        );
    }

    #[test]
    fn test_base_class_extraction() {
        let source = r#"
class Base {};

class Derived : public Base {
public:
    int method() {
        return 0;
    }
};
"#;
        let path = PathBuf::from("test.cpp");
        let result = parse_source(source, &path).expect("should parse C++ source");

        let derived = result
            .classes
            .iter()
            .find(|c| c.name == "Derived")
            .expect("should find Derived class");
        assert_eq!(derived.bases, vec!["Base"]);
    }

    #[test]
    fn test_extern_free_function_exported() {
        let source = r#"
extern int api_func(int x) {
    return x;
}

int internal_func(int x) {
    return x;
}
"#;
        let path = PathBuf::from("test.cpp");
        let result = parse_source(source, &path).expect("should parse C++ source");

        let api = result
            .functions
            .iter()
            .find(|f| f.name == "api_func")
            .expect("should find api_func");
        assert!(
            api.annotations.contains(&"exported".to_string()),
            "extern free function should be exported"
        );

        let internal = result
            .functions
            .iter()
            .find(|f| f.name == "internal_func")
            .expect("should find internal_func");
        assert!(
            internal.annotations.is_empty(),
            "plain free function should not be exported"
        );
    }
}