codegraph-typescript 0.3.2

TypeScript/JavaScript parser for CodeGraph - extracts code entities and relationships
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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
//! AST visitor for extracting TypeScript/JavaScript entities

use codegraph_parser_api::{
    CallRelation, ClassEntity, ComplexityBuilder, ComplexityMetrics, FunctionEntity,
    ImplementationRelation, ImportRelation, InheritanceRelation, Parameter, ParserConfig,
    TraitEntity,
};
use tree_sitter::Node;

/// Visitor that extracts entities and relationships from TypeScript/JavaScript AST
pub struct TypeScriptVisitor<'a> {
    pub source: &'a [u8],
    #[allow(dead_code)]
    pub config: ParserConfig,
    pub functions: Vec<FunctionEntity>,
    pub classes: Vec<ClassEntity>,
    pub interfaces: Vec<TraitEntity>,
    pub imports: Vec<ImportRelation>,
    pub calls: Vec<CallRelation>,
    pub implementations: Vec<ImplementationRelation>,
    pub inheritance: Vec<InheritanceRelation>,
    current_class: Option<String>,
    current_function: Option<String>,
}

impl<'a> TypeScriptVisitor<'a> {
    pub fn new(source: &'a [u8], config: ParserConfig) -> Self {
        Self {
            source,
            config,
            functions: Vec::new(),
            classes: Vec::new(),
            interfaces: Vec::new(),
            imports: Vec::new(),
            calls: Vec::new(),
            implementations: Vec::new(),
            inheritance: Vec::new(),
            current_class: None,
            current_function: None,
        }
    }

    /// Get text for a node
    fn node_text(&self, node: Node) -> String {
        node.utf8_text(self.source).unwrap_or("").to_string()
    }

    /// Visit a tree-sitter node
    pub fn visit_node(&mut self, node: Node) {
        match node.kind() {
            // Only match declaration nodes to avoid duplicates
            "function_declaration" => {
                self.visit_function(node);
            }
            "arrow_function" => {
                self.visit_arrow_function(node);
            }
            "method_definition" => {
                self.visit_method(node);
            }
            "class_declaration" => {
                self.visit_class(node);
            }
            "interface_declaration" => {
                self.visit_interface(node);
            }
            "import_statement" => {
                self.visit_import(node);
            }
            "call_expression" => {
                self.visit_call_expression(node);
                // Also recurse into call expression children (e.g., nested calls)
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.visit_node(child);
                }
            }
            _ => {
                // Recursively visit children for unhandled node types
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.visit_node(child);
                }
            }
        }
    }

    fn visit_function(&mut self, node: Node) {
        // Extract function name
        let name = node
            .child_by_field_name("name")
            .map(|n| self.node_text(n))
            .unwrap_or_else(|| "anonymous".to_string());

        // Extract parameters
        let parameters = if let Some(params_node) = node.child_by_field_name("parameters") {
            self.extract_parameters(params_node)
        } else {
            Vec::new()
        };

        // Check if async
        let is_async = self.node_text(node).starts_with("async");

        // Calculate complexity from the function body
        let complexity = node
            .child_by_field_name("body")
            .map(|body| self.calculate_complexity(body));

        let func = FunctionEntity {
            name: name.clone(),
            signature: self
                .node_text(node)
                .lines()
                .next()
                .unwrap_or("")
                .to_string(),
            visibility: "public".to_string(),
            line_start: node.start_position().row + 1,
            line_end: node.end_position().row + 1,
            is_async,
            is_test: false,
            is_static: false,
            is_abstract: false,
            parameters,
            return_type: None,
            doc_comment: None,
            attributes: Vec::new(),
            parent_class: self.current_class.clone(),
            complexity,
        };

        self.functions.push(func);

        // Set current function context and visit body to extract calls
        let previous_function = self.current_function.clone();
        self.current_function = Some(name);

        // Visit function body to extract call expressions
        if let Some(body) = node.child_by_field_name("body") {
            let mut cursor = body.walk();
            for child in body.children(&mut cursor) {
                self.visit_node(child);
            }
        }

        self.current_function = previous_function;
    }

    fn visit_arrow_function(&mut self, node: Node) {
        // Calculate complexity from the arrow function body
        let complexity = node
            .child_by_field_name("body")
            .map(|body| self.calculate_complexity(body));

        let func = FunctionEntity {
            name: "arrow_function".to_string(),
            signature: "() => {}".to_string(),
            visibility: "public".to_string(),
            line_start: node.start_position().row + 1,
            line_end: node.end_position().row + 1,
            is_async: false,
            is_test: false,
            is_static: false,
            is_abstract: false,
            parameters: Vec::new(),
            return_type: None,
            doc_comment: None,
            attributes: Vec::new(),
            parent_class: None,
            complexity,
        };

        self.functions.push(func);
    }

    fn visit_method(&mut self, node: Node) {
        // Extract method name from property_identifier or identifier
        let name = node
            .child_by_field_name("name")
            .map(|n| self.node_text(n))
            .unwrap_or_else(|| "method".to_string());

        // Extract parameters if available
        let parameters = if let Some(params_node) = node.child_by_field_name("parameters") {
            self.extract_parameters(params_node)
        } else {
            Vec::new()
        };

        // Check if method is static or async
        let node_text = self.node_text(node);
        let is_static = node_text.contains("static ");
        let is_async = node_text.contains("async ");

        // Determine visibility (private/public based on # prefix in name or explicit keyword)
        let visibility = if name.starts_with('#') {
            "private".to_string()
        } else {
            "public".to_string()
        };

        // Calculate complexity from the method body
        let complexity = node
            .child_by_field_name("body")
            .map(|body| self.calculate_complexity(body));

        let func = FunctionEntity {
            name: name.clone(),
            signature: node_text.lines().next().unwrap_or("").to_string(),
            visibility,
            line_start: node.start_position().row + 1,
            line_end: node.end_position().row + 1,
            is_async,
            is_test: false,
            is_static,
            is_abstract: false,
            parameters,
            return_type: None,
            doc_comment: None,
            attributes: Vec::new(),
            parent_class: self.current_class.clone(),
            complexity,
        };

        self.functions.push(func);

        // Set current function context and visit body to extract calls
        let previous_function = self.current_function.clone();
        self.current_function = Some(name);

        // Visit method body to extract call expressions
        if let Some(body) = node.child_by_field_name("body") {
            let mut cursor = body.walk();
            for child in body.children(&mut cursor) {
                self.visit_node(child);
            }
        }

        self.current_function = previous_function;
    }

    fn visit_class(&mut self, node: Node) {
        let name = node
            .child_by_field_name("name")
            .map(|n| self.node_text(n))
            .unwrap_or_else(|| "AnonymousClass".to_string());

        // Set current class context
        let previous_class = self.current_class.clone();
        self.current_class = Some(name.clone());

        let class = ClassEntity {
            name: name.clone(),
            visibility: "public".to_string(),
            line_start: node.start_position().row + 1,
            line_end: node.end_position().row + 1,
            is_abstract: false,
            is_interface: false,
            base_classes: Vec::new(),
            implemented_traits: Vec::new(),
            methods: Vec::new(),
            fields: Vec::new(),
            doc_comment: None,
            attributes: Vec::new(),
            type_parameters: Vec::new(),
        };

        self.classes.push(class);

        // Visit children (methods, properties)
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "class_body" {
                let mut body_cursor = child.walk();
                for member in child.children(&mut body_cursor) {
                    self.visit_node(member);
                }
            }
        }

        // Restore previous class context
        self.current_class = previous_class;
    }

    fn visit_interface(&mut self, node: Node) {
        let name = node
            .child_by_field_name("name")
            .map(|n| self.node_text(n))
            .unwrap_or_else(|| "AnonymousInterface".to_string());

        let interface = TraitEntity {
            name,
            visibility: "public".to_string(),
            line_start: node.start_position().row + 1,
            line_end: node.end_position().row + 1,
            required_methods: Vec::new(),
            parent_traits: Vec::new(),
            doc_comment: None,
            attributes: Vec::new(),
        };

        self.interfaces.push(interface);
    }

    fn visit_import(&mut self, node: Node) {
        // Extract the source (from 'react', './utils', etc.)
        let source = node
            .child_by_field_name("source")
            .map(|n| {
                let text = self.node_text(n);
                // Remove quotes from source
                text.trim_matches(|c| c == '"' || c == '\'').to_string()
            })
            .unwrap_or_default();

        let mut symbols = Vec::new();
        let mut alias = None;
        let mut is_wildcard = false;

        // Parse import_clause to extract specifiers
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "import_clause" {
                // Parse the import_clause
                let mut clause_cursor = child.walk();
                for clause_child in child.children(&mut clause_cursor) {
                    match clause_child.kind() {
                        // Default import: import React from 'react'
                        "identifier" => {
                            symbols.push(self.node_text(clause_child));
                        }
                        // Named imports: { useState, useEffect }
                        "named_imports" => {
                            symbols.extend(self.extract_named_imports(clause_child));
                        }
                        // Namespace import: * as Utils
                        "namespace_import" => {
                            is_wildcard = true;
                            // Extract the identifier after 'as'
                            let mut ns_cursor = clause_child.walk();
                            for ns_child in clause_child.children(&mut ns_cursor) {
                                if ns_child.kind() == "identifier" {
                                    alias = Some(self.node_text(ns_child));
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
        }

        let import = ImportRelation {
            importer: "current_module".to_string(),
            imported: source,
            symbols,
            is_wildcard,
            alias,
        };

        self.imports.push(import);
    }

    fn extract_named_imports(&self, node: Node) -> Vec<String> {
        let mut imports = Vec::new();
        let mut cursor = node.walk();

        for child in node.children(&mut cursor) {
            if child.kind() == "import_specifier" {
                // Handle both "name" and "name as alias" forms
                let mut spec_cursor = child.walk();
                for spec_child in child.children(&mut spec_cursor) {
                    if spec_child.kind() == "identifier" {
                        imports.push(self.node_text(spec_child));
                        break; // Only take the first identifier (the imported name, not the alias)
                    }
                }
            }
        }

        imports
    }

    fn extract_parameters(&self, params_node: Node) -> Vec<Parameter> {
        let mut parameters = Vec::new();
        let mut cursor = params_node.walk();

        for child in params_node.children(&mut cursor) {
            if child.kind() == "required_parameter" || child.kind() == "optional_parameter" {
                let name = child
                    .child_by_field_name("pattern")
                    .map(|n| self.node_text(n))
                    .unwrap_or_else(|| "param".to_string());

                let type_annotation = child.child_by_field_name("type").map(|n| self.node_text(n));

                parameters.push(Parameter {
                    name,
                    type_annotation,
                    default_value: None,
                    is_variadic: false,
                });
            }
        }

        parameters
    }

    /// Visit a call expression and extract the call relationship
    fn visit_call_expression(&mut self, node: Node) {
        // Only record calls if we're inside a function/method
        let caller = match &self.current_function {
            Some(name) => name.clone(),
            None => return,
        };

        // Extract the callee name from the call expression
        // call_expression has a "function" field that is the thing being called
        if let Some(function_node) = node.child_by_field_name("function") {
            let callee = self.extract_callee_name(function_node);

            // Skip empty or "this" only callees
            if callee.is_empty() || callee == "this" {
                return;
            }

            let call_site_line = node.start_position().row + 1;

            let call = CallRelation {
                caller: caller.clone(),
                callee,
                call_site_line,
                is_direct: true,
            };

            self.calls.push(call);
        }
    }

    /// Extract the callee name from a function node in a call expression
    fn extract_callee_name(&self, node: Node) -> String {
        match node.kind() {
            // Simple identifier: foo()
            "identifier" => self.node_text(node),

            // Member expression: this.foo(), obj.method()
            "member_expression" => {
                // Get the property (method name) from member expression
                if let Some(property) = node.child_by_field_name("property") {
                    self.node_text(property)
                } else {
                    self.node_text(node)
                }
            }

            // Optional chaining: this?.foo()
            "call_expression" => {
                // Nested call, e.g., getProvider()()
                if let Some(func) = node.child_by_field_name("function") {
                    self.extract_callee_name(func)
                } else {
                    String::new()
                }
            }

            // Await expression: await this.foo()
            "await_expression" => {
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    if child.kind() != "await" {
                        return self.extract_callee_name(child);
                    }
                }
                String::new()
            }

            _ => self.node_text(node),
        }
    }

    /// Calculate cyclomatic complexity for a function/method body
    fn calculate_complexity(&self, body: Node) -> ComplexityMetrics {
        let mut builder = ComplexityBuilder::new();
        self.calculate_complexity_recursive(body, &mut builder);
        builder.build()
    }

    /// Recursively calculate complexity from a tree-sitter node
    fn calculate_complexity_recursive(&self, node: Node, builder: &mut ComplexityBuilder) {
        match node.kind() {
            // Control flow - branches
            "if_statement" => {
                builder.add_branch();
                builder.enter_scope();
                // Process children
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.calculate_complexity_recursive(child, builder);
                }
                builder.exit_scope();
            }
            "else_clause" => {
                builder.add_branch();
                builder.enter_scope();
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.calculate_complexity_recursive(child, builder);
                }
                builder.exit_scope();
            }
            "switch_statement" => {
                builder.enter_scope();
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.calculate_complexity_recursive(child, builder);
                }
                builder.exit_scope();
            }
            "switch_case" | "switch_default" => {
                builder.add_branch();
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.calculate_complexity_recursive(child, builder);
                }
            }
            "ternary_expression" => {
                builder.add_branch();
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.calculate_complexity_recursive(child, builder);
                }
            }

            // Loops
            "for_statement" | "for_in_statement" | "for_of_statement" | "while_statement"
            | "do_statement" => {
                builder.add_loop();
                builder.enter_scope();
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.calculate_complexity_recursive(child, builder);
                }
                builder.exit_scope();
            }

            // Exception handling
            "try_statement" => {
                builder.enter_scope();
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.calculate_complexity_recursive(child, builder);
                }
                builder.exit_scope();
            }
            "catch_clause" => {
                builder.add_exception_handler();
                builder.enter_scope();
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.calculate_complexity_recursive(child, builder);
                }
                builder.exit_scope();
            }

            // Logical operators
            "binary_expression" => {
                // Check for && or ||
                if let Some(operator) = node.child_by_field_name("operator") {
                    let op_text = self.node_text(operator);
                    if op_text == "&&" || op_text == "||" {
                        builder.add_logical_operator();
                    }
                }
                // Process children
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.calculate_complexity_recursive(child, builder);
                }
            }

            // Optional chaining adds a path but doesn't add complexity per se
            "optional_chain_expression" => {
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.calculate_complexity_recursive(child, builder);
                }
            }

            // Nullish coalescing adds a branch-like path
            // Usually captured as binary_expression with ?? operator

            // Don't recurse into nested functions/arrows - they have their own complexity
            "function_declaration"
            | "function_expression"
            | "arrow_function"
            | "method_definition" => {
                // Skip nested functions - they are analyzed separately
            }

            // All other nodes - recurse into children
            _ => {
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    self.calculate_complexity_recursive(child, builder);
                }
            }
        }
    }
}

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

    #[test]
    fn test_visitor_basics() {
        let visitor = TypeScriptVisitor::new(b"test", ParserConfig::default());
        assert_eq!(visitor.functions.len(), 0);
        assert_eq!(visitor.classes.len(), 0);
    }

    #[test]
    fn test_visitor_function_parameters() {
        use tree_sitter::Parser;

        let source = b"function greet(name: string, age: number): void {}";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        assert_eq!(visitor.functions[0].name, "greet");
        assert_eq!(visitor.functions[0].parameters.len(), 2);
        assert_eq!(visitor.functions[0].parameters[0].name, "name");
        assert_eq!(visitor.functions[0].parameters[1].name, "age");
    }

    #[test]
    fn test_visitor_async_function_detection() {
        use tree_sitter::Parser;

        let source = b"async function loadData() { await fetch(); }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        assert!(visitor.functions[0].is_async);
    }

    #[test]
    fn test_visitor_class_context() {
        use tree_sitter::Parser;

        let source = b"class MyClass { myMethod() {} }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.classes.len(), 1);
        assert_eq!(visitor.classes[0].name, "MyClass");
        // Note: Method extraction not yet implemented
        // Visitor would need to match "method_definition" node type
    }

    #[test]
    fn test_visitor_interface_extraction() {
        use tree_sitter::Parser;

        let source = b"interface IPerson { name: string; age: number; }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.interfaces.len(), 1);
        assert_eq!(visitor.interfaces[0].name, "IPerson");
    }

    #[test]
    fn test_visitor_import_extraction() {
        use tree_sitter::Parser;

        let source = b"import { useState } from 'react';";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.imports.len(), 1);
    }

    #[test]
    fn test_visitor_named_imports() {
        use tree_sitter::Parser;

        let source = b"import { useState, useEffect } from 'react';";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.imports.len(), 1);
        assert_eq!(visitor.imports[0].imported, "react");
        assert_eq!(visitor.imports[0].symbols.len(), 2);
        assert_eq!(visitor.imports[0].symbols[0], "useState");
        assert_eq!(visitor.imports[0].symbols[1], "useEffect");
        assert!(!visitor.imports[0].is_wildcard);
    }

    #[test]
    fn test_visitor_default_import() {
        use tree_sitter::Parser;

        let source = b"import React from 'react';";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.imports.len(), 1);
        assert_eq!(visitor.imports[0].imported, "react");
        assert_eq!(visitor.imports[0].symbols.len(), 1);
        assert_eq!(visitor.imports[0].symbols[0], "React");
    }

    #[test]
    fn test_visitor_namespace_import() {
        use tree_sitter::Parser;

        let source = b"import * as Utils from './utils';";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.imports.len(), 1);
        assert_eq!(visitor.imports[0].imported, "./utils");
        assert!(visitor.imports[0].is_wildcard);
        assert_eq!(visitor.imports[0].alias, Some("Utils".to_string()));
    }

    #[test]
    fn test_visitor_side_effect_import() {
        use tree_sitter::Parser;

        let source = b"import './styles.css';";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.imports.len(), 1);
        assert_eq!(visitor.imports[0].imported, "./styles.css");
        assert_eq!(visitor.imports[0].symbols.len(), 0);
    }

    #[test]
    fn test_visitor_mixed_default_and_named_imports() {
        use tree_sitter::Parser;

        let source = b"import React, { useState, useEffect } from 'react';";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.imports.len(), 1);
        assert_eq!(visitor.imports[0].imported, "react");
        assert_eq!(visitor.imports[0].symbols.len(), 3);
        assert_eq!(visitor.imports[0].symbols[0], "React");
        assert_eq!(visitor.imports[0].symbols[1], "useState");
        assert_eq!(visitor.imports[0].symbols[2], "useEffect");
    }

    #[test]
    fn test_visitor_arrow_function_extraction() {
        use tree_sitter::Parser;

        let source = b"const func = () => { return 42; };";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        // Arrow functions should be extracted
        assert!(!visitor.functions.is_empty());
    }

    #[test]
    fn test_visitor_method_extraction() {
        use tree_sitter::Parser;

        let source = b"class Calculator { add(a: number, b: number): number { return a + b; } }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.classes.len(), 1);
        assert_eq!(visitor.classes[0].name, "Calculator");
        // Should extract method as a function with parent_class
        assert_eq!(visitor.functions.len(), 1);
        assert_eq!(visitor.functions[0].name, "add");
        assert_eq!(
            visitor.functions[0].parent_class,
            Some("Calculator".to_string())
        );
    }

    #[test]
    fn test_visitor_multiple_methods() {
        use tree_sitter::Parser;

        let source = b"class Math { add(a, b) { return a + b; } subtract(a, b) { return a - b; } multiply(a, b) { return a * b; } }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.classes.len(), 1);
        // Should extract all 3 methods
        assert_eq!(visitor.functions.len(), 3);
        assert_eq!(visitor.functions[0].name, "add");
        assert_eq!(visitor.functions[1].name, "subtract");
        assert_eq!(visitor.functions[2].name, "multiply");
        // All methods should have parent_class set
        assert!(visitor
            .functions
            .iter()
            .all(|f| f.parent_class == Some("Math".to_string())));
    }

    #[test]
    fn test_visitor_constructor_extraction() {
        use tree_sitter::Parser;

        let source = b"class Person { constructor(name: string) { this.name = name; } }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.classes.len(), 1);
        // Should extract constructor
        assert_eq!(visitor.functions.len(), 1);
        assert_eq!(visitor.functions[0].name, "constructor");
        assert_eq!(
            visitor.functions[0].parent_class,
            Some("Person".to_string())
        );
    }

    #[test]
    fn test_visitor_static_method() {
        use tree_sitter::Parser;

        let source = b"class Utils { static format(value: string): string { return value; } }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.classes.len(), 1);
        // Should extract static method
        assert_eq!(visitor.functions.len(), 1);
        assert_eq!(visitor.functions[0].name, "format");
        assert!(visitor.functions[0].is_static);
        assert_eq!(visitor.functions[0].parent_class, Some("Utils".to_string()));
    }

    #[test]
    fn test_visitor_call_extraction() {
        use tree_sitter::Parser;

        let source = b"function caller() { callee(); helper(); }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        assert_eq!(visitor.functions[0].name, "caller");

        // Should extract 2 call relationships
        assert_eq!(visitor.calls.len(), 2);
        assert_eq!(visitor.calls[0].caller, "caller");
        assert_eq!(visitor.calls[0].callee, "callee");
        assert_eq!(visitor.calls[1].caller, "caller");
        assert_eq!(visitor.calls[1].callee, "helper");
    }

    #[test]
    fn test_visitor_method_call_extraction() {
        use tree_sitter::Parser;

        let source = b"class MyClass { myMethod() { this.helper(); this.anotherMethod(); } }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.classes.len(), 1);
        assert_eq!(visitor.functions.len(), 1);
        assert_eq!(visitor.functions[0].name, "myMethod");

        // Should extract 2 call relationships (this.helper and this.anotherMethod)
        assert_eq!(visitor.calls.len(), 2);
        assert_eq!(visitor.calls[0].caller, "myMethod");
        assert_eq!(visitor.calls[0].callee, "helper");
        assert_eq!(visitor.calls[1].caller, "myMethod");
        assert_eq!(visitor.calls[1].callee, "anotherMethod");
    }

    #[test]
    fn test_visitor_async_call_extraction() {
        use tree_sitter::Parser;

        let source = b"async function fetchData() { await this.initialize(); const result = await this.getData(); }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        assert!(visitor.functions[0].is_async);

        // Should extract calls from await expressions
        assert!(visitor.calls.len() >= 2);
        let callee_names: Vec<&str> = visitor.calls.iter().map(|c| c.callee.as_str()).collect();
        assert!(callee_names.contains(&"initialize"));
        assert!(callee_names.contains(&"getData"));
    }

    // ==========================================
    // Complexity Tests
    // ==========================================

    #[test]
    fn test_complexity_simple_function() {
        use tree_sitter::Parser;

        let source = b"function simple() { return 1; }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        let complexity = visitor.functions[0].complexity.as_ref().unwrap();
        assert_eq!(complexity.cyclomatic_complexity, 1); // Base complexity
        assert_eq!(complexity.branches, 0);
        assert_eq!(complexity.loops, 0);
    }

    #[test]
    fn test_complexity_with_if_else() {
        use tree_sitter::Parser;

        let source = b"function check(x: number) { if (x > 0) { return 1; } else { return 0; } }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        let complexity = visitor.functions[0].complexity.as_ref().unwrap();
        assert_eq!(complexity.branches, 2); // if + else
        assert!(complexity.cyclomatic_complexity >= 2);
    }

    #[test]
    fn test_complexity_with_loops() {
        use tree_sitter::Parser;

        let source = b"function loop() { for (let i = 0; i < 10; i++) { console.log(i); } while (true) { break; } }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        let complexity = visitor.functions[0].complexity.as_ref().unwrap();
        assert_eq!(complexity.loops, 2); // for + while
        assert!(complexity.cyclomatic_complexity >= 3); // 1 + 2 loops
    }

    #[test]
    fn test_complexity_with_logical_operators() {
        use tree_sitter::Parser;

        let source = b"function check(a: boolean, b: boolean, c: boolean) { if (a && b || c) { return true; } return false; }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        let complexity = visitor.functions[0].complexity.as_ref().unwrap();
        assert_eq!(complexity.logical_operators, 2); // && and ||
        assert!(complexity.cyclomatic_complexity >= 4); // 1 + 1 branch + 2 logical ops
    }

    #[test]
    fn test_complexity_with_try_catch() {
        use tree_sitter::Parser;

        let source = b"function safe() { try { doSomething(); } catch (e) { console.error(e); } }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        let complexity = visitor.functions[0].complexity.as_ref().unwrap();
        assert_eq!(complexity.exception_handlers, 1); // catch
        assert!(complexity.cyclomatic_complexity >= 2);
    }

    #[test]
    fn test_complexity_with_switch() {
        use tree_sitter::Parser;

        let source = b"function grade(score: number) { switch (score) { case 90: return 'A'; case 80: return 'B'; default: return 'C'; } }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        let complexity = visitor.functions[0].complexity.as_ref().unwrap();
        assert_eq!(complexity.branches, 3); // case 90, case 80, default
        assert!(complexity.cyclomatic_complexity >= 4);
    }

    #[test]
    fn test_complexity_with_ternary() {
        use tree_sitter::Parser;

        let source = b"function abs(x: number) { return x >= 0 ? x : -x; }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        let complexity = visitor.functions[0].complexity.as_ref().unwrap();
        assert_eq!(complexity.branches, 1); // ternary
        assert!(complexity.cyclomatic_complexity >= 2);
    }

    #[test]
    fn test_complexity_nesting_depth() {
        use tree_sitter::Parser;

        let source = b"function nested(x: number) { if (x > 0) { if (x > 10) { if (x > 100) { return 3; } return 2; } return 1; } return 0; }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        let complexity = visitor.functions[0].complexity.as_ref().unwrap();
        assert_eq!(complexity.max_nesting_depth, 3); // 3 levels of if
        assert_eq!(complexity.branches, 3); // 3 if statements
    }

    #[test]
    fn test_complexity_grade() {
        use tree_sitter::Parser;

        // Simple function should get grade A
        let source = b"function simple() { return 1; }";
        let mut parser = Parser::new();
        parser
            .set_language(tree_sitter_typescript::language_typescript())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = TypeScriptVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        let complexity = visitor.functions[0].complexity.as_ref().unwrap();
        assert_eq!(complexity.grade(), 'A');
    }
}