sqry-lang-python 8.0.4

python language plugin for sqry
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
//! Local scope tracking and reference resolution for Python.
//!
//! Python's scoping model (LEGB: Local, Enclosing, Global, Built-in) differs
//! significantly from block-scoped languages:
//!
//! - **No block scope**: `if`, `for`, `while`, `try`, `with` do NOT create scopes.
//!   Variables bind to the enclosing function/module scope.
//! - **Assignment = declaration**: `x = 5` both declares and assigns. There is no
//!   `let`/`var` keyword.
//! - **`global`/`nonlocal`**: Pre-pass collects these to exclude names from local binding.
//! - **Comprehension scope**: Python 3 comprehension/generator variables are scoped
//!   to the comprehension expression.
//! - **Class scope**: NOT accessible in nested functions (only via `self`).
//! - **Walrus operator**: `:=` creates binding in enclosing function scope, NOT
//!   comprehension scope.

use std::collections::HashSet;

use sqry_core::graph::local_scopes::{self, ResolutionOutcome, ScopeId, ScopeKindTrait, ScopeTree};
use sqry_core::graph::unified::build::helper::GraphBuildHelper;
use sqry_core::graph::{GraphResult, Span};
use tree_sitter::Node;

// ============================================================================
// Python-specific ScopeKind
// ============================================================================

/// Python scope kinds.
///
/// Only functions, lambdas, classes, comprehensions, and the module create
/// variable scopes. Block statements (`if`/`for`/`while`/`try`/`with`) do NOT
/// create scopes — variables bind to the nearest enclosing function or module.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(crate) enum ScopeKind {
    /// Module scope (implicit top-level).
    Module,
    /// Function body (`def foo(): ...`).
    Function,
    /// Lambda expression (`lambda x: x + 1`).
    Lambda,
    /// Class body (`class Foo: ...`).
    ///
    /// Class scopes are NOT accessible from nested functions — they act as
    /// a boundary. Variables in a class body are only accessible within the
    /// class body itself, not in nested `def` blocks.
    Class,
    /// Comprehension/generator scope.
    ///
    /// In Python 3, the iteration variable of a comprehension is scoped to
    /// the comprehension expression. The walrus operator (`:=`) does NOT
    /// bind in the comprehension scope but in the enclosing function scope.
    Comprehension,
}

impl ScopeKindTrait for ScopeKind {
    fn is_class_scope(&self) -> bool {
        *self == ScopeKind::Class
    }

    fn is_overlap_boundary(&self) -> bool {
        *self == ScopeKind::Class
    }

    fn allows_nested_shadowing(&self) -> bool {
        true // Python allows reassignment / shadowing freely
    }
}

/// Type alias for the Python-specialized scope tree.
pub(crate) type PythonScopeTree = ScopeTree<ScopeKind>;

// ============================================================================
// Build pipeline
// ============================================================================

/// Build a scope tree for a Python source file.
pub(crate) fn build(root: Node, content: &[u8]) -> GraphResult<PythonScopeTree> {
    let content_len = content.len();
    let mut tree = PythonScopeTree::new(content_len);

    let mut guard = local_scopes::load_recursion_guard();

    // Phase 0: Create module scope for the entire file
    let module_scope = tree.add_scope(ScopeKind::Module, 0, content_len, None);

    // Phase 1: Build scopes (functions, classes, comprehensions)
    build_scopes_recursive(&mut tree, root, content, module_scope, &mut guard)?;
    tree.rebuild_index();

    // Phase 2: Bind declarations (assignments, for-loop variables, parameters, etc.)
    bind_declarations_recursive(&mut tree, root, content, &mut guard)?;
    tree.rebuild_index();

    Ok(tree)
}

// ============================================================================
// Phase 1: Build scopes
// ============================================================================

#[allow(clippy::only_used_in_recursion)]
fn build_scopes_recursive(
    tree: &mut PythonScopeTree,
    node: Node,
    content: &[u8],
    current_scope: Option<ScopeId>,
    guard: &mut sqry_core::query::security::RecursionGuard,
) -> GraphResult<()> {
    guard
        .enter()
        .map_err(|e| local_scopes::recursion_error_to_graph_error(&e, node))?;

    let new_scope = match node.kind() {
        "function_definition" => {
            // `def foo():` or `async def foo():`
            tree.add_scope(
                ScopeKind::Function,
                node.start_byte(),
                node.end_byte(),
                current_scope,
            )
        }
        "lambda" => {
            // `lambda x: x + 1`
            tree.add_scope(
                ScopeKind::Lambda,
                node.start_byte(),
                node.end_byte(),
                current_scope,
            )
        }
        "class_definition" => {
            // `class Foo:`
            tree.add_scope(
                ScopeKind::Class,
                node.start_byte(),
                node.end_byte(),
                current_scope,
            )
        }
        "list_comprehension"
        | "set_comprehension"
        | "dictionary_comprehension"
        | "generator_expression" => tree.add_scope(
            ScopeKind::Comprehension,
            node.start_byte(),
            node.end_byte(),
            current_scope,
        ),
        _ => None,
    };

    let scope_for_children = new_scope.or(current_scope);

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        build_scopes_recursive(tree, child, content, scope_for_children, guard)?;
    }

    guard.exit();
    Ok(())
}

// ============================================================================
// Phase 2: Bind declarations
// ============================================================================

fn bind_declarations_recursive(
    tree: &mut PythonScopeTree,
    node: Node,
    content: &[u8],
    guard: &mut sqry_core::query::security::RecursionGuard,
) -> GraphResult<()> {
    guard
        .enter()
        .map_err(|e| local_scopes::recursion_error_to_graph_error(&e, node))?;

    match node.kind() {
        "function_definition" => {
            // Bind parameters to the function scope
            bind_parameters(tree, node, content);
        }
        "lambda" => {
            // Bind lambda parameters
            bind_lambda_parameters(tree, node, content);
        }
        "for_statement" => {
            // `for x in iterable:` — bind x to enclosing function/module scope
            bind_for_variable(tree, node, content);
        }
        "expression_statement" => {
            // Check for assignment inside expression_statement
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "assignment" {
                    bind_assignment(tree, child, content);
                }
            }
        }
        "assignment" => {
            // Direct assignment (may appear outside expression_statement in some contexts)
            bind_assignment(tree, node, content);
        }
        "named_expression" => {
            // Walrus operator: `(x := expr)` — binds to enclosing function scope
            bind_walrus(tree, node, content);
        }
        "except_clause" => {
            // `except Exception as e:` — bind e to enclosing function scope
            bind_except_variable(tree, node, content);
        }
        "with_statement" => {
            // `with expr as x:` — bind x to enclosing function scope
            bind_with_variable(tree, node, content);
        }
        "for_in_clause" => {
            // Comprehension variable: `for x in iterable`
            // Bind to the comprehension scope
            bind_comprehension_variable(tree, node, content);
        }
        _ => {}
    }

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        bind_declarations_recursive(tree, child, content, guard)?;
    }

    guard.exit();
    Ok(())
}

// ============================================================================
// Binding helpers
// ============================================================================

/// Bind function parameters to the function's scope.
fn bind_parameters(tree: &mut PythonScopeTree, func_node: Node, content: &[u8]) {
    let Some(params_node) = func_node.child_by_field_name("parameters") else {
        return;
    };

    let Some(scope_id) = tree.innermost_scope_at(func_node.start_byte()) else {
        return;
    };

    for param in params_node.children(&mut params_node.walk()) {
        match param.kind() {
            "identifier" => {
                // Simple parameter: `def foo(x):`
                bind_identifier_param(tree, scope_id, param, content);
            }
            "typed_parameter" => {
                // Typed parameter: `def foo(x: int):`
                // The name is either in the "name" field or as a direct identifier child
                if let Some(name_node) = param.child_by_field_name("name") {
                    bind_identifier_param(tree, scope_id, name_node, content);
                } else {
                    // Check for identifier child (for *args, **kwargs patterns)
                    let mut cursor = param.walk();
                    for child in param.children(&mut cursor) {
                        if child.kind() == "identifier" {
                            bind_identifier_param(tree, scope_id, child, content);
                            break;
                        }
                        if child.kind() == "list_splat_pattern"
                            || child.kind() == "dictionary_splat_pattern"
                        {
                            if let Some(id) = local_scopes::first_child_of_kind(child, "identifier")
                            {
                                bind_identifier_param(tree, scope_id, id, content);
                            }
                            break;
                        }
                    }
                }
            }
            "default_parameter" => {
                // Default parameter: `def foo(x=5):`
                if let Some(name_node) = param.child_by_field_name("name") {
                    bind_identifier_param(tree, scope_id, name_node, content);
                }
            }
            "typed_default_parameter" => {
                // Typed default: `def foo(x: int = 5):`
                if let Some(name_node) = param.child_by_field_name("name") {
                    bind_identifier_param(tree, scope_id, name_node, content);
                }
            }
            "list_splat_pattern" => {
                // *args pattern
                if let Some(id) = local_scopes::first_child_of_kind(param, "identifier") {
                    bind_identifier_param(tree, scope_id, id, content);
                }
            }
            "dictionary_splat_pattern" => {
                // **kwargs pattern
                if let Some(id) = local_scopes::first_child_of_kind(param, "identifier") {
                    bind_identifier_param(tree, scope_id, id, content);
                }
            }
            _ => {}
        }
    }
}

/// Bind lambda parameters to the lambda's scope.
fn bind_lambda_parameters(tree: &mut PythonScopeTree, lambda_node: Node, content: &[u8]) {
    let Some(params_node) = lambda_node.child_by_field_name("parameters") else {
        return;
    };

    let Some(scope_id) = tree.innermost_scope_at(lambda_node.start_byte()) else {
        return;
    };

    // Lambda parameters use `lambda_parameters` node type
    for param in params_node.children(&mut params_node.walk()) {
        match param.kind() {
            "identifier" => {
                bind_identifier_param(tree, scope_id, param, content);
            }
            "default_parameter" => {
                if let Some(name_node) = param.child_by_field_name("name") {
                    bind_identifier_param(tree, scope_id, name_node, content);
                }
            }
            "list_splat_pattern" | "dictionary_splat_pattern" => {
                if let Some(id) = local_scopes::first_child_of_kind(param, "identifier") {
                    bind_identifier_param(tree, scope_id, id, content);
                }
            }
            _ => {}
        }
    }
}

/// Bind a single identifier as a parameter.
fn bind_identifier_param(
    tree: &mut PythonScopeTree,
    scope_id: ScopeId,
    name_node: Node,
    content: &[u8],
) {
    let Ok(name) = name_node.utf8_text(content) else {
        return;
    };
    let name = name.trim();
    if name.is_empty() || name == "self" || name == "cls" {
        return;
    }
    tree.add_binding(
        scope_id,
        name,
        name_node.start_byte(),
        name_node.end_byte(),
        name_node.end_byte(), // parameters have no initializer
        None,
    );
}

/// Bind assignment targets.
///
/// In Python, `x = expr` both declares and assigns. The left-hand side
/// can be a simple identifier, a tuple/list pattern, or an attribute/subscript
/// (which we skip — not local variable declarations).
fn bind_assignment(tree: &mut PythonScopeTree, assignment_node: Node, content: &[u8]) {
    let Some(left) = assignment_node.child_by_field_name("left") else {
        return;
    };

    // Find the enclosing function scope (NOT class or comprehension scope).
    // In Python, assignments bind to the nearest enclosing function/module scope.
    let Some(scope_id) = find_binding_scope(tree, assignment_node.start_byte()) else {
        return;
    };

    // Determine initializer start byte for self-reference prevention
    let init_start = assignment_node
        .child_by_field_name("right")
        .map(|r| r.start_byte());

    bind_pattern(tree, scope_id, left, content, init_start, assignment_node);
}

/// Bind for-loop variables.
///
/// `for x in iterable:` — binds x to the enclosing function/module scope
/// (NOT a new scope, since Python has no block scoping).
fn bind_for_variable(tree: &mut PythonScopeTree, for_node: Node, content: &[u8]) {
    let Some(left) = for_node.child_by_field_name("left") else {
        return;
    };

    // For loop variables bind to enclosing function scope
    let Some(scope_id) = find_binding_scope(tree, for_node.start_byte()) else {
        return;
    };

    bind_pattern(tree, scope_id, left, content, None, for_node);
}

/// Bind walrus operator target.
///
/// `(x := expr)` binds to the enclosing function scope, even when inside
/// a comprehension (unlike regular assignment which would bind to the
/// comprehension scope in list/dict/set comprehensions).
fn bind_walrus(tree: &mut PythonScopeTree, walrus_node: Node, content: &[u8]) {
    let Some(name_node) = walrus_node.child_by_field_name("name") else {
        return;
    };

    // Walrus binds to enclosing function/module scope, skipping comprehensions
    let Some(scope_id) = find_function_scope(tree, walrus_node.start_byte()) else {
        return;
    };

    let Ok(name) = name_node.utf8_text(content) else {
        return;
    };
    let name = name.trim();
    if name.is_empty() {
        return;
    }

    let init_start = walrus_node
        .child_by_field_name("value")
        .map(|v| v.start_byte());

    tree.add_binding(
        scope_id,
        name,
        name_node.start_byte(),
        name_node.end_byte(),
        walrus_node.end_byte(),
        init_start,
    );
}

/// Bind except clause variable (`except Exception as e:`)
///
/// tree-sitter-python AST structure:
/// ```text
/// except_clause
///   except
///   as_pattern
///     identifier (exception type, e.g., "ValueError")
///     as
///     as_pattern_target
///       identifier (binding name, e.g., "e")
///   :
///   block
/// ```
fn bind_except_variable(tree: &mut PythonScopeTree, except_node: Node, content: &[u8]) {
    let mut cursor = except_node.walk();
    for child in except_node.children(&mut cursor) {
        if child.kind() == "as_pattern" {
            // Find the as_pattern_target child
            let mut inner_cursor = child.walk();
            for inner_child in child.children(&mut inner_cursor) {
                if inner_child.kind() == "as_pattern_target" {
                    if let Some(id) = local_scopes::first_child_of_kind(inner_child, "identifier") {
                        let Some(scope_id) = find_binding_scope(tree, except_node.start_byte())
                        else {
                            return;
                        };
                        let Ok(name) = id.utf8_text(content) else {
                            return;
                        };
                        let name = name.trim();
                        if !name.is_empty() {
                            tree.add_binding(
                                scope_id,
                                name,
                                id.start_byte(),
                                id.end_byte(),
                                id.end_byte(),
                                None,
                            );
                        }
                    }
                    return;
                }
            }
        }
    }
}

/// Bind with-statement variable (`with expr as x:`)
///
/// tree-sitter-python AST structure:
/// ```text
/// with_statement
///   with
///   with_clause
///     with_item
///       as_pattern
///         call (the context manager expression)
///         as
///         as_pattern_target
///           identifier (binding name, e.g., "f")
///   :
///   block
/// ```
fn bind_with_variable(tree: &mut PythonScopeTree, with_node: Node, content: &[u8]) {
    let mut cursor = with_node.walk();
    for child in with_node.children(&mut cursor) {
        if child.kind() == "with_clause" {
            let mut clause_cursor = child.walk();
            for item in child.children(&mut clause_cursor) {
                if item.kind() == "with_item" {
                    bind_with_item(tree, item, content, with_node.start_byte());
                }
            }
        }
    }
}

/// Bind a single `with_item`'s `as` target via `as_pattern` → `as_pattern_target`.
fn bind_with_item(tree: &mut PythonScopeTree, item: Node, content: &[u8], context_byte: usize) {
    let mut cursor = item.walk();
    for child in item.children(&mut cursor) {
        if child.kind() == "as_pattern" {
            let mut inner_cursor = child.walk();
            for inner_child in child.children(&mut inner_cursor) {
                if inner_child.kind() == "as_pattern_target" {
                    let Some(scope_id) = find_binding_scope(tree, context_byte) else {
                        return;
                    };
                    // as_pattern_target contains an identifier or pattern
                    if let Some(id) = local_scopes::first_child_of_kind(inner_child, "identifier") {
                        let Ok(name) = id.utf8_text(content) else {
                            return;
                        };
                        let name = name.trim();
                        if !name.is_empty() {
                            tree.add_binding(
                                scope_id,
                                name,
                                id.start_byte(),
                                id.end_byte(),
                                id.end_byte(),
                                None,
                            );
                        }
                    } else {
                        // Tuple pattern in as target
                        bind_pattern(tree, scope_id, inner_child, content, None, inner_child);
                    }
                    return;
                }
            }
        }
    }
}

/// Bind comprehension iteration variable.
///
/// `for x in iterable` inside a comprehension — binds to the comprehension scope.
fn bind_comprehension_variable(tree: &mut PythonScopeTree, for_in_node: Node, content: &[u8]) {
    // for_in_clause has a "left" field with the iteration variable(s)
    let Some(left) = for_in_node.child_by_field_name("left") else {
        return;
    };

    // Comprehension variables bind to the comprehension scope itself
    let Some(scope_id) = tree.innermost_scope_at(for_in_node.start_byte()) else {
        return;
    };

    bind_pattern(tree, scope_id, left, content, None, for_in_node);
}

// ============================================================================
// Pattern binding — handles destructuring
// ============================================================================

/// Bind identifiers from a pattern (LHS of assignment/for).
///
/// Handles:
/// - `identifier` — simple variable
/// - `pattern_list` / `tuple_pattern` — tuple unpacking: `a, b = ...`
/// - `list_pattern` — list unpacking: `[a, b] = ...`
/// - `*rest` — star expressions in unpacking
fn bind_pattern(
    tree: &mut PythonScopeTree,
    scope_id: ScopeId,
    pattern: Node,
    content: &[u8],
    init_start: Option<usize>,
    declarator_node: Node,
) {
    match pattern.kind() {
        "identifier" => {
            let Ok(name) = pattern.utf8_text(content) else {
                return;
            };
            let name = name.trim();
            // Skip _ wildcard and special names
            if name.is_empty() || name == "_" {
                return;
            }
            tree.add_binding(
                scope_id,
                name,
                pattern.start_byte(),
                pattern.end_byte(),
                declarator_node.end_byte(),
                init_start,
            );
        }
        "pattern_list" | "tuple_pattern" | "list_pattern" => {
            // Tuple/list unpacking: `a, b = ...` or `[a, b] = ...`
            let mut cursor = pattern.walk();
            for child in pattern.children(&mut cursor) {
                bind_pattern(tree, scope_id, child, content, init_start, declarator_node);
            }
        }
        "list_splat_pattern" => {
            // `*rest` in unpacking
            if let Some(id) = local_scopes::first_child_of_kind(pattern, "identifier") {
                let Ok(name) = id.utf8_text(content) else {
                    return;
                };
                let name = name.trim();
                if !name.is_empty() && name != "_" {
                    tree.add_binding(
                        scope_id,
                        name,
                        id.start_byte(),
                        id.end_byte(),
                        declarator_node.end_byte(),
                        init_start,
                    );
                }
            }
        }
        _ => {
            // attribute, subscript, etc. — not local variable bindings, skip
        }
    }
}

// ============================================================================
// Scope finding helpers
// ============================================================================

/// Find the scope where a variable should be bound.
///
/// In Python, variables bind to the nearest enclosing function, lambda, or module scope.
/// Class and comprehension scopes are skipped for regular assignments (but NOT for
/// comprehension iteration variables, which bind to the comprehension scope).
fn find_binding_scope(tree: &PythonScopeTree, byte: usize) -> Option<ScopeId> {
    let innermost = tree.innermost_scope_at(byte)?;
    let chain = tree.scope_chain(innermost);

    for scope_id in &chain {
        let kind = tree.scopes[*scope_id].kind;
        match kind {
            ScopeKind::Function | ScopeKind::Lambda | ScopeKind::Module => {
                return Some(*scope_id);
            }
            ScopeKind::Class | ScopeKind::Comprehension => {
                // Skip — assignments don't bind here
            }
        }
    }
    None
}

/// Find the nearest enclosing function/module scope, skipping both
/// class AND comprehension scopes.
///
/// Used for walrus operator (`:=`) which explicitly skips comprehension scopes.
fn find_function_scope(tree: &PythonScopeTree, byte: usize) -> Option<ScopeId> {
    let innermost = tree.innermost_scope_at(byte)?;
    let chain = tree.scope_chain(innermost);

    for scope_id in &chain {
        let kind = tree.scopes[*scope_id].kind;
        match kind {
            ScopeKind::Function | ScopeKind::Lambda | ScopeKind::Module => {
                return Some(*scope_id);
            }
            ScopeKind::Class | ScopeKind::Comprehension => {}
        }
    }
    None
}

// ============================================================================
// Identifier resolution — handle_identifier_for_reference
// ============================================================================

/// Handle an identifier node for potential local variable reference.
///
/// Called from the graph builder's walker for each `"identifier"` node.
/// Creates a `Variable` node and `References` edge if the identifier resolves
/// to a local variable or parameter.
pub(crate) fn handle_identifier_for_reference(
    node: Node,
    content: &[u8],
    scope_tree: &mut PythonScopeTree,
    helper: &mut GraphBuildHelper,
) {
    let Ok(name) = node.utf8_text(content) else {
        return;
    };
    let name = name.trim();

    // Skip empty, wildcard, self/cls, and common built-in names
    if name.is_empty() || name == "_" || name == "self" || name == "cls" {
        return;
    }

    // Skip if in a non-reference context
    if is_declaration_context(node) {
        return;
    }
    if is_decorator_or_import_context(node) {
        return;
    }
    if is_call_context(node) {
        return;
    }
    if is_attribute_access(node) {
        return;
    }
    if is_type_annotation_context(node) {
        return;
    }
    if !is_inside_scope(node) {
        return;
    }

    // Try to resolve the identifier
    let usage_byte = node.start_byte();
    match scope_tree.resolve_identifier(usage_byte, name) {
        ResolutionOutcome::Local(binding) => {
            let span = Span::from_bytes(node.start_byte(), node.end_byte());
            let qualified_name = format!("{}@{}", name, binding.decl_start_byte);
            let var_id = helper.add_variable(&qualified_name, Some(span));

            if let Some(decl_id) = binding.node_id {
                helper.add_reference_edge(var_id, decl_id);
            } else {
                // Create declaration node if not yet attached
                let decl_span = Span::from_bytes(binding.decl_start_byte, binding.decl_end_byte);
                let decl_id = helper.add_variable(&qualified_name, Some(decl_span));
                scope_tree.attach_node_id(name, binding.decl_start_byte, decl_id);
                helper.add_reference_edge(var_id, decl_id);
            }
        }
        ResolutionOutcome::Member { .. }
        | ResolutionOutcome::Ambiguous
        | ResolutionOutcome::NoMatch => {}
    }
}

// ============================================================================
// Context filters — prevent false positive References edges
// ============================================================================

/// Check if the identifier is in a declaration/definition context.
///
/// Returns `true` for identifiers that ARE the declaration, not a usage:
/// - Function/class name being defined
/// - Assignment left-hand side target
/// - For-loop variable
/// - Parameter name in definition
#[allow(clippy::match_same_arms)] // Arms separated for documentation clarity; each pattern is semantically distinct
fn is_declaration_context(node: Node) -> bool {
    let Some(parent) = node.parent() else {
        return false;
    };

    match parent.kind() {
        // Function or class name being defined
        "function_definition" | "class_definition" => parent
            .child_by_field_name("name")
            .is_some_and(|n| n.id() == node.id()),
        // Assignment LHS: `x = 5` — the `x` is a declaration
        "assignment" | "augmented_assignment" => parent
            .child_by_field_name("left")
            .is_some_and(|left| contains_node(left, node)),
        // For-loop variable
        "for_statement" => parent
            .child_by_field_name("left")
            .is_some_and(|left| contains_node(left, node)),
        // Walrus operator name
        "named_expression" => parent
            .child_by_field_name("name")
            .is_some_and(|n| n.id() == node.id()),
        // Parameter names
        "typed_parameter" | "typed_default_parameter" | "default_parameter" => parent
            .child_by_field_name("name")
            .is_some_and(|n| n.id() == node.id()),
        #[allow(clippy::match_same_arms)]
        // Arms separated by AST node type for documentation clarity
        // Plain parameter identifier (not wrapped in typed_parameter)
        "parameters" | "lambda_parameters" => true,
        // Pattern list elements (e.g., `a, b = pair` — the `a` and `b`)
        "pattern_list" | "tuple_pattern" | "list_pattern" => {
            // Check if the grandparent is an assignment/for LHS
            if let Some(grandparent) = parent.parent() {
                match grandparent.kind() {
                    "assignment" | "augmented_assignment" => grandparent
                        .child_by_field_name("left")
                        .is_some_and(|left| contains_node(left, node)),
                    "for_statement" => grandparent
                        .child_by_field_name("left")
                        .is_some_and(|left| contains_node(left, node)),
                    _ => false,
                }
            } else {
                false
            }
        }
        // Splat patterns in assignments
        "list_splat_pattern" | "dictionary_splat_pattern" => true,
        // Comprehension iteration variable
        "for_in_clause" => parent
            .child_by_field_name("left")
            .is_some_and(|left| contains_node(left, node)),
        // Global/nonlocal declarations
        "global_statement" | "nonlocal_statement" => true,
        // as_pattern_target (except clause `as` binding target)
        "as_pattern_target" => true,
        _ => false,
    }
}

/// Check if the identifier is in a decorator or import context.
fn is_decorator_or_import_context(node: Node) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "decorator" | "import_statement" | "import_from_statement" | "aliased_import" => {
                return true;
            }
            "function_definition" | "class_definition" | "module" => {
                return false;
            }
            _ => current = parent.parent(),
        }
    }
    false
}

/// Check if the identifier is a function/method call target.
///
/// `foo()` — the `foo` is a call target, not a variable reference.
fn is_call_context(node: Node) -> bool {
    let Some(parent) = node.parent() else {
        return false;
    };
    if parent.kind() == "call" {
        return parent
            .child_by_field_name("function")
            .is_some_and(|f| f.id() == node.id());
    }
    false
}

/// Check if the identifier is the attribute part of a member access.
///
/// `obj.attr` — the `attr` is member access, not a local variable reference.
/// But `obj` IS a reference (it could be a local variable).
fn is_attribute_access(node: Node) -> bool {
    let Some(parent) = node.parent() else {
        return false;
    };
    if parent.kind() == "attribute" {
        // `attribute` node has `object` and `attribute` fields.
        // The `attribute` field (right side) is NOT a local variable reference.
        // The `object` field (left side) IS a potential reference.
        return parent
            .child_by_field_name("attribute")
            .is_some_and(|a| a.id() == node.id());
    }
    false
}

/// Check if the identifier is in a type annotation context.
///
/// Type annotations reference types, not local variables:
/// - `x: int` → `int` is a type
/// - `def foo(x: str):` → `str` is a type
/// - `-> int` → `int` is a type
fn is_type_annotation_context(node: Node) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "type" => return true,
            // Type annotation field in various contexts
            "assignment" | "typed_parameter" | "typed_default_parameter" => {
                if parent
                    .child_by_field_name("type")
                    .is_some_and(|t| contains_node(t, node))
                {
                    return true;
                }
                return false;
            }
            // Return type annotation
            "function_definition" => {
                if parent
                    .child_by_field_name("return_type")
                    .is_some_and(|r| contains_node(r, node))
                {
                    return true;
                }
                return false;
            }
            _ => current = parent.parent(),
        }
    }
    false
}

/// Check if the identifier is inside a function, class, or module scope.
///
/// We only track identifiers inside scope-creating constructs.
fn is_inside_scope(node: Node) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "function_definition" | "class_definition" | "lambda" | "module" => return true,
            _ => current = parent.parent(),
        }
    }
    false
}

// ============================================================================
// Utility helpers
// ============================================================================

/// Check if a node contains another node (by ID).
fn contains_node(haystack: Node, needle: Node) -> bool {
    if haystack.id() == needle.id() {
        return true;
    }
    let mut cursor = haystack.walk();
    for child in haystack.children(&mut cursor) {
        if contains_node(child, needle) {
            return true;
        }
    }
    false
}

/// Collect `global` and `nonlocal` names in a function scope.
///
/// These names should NOT be treated as local variables — they refer
/// to variables in outer scopes.
#[allow(dead_code)] // Reserved for future enhanced resolution
fn collect_global_nonlocal_names(func_body: Node, content: &[u8]) -> HashSet<String> {
    let mut names = HashSet::new();
    collect_global_nonlocal_recursive(func_body, content, &mut names);
    names
}

fn collect_global_nonlocal_recursive(node: Node, content: &[u8], names: &mut HashSet<String>) {
    match node.kind() {
        "global_statement" | "nonlocal_statement" => {
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "identifier"
                    && let Ok(name) = child.utf8_text(content)
                {
                    names.insert(name.to_string());
                }
            }
        }
        // Don't recurse into nested functions — they have their own global/nonlocal
        "function_definition" | "class_definition" | "lambda" => {}
        _ => {
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                collect_global_nonlocal_recursive(child, content, names);
            }
        }
    }
}