brokk-bifrost-python 0.10.8

Python language knowledge for brokk-bifrost: module identity, declarations, imports, and usage-graph resolution
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
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
use tree_sitter::Node;

use brokk_bifrost_core::hash::{HashMap, HashSet};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PythonLexicalNameResolution {
    Unbound,
    Local,
    Nonlocal,
    Global,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PythonDirectScopeBindingKind {
    ClassDeclaration,
    Other,
}

/// Whether `reference` reads a target introduced by an enclosing comprehension.
///
/// Comprehensions create an implicit scope even at module level. The element
/// expression is textually before its `for` clauses but evaluates after their
/// binders, while a clause's own iterable evaluates before that clause binds
/// its target. This structured walk models that ordering without source-text
/// parsing.
pub fn python_comprehension_binds_name_at(name: &str, reference: Node<'_>, source: &str) -> bool {
    let mut current = reference;
    while let Some(parent) = current.parent() {
        if is_comprehension(parent.kind()) {
            let mut cursor = parent.walk();
            for clause in parent
                .named_children(&mut cursor)
                .filter(|child| child.kind() == "for_in_clause")
            {
                let Some(target) = clause.child_by_field_name("left") else {
                    continue;
                };
                let mut bound = false;
                let _ = collect_binding_targets(target, source, &mut || true, |candidate, _| {
                    bound |= candidate == name;
                });
                if !bound {
                    continue;
                }
                let inside_own_iterable =
                    clause.child_by_field_name("right").is_some_and(|right| {
                        right.start_byte() <= reference.start_byte()
                            && reference.end_byte() <= right.end_byte()
                    });
                if !inside_own_iterable {
                    return true;
                }
            }
        }
        if matches!(
            parent.kind(),
            "function_definition" | "lambda" | "class_definition" | "module"
        ) {
            break;
        }
        current = parent;
    }
    false
}

/// Whether `reference` reads a PEP 695 type parameter declared by its enclosing
/// class, function, or type-alias definition.
///
/// Type parameters are lexical bindings rather than indexed workspace
/// declarations. The binder is the first identifier in each structured
/// parameter node; identifiers in bounds and constraints remain references.
pub fn python_type_parameter_binds_name_at(name: &str, reference: Node<'_>, source: &str) -> bool {
    let mut current = reference;
    let mut enclosing_functions = Vec::new();
    while let Some(parent) = current.parent() {
        if parent.kind() == "function_definition" {
            enclosing_functions.push(parent);
        }
        if matches!(
            parent.kind(),
            "class_definition" | "function_definition" | "type_alias_statement"
        ) && let Some(parameters) = parent.child_by_field_name("type_parameters")
            && !(parameters.start_byte() <= reference.start_byte()
                && reference.end_byte() <= parameters.end_byte())
        {
            let mut cursor = parameters.walk();
            for parameter in parameters.named_children(&mut cursor) {
                let binder = if parameter.kind() == "identifier" {
                    Some(parameter)
                } else {
                    first_identifier_bounded(parameter, &mut || true).flatten()
                };
                if binder.is_some_and(|binder| node_text(binder, source) == name) {
                    // Only a name that actually matched an enclosing type
                    // parameter needs the function-wide directive scans. This
                    // keeps the hot-path check for ordinary identifiers a
                    // bounded ancestor walk with no scope-inventory builds.
                    return !python_name_declared_global_at_in_functions(
                        name,
                        reference,
                        source,
                        enclosing_functions,
                    );
                }
            }
        }
        current = parent;
    }
    false
}

/// Resolve `name` through the nearest enclosing function scope. This is the
/// structured fallback for references inside nested functions that do not
/// have their own indexed `CodeUnit` scope snapshot.
pub fn python_name_resolution_at(
    name: &str,
    reference: Node<'_>,
    source: &str,
) -> PythonLexicalNameResolution {
    let mut functions = Vec::new();
    let mut current = reference;
    while let Some(parent) = current.parent() {
        if parent.kind() == "function_definition" {
            functions.push(parent);
        }
        current = parent;
    }
    python_name_resolution_at_in_functions(name, reference, source, functions)
}

fn python_name_declared_global_at_in_functions(
    name: &str,
    reference: Node<'_>,
    source: &str,
    functions: Vec<Node<'_>>,
) -> bool {
    python_name_resolution_at_in_functions(name, reference, source, functions)
        == PythonLexicalNameResolution::Global
}

fn python_name_resolution_at_in_functions(
    name: &str,
    reference: Node<'_>,
    source: &str,
    functions: Vec<Node<'_>>,
) -> PythonLexicalNameResolution {
    for function in functions {
        let parameter_names = function
            .child_by_field_name("parameters")
            .into_iter()
            .flat_map(|parameters| {
                let mut cursor = parameters.walk();
                parameters
                    .named_children(&mut cursor)
                    .filter_map(|parameter| python_parameter_name(parameter, source))
                    .collect::<Vec<_>>()
            })
            .collect::<Vec<_>>();
        let Some(inventory) =
            PythonLexicalScopeInventory::collect_bounded(function, source, parameter_names, || {
                true
            })
        else {
            return PythonLexicalNameResolution::Unbound;
        };
        let resolution = inventory.name_resolution_at(name, reference);
        match resolution {
            PythonLexicalNameResolution::Global => return PythonLexicalNameResolution::Global,
            PythonLexicalNameResolution::Local | PythonLexicalNameResolution::Nonlocal => {
                return resolution;
            }
            PythonLexicalNameResolution::Unbound => {}
        }
    }
    PythonLexicalNameResolution::Unbound
}

fn python_parameter_name(node: Node<'_>, source: &str) -> Option<String> {
    match node.kind() {
        "identifier" => Some(node_text(node, source).trim().to_string()),
        "typed_parameter"
        | "typed_default_parameter"
        | "default_parameter"
        | "list_splat_pattern"
        | "dictionary_splat_pattern" => node
            .child_by_field_name("name")
            .or_else(|| {
                let mut cursor = node.walk();
                node.named_children(&mut cursor)
                    .find(|child| child.kind() == "identifier")
            })
            .and_then(|name| python_parameter_name(name, source)),
        _ => None,
    }
    .filter(|name| !name.is_empty())
}

/// Whether this identifier is the binder (rather than a bound/constraint use)
/// of one structured PEP 695 type parameter.
pub fn python_is_type_parameter_binder(node: Node<'_>) -> bool {
    if node.kind() != "identifier" {
        return false;
    }
    let mut current = node;
    while let Some(parent) = current.parent() {
        if matches!(
            parent.kind(),
            "class_definition" | "function_definition" | "type_alias_statement"
        ) && let Some(parameters) = parent.child_by_field_name("type_parameters")
            && parameters.start_byte() <= node.start_byte()
            && node.end_byte() <= parameters.end_byte()
        {
            let mut cursor = parameters.walk();
            return parameters.named_children(&mut cursor).any(|parameter| {
                let binder = if parameter.kind() == "identifier" {
                    Some(parameter)
                } else {
                    first_identifier_bounded(parameter, &mut || true).flatten()
                };
                binder.is_some_and(|binder| binder.id() == node.id())
            });
        }
        if matches!(
            parent.kind(),
            "module" | "class_definition" | "function_definition" | "type_alias_statement"
        ) {
            return false;
        }
        current = parent;
    }
    false
}

#[derive(Clone, Copy, Debug)]
pub struct PythonDirectScopeBinding<'tree> {
    pub declaration: Node<'tree>,
    pub kind: PythonDirectScopeBindingKind,
}

#[derive(Clone, Debug)]
struct PythonLocalBinding<'tree> {
    name: Box<str>,
    declaration: Node<'tree>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PythonLocalBindingKind {
    FunctionOnly,
    Other,
}

#[derive(Clone, Debug)]
struct PythonComprehensionBinding {
    name: Box<str>,
    start_byte: usize,
    end_byte: usize,
    enclosing_iterable_ranges: Vec<(usize, usize)>,
}

/// Function-scope Python bindings discovered from tree-sitter structure.
///
/// The inventory models Python's whole-function symbol-table behavior while
/// retaining the implicit scope of comprehension targets. Construction is
/// iterative and every inspected node is gated by `scope_step`; `None` means
/// the caller stopped discovery and must conservatively avoid module fallback.
pub struct PythonLexicalScopeInventory<'tree> {
    parameters: HashSet<Box<str>>,
    locals: Vec<PythonLocalBinding<'tree>>,
    local_names: HashMap<Box<str>, PythonLocalBindingKind>,
    binding_writes: HashSet<Box<str>>,
    globals: HashSet<Box<str>>,
    nonlocals: HashSet<Box<str>>,
    comprehensions: Vec<PythonComprehensionBinding>,
}

#[derive(Clone, Copy)]
struct ScanFrame<'tree> {
    node: Node<'tree>,
    in_comprehension: bool,
}

impl<'tree> PythonLexicalScopeInventory<'tree> {
    /// `parameter_names` is the callable's formal-parameter name stream. The
    /// layout it comes from is resolved by `analyzer/lexical_definitions.rs`,
    /// which dispatches through the analysis-side language registry and so
    /// cannot be named here; `analyzer/python/lexical_scope.rs` in
    /// `brokk-bifrost-analysis` is the one caller that computes it, under the
    /// same `scope_step` meter this walk uses.
    pub fn collect_bounded(
        callable: Node<'tree>,
        source: &str,
        parameter_names: impl IntoIterator<Item = String>,
        mut scope_step: impl FnMut() -> bool,
    ) -> Option<Self> {
        let mut inventory = Self {
            parameters: parameter_names.into_iter().map(Box::<str>::from).collect(),
            locals: Vec::new(),
            local_names: HashMap::default(),
            binding_writes: HashSet::default(),
            globals: HashSet::default(),
            nonlocals: HashSet::default(),
            comprehensions: Vec::new(),
        };
        let Some(body) = callable.child_by_field_name("body") else {
            return Some(inventory);
        };
        let mut stack = vec![ScanFrame {
            node: body,
            in_comprehension: false,
        }];

        while let Some(frame) = stack.pop() {
            if !scope_step() {
                return None;
            }
            let node = frame.node;
            let nested_scope = node != body
                && matches!(
                    node.kind(),
                    "function_definition" | "lambda" | "class_definition"
                );
            if nested_scope {
                if matches!(node.kind(), "function_definition" | "class_definition")
                    && let Some(name) = node.child_by_field_name("name")
                {
                    inventory.record_local_node(name, source);
                }
                // Defaults, annotations, bases, and type-parameter expressions
                // execute in an enclosing scope. Keep scanning those headers
                // for walrus/comprehension bindings while pruning the nested
                // callable or class body itself.
                push_nested_scope_header_children(
                    &mut stack,
                    node,
                    frame.in_comprehension,
                    &mut scope_step,
                )?;
                continue;
            }

            match node.kind() {
                "global_statement" => {
                    collect_direct_identifier_names(node, source, &mut scope_step, |name| {
                        inventory.globals.insert(name.into());
                    })?;
                    continue;
                }
                "nonlocal_statement" => {
                    collect_direct_identifier_names(node, source, &mut scope_step, |name| {
                        inventory.nonlocals.insert(name.into());
                    })?;
                    continue;
                }
                "import_statement" | "import_from_statement" => {
                    collect_import_bindings(node, &mut scope_step, |binding| {
                        inventory.record_local_node(binding, source)
                    })?;
                    continue;
                }
                "assignment" | "augmented_assignment" => {
                    if let Some(target) = node.child_by_field_name("left") {
                        collect_binding_targets(
                            target,
                            source,
                            &mut scope_step,
                            |name, declaration| {
                                inventory.record_binding_write(name, declaration);
                            },
                        )?;
                    }
                }
                "type_alias_statement" => {
                    if let Some(target) = node.child_by_field_name("left")
                        && let Some(binding) = first_identifier_bounded(target, &mut scope_step)?
                    {
                        inventory.record_local_node(binding, source);
                    }
                }
                "named_expression" => {
                    // PEP 572 binds a comprehension walrus in the containing
                    // non-comprehension scope, so this remains a function local.
                    if let Some(target) = node.child_by_field_name("name") {
                        collect_binding_targets(
                            target,
                            source,
                            &mut scope_step,
                            |name, declaration| {
                                inventory.record_binding_write(name, declaration);
                            },
                        )?;
                    }
                }
                "for_statement" => {
                    if let Some(target) = node.child_by_field_name("left") {
                        collect_binding_targets(
                            target,
                            source,
                            &mut scope_step,
                            |name, declaration| {
                                inventory.record_binding_write(name, declaration);
                            },
                        )?;
                    }
                }
                "for_in_clause" => {
                    // These occur inside comprehensions and belong to their
                    // implicit scope. The enclosing comprehension records them.
                }
                "delete_statement" => {
                    for target in named_children_bounded(node, &mut scope_step)? {
                        collect_binding_targets(
                            target,
                            source,
                            &mut scope_step,
                            |name, declaration| {
                                inventory.record_binding_write(name, declaration);
                            },
                        )?;
                    }
                    continue;
                }
                "as_pattern" => {
                    if let Some(alias) = node.child_by_field_name("alias") {
                        collect_binding_targets(
                            alias,
                            source,
                            &mut scope_step,
                            |name, declaration| {
                                inventory.record_binding_write(name, declaration);
                            },
                        )?;
                        push_named_children_except(
                            &mut stack,
                            node,
                            alias,
                            frame.in_comprehension,
                            &mut scope_step,
                        )?;
                        continue;
                    }
                }
                "except_clause" => {
                    // Older grammar shapes expose the alias directly. Current
                    // tree-sitter-python nests it in an `as_pattern`, handled
                    // above when the clause's children are scanned.
                    if let Some(alias) = node.child_by_field_name("alias") {
                        collect_binding_targets(
                            alias,
                            source,
                            &mut scope_step,
                            |name, declaration| {
                                inventory.record_binding_write(name, declaration);
                            },
                        )?;
                    }
                }
                "case_clause" => {
                    let children = named_children_bounded(node, &mut scope_step)?;
                    for child in children.iter().copied() {
                        if child.kind() == "case_pattern" {
                            collect_match_pattern_bindings(
                                child,
                                source,
                                &mut scope_step,
                                |name, declaration| {
                                    inventory.record_binding_write(name, declaration);
                                },
                            )?;
                        }
                    }
                    for child in children.into_iter().rev() {
                        if child.kind() != "case_pattern" {
                            stack.push(ScanFrame {
                                node: child,
                                in_comprehension: frame.in_comprehension,
                            });
                        }
                    }
                    continue;
                }
                kind if is_comprehension(kind) => {
                    let range = (node.start_byte(), node.end_byte());
                    let children = named_children_bounded(node, &mut scope_step)?;
                    let enclosing_iterable_ranges = if let Some(first_clause) = children
                        .iter()
                        .copied()
                        .find(|child| child.kind() == "for_in_clause")
                    {
                        children_by_field_name_bounded(first_clause, "right", &mut scope_step)?
                            .into_iter()
                            .map(|iterable| (iterable.start_byte(), iterable.end_byte()))
                            .collect()
                    } else {
                        Vec::new()
                    };
                    for clause in children
                        .iter()
                        .copied()
                        .filter(|child| child.kind() == "for_in_clause")
                    {
                        if let Some(target) = clause.child_by_field_name("left") {
                            collect_binding_targets(target, source, &mut scope_step, |name, _| {
                                inventory.comprehensions.push(PythonComprehensionBinding {
                                    name: name.into(),
                                    start_byte: range.0,
                                    end_byte: range.1,
                                    enclosing_iterable_ranges: enclosing_iterable_ranges.clone(),
                                });
                            })?;
                        }
                    }
                    for child in children.into_iter().rev() {
                        stack.push(ScanFrame {
                            node: child,
                            in_comprehension: true,
                        });
                    }
                    continue;
                }
                _ => {}
            }

            push_named_children(&mut stack, node, frame.in_comprehension, &mut scope_step)?;
        }

        // `global` and `nonlocal` are whole-function directives regardless of
        // source order. Neither declaration may become a semantic local.
        inventory.locals.retain(|binding| {
            !inventory.globals.contains(binding.name.as_ref())
                && !inventory.nonlocals.contains(binding.name.as_ref())
        });
        inventory.local_names.retain(|name, _| {
            !inventory.globals.contains(name.as_ref())
                && !inventory.nonlocals.contains(name.as_ref())
        });
        Some(inventory)
    }

    pub fn name_resolution_at(
        &self,
        name: &str,
        reference: Node<'_>,
    ) -> PythonLexicalNameResolution {
        let reference_byte = reference.start_byte();
        if self.comprehensions.iter().any(|binding| {
            binding.name.as_ref() == name
                && binding.start_byte <= reference_byte
                && reference_byte < binding.end_byte
                && !binding
                    .enclosing_iterable_ranges
                    .iter()
                    .any(|(start, end)| *start <= reference_byte && reference_byte < *end)
        }) {
            return PythonLexicalNameResolution::Local;
        }
        if self.nonlocals.contains(name) {
            return PythonLexicalNameResolution::Nonlocal;
        }
        if self.globals.contains(name) {
            return PythonLexicalNameResolution::Global;
        }
        if self.parameters.contains(name) || self.local_names.contains_key(name) {
            PythonLexicalNameResolution::Local
        } else {
            PythonLexicalNameResolution::Unbound
        }
    }

    pub fn resolves_to_local_function(&self, name: &str, reference: Node<'_>) -> bool {
        let reference_byte = reference.start_byte();
        !self.parameters.contains(name)
            && !self.comprehensions.iter().any(|binding| {
                binding.name.as_ref() == name
                    && binding.start_byte <= reference_byte
                    && reference_byte < binding.end_byte
                    && !binding
                        .enclosing_iterable_ranges
                        .iter()
                        .any(|(start, end)| *start <= reference_byte && reference_byte < *end)
            })
            && self.local_names.get(name) == Some(&PythonLocalBindingKind::FunctionOnly)
    }

    /// Whether the active callable obtains `name` from a runtime binding
    /// rather than an untouched function or import declaration.
    pub fn has_runtime_callable_binding_at(&self, name: &str, reference: Node<'_>) -> bool {
        let reference_byte = reference.start_byte();
        self.parameters.contains(name)
            || self.binding_writes.contains(name)
            || self.comprehensions.iter().any(|binding| {
                binding.name.as_ref() == name
                    && binding.start_byte <= reference_byte
                    && reference_byte < binding.end_byte
                    && !binding
                        .enclosing_iterable_ranges
                        .iter()
                        .any(|(start, end)| *start <= reference_byte && reference_byte < *end)
            })
    }

    pub fn local_function_declaration(
        &self,
        name: &str,
        reference: Node<'_>,
    ) -> Option<Node<'tree>> {
        self.resolves_to_local_function(name, reference)
            .then(|| {
                self.locals
                    .iter()
                    .find(|binding| binding.name.as_ref() == name)
                    .and_then(|binding| binding.declaration.parent())
                    .filter(|declaration| declaration.kind() == "function_definition")
            })
            .flatten()
    }

    pub fn local_bindings(&self) -> impl Iterator<Item = (&str, Node<'tree>)> + '_ {
        self.locals
            .iter()
            .map(|binding| (binding.name.as_ref(), binding.declaration))
    }

    fn record_local_node(&mut self, node: Node<'tree>, source: &str) {
        let name = node_text(node, source);
        self.record_local(name, node);
    }

    fn record_local(&mut self, name: &str, declaration: Node<'tree>) {
        if name.is_empty() {
            return;
        }
        let binding_kind = if is_function_declaration_name(declaration) {
            PythonLocalBindingKind::FunctionOnly
        } else {
            PythonLocalBindingKind::Other
        };
        match self.local_names.entry(name.into()) {
            std::collections::hash_map::Entry::Vacant(entry) => {
                entry.insert(binding_kind);
                self.locals.push(PythonLocalBinding {
                    name: name.into(),
                    declaration,
                });
            }
            std::collections::hash_map::Entry::Occupied(mut entry) => {
                entry.insert(PythonLocalBindingKind::Other);
            }
        }
    }

    fn record_binding_write(&mut self, name: &str, declaration: Node<'tree>) {
        if !name.is_empty() {
            self.binding_writes.insert(name.into());
        }
        self.record_local(name, declaration);
    }
}

fn is_function_declaration_name(node: Node<'_>) -> bool {
    node.parent().is_some_and(|parent| {
        parent.kind() == "function_definition"
            && parent
                .child_by_field_name("name")
                .is_some_and(|name| name.id() == node.id())
    })
}

/// Return the bindings introduced directly by `node`.
///
/// Descendant traversal remains the caller's responsibility. This lets the
/// semantic file walk build a module binding inventory without adding a
/// second whole-file scan, while reusing the same structured target handling
/// as function symbol-table discovery.
pub fn python_direct_scope_bindings_bounded<'tree>(
    node: Node<'tree>,
    source: &str,
    mut scope_step: impl FnMut() -> bool,
) -> Option<Vec<PythonDirectScopeBinding<'tree>>> {
    let mut bindings = Vec::new();

    match node.kind() {
        "function_definition" => {
            if let Some(name) = node.child_by_field_name("name") {
                bindings.push(PythonDirectScopeBinding {
                    declaration: name,
                    kind: PythonDirectScopeBindingKind::Other,
                });
            }
        }
        "class_definition" => {
            if let Some(name) = node.child_by_field_name("name") {
                bindings.push(PythonDirectScopeBinding {
                    declaration: name,
                    kind: if is_direct_module_definition_bounded(node, &mut scope_step)? {
                        PythonDirectScopeBindingKind::ClassDeclaration
                    } else {
                        PythonDirectScopeBindingKind::Other
                    },
                });
            }
        }
        "import_statement" | "import_from_statement" => {
            collect_import_bindings(node, &mut scope_step, |declaration| {
                bindings.push(PythonDirectScopeBinding {
                    declaration,
                    kind: PythonDirectScopeBindingKind::Other,
                });
            })?;
        }
        "assignment" | "augmented_assignment" => {
            if let Some(target) = node.child_by_field_name("left") {
                collect_binding_targets(target, source, &mut scope_step, |_, declaration| {
                    bindings.push(PythonDirectScopeBinding {
                        declaration,
                        kind: PythonDirectScopeBindingKind::Other,
                    });
                })?;
            }
        }
        "type_alias_statement" => {
            if let Some(target) = node.child_by_field_name("left")
                && let Some(declaration) = first_identifier_bounded(target, &mut scope_step)?
            {
                bindings.push(PythonDirectScopeBinding {
                    declaration,
                    kind: PythonDirectScopeBindingKind::Other,
                });
            }
        }
        "named_expression" => {
            if let Some(target) = node.child_by_field_name("name") {
                collect_binding_targets(target, source, &mut scope_step, |_, declaration| {
                    bindings.push(PythonDirectScopeBinding {
                        declaration,
                        kind: PythonDirectScopeBindingKind::Other,
                    });
                })?;
            }
        }
        "for_statement" => {
            if let Some(target) = node.child_by_field_name("left") {
                collect_binding_targets(target, source, &mut scope_step, |_, declaration| {
                    bindings.push(PythonDirectScopeBinding {
                        declaration,
                        kind: PythonDirectScopeBindingKind::Other,
                    });
                })?;
            }
        }
        "delete_statement" => {
            for target in named_children_bounded(node, &mut scope_step)? {
                collect_binding_targets(target, source, &mut scope_step, |_, declaration| {
                    bindings.push(PythonDirectScopeBinding {
                        declaration,
                        kind: PythonDirectScopeBindingKind::Other,
                    });
                })?;
            }
        }
        "as_pattern" => {
            if let Some(alias) = node.child_by_field_name("alias") {
                collect_binding_targets(alias, source, &mut scope_step, |_, declaration| {
                    bindings.push(PythonDirectScopeBinding {
                        declaration,
                        kind: PythonDirectScopeBindingKind::Other,
                    });
                })?;
            }
        }
        "except_clause" => {
            if let Some(alias) = node.child_by_field_name("alias") {
                collect_binding_targets(alias, source, &mut scope_step, |_, declaration| {
                    bindings.push(PythonDirectScopeBinding {
                        declaration,
                        kind: PythonDirectScopeBindingKind::Other,
                    });
                })?;
            }
        }
        "case_clause" => {
            for child in named_children_bounded(node, &mut scope_step)? {
                if child.kind() == "case_pattern" {
                    collect_match_pattern_bindings(
                        child,
                        source,
                        &mut scope_step,
                        |_, declaration| {
                            bindings.push(PythonDirectScopeBinding {
                                declaration,
                                kind: PythonDirectScopeBindingKind::Other,
                            });
                        },
                    )?;
                }
            }
        }
        _ => {}
    }
    Some(bindings)
}

pub fn python_unambiguous_module_class_binding_bounded(
    root: Node<'_>,
    source: &str,
    target_name: &str,
    mut scope_step: impl FnMut() -> bool,
) -> Option<bool> {
    let mut matched = None;
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if !scope_step() {
            return None;
        }
        for binding in python_direct_scope_bindings_bounded(node, source, &mut scope_step)? {
            if node_text(binding.declaration, source) != target_name {
                continue;
            }
            if matched.is_some() {
                return Some(false);
            }
            matched = Some(binding.kind);
            if binding.kind == PythonDirectScopeBindingKind::Other {
                return Some(false);
            }
        }

        let body = matches!(
            node.kind(),
            "function_definition" | "class_definition" | "lambda"
        )
        .then(|| node.child_by_field_name("body").map(|child| child.id()))
        .flatten();
        let name = matches!(node.kind(), "function_definition" | "class_definition")
            .then(|| node.child_by_field_name("name").map(|child| child.id()))
            .flatten();
        for child in named_children_bounded(node, &mut scope_step)?
            .into_iter()
            .filter(|child| Some(child.id()) != body && Some(child.id()) != name)
            .rev()
        {
            stack.push(child);
        }
    }
    Some(matched == Some(PythonDirectScopeBindingKind::ClassDeclaration))
}

fn is_direct_module_definition_bounded(
    node: Node<'_>,
    scope_step: &mut impl FnMut() -> bool,
) -> Option<bool> {
    if !scope_step() {
        return None;
    }
    let Some(mut parent) = node.parent() else {
        return Some(false);
    };
    if parent.kind() == "decorated_definition" {
        if !scope_step() {
            return None;
        }
        let Some(grandparent) = parent.parent() else {
            return Some(false);
        };
        parent = grandparent;
    }
    Some(parent.kind() == "module")
}

fn collect_direct_identifier_names(
    node: Node<'_>,
    source: &str,
    scope_step: &mut impl FnMut() -> bool,
    mut record: impl FnMut(&str),
) -> Option<()> {
    for child in named_children_bounded(node, scope_step)? {
        if child.kind() == "identifier" {
            let name = node_text(child, source);
            if !name.is_empty() {
                record(name);
            }
        }
    }
    Some(())
}

fn collect_import_bindings<'tree>(
    statement: Node<'tree>,
    scope_step: &mut impl FnMut() -> bool,
    mut record: impl FnMut(Node<'tree>),
) -> Option<()> {
    let mut cursor = statement.walk();
    let mut imports = Vec::new();
    for imported in statement.children_by_field_name("name", &mut cursor) {
        if !scope_step() {
            return None;
        }
        imports.push(imported);
    }
    for imported in imports {
        if let Some(alias) = imported.child_by_field_name("alias") {
            record(alias);
            continue;
        }
        let name = imported.child_by_field_name("name").unwrap_or(imported);
        let binding = if statement.kind() == "import_statement" {
            first_identifier_bounded(name, scope_step)?
        } else {
            last_identifier_bounded(name, scope_step)?
        };
        if let Some(binding) = binding {
            record(binding);
        }
    }
    Some(())
}

fn first_identifier_bounded<'tree>(
    root: Node<'tree>,
    scope_step: &mut impl FnMut() -> bool,
) -> Option<Option<Node<'tree>>> {
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if !scope_step() {
            return None;
        }
        if node.kind() == "identifier" {
            return Some(Some(node));
        }
        let children = named_children_bounded(node, scope_step)?;
        stack.extend(children.into_iter().rev());
    }
    Some(None)
}

fn last_identifier_bounded<'tree>(
    root: Node<'tree>,
    scope_step: &mut impl FnMut() -> bool,
) -> Option<Option<Node<'tree>>> {
    let mut result = None;
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if !scope_step() {
            return None;
        }
        if node.kind() == "identifier" {
            result = Some(node);
            continue;
        }
        let children = named_children_bounded(node, scope_step)?;
        stack.extend(children.into_iter().rev());
    }
    Some(result)
}

fn collect_binding_targets<'tree>(
    target: Node<'tree>,
    source: &str,
    scope_step: &mut impl FnMut() -> bool,
    mut record: impl FnMut(&str, Node<'tree>),
) -> Option<()> {
    let mut stack = vec![target];
    while let Some(node) = stack.pop() {
        if !scope_step() {
            return None;
        }
        match node.kind() {
            // These mutate an existing object and do not bind either the
            // receiver or member name in the function.
            "attribute" | "subscript" => continue,
            "identifier" | "keyword_identifier" => {
                let name = node_text(node, source);
                if !name.is_empty() {
                    record(name, node);
                }
                continue;
            }
            _ => {}
        }
        let children = named_children_bounded(node, scope_step)?;
        if node.kind() == "as_pattern_target" && children.is_empty() {
            let name = node_text(node, source);
            if !name.is_empty() {
                record(name, node);
            }
            continue;
        }
        stack.extend(children.into_iter().rev());
    }
    Some(())
}

fn collect_match_pattern_bindings<'tree>(
    pattern: Node<'tree>,
    source: &str,
    scope_step: &mut impl FnMut() -> bool,
    mut record: impl FnMut(&str, Node<'tree>),
) -> Option<()> {
    let mut stack = vec![pattern];
    while let Some(node) = stack.pop() {
        if !scope_step() {
            return None;
        }
        match node.kind() {
            "dotted_name" => {
                let identifiers = named_children_bounded(node, scope_step)?
                    .into_iter()
                    .filter(|child| child.kind() == "identifier")
                    .collect::<Vec<_>>();
                if let [binding] = identifiers.as_slice() {
                    let name = node_text(*binding, source);
                    if !name.is_empty() {
                        record(name, *binding);
                    }
                }
                continue;
            }
            "splat_pattern" => {
                for child in named_children_bounded(node, scope_step)? {
                    if child.kind() == "identifier" {
                        let name = node_text(child, source);
                        if !name.is_empty() {
                            record(name, child);
                        }
                    }
                }
                continue;
            }
            "class_pattern" => {
                let mut children = named_children_bounded(node, scope_step)?;
                if children
                    .first()
                    .is_some_and(|child| child.kind() == "dotted_name")
                {
                    children.remove(0);
                }
                stack.extend(children.into_iter().rev());
                continue;
            }
            "keyword_pattern" => {
                let mut children = named_children_bounded(node, scope_step)?;
                if children
                    .first()
                    .is_some_and(|child| child.kind() == "identifier")
                {
                    children.remove(0);
                }
                stack.extend(children.into_iter().rev());
                continue;
            }
            "dict_pattern" => {
                let key_ids = children_by_field_name_bounded(node, "key", scope_step)?
                    .into_iter()
                    .map(|key| key.id())
                    .collect::<HashSet<_>>();
                let children = named_children_bounded(node, scope_step)?;
                stack.extend(
                    children
                        .into_iter()
                        .filter(|child| !key_ids.contains(&child.id()))
                        .rev(),
                );
                continue;
            }
            "as_pattern" => {
                if let Some(alias) = node.child_by_field_name("alias") {
                    collect_binding_targets(alias, source, scope_step, &mut record)?;
                    let children = named_children_bounded(node, scope_step)?;
                    stack.extend(
                        children
                            .into_iter()
                            .filter(|child| child.id() != alias.id())
                            .rev(),
                    );
                    continue;
                }
                let mut children = named_children_bounded(node, scope_step)?;
                if let Some(alias) = children
                    .last()
                    .copied()
                    .filter(|child| child.kind() == "identifier")
                {
                    let name = node_text(alias, source);
                    if !name.is_empty() {
                        record(name, alias);
                    }
                    children.pop();
                }
                stack.extend(children.into_iter().rev());
                continue;
            }
            "identifier" => {
                // Direct identifiers are match `as` aliases handled by their
                // parent. Keyword names and class heads are likewise skipped.
                continue;
            }
            kind if is_pattern_literal(kind) => continue,
            _ => {}
        }
        let children = named_children_bounded(node, scope_step)?;
        stack.extend(children.into_iter().rev());
    }
    Some(())
}

fn push_named_children<'tree>(
    stack: &mut Vec<ScanFrame<'tree>>,
    node: Node<'tree>,
    in_comprehension: bool,
    scope_step: &mut impl FnMut() -> bool,
) -> Option<()> {
    for child in named_children_bounded(node, scope_step)?.into_iter().rev() {
        stack.push(ScanFrame {
            node: child,
            in_comprehension,
        });
    }
    Some(())
}

fn push_named_children_except<'tree>(
    stack: &mut Vec<ScanFrame<'tree>>,
    node: Node<'tree>,
    excluded: Node<'tree>,
    in_comprehension: bool,
    scope_step: &mut impl FnMut() -> bool,
) -> Option<()> {
    for child in named_children_bounded(node, scope_step)?
        .into_iter()
        .filter(|child| child.id() != excluded.id())
        .rev()
    {
        stack.push(ScanFrame {
            node: child,
            in_comprehension,
        });
    }
    Some(())
}

fn push_nested_scope_header_children<'tree>(
    stack: &mut Vec<ScanFrame<'tree>>,
    node: Node<'tree>,
    in_comprehension: bool,
    scope_step: &mut impl FnMut() -> bool,
) -> Option<()> {
    let body = node.child_by_field_name("body").map(|child| child.id());
    let name = node.child_by_field_name("name").map(|child| child.id());
    for child in named_children_bounded(node, scope_step)?
        .into_iter()
        .filter(|child| Some(child.id()) != body && Some(child.id()) != name)
        .rev()
    {
        stack.push(ScanFrame {
            node: child,
            in_comprehension,
        });
    }
    Some(())
}

fn named_children_bounded<'tree>(
    node: Node<'tree>,
    scope_step: &mut impl FnMut() -> bool,
) -> Option<Vec<Node<'tree>>> {
    let mut cursor = node.walk();
    let mut children = Vec::new();
    for child in node.named_children(&mut cursor) {
        if !scope_step() {
            return None;
        }
        children.push(child);
    }
    Some(children)
}

fn children_by_field_name_bounded<'tree>(
    node: Node<'tree>,
    field: &str,
    scope_step: &mut impl FnMut() -> bool,
) -> Option<Vec<Node<'tree>>> {
    let mut cursor = node.walk();
    let mut children = Vec::new();
    for child in node.children_by_field_name(field, &mut cursor) {
        if !scope_step() {
            return None;
        }
        children.push(child);
    }
    Some(children)
}

fn is_comprehension(kind: &str) -> bool {
    matches!(
        kind,
        "list_comprehension"
            | "set_comprehension"
            | "dictionary_comprehension"
            | "generator_expression"
    )
}

fn is_pattern_literal(kind: &str) -> bool {
    matches!(
        kind,
        "string"
            | "concatenated_string"
            | "integer"
            | "float"
            | "complex_pattern"
            | "true"
            | "false"
            | "none"
    )
}

fn node_text<'a>(node: Node<'_>, source: &'a str) -> &'a str {
    brokk_bifrost_core::analyzer::common::node_source_text_trimmed(node, source)
}