codegraph-python 0.4.1

Python parser plugin for CodeGraph - extracts code entities and relationships from Python source files
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
//! AST extraction for Python source code using tree-sitter
//!
//! This module parses Python source code and extracts entities and relationships
//! into a CodeIR representation.

use crate::config::ParserConfig;
use crate::visitor::{extract_decorators, extract_docstring};
use codegraph_parser_api::{
    CallRelation, ClassEntity, CodeIR, ComplexityBuilder, ComplexityMetrics, FunctionEntity,
    ImportRelation, InheritanceRelation, ModuleEntity, Parameter,
};
use std::path::Path;
use tree_sitter::{Node, Parser};

/// Extract all entities and relationships from Python source code
pub fn extract(source: &str, file_path: &Path, config: &ParserConfig) -> Result<CodeIR, String> {
    // Initialize tree-sitter parser
    let mut parser = Parser::new();
    parser
        .set_language(tree_sitter_python::language())
        .map_err(|e| format!("Failed to set language: {e}"))?;

    // Parse the source code
    let tree = parser
        .parse(source, None)
        .ok_or_else(|| "Failed to parse".to_string())?;

    let root_node = tree.root_node();

    // Check for syntax errors
    if root_node.has_error() {
        // Find the first error node for better error reporting
        let mut cursor = root_node.walk();
        for child in root_node.children(&mut cursor) {
            if child.is_error() || child.has_error() {
                return Err(format!(
                    "Syntax error at line {}, column {}: {}",
                    child.start_position().row + 1,
                    child.start_position().column,
                    file_path.display()
                ));
            }
        }
        return Err(format!("Syntax error in {}", file_path.display()));
    }

    let source_bytes = source.as_bytes();

    let mut ir = CodeIR::new(file_path.to_path_buf());

    // Extract module entity
    let module_name = file_path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("module")
        .to_string();

    let line_count = source.lines().count();
    let module = ModuleEntity::new(
        module_name.clone(),
        file_path.display().to_string(),
        "python",
    )
    .with_line_count(line_count);
    ir.set_module(module);

    // Walk through top-level statements
    let mut cursor = root_node.walk();
    for child in root_node.children(&mut cursor) {
        match child.kind() {
            "function_definition" => {
                if let Some(func) = extract_function(source_bytes, child, config, None) {
                    // Extract calls from function body
                    let calls =
                        extract_calls_from_node(source_bytes, child, &func.name, func.line_start);
                    for call in calls {
                        ir.add_call(call);
                    }
                    ir.add_function(func);
                }
            }
            "decorated_definition" => {
                // Handle decorated functions/classes
                if let Some(definition) = find_definition_in_decorated(child) {
                    match definition.kind() {
                        "function_definition" => {
                            if let Some(func) =
                                extract_function(source_bytes, definition, config, None)
                            {
                                let calls = extract_calls_from_node(
                                    source_bytes,
                                    definition,
                                    &func.name,
                                    func.line_start,
                                );
                                for call in calls {
                                    ir.add_call(call);
                                }
                                ir.add_function(func);
                            }
                        }
                        "class_definition" => {
                            if let Some((class, methods, calls, inheritance)) =
                                extract_class(source_bytes, definition, config)
                            {
                                for method in methods {
                                    ir.add_function(method);
                                }
                                for call in calls {
                                    ir.add_call(call);
                                }
                                for inh in inheritance {
                                    ir.add_inheritance(inh);
                                }
                                ir.add_class(class);
                            }
                        }
                        _ => {}
                    }
                }
            }
            "class_definition" => {
                if let Some((class, methods, calls, inheritance)) =
                    extract_class(source_bytes, child, config)
                {
                    for method in methods {
                        ir.add_function(method);
                    }
                    for call in calls {
                        ir.add_call(call);
                    }
                    for inh in inheritance {
                        ir.add_inheritance(inh);
                    }
                    ir.add_class(class);
                }
            }
            "import_statement" => {
                let imports = extract_import(source_bytes, child, &module_name);
                for import in imports {
                    ir.add_import(import);
                }
            }
            "import_from_statement" => {
                let imports = extract_import_from(source_bytes, child, &module_name);
                for import in imports {
                    ir.add_import(import);
                }
            }
            _ => {}
        }
    }

    Ok(ir)
}

/// Find the actual function/class definition inside a decorated_definition
fn find_definition_in_decorated(node: Node) -> Option<Node> {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "function_definition" | "class_definition" => return Some(child),
            _ => {}
        }
    }
    None
}

/// Extract a function entity from a function_definition node
fn extract_function(
    source: &[u8],
    node: Node,
    config: &ParserConfig,
    parent_class: Option<&str>,
) -> Option<FunctionEntity> {
    let name = node
        .child_by_field_name("name")
        .map(|n| n.utf8_text(source).unwrap_or("unknown").to_string())?;

    // Skip private functions if configured
    // In Python: _private is private, __mangled is name-mangled private
    // But __init__, __str__ (dunder methods) should be kept as they're special methods
    let is_dunder = name.starts_with("__") && name.ends_with("__") && name.len() > 4;
    if !config.include_private && name.starts_with('_') && !is_dunder {
        return None;
    }

    // Skip test functions if configured
    if !config.include_tests && (name.starts_with("test_") || name.starts_with("Test")) {
        return None;
    }

    let line_start = node.start_position().row + 1;
    let line_end = node.end_position().row + 1;

    // Check for async
    let is_async = node
        .parent()
        .map(|p| p.kind() == "decorated_definition")
        .unwrap_or(false)
        || has_async_keyword(source, node);

    // Extract parameters
    let parameters = extract_parameters(source, node);

    // Extract return type
    let return_type = node
        .child_by_field_name("return_type")
        .map(|n| n.utf8_text(source).unwrap_or("").to_string());

    // Extract docstring from body
    let doc_comment = node
        .child_by_field_name("body")
        .and_then(|body| extract_docstring(source, body));

    // Check decorators for staticmethod/classmethod
    let decorators = if let Some(parent) = node.parent() {
        if parent.kind() == "decorated_definition" {
            extract_decorators(source, parent)
        } else {
            Vec::new()
        }
    } else {
        Vec::new()
    };

    let is_static = decorators.iter().any(|d| d.contains("staticmethod"));
    let is_test = decorators
        .iter()
        .any(|d| d.contains("test") || d.contains("pytest"));

    // Calculate complexity
    let complexity = node
        .child_by_field_name("body")
        .map(|body| calculate_complexity_from_node(source, body));

    let mut func = FunctionEntity::new(&name, line_start, line_end);
    func.parameters = parameters;
    func.return_type = return_type;
    func.doc_comment = doc_comment;
    func.is_async = is_async;
    func.is_static = is_static;
    func.is_test = is_test;
    func.complexity = complexity;

    if let Some(class_name) = parent_class {
        func.parent_class = Some(class_name.to_string());
    }

    Some(func)
}

/// Check if a function has async keyword
fn has_async_keyword(source: &[u8], node: Node) -> bool {
    // The function might be inside an async function definition
    if let Some(first_child) = node.child(0) {
        let text = first_child.utf8_text(source).unwrap_or("");
        return text == "async";
    }
    false
}

/// Extract parameters from a function's parameter list
fn extract_parameters(source: &[u8], node: Node) -> Vec<Parameter> {
    let mut params = Vec::new();

    if let Some(params_node) = node.child_by_field_name("parameters") {
        let mut cursor = params_node.walk();
        for child in params_node.children(&mut cursor) {
            match child.kind() {
                "identifier" => {
                    // Simple parameter: x
                    let name = child.utf8_text(source).unwrap_or("unknown").to_string();
                    params.push(Parameter {
                        name,
                        type_annotation: None,
                        default_value: None,
                        is_variadic: false,
                    });
                }
                "typed_parameter" => {
                    // Parameter with type: x: int
                    let name = child
                        .child_by_field_name("name")
                        .or_else(|| child.child(0))
                        .map(|n| n.utf8_text(source).unwrap_or("unknown").to_string())
                        .unwrap_or_else(|| "unknown".to_string());

                    let type_annotation = child
                        .child_by_field_name("type")
                        .map(|n| n.utf8_text(source).unwrap_or("").to_string());

                    params.push(Parameter {
                        name,
                        type_annotation,
                        default_value: None,
                        is_variadic: false,
                    });
                }
                "default_parameter" => {
                    // Parameter with default: x=1 or x: int = 1
                    let name = child
                        .child_by_field_name("name")
                        .or_else(|| child.child(0))
                        .map(|n| n.utf8_text(source).unwrap_or("unknown").to_string())
                        .unwrap_or_else(|| "unknown".to_string());

                    let type_annotation = child
                        .child_by_field_name("type")
                        .map(|n| n.utf8_text(source).unwrap_or("").to_string());

                    let default_value = child
                        .child_by_field_name("value")
                        .map(|n| n.utf8_text(source).unwrap_or("").to_string());

                    params.push(Parameter {
                        name,
                        type_annotation,
                        default_value,
                        is_variadic: false,
                    });
                }
                "typed_default_parameter" => {
                    // Parameter with type and default: x: int = 1
                    let name = child
                        .child_by_field_name("name")
                        .or_else(|| child.child(0))
                        .map(|n| n.utf8_text(source).unwrap_or("unknown").to_string())
                        .unwrap_or_else(|| "unknown".to_string());

                    let type_annotation = child
                        .child_by_field_name("type")
                        .map(|n| n.utf8_text(source).unwrap_or("").to_string());

                    let default_value = child
                        .child_by_field_name("value")
                        .map(|n| n.utf8_text(source).unwrap_or("").to_string());

                    params.push(Parameter {
                        name,
                        type_annotation,
                        default_value,
                        is_variadic: false,
                    });
                }
                "list_splat_pattern" | "dictionary_splat_pattern" => {
                    // *args or **kwargs
                    let name = child
                        .child(1)
                        .map(|n| n.utf8_text(source).unwrap_or("unknown").to_string())
                        .unwrap_or_else(|| "args".to_string());

                    params.push(Parameter {
                        name,
                        type_annotation: None,
                        default_value: None,
                        is_variadic: true,
                    });
                }
                _ => {}
            }
        }
    }

    params
}

/// Extract a class entity with its methods
fn extract_class(
    source: &[u8],
    node: Node,
    config: &ParserConfig,
) -> Option<(
    ClassEntity,
    Vec<FunctionEntity>,
    Vec<CallRelation>,
    Vec<InheritanceRelation>,
)> {
    let name = node
        .child_by_field_name("name")
        .map(|n| n.utf8_text(source).unwrap_or("Class").to_string())?;

    let line_start = node.start_position().row + 1;
    let line_end = node.end_position().row + 1;

    // Extract base classes
    let mut inheritance = Vec::new();
    if let Some(bases) = node.child_by_field_name("superclasses") {
        // The superclasses field is the argument_list directly
        let mut cursor = bases.walk();
        for child in bases.children(&mut cursor) {
            if let Some(base_name) = extract_base_class_name(source, child) {
                inheritance.push(InheritanceRelation::new(&name, base_name));
            }
        }
    }

    // Extract docstring
    let doc_comment = node
        .child_by_field_name("body")
        .and_then(|body| extract_docstring(source, body));

    // Extract methods and calls
    let mut methods = Vec::new();
    let mut calls = Vec::new();

    if let Some(body) = node.child_by_field_name("body") {
        let mut cursor = body.walk();
        for child in body.children(&mut cursor) {
            match child.kind() {
                "function_definition" => {
                    if let Some(method) = extract_function(source, child, config, Some(&name)) {
                        let method_qualified_name = format!("{}.{}", name, method.name);
                        let method_calls = extract_calls_from_node(
                            source,
                            child,
                            &method_qualified_name,
                            method.line_start,
                        );
                        calls.extend(method_calls);
                        methods.push(method);
                    }
                }
                "decorated_definition" => {
                    if let Some(definition) = find_definition_in_decorated(child) {
                        if definition.kind() == "function_definition" {
                            if let Some(method) =
                                extract_function(source, definition, config, Some(&name))
                            {
                                let method_qualified_name = format!("{}.{}", name, method.name);
                                let method_calls = extract_calls_from_node(
                                    source,
                                    definition,
                                    &method_qualified_name,
                                    method.line_start,
                                );
                                calls.extend(method_calls);
                                methods.push(method);
                            }
                        }
                    }
                }
                _ => {}
            }
        }
    }

    let mut class = ClassEntity::new(&name, line_start, line_end);
    class.doc_comment = doc_comment;
    class.methods = methods.clone();

    Some((class, methods, calls, inheritance))
}

/// Extract base class name from an argument node
fn extract_base_class_name(source: &[u8], node: Node) -> Option<String> {
    match node.kind() {
        "identifier" => Some(node.utf8_text(source).unwrap_or("").to_string()),
        "attribute" => {
            // Handle module.ClassName
            Some(node.utf8_text(source).unwrap_or("").to_string())
        }
        _ => None,
    }
}

/// Extract calls from a node (function body, class body, etc.)
fn extract_calls_from_node(
    source: &[u8],
    node: Node,
    caller_name: &str,
    line_offset: usize,
) -> Vec<CallRelation> {
    let mut calls = Vec::new();
    extract_calls_recursive(source, node, caller_name, line_offset, &mut calls);
    calls
}

fn extract_calls_recursive(
    source: &[u8],
    node: Node,
    caller_name: &str,
    line_offset: usize,
    calls: &mut Vec<CallRelation>,
) {
    if node.kind() == "call" {
        if let Some(func_node) = node.child_by_field_name("function") {
            let callee_name = extract_callee_name(source, func_node);
            if !callee_name.is_empty() {
                let call_line = node.start_position().row + 1;
                calls.push(CallRelation::new(caller_name, &callee_name, call_line));
            }
        }
    }

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        extract_calls_recursive(source, child, caller_name, line_offset, calls);
    }
}

/// Extract the callee name from a call's function node
fn extract_callee_name(source: &[u8], node: Node) -> String {
    match node.kind() {
        "identifier" => node.utf8_text(source).unwrap_or("").to_string(),
        "attribute" => {
            // Handle obj.method() or self.method()
            node.utf8_text(source).unwrap_or("").to_string()
        }
        _ => String::new(),
    }
}

/// Extract import statement
fn extract_import(source: &[u8], node: Node, importer: &str) -> Vec<ImportRelation> {
    let mut imports = Vec::new();
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if child.kind() == "dotted_name" || child.kind() == "aliased_import" {
            let module_name = if child.kind() == "aliased_import" {
                child
                    .child_by_field_name("name")
                    .map(|n| n.utf8_text(source).unwrap_or("").to_string())
            } else {
                Some(child.utf8_text(source).unwrap_or("").to_string())
            };

            let alias = if child.kind() == "aliased_import" {
                child
                    .child_by_field_name("alias")
                    .map(|n| n.utf8_text(source).unwrap_or("").to_string())
            } else {
                None
            };

            if let Some(module) = module_name {
                let mut import_rel = ImportRelation::new(importer, &module);
                if let Some(a) = alias {
                    import_rel = import_rel.with_alias(&a);
                }
                imports.push(import_rel);
            }
        }
    }

    imports
}

/// Extract from import statement
fn extract_import_from(source: &[u8], node: Node, importer: &str) -> Vec<ImportRelation> {
    let from_module = node
        .child_by_field_name("module_name")
        .map(|n| n.utf8_text(source).unwrap_or(".").to_string())
        .unwrap_or_else(|| ".".to_string());

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

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "wildcard_import" => {
                is_wildcard = true;
            }
            "dotted_name" | "identifier" => {
                // Skip the module name part
                if child.start_byte()
                    > node
                        .child_by_field_name("module_name")
                        .map_or(0, |n| n.end_byte())
                {
                    symbols.push(child.utf8_text(source).unwrap_or("").to_string());
                }
            }
            "aliased_import" => {
                if let Some(name_node) = child.child_by_field_name("name") {
                    symbols.push(name_node.utf8_text(source).unwrap_or("").to_string());
                }
            }
            _ => {}
        }
    }

    if is_wildcard {
        vec![ImportRelation::new(importer, &from_module).wildcard()]
    } else if !symbols.is_empty() {
        vec![ImportRelation::new(importer, &from_module).with_symbols(symbols)]
    } else {
        vec![ImportRelation::new(importer, &from_module)]
    }
}

/// Calculate complexity metrics from a function body node
fn calculate_complexity_from_node(source: &[u8], node: Node) -> ComplexityMetrics {
    let mut builder = ComplexityBuilder::new();
    calculate_complexity_recursive(source, node, &mut builder);
    builder.build()
}

fn calculate_complexity_recursive(source: &[u8], node: Node, builder: &mut ComplexityBuilder) {
    match node.kind() {
        "if_statement" => {
            builder.add_branch();
            builder.enter_scope();

            // Process if body
            if let Some(body) = node.child_by_field_name("consequence") {
                calculate_complexity_recursive(source, body, builder);
            }

            builder.exit_scope();

            // Process elif/else
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                match child.kind() {
                    "elif_clause" => {
                        builder.add_branch();
                        builder.enter_scope();
                        if let Some(body) = child.child_by_field_name("consequence") {
                            calculate_complexity_recursive(source, body, builder);
                        }
                        builder.exit_scope();
                    }
                    "else_clause" => {
                        builder.add_branch();
                        builder.enter_scope();
                        if let Some(body) = child.child_by_field_name("body") {
                            calculate_complexity_recursive(source, body, builder);
                        }
                        builder.exit_scope();
                    }
                    _ => {}
                }
            }

            // Check for logical operators in condition
            if let Some(condition) = node.child_by_field_name("condition") {
                count_logical_operators(source, condition, builder);
            }
        }
        "while_statement" => {
            builder.add_loop();
            builder.enter_scope();

            if let Some(body) = node.child_by_field_name("body") {
                calculate_complexity_recursive(source, body, builder);
            }

            builder.exit_scope();

            // Check condition for logical operators
            if let Some(condition) = node.child_by_field_name("condition") {
                count_logical_operators(source, condition, builder);
            }
        }
        "for_statement" => {
            builder.add_loop();
            builder.enter_scope();

            if let Some(body) = node.child_by_field_name("body") {
                calculate_complexity_recursive(source, body, builder);
            }

            builder.exit_scope();
        }
        "with_statement" => {
            builder.enter_scope();

            if let Some(body) = node.child_by_field_name("body") {
                calculate_complexity_recursive(source, body, builder);
            }

            builder.exit_scope();
        }
        "try_statement" => {
            builder.enter_scope();

            if let Some(body) = node.child_by_field_name("body") {
                calculate_complexity_recursive(source, body, builder);
            }

            builder.exit_scope();

            // Count exception handlers
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "except_clause" {
                    builder.add_exception_handler();
                    builder.enter_scope();
                    let mut except_cursor = child.walk();
                    for except_child in child.children(&mut except_cursor) {
                        if except_child.kind() == "block" {
                            calculate_complexity_recursive(source, except_child, builder);
                        }
                    }
                    builder.exit_scope();
                } else if child.kind() == "finally_clause" {
                    builder.enter_scope();
                    let mut finally_cursor = child.walk();
                    for finally_child in child.children(&mut finally_cursor) {
                        if finally_child.kind() == "block" {
                            calculate_complexity_recursive(source, finally_child, builder);
                        }
                    }
                    builder.exit_scope();
                }
            }
        }
        "match_statement" => {
            // Each match case adds a branch
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "case_clause" {
                    builder.add_branch();
                    builder.enter_scope();
                    if let Some(body) = child.child_by_field_name("consequence") {
                        calculate_complexity_recursive(source, body, builder);
                    }
                    builder.exit_scope();
                }
            }
        }
        "boolean_operator" => {
            // 'and' or 'or' operators
            builder.add_logical_operator();
        }
        "conditional_expression" => {
            // Ternary: a if condition else b
            builder.add_branch();
        }
        "list_comprehension"
        | "set_comprehension"
        | "dictionary_comprehension"
        | "generator_expression" => {
            // Comprehensions with conditions
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "for_in_clause" {
                    builder.add_loop();
                }
                if child.kind() == "if_clause" {
                    builder.add_branch();
                }
            }
        }
        _ => {}
    }

    // Recurse into children (except for already handled cases)
    if !matches!(
        node.kind(),
        "if_statement" | "while_statement" | "for_statement" | "try_statement" | "match_statement"
    ) {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            calculate_complexity_recursive(source, child, builder);
        }
    }
}

fn count_logical_operators(source: &[u8], node: Node, builder: &mut ComplexityBuilder) {
    if node.kind() == "boolean_operator" {
        builder.add_logical_operator();
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        count_logical_operators(source, child, builder);
    }
}

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

    #[test]
    fn test_code_ir_new() {
        let path = Path::new("test.py");
        let ir = CodeIR::new(path.to_path_buf());
        assert_eq!(ir.entity_count(), 0);
        assert_eq!(ir.relationship_count(), 0);
    }

    #[test]
    fn test_extract_simple_function() {
        let source = r#"
def greet(name):
    print(f"Hello, {name}")
    return name.upper()
"#;
        let path = Path::new("test.py");
        let config = ParserConfig::default();
        let ir = extract(source, path, &config).unwrap();

        assert_eq!(ir.functions.len(), 1);
        assert_eq!(ir.functions[0].name, "greet");
        assert_eq!(ir.functions[0].line_start, 2);
    }

    #[test]
    fn test_extract_class_with_methods() {
        let source = r#"
class Calculator:
    def add(self, a, b):
        return a + b

    def multiply(self, a, b):
        return a * b
"#;
        let path = Path::new("test.py");
        let config = ParserConfig::default();
        let ir = extract(source, path, &config).unwrap();

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

    #[test]
    fn test_extract_calls() {
        let source = r#"
def main():
    greet("World")
    result = greet("Alice")

def greet(name):
    print(f"Hello, {name}")
"#;
        let path = Path::new("test.py");
        let config = ParserConfig::default();
        let ir = extract(source, path, &config).unwrap();

        assert_eq!(ir.functions.len(), 2);
        assert!(ir.calls.len() >= 2, "Should find at least 2 calls");
    }

    #[test]
    fn test_extract_imports() {
        let source = r#"
import os
import sys
from pathlib import Path
from typing import List, Dict
from collections import *

def main():
    pass
"#;
        let path = Path::new("test.py");
        let config = ParserConfig::default();
        let ir = extract(source, path, &config).unwrap();

        assert!(
            ir.imports.len() >= 4,
            "Should find at least 4 import statements"
        );
    }

    #[test]
    fn test_extract_inheritance() {
        let source = r#"
class Animal:
    def move(self):
        pass

class Dog(Animal):
    def bark(self):
        pass
"#;
        let path = Path::new("test.py");
        let config = ParserConfig::default();
        let ir = extract(source, path, &config).unwrap();

        assert_eq!(ir.classes.len(), 2);
        assert_eq!(ir.inheritance.len(), 1);
        assert_eq!(ir.inheritance[0].child, "Dog");
        assert_eq!(ir.inheritance[0].parent, "Animal");
    }

    #[test]
    fn test_complexity_simple_function() {
        let source = r#"
def simple():
    return 1
"#;
        let path = Path::new("test.py");
        let config = ParserConfig::default();
        let ir = extract(source, path, &config).unwrap();

        assert_eq!(ir.functions.len(), 1);
        let func = &ir.functions[0];
        assert!(func.complexity.is_some());
        let complexity = func.complexity.as_ref().unwrap();
        assert_eq!(complexity.cyclomatic_complexity, 1);
    }

    #[test]
    fn test_complexity_with_branches() {
        let source = r#"
def branching(x):
    if x > 0:
        return 1
    elif x < 0:
        return -1
    else:
        return 0
"#;
        let path = Path::new("test.py");
        let config = ParserConfig::default();
        let ir = extract(source, path, &config).unwrap();

        assert_eq!(ir.functions.len(), 1);
        let func = &ir.functions[0];
        let complexity = func.complexity.as_ref().unwrap();
        assert!(complexity.branches >= 3);
    }

    #[test]
    fn test_complexity_with_loops() {
        let source = r#"
def loopy(items):
    total = 0
    for item in items:
        while item > 0:
            total += 1
            item -= 1
    return total
"#;
        let path = Path::new("test.py");
        let config = ParserConfig::default();
        let ir = extract(source, path, &config).unwrap();

        assert_eq!(ir.functions.len(), 1);
        let func = &ir.functions[0];
        let complexity = func.complexity.as_ref().unwrap();
        assert_eq!(complexity.loops, 2);
    }

    #[test]
    fn test_complexity_with_logical_operators() {
        let source = r#"
def complex_condition(a, b, c):
    if a > 0 and b > 0 or c > 0:
        return True
    return False
"#;
        let path = Path::new("test.py");
        let config = ParserConfig::default();
        let ir = extract(source, path, &config).unwrap();

        assert_eq!(ir.functions.len(), 1);
        let func = &ir.functions[0];
        let complexity = func.complexity.as_ref().unwrap();
        assert!(complexity.logical_operators >= 2);
    }

    #[test]
    fn test_complexity_with_try_except() {
        let source = r#"
def risky():
    try:
        result = dangerous_operation()
    except ValueError:
        result = 0
    except TypeError:
        result = -1
    return result
"#;
        let path = Path::new("test.py");
        let config = ParserConfig::default();
        let ir = extract(source, path, &config).unwrap();

        assert_eq!(ir.functions.len(), 1);
        let func = &ir.functions[0];
        let complexity = func.complexity.as_ref().unwrap();
        assert_eq!(complexity.exception_handlers, 2);
    }

    #[test]
    fn test_accurate_line_numbers() {
        let source = "def first():\n    pass\n\ndef second():\n    pass";
        let path = Path::new("test.py");
        let config = ParserConfig::default();
        let ir = extract(source, path, &config).unwrap();

        assert_eq!(ir.functions.len(), 2);
        assert_eq!(ir.functions[0].name, "first");
        assert_eq!(ir.functions[0].line_start, 1);
        assert_eq!(ir.functions[1].name, "second");
        assert_eq!(ir.functions[1].line_start, 4);
    }

    #[test]
    fn test_async_function() {
        let source = r#"
async def fetch_data():
    return "data"
"#;
        let path = Path::new("test.py");
        let config = ParserConfig::default();
        let ir = extract(source, path, &config).unwrap();

        assert_eq!(ir.functions.len(), 1);
        // Note: async detection depends on tree-sitter grammar details
    }
}