Skip to main content

reflex/parsers/
cpp.rs

1//! C++ language parser using Tree-sitter
2//!
3//! Extracts symbols from C++ source code:
4//! - Functions (regular and template)
5//! - Classes (regular, abstract, template)
6//! - Structs
7//! - Namespaces
8//! - Templates (class and function)
9//! - Methods (with class scope, virtual, override)
10//! - Constructors/Destructors
11//! - Operators
12//! - Enums (enum and enum class)
13//! - Local variables (inside functions and methods)
14//! - Using declarations
15//! - Type aliases
16
17use crate::models::{Language, SearchResult, Span, SymbolKind};
18use anyhow::{Context, Result};
19use streaming_iterator::StreamingIterator;
20use tree_sitter::{Parser, QueryCursor};
21
22/// Parse C++ source code and extract symbols
23pub fn parse(path: &str, source: &str) -> Result<Vec<SearchResult>> {
24    let mut parser = Parser::new();
25    let language = tree_sitter_cpp::LANGUAGE;
26
27    parser
28        .set_language(&language.into())
29        .context("Failed to set C++ language")?;
30
31    let tree = parser
32        .parse(source, None)
33        .context("Failed to parse C++ source")?;
34
35    let root_node = tree.root_node();
36    let table = SYMBOL_QUERIES.run(&language.into(), &root_node, source)?;
37
38    let mut symbols = Vec::new();
39
40    // Extract different types of symbols using Tree-sitter queries
41    symbols.extend(extract_functions(source, &table)?);
42    symbols.extend(extract_classes(source, &table)?);
43    symbols.extend(extract_structs(source, &table)?);
44    symbols.extend(extract_namespaces(source, &table)?);
45    symbols.extend(extract_enums(source, &table)?);
46    symbols.extend(extract_methods(source, &table)?);
47    symbols.extend(extract_local_variables(source, &table)?);
48    symbols.extend(extract_type_aliases(source, &table)?);
49
50    // Add file path to all symbols
51    for symbol in &mut symbols {
52        symbol.path = path.to_string();
53        symbol.lang = Language::Cpp;
54    }
55
56    Ok(symbols)
57}
58
59/// Extract function declarations and definitions
60fn extract_functions(
61    source: &str,
62    table: &crate::parsers::MatchTable<'_>,
63) -> Result<Vec<SearchResult>> {
64    extract_symbols(source, table, 0, SymbolKind::Function, None)
65}
66
67/// Extract class declarations
68fn extract_classes(
69    source: &str,
70    table: &crate::parsers::MatchTable<'_>,
71) -> Result<Vec<SearchResult>> {
72    extract_symbols(source, table, 1, SymbolKind::Class, None)
73}
74
75/// Extract struct declarations
76fn extract_structs(
77    source: &str,
78    table: &crate::parsers::MatchTable<'_>,
79) -> Result<Vec<SearchResult>> {
80    extract_symbols(source, table, 2, SymbolKind::Struct, None)
81}
82
83/// Extract namespace definitions
84fn extract_namespaces(
85    source: &str,
86    table: &crate::parsers::MatchTable<'_>,
87) -> Result<Vec<SearchResult>> {
88    extract_symbols(source, table, 3, SymbolKind::Namespace, None)
89}
90
91/// Extract enum declarations
92fn extract_enums(
93    source: &str,
94    table: &crate::parsers::MatchTable<'_>,
95) -> Result<Vec<SearchResult>> {
96    extract_symbols(source, table, 4, SymbolKind::Enum, None)
97}
98
99/// Extract method definitions from classes and structs
100fn extract_methods(
101    source: &str,
102    table: &crate::parsers::MatchTable<'_>,
103) -> Result<Vec<SearchResult>> {
104    let query = table.query();
105    let matches = table.sub(5);
106
107    let mut symbols = Vec::new();
108
109    for match_ in matches {
110        let mut scope_name = None;
111        let mut scope_type = None;
112        let mut method_name = None;
113        let mut method_node = None;
114
115        for capture in &match_.captures {
116            let capture_name: &str = query.capture_names()[capture.index as usize];
117            match capture_name {
118                "class_name" => {
119                    scope_name = Some(
120                        capture
121                            .node
122                            .utf8_text(source.as_bytes())
123                            .unwrap_or("")
124                            .to_string(),
125                    );
126                    scope_type = Some("class");
127                }
128                "struct_name" => {
129                    scope_name = Some(
130                        capture
131                            .node
132                            .utf8_text(source.as_bytes())
133                            .unwrap_or("")
134                            .to_string(),
135                    );
136                    scope_type = Some("struct");
137                }
138                "method_name" => {
139                    method_name = Some(
140                        capture
141                            .node
142                            .utf8_text(source.as_bytes())
143                            .unwrap_or("")
144                            .to_string(),
145                    );
146                    // Find the parent function_definition node
147                    let mut current = capture.node;
148                    while let Some(parent) = current.parent() {
149                        if parent.kind() == "function_definition" {
150                            method_node = Some(parent);
151                            break;
152                        }
153                        current = parent;
154                    }
155                }
156                _ => {}
157            }
158        }
159
160        if let (Some(scope_name), Some(scope_type), Some(method_name), Some(node)) =
161            (scope_name, scope_type, method_name, method_node)
162        {
163            let scope = format!("{} {}", scope_type, scope_name);
164            let span = node_to_span(&node);
165            let preview = extract_preview(source, &node);
166
167            symbols.push(SearchResult::new(
168                String::new(),
169                Language::Cpp,
170                SymbolKind::Method,
171                Some(method_name),
172                span,
173                Some(scope),
174                preview,
175            ));
176        }
177    }
178
179    Ok(symbols)
180}
181
182/// Extract local variable declarations inside functions and methods
183fn extract_local_variables(
184    source: &str,
185    table: &crate::parsers::MatchTable<'_>,
186) -> Result<Vec<SearchResult>> {
187    let query = table.query();
188    let matches = table.sub(6);
189
190    let mut symbols = Vec::new();
191
192    for match_ in matches {
193        let mut name = None;
194        let mut var_node = None;
195
196        for capture in &match_.captures {
197            let capture_name: &str = query.capture_names()[capture.index as usize];
198            match capture_name {
199                "name" => {
200                    name = Some(
201                        capture
202                            .node
203                            .utf8_text(source.as_bytes())
204                            .unwrap_or("")
205                            .to_string(),
206                    );
207                }
208                "var" => {
209                    var_node = Some(capture.node);
210                }
211                _ => {}
212            }
213        }
214
215        // Only extract variables that are inside function definitions (local variables)
216        if let (Some(name), Some(node)) = (name, var_node) {
217            let mut is_local_var = false;
218            let mut current = node;
219
220            while let Some(parent) = current.parent() {
221                if parent.kind() == "function_definition" {
222                    is_local_var = true;
223                    break;
224                }
225                current = parent;
226            }
227
228            if is_local_var {
229                let span = node_to_span(&node);
230                let preview = extract_preview(source, &node);
231
232                symbols.push(SearchResult::new(
233                    String::new(),
234                    Language::Cpp,
235                    SymbolKind::Variable,
236                    Some(name),
237                    span,
238                    None, // No scope for local variables
239                    preview,
240                ));
241            }
242        }
243    }
244
245    Ok(symbols)
246}
247
248/// Extract type aliases (using and typedef)
249fn extract_type_aliases(
250    source: &str,
251    table: &crate::parsers::MatchTable<'_>,
252) -> Result<Vec<SearchResult>> {
253    extract_symbols(source, table, 7, SymbolKind::Type, None)
254}
255
256/// Generic symbol extraction helper
257fn extract_symbols(
258    source: &str,
259    table: &crate::parsers::MatchTable<'_>,
260    sub: usize,
261    kind: SymbolKind,
262    scope: Option<String>,
263) -> Result<Vec<SearchResult>> {
264    let query = table.query();
265    let matches = table.sub(sub);
266
267    let mut symbols = Vec::new();
268    let mut seen_names = std::collections::HashSet::new();
269
270    for match_ in matches {
271        // Find the name capture and the full node
272        let mut name = None;
273        let mut name_node = None;
274        let mut full_node = None;
275
276        for capture in &match_.captures {
277            let capture_name: &str = query.capture_names()[capture.index as usize];
278            if capture_name == "name" {
279                name = Some(
280                    capture
281                        .node
282                        .utf8_text(source.as_bytes())
283                        .unwrap_or("")
284                        .to_string(),
285                );
286                name_node = Some(capture.node);
287            } else {
288                // Assume any other capture is the full node
289                full_node = Some(capture.node);
290            }
291        }
292
293        if let (Some(name), Some(name_node), Some(node)) = (name, name_node, full_node) {
294            // Deduplicate by name position - this handles cases where template patterns
295            // match the same symbol twice (e.g., both template_declaration and class_specifier)
296            let name_key = (name_node.start_byte(), name_node.end_byte(), name.clone());
297            if seen_names.contains(&name_key) {
298                continue; // Skip duplicate
299            }
300            seen_names.insert(name_key);
301
302            let span = node_to_span(&node);
303            let preview = extract_preview(source, &node);
304
305            symbols.push(SearchResult::new(
306                String::new(),
307                Language::Cpp,
308                kind.clone(),
309                Some(name),
310                span,
311                scope.clone(),
312                preview,
313            ));
314        }
315    }
316
317    Ok(symbols)
318}
319
320/// Convert a Tree-sitter node to a Span
321fn node_to_span(node: &tree_sitter::Node) -> Span {
322    let start = node.start_position();
323    let end = node.end_position();
324
325    Span::new(
326        start.row + 1, // Convert 0-indexed to 1-indexed
327        start.column,
328        end.row + 1,
329        end.column,
330    )
331}
332
333/// Extract a preview (7 lines) around the symbol
334fn extract_preview(source: &str, node: &tree_sitter::Node) -> String {
335    // Starts at the node, not at byte 0: see `crate::parsers::preview`.
336    crate::parsers::preview::extract_preview_for_node(source, node)
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    #[test]
344    fn test_parse_function() {
345        let source = r#"
346int add(int a, int b) {
347    return a + b;
348}
349        "#;
350
351        let symbols = parse("test.cpp", source).unwrap();
352        assert_eq!(symbols.len(), 1);
353        assert_eq!(symbols[0].symbol.as_deref(), Some("add"));
354        assert!(matches!(symbols[0].kind, SymbolKind::Function));
355    }
356
357    #[test]
358    fn test_parse_class() {
359        let source = r#"
360class User {
361private:
362    std::string name;
363    int age;
364
365public:
366    User(std::string n, int a) : name(n), age(a) {}
367};
368        "#;
369
370        let symbols = parse("test.cpp", source).unwrap();
371
372        let class_symbols: Vec<_> = symbols
373            .iter()
374            .filter(|s| matches!(s.kind, SymbolKind::Class))
375            .collect();
376
377        assert_eq!(class_symbols.len(), 1);
378        assert_eq!(class_symbols[0].symbol.as_deref(), Some("User"));
379    }
380
381    #[test]
382    fn test_parse_namespace() {
383        let source = r#"
384namespace MyNamespace {
385    int value = 42;
386}
387
388namespace Nested::Namespace {
389    void function() {}
390}
391        "#;
392
393        let symbols = parse("test.cpp", source).unwrap();
394
395        let namespace_symbols: Vec<_> = symbols
396            .iter()
397            .filter(|s| matches!(s.kind, SymbolKind::Namespace))
398            .collect();
399
400        assert!(!namespace_symbols.is_empty());
401        assert!(
402            namespace_symbols
403                .iter()
404                .any(|s| s.symbol.as_deref() == Some("MyNamespace"))
405        );
406    }
407
408    #[test]
409    fn test_parse_struct() {
410        let source = r#"
411struct Point {
412    int x;
413    int y;
414};
415        "#;
416
417        let symbols = parse("test.cpp", source).unwrap();
418        assert_eq!(symbols.len(), 1);
419        assert_eq!(symbols[0].symbol.as_deref(), Some("Point"));
420        assert!(matches!(symbols[0].kind, SymbolKind::Struct));
421    }
422
423    #[test]
424    fn test_parse_enum() {
425        let source = r#"
426enum Color {
427    RED,
428    GREEN,
429    BLUE
430};
431
432enum class Status {
433    Active,
434    Inactive
435};
436        "#;
437
438        let symbols = parse("test.cpp", source).unwrap();
439
440        let enum_symbols: Vec<_> = symbols
441            .iter()
442            .filter(|s| matches!(s.kind, SymbolKind::Enum))
443            .collect();
444
445        assert_eq!(enum_symbols.len(), 2);
446        assert!(
447            enum_symbols
448                .iter()
449                .any(|s| s.symbol.as_deref() == Some("Color"))
450        );
451        assert!(
452            enum_symbols
453                .iter()
454                .any(|s| s.symbol.as_deref() == Some("Status"))
455        );
456    }
457
458    #[test]
459    fn test_parse_template_class() {
460        let source = r#"
461template <typename T>
462class Container {
463private:
464    T value;
465
466public:
467    Container(T v) : value(v) {}
468    T getValue() { return value; }
469};
470        "#;
471
472        let symbols = parse("test.cpp", source).unwrap();
473
474        let class_symbols: Vec<_> = symbols
475            .iter()
476            .filter(|s| matches!(s.kind, SymbolKind::Class))
477            .collect();
478
479        assert_eq!(class_symbols.len(), 1);
480        assert_eq!(class_symbols[0].symbol.as_deref(), Some("Container"));
481    }
482
483    #[test]
484    fn test_parse_template_function() {
485        let source = r#"
486template <typename T>
487T max(T a, T b) {
488    return (a > b) ? a : b;
489}
490        "#;
491
492        let symbols = parse("test.cpp", source).unwrap();
493        assert_eq!(symbols.len(), 1);
494        assert_eq!(symbols[0].symbol.as_deref(), Some("max"));
495        assert!(matches!(symbols[0].kind, SymbolKind::Function));
496    }
497
498    #[test]
499    fn test_parse_class_with_methods() {
500        let source = r#"
501class Calculator {
502public:
503    int add(int a, int b) {
504        return a + b;
505    }
506
507    int subtract(int a, int b) {
508        return a - b;
509    }
510};
511        "#;
512
513        let symbols = parse("test.cpp", source).unwrap();
514
515        let method_symbols: Vec<_> = symbols
516            .iter()
517            .filter(|s| matches!(s.kind, SymbolKind::Method))
518            .collect();
519
520        assert_eq!(method_symbols.len(), 2);
521        assert!(
522            method_symbols
523                .iter()
524                .any(|s| s.symbol.as_deref() == Some("add"))
525        );
526        assert!(
527            method_symbols
528                .iter()
529                .any(|s| s.symbol.as_deref() == Some("subtract"))
530        );
531
532        // Check scope
533        for _method in method_symbols {
534            // Removed: scope field no longer exists: assert_eq!(method.scope.as_ref().unwrap(), "class Calculator");
535        }
536    }
537
538    #[test]
539    fn test_parse_using_declaration() {
540        let source = r#"
541using StringVector = std::vector<std::string>;
542using IntPtr = int*;
543        "#;
544
545        let symbols = parse("test.cpp", source).unwrap();
546
547        let type_symbols: Vec<_> = symbols
548            .iter()
549            .filter(|s| matches!(s.kind, SymbolKind::Type))
550            .collect();
551
552        assert!(!type_symbols.is_empty());
553        assert!(
554            type_symbols
555                .iter()
556                .any(|s| s.symbol.as_deref() == Some("StringVector"))
557        );
558    }
559
560    #[test]
561    fn test_parse_typedef() {
562        let source = r#"
563typedef unsigned int uint;
564typedef struct {
565    int x, y;
566} Point;
567        "#;
568
569        let symbols = parse("test.cpp", source).unwrap();
570
571        let type_symbols: Vec<_> = symbols
572            .iter()
573            .filter(|s| matches!(s.kind, SymbolKind::Type))
574            .collect();
575
576        assert!(!type_symbols.is_empty());
577    }
578
579    #[test]
580    fn test_parse_mixed_symbols() {
581        let source = r#"
582namespace Math {
583    class Vector {
584    private:
585        double x, y;
586
587    public:
588        Vector(double x, double y) : x(x), y(y) {}
589
590        double magnitude() {
591            return sqrt(x*x + y*y);
592        }
593    };
594
595    enum Operation {
596        ADD,
597        SUBTRACT
598    };
599
600    template <typename T>
601    T multiply(T a, T b) {
602        return a * b;
603    }
604}
605        "#;
606
607        let symbols = parse("test.cpp", source).unwrap();
608
609        // Should find: namespace, class, enum, method, function
610        assert!(symbols.len() >= 5);
611
612        let kinds: Vec<&SymbolKind> = symbols.iter().map(|s| &s.kind).collect();
613        assert!(kinds.contains(&&SymbolKind::Namespace));
614        assert!(kinds.contains(&&SymbolKind::Class));
615        assert!(kinds.contains(&&SymbolKind::Enum));
616        assert!(kinds.contains(&&SymbolKind::Method));
617        assert!(kinds.contains(&&SymbolKind::Function));
618    }
619
620    #[test]
621    fn test_parse_nested_namespace() {
622        let source = r#"
623namespace Outer {
624    namespace Inner {
625        void function() {}
626    }
627}
628        "#;
629
630        let symbols = parse("test.cpp", source).unwrap();
631
632        let namespace_symbols: Vec<_> = symbols
633            .iter()
634            .filter(|s| matches!(s.kind, SymbolKind::Namespace))
635            .collect();
636
637        assert_eq!(namespace_symbols.len(), 2);
638        assert!(
639            namespace_symbols
640                .iter()
641                .any(|s| s.symbol.as_deref() == Some("Outer"))
642        );
643        assert!(
644            namespace_symbols
645                .iter()
646                .any(|s| s.symbol.as_deref() == Some("Inner"))
647        );
648    }
649
650    #[test]
651    fn test_parse_virtual_methods() {
652        let source = r#"
653class Base {
654public:
655    virtual void draw() = 0;
656    virtual void update() {}
657};
658
659class Derived : public Base {
660public:
661    void draw() override {
662        // Implementation
663    }
664};
665        "#;
666
667        let symbols = parse("test.cpp", source).unwrap();
668
669        let class_symbols: Vec<_> = symbols
670            .iter()
671            .filter(|s| matches!(s.kind, SymbolKind::Class))
672            .collect();
673
674        assert_eq!(class_symbols.len(), 2);
675        assert!(
676            class_symbols
677                .iter()
678                .any(|s| s.symbol.as_deref() == Some("Base"))
679        );
680        assert!(
681            class_symbols
682                .iter()
683                .any(|s| s.symbol.as_deref() == Some("Derived"))
684        );
685
686        let method_symbols: Vec<_> = symbols
687            .iter()
688            .filter(|s| matches!(s.kind, SymbolKind::Method))
689            .collect();
690
691        assert!(method_symbols.len() >= 2);
692    }
693
694    #[test]
695    fn test_parse_operator_overload() {
696        let source = r#"
697class Complex {
698private:
699    double real, imag;
700
701public:
702    Complex operator+(const Complex& other) {
703        return Complex(real + other.real, imag + other.imag);
704    }
705};
706        "#;
707
708        let symbols = parse("test.cpp", source).unwrap();
709
710        let class_symbols: Vec<_> = symbols
711            .iter()
712            .filter(|s| matches!(s.kind, SymbolKind::Class))
713            .collect();
714
715        assert_eq!(class_symbols.len(), 1);
716        assert_eq!(class_symbols[0].symbol.as_deref(), Some("Complex"));
717    }
718
719    #[test]
720    fn test_local_variables_included() {
721        let source = r#"
722int calculate(int input) {
723    int localVar = input * 2;
724    auto result = localVar + 10;
725    return result;
726}
727
728class Calculator {
729public:
730    int compute(int value) {
731        int temp = value * 3;
732        auto final = temp + 5;
733        return final;
734    }
735};
736        "#;
737
738        let symbols = parse("test.cpp", source).unwrap();
739
740        // Filter to just variables
741        let variables: Vec<_> = symbols
742            .iter()
743            .filter(|s| matches!(s.kind, SymbolKind::Variable))
744            .collect();
745
746        // Check that local variables are captured
747        assert!(
748            variables
749                .iter()
750                .any(|v| v.symbol.as_deref() == Some("localVar"))
751        );
752        assert!(
753            variables
754                .iter()
755                .any(|v| v.symbol.as_deref() == Some("result"))
756        );
757        assert!(
758            variables
759                .iter()
760                .any(|v| v.symbol.as_deref() == Some("temp"))
761        );
762        assert!(
763            variables
764                .iter()
765                .any(|v| v.symbol.as_deref() == Some("final"))
766        );
767
768        // Verify that local variables have no scope
769        for _var in variables {
770            // Removed: scope field no longer exists: assert_eq!(var.scope, None);
771        }
772    }
773
774    #[test]
775    fn test_parse_destructor() {
776        let source = r#"
777class Resource {
778private:
779    int* data;
780
781public:
782    Resource() {
783        data = new int[100];
784    }
785
786    ~Resource() {
787        delete[] data;
788    }
789};
790        "#;
791
792        let symbols = parse("test.cpp", source).unwrap();
793
794        let class_symbols: Vec<_> = symbols
795            .iter()
796            .filter(|s| matches!(s.kind, SymbolKind::Class))
797            .collect();
798
799        assert_eq!(class_symbols.len(), 1);
800        assert_eq!(class_symbols[0].symbol.as_deref(), Some("Resource"));
801
802        // Check if destructor is extracted
803        let method_symbols: Vec<_> = symbols
804            .iter()
805            .filter(|s| matches!(s.kind, SymbolKind::Method))
806            .collect();
807
808        // Should have both constructor and destructor
809        assert!(
810            !method_symbols.is_empty(),
811            "Expected at least constructor or destructor to be extracted"
812        );
813
814        // Print what methods we found for debugging
815        for method in &method_symbols {
816            println!("Found method: {:?}", method.symbol);
817        }
818
819        // Check if destructor is present (might be ~Resource or just Resource)
820        let has_destructor = method_symbols.iter().any(|s| {
821            s.symbol
822                .as_deref()
823                .map(|name| name.contains("~") || name == "Resource")
824                .unwrap_or(false)
825        });
826
827        // This test documents current behavior - we'll fix if destructors aren't extracted
828        if !has_destructor {
829            println!("WARNING: Destructor extraction may not be working");
830        }
831    }
832}
833
834// ============================================================================
835// Dependency Extraction
836// ============================================================================
837
838use crate::models::ImportType;
839use crate::parsers::{DependencyExtractor, ImportInfo};
840
841const SYMQ_0: &str = r#"
842        (function_definition
843            declarator: (function_declarator
844                declarator: (identifier) @name)) @function
845
846        (function_definition
847            declarator: (function_declarator
848                declarator: (qualified_identifier
849                    name: (identifier) @name))) @function
850
851        (template_declaration
852            (function_definition
853                declarator: (function_declarator
854                    declarator: (identifier) @name))) @function
855    "#;
856const SYMQ_1: &str = r#"
857        (class_specifier
858            name: (type_identifier) @name) @class
859
860        (template_declaration
861            (class_specifier
862                name: (type_identifier) @name)) @class
863    "#;
864const SYMQ_2: &str = r#"
865        (struct_specifier
866            name: (type_identifier) @name) @struct
867
868        (template_declaration
869            (struct_specifier
870                name: (type_identifier) @name)) @struct
871    "#;
872const SYMQ_3: &str = r#"
873        (namespace_definition
874            name: (_) @name) @namespace
875    "#;
876const SYMQ_4: &str = r#"
877        (enum_specifier
878            name: (type_identifier) @name) @enum
879    "#;
880const SYMQ_5: &str = r#"
881        (class_specifier
882            name: (type_identifier) @class_name
883            body: (field_declaration_list
884                (function_definition
885                    declarator: (function_declarator
886                        declarator: (field_identifier) @method_name)))) @class
887
888        (class_specifier
889            name: (type_identifier) @class_name
890            body: (field_declaration_list
891                (function_definition
892                    declarator: (function_declarator
893                        declarator: (destructor_name) @method_name)))) @class
894
895        (struct_specifier
896            name: (type_identifier) @struct_name
897            body: (field_declaration_list
898                (function_definition
899                    declarator: (function_declarator
900                        declarator: (field_identifier) @method_name)))) @struct
901
902        (struct_specifier
903            name: (type_identifier) @struct_name
904            body: (field_declaration_list
905                (function_definition
906                    declarator: (function_declarator
907                        declarator: (destructor_name) @method_name)))) @struct
908    "#;
909const SYMQ_6: &str = r#"
910        (declaration
911            declarator: (init_declarator
912                declarator: (identifier) @name)) @var
913    "#;
914const SYMQ_7: &str = r#"
915        (type_definition
916            declarator: (type_identifier) @name) @typedef
917
918        (alias_declaration
919            name: (type_identifier) @name) @using
920    "#;
921
922/// Every symbol query of this module, run as ONE query per file (see
923/// `crate::parsers::LanguageQueries`).
924static SYMBOL_QUERIES: crate::parsers::LanguageQueries = crate::parsers::LanguageQueries::new(&[
925    SYMQ_0, SYMQ_1, SYMQ_2, SYMQ_3, SYMQ_4, SYMQ_5, SYMQ_6, SYMQ_7,
926]);
927
928/// C++ dependency extractor
929pub struct CppDependencyExtractor;
930
931impl DependencyExtractor for CppDependencyExtractor {
932    fn extract_dependencies(source: &str) -> Result<Vec<ImportInfo>> {
933        let mut parser = Parser::new();
934        let language = tree_sitter_cpp::LANGUAGE;
935
936        parser
937            .set_language(&language.into())
938            .context("Failed to set C++ language")?;
939
940        let tree = parser
941            .parse(source, None)
942            .context("Failed to parse C++ source")?;
943
944        let root_node = tree.root_node();
945
946        let mut imports = Vec::new();
947
948        // Extract #include directives
949        imports.extend(extract_cpp_includes(source, &root_node)?);
950
951        Ok(imports)
952    }
953}
954
955/// Extract C++ #include directives
956fn extract_cpp_includes(source: &str, root: &tree_sitter::Node) -> Result<Vec<ImportInfo>> {
957    let language = tree_sitter_cpp::LANGUAGE;
958
959    let query_str = r#"
960        (preproc_include
961            path: (string_literal) @include_path) @include
962
963        (preproc_include
964            path: (system_lib_string) @include_path) @include
965    "#;
966
967    static QUERY_1: crate::parsers::CachedQuery = crate::parsers::CachedQuery::new();
968    let query = crate::parsers::cached_query(&QUERY_1, language, query_str)
969        .context("Failed to create C++ include query")?;
970
971    let mut cursor = QueryCursor::new();
972    let mut matches = cursor.matches(query, *root, source.as_bytes());
973
974    let mut imports = Vec::new();
975
976    while let Some(match_) = matches.next() {
977        let mut include_path = None;
978        let mut include_node = None;
979
980        for capture in match_.captures {
981            let capture_name: &str = query.capture_names()[capture.index as usize];
982            match capture_name {
983                "include_path" => {
984                    // Remove quotes or angle brackets from path
985                    let raw_path = capture.node.utf8_text(source.as_bytes()).unwrap_or("");
986                    include_path = Some(
987                        raw_path
988                            .trim_matches(|c| c == '"' || c == '<' || c == '>')
989                            .to_string(),
990                    );
991                }
992                "include" => {
993                    include_node = Some(capture.node);
994                }
995                _ => {}
996            }
997        }
998
999        if let (Some(path), Some(node)) = (include_path, include_node) {
1000            let import_type = classify_cpp_include(&path, source, &node);
1001            let line_number = node.start_position().row + 1;
1002
1003            imports.push(ImportInfo {
1004                imported_path: path,
1005                import_type,
1006                line_number,
1007                imported_symbols: None, // C++ includes entire header
1008            });
1009        }
1010    }
1011
1012    Ok(imports)
1013}
1014
1015/// Classify a C++ include as internal, external, or stdlib
1016fn classify_cpp_include(include_path: &str, source: &str, node: &tree_sitter::Node) -> ImportType {
1017    // Get the actual #include line to check if it uses quotes or angle brackets
1018    let line_start = node.start_position();
1019    let lines: Vec<&str> = source.lines().collect();
1020
1021    if line_start.row < lines.len() {
1022        let line = lines[line_start.row];
1023
1024        // Internal: #include "..." (quotes = local project files)
1025        if line.contains(&format!("\"{}\"", include_path)) {
1026            return ImportType::Internal;
1027        }
1028    }
1029
1030    // C++ standard library headers (angle brackets)
1031    const CPP_STDLIB_HEADERS: &[&str] = &[
1032        // C standard library (inherited)
1033        "stdio.h",
1034        "stdlib.h",
1035        "string.h",
1036        "math.h",
1037        "time.h",
1038        "ctype.h",
1039        "assert.h",
1040        "errno.h",
1041        "limits.h",
1042        "float.h",
1043        "stddef.h",
1044        "stdint.h",
1045        "stdbool.h",
1046        "stdarg.h",
1047        "setjmp.h",
1048        "signal.h",
1049        "locale.h",
1050        "wchar.h",
1051        "wctype.h",
1052        "complex.h",
1053        "fenv.h",
1054        "inttypes.h",
1055        "iso646.h",
1056        "tgmath.h",
1057        "threads.h",
1058        // C++ standard library headers (no .h extension)
1059        "algorithm",
1060        "any",
1061        "array",
1062        "atomic",
1063        "barrier",
1064        "bit",
1065        "bitset",
1066        "charconv",
1067        "chrono",
1068        "codecvt",
1069        "compare",
1070        "complex",
1071        "concepts",
1072        "condition_variable",
1073        "coroutine",
1074        "deque",
1075        "exception",
1076        "execution",
1077        "expected",
1078        "filesystem",
1079        "format",
1080        "forward_list",
1081        "fstream",
1082        "functional",
1083        "future",
1084        "initializer_list",
1085        "iomanip",
1086        "ios",
1087        "iosfwd",
1088        "iostream",
1089        "istream",
1090        "iterator",
1091        "latch",
1092        "limits",
1093        "list",
1094        "locale",
1095        "map",
1096        "mdspan",
1097        "memory",
1098        "memory_resource",
1099        "mutex",
1100        "new",
1101        "numbers",
1102        "numeric",
1103        "optional",
1104        "ostream",
1105        "queue",
1106        "random",
1107        "ranges",
1108        "ratio",
1109        "regex",
1110        "scoped_allocator",
1111        "semaphore",
1112        "set",
1113        "shared_mutex",
1114        "source_location",
1115        "span",
1116        "sstream",
1117        "stack",
1118        "stacktrace",
1119        "stdexcept",
1120        "stop_token",
1121        "streambuf",
1122        "string",
1123        "string_view",
1124        "strstream",
1125        "syncstream",
1126        "system_error",
1127        "thread",
1128        "tuple",
1129        "type_traits",
1130        "typeindex",
1131        "typeinfo",
1132        "unordered_map",
1133        "unordered_set",
1134        "utility",
1135        "valarray",
1136        "variant",
1137        "vector",
1138        "version",
1139        // C++ C-compatibility headers (c-prefixed)
1140        "cassert",
1141        "cctype",
1142        "cerrno",
1143        "cfenv",
1144        "cfloat",
1145        "cinttypes",
1146        "climits",
1147        "clocale",
1148        "cmath",
1149        "csetjmp",
1150        "csignal",
1151        "cstdarg",
1152        "cstddef",
1153        "cstdint",
1154        "cstdio",
1155        "cstdlib",
1156        "cstring",
1157        "ctime",
1158        "cuchar",
1159        "cwchar",
1160        "cwctype",
1161    ];
1162
1163    if CPP_STDLIB_HEADERS.contains(&include_path) {
1164        return ImportType::Stdlib;
1165    }
1166
1167    // Everything else with angle brackets is external (third-party libraries)
1168    ImportType::External
1169}
1170
1171// ============================================================================
1172// Path Resolution
1173// ============================================================================
1174
1175/// Resolve a C++ #include directive to a file path
1176///
1177/// # Arguments
1178/// * `include_path` - The path from the #include directive (e.g., "utils/helper.hpp")
1179/// * `current_file_path` - Path to the file containing the #include directive
1180///
1181/// # Returns
1182/// * `Some(path)` if the include can be resolved (quoted includes only)
1183/// * `None` for angle bracket includes (system/library headers)
1184pub fn resolve_cpp_include_to_path(
1185    include_path: &str,
1186    current_file_path: Option<&str>,
1187) -> Option<String> {
1188    // Only resolve relative includes (quoted includes, which are Internal)
1189    // Angle bracket includes are system/library headers and won't be resolved
1190
1191    // Beside the including file, folded without reading the disk
1192    let current_file = current_file_path?;
1193    crate::dependency_resolve::fold_path(
1194        crate::dependency_resolve::parent_dir(current_file),
1195        include_path,
1196    )
1197}
1198
1199// ============================================================================
1200// Tests for Path Resolution
1201// ============================================================================
1202
1203#[cfg(test)]
1204mod resolution_tests {
1205    use super::*;
1206
1207    #[test]
1208    fn test_resolve_cpp_include_same_directory() {
1209        let result = resolve_cpp_include_to_path("helper.hpp", Some("/project/src/main.cpp"));
1210
1211        assert!(result.is_some());
1212        let path = result.unwrap();
1213        assert!(path.ends_with("src/helper.hpp"));
1214    }
1215
1216    #[test]
1217    fn test_resolve_cpp_include_subdirectory() {
1218        let result = resolve_cpp_include_to_path("utils/helper.hpp", Some("/project/src/main.cpp"));
1219
1220        assert!(result.is_some());
1221        let path = result.unwrap();
1222        assert!(path.ends_with("src/utils/helper.hpp"));
1223    }
1224
1225    #[test]
1226    fn test_resolve_cpp_include_parent_directory() {
1227        let result =
1228            resolve_cpp_include_to_path("../include/common.hpp", Some("/project/src/main.cpp"));
1229
1230        assert!(result.is_some());
1231        let path = result.unwrap();
1232        assert!(path.contains("include") && path.contains("common.hpp"));
1233    }
1234
1235    #[test]
1236    fn test_resolve_cpp_include_h_extension() {
1237        let result = resolve_cpp_include_to_path("legacy.h", Some("/project/src/main.cpp"));
1238
1239        assert!(result.is_some());
1240        let path = result.unwrap();
1241        assert!(path.ends_with("src/legacy.h"));
1242    }
1243
1244    #[test]
1245    fn test_resolve_cpp_include_no_current_file() {
1246        let result = resolve_cpp_include_to_path("helper.hpp", None);
1247
1248        assert!(result.is_none());
1249    }
1250}