Skip to main content

brokk_bifrost_python/
bindings.rs

1use brokk_bifrost_core::analyzer::common::node_source_text_trimmed as node_text;
2use brokk_bifrost_core::analyzer::tree_walk::{named_children_iter, push_bounded_nodes};
3use tree_sitter::Node;
4
5use brokk_bifrost_core::hash::{HashMap, HashSet};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum PythonLexicalNameResolution {
9    Unbound,
10    Local,
11    Nonlocal,
12    Global,
13}
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum PythonDirectScopeBindingKind {
17    ClassDeclaration,
18    FunctionDeclaration,
19    Import,
20    Other,
21}
22
23impl brokk_bifrost_core::retention_budget::RetainedBytes for PythonDirectScopeBindingKind {
24    fn retained_bytes(&self) -> usize {
25        std::mem::size_of::<Self>()
26    }
27}
28
29/// Whether `reference` reads a target introduced by an enclosing comprehension.
30///
31/// Comprehensions create an implicit scope even at module level. The element
32/// expression is textually before its `for` clauses but evaluates after their
33/// binders. Only the first iterable evaluates in the enclosing scope; later
34/// iterables use comprehension-local names, including not-yet-bound targets.
35/// This structured walk models those scopes without source-text parsing.
36pub fn python_comprehension_binds_name_at(name: &str, reference: Node<'_>, source: &str) -> bool {
37    python_comprehension_binds_name_at_bounded(name, reference, source, || true)
38        .expect("unbounded comprehension binding lookup completes")
39}
40
41/// The same scope proof under the caller's work/cancellation ledger.
42/// An interrupted walk must not be interpreted as an unbound name.
43pub fn python_comprehension_binds_name_at_bounded(
44    name: &str,
45    reference: Node<'_>,
46    source: &str,
47    mut scope_step: impl FnMut() -> bool,
48) -> Option<bool> {
49    if !scope_step() {
50        return None;
51    }
52    let mut current = reference;
53    while let Some(parent) = current.parent() {
54        if !scope_step() {
55            return None;
56        }
57        if is_comprehension(parent.kind()) {
58            let mut cursor = parent.walk();
59            let mut clauses = Vec::new();
60            for child in parent.named_children(&mut cursor) {
61                if !scope_step() {
62                    return None;
63                }
64                if child.kind() == "for_in_clause" {
65                    clauses.push(child);
66                }
67            }
68            let mut in_outer_iterable = false;
69            if let Some(clause) = clauses.first() {
70                let mut cursor = clause.walk();
71                for right in clause.children_by_field_name("right", &mut cursor) {
72                    if !scope_step() {
73                        return None;
74                    }
75                    if right.start_byte() <= reference.start_byte()
76                        && reference.end_byte() <= right.end_byte()
77                    {
78                        in_outer_iterable = true;
79                        break;
80                    }
81                }
82            }
83            if in_outer_iterable {
84                current = parent;
85                continue;
86            }
87            for clause in clauses {
88                if !scope_step() {
89                    return None;
90                }
91                let Some(target) = clause.child_by_field_name("left") else {
92                    continue;
93                };
94                let mut bound = false;
95                collect_binding_targets(target, source, &mut scope_step, |candidate, _| {
96                    bound |= candidate == name;
97                })?;
98                if bound {
99                    return Some(true);
100                }
101            }
102        }
103        if matches!(
104            parent.kind(),
105            "function_definition" | "lambda" | "class_definition" | "module"
106        ) {
107            break;
108        }
109        current = parent;
110    }
111    Some(false)
112}
113
114/// Whether `reference` reads a PEP 695 type parameter declared by its enclosing
115/// class, function, or type-alias definition.
116///
117/// Type parameters are lexical bindings rather than indexed workspace
118/// declarations. The binder is the first identifier in each structured
119/// parameter node; identifiers in bounds and constraints remain references.
120pub fn python_type_parameter_binds_name_at(name: &str, reference: Node<'_>, source: &str) -> bool {
121    python_type_parameter_binds_name_at_bounded(name, reference, source, || true)
122        .expect("unbounded type parameter lookup completes")
123}
124
125/// The shared type-parameter proof under the caller's live work budget.
126/// An interrupted ancestor, binder, or directive walk supplies no answer.
127pub fn python_type_parameter_binds_name_at_bounded(
128    name: &str,
129    reference: Node<'_>,
130    source: &str,
131    mut scope_step: impl FnMut() -> bool,
132) -> Option<bool> {
133    let mut current = reference;
134    let mut enclosing_functions = Vec::new();
135    while let Some(parent) = current.parent() {
136        if !scope_step() {
137            return None;
138        }
139        if parent.kind() == "function_definition" {
140            enclosing_functions.push(parent);
141        }
142        if matches!(
143            parent.kind(),
144            "class_definition" | "function_definition" | "type_alias_statement"
145        ) && let Some(parameters) = python_type_parameters(parent)
146            && !(parameters.start_byte() <= reference.start_byte()
147                && reference.end_byte() <= parameters.end_byte())
148        {
149            let mut cursor = parameters.walk();
150            for parameter in parameters.named_children(&mut cursor) {
151                if !scope_step() {
152                    return None;
153                }
154                let binder = first_identifier_bounded(parameter, &mut scope_step)?;
155                if binder.is_some_and(|binder| node_text(binder, source) == name) {
156                    // Preserve the existing function-wide directive precedence.
157                    return Some(
158                        python_name_resolution_at_in_functions_bounded(
159                            name,
160                            reference,
161                            source,
162                            enclosing_functions,
163                            &mut scope_step,
164                        )? != PythonLexicalNameResolution::Global,
165                    );
166                }
167            }
168        }
169        current = parent;
170    }
171    Some(false)
172}
173
174/// Resolve `name` through the nearest enclosing function scope. This is the
175/// structured fallback for references inside nested functions that do not
176/// have their own indexed `CodeUnit` scope snapshot.
177pub fn python_name_resolution_at(
178    name: &str,
179    reference: Node<'_>,
180    source: &str,
181) -> PythonLexicalNameResolution {
182    let mut functions = Vec::new();
183    let mut current = reference;
184    while let Some(parent) = current.parent() {
185        if parent.kind() == "function_definition" {
186            functions.push(parent);
187        }
188        current = parent;
189    }
190    python_name_resolution_at_in_functions(name, reference, source, functions)
191}
192
193fn python_name_resolution_at_in_functions(
194    name: &str,
195    reference: Node<'_>,
196    source: &str,
197    functions: Vec<Node<'_>>,
198) -> PythonLexicalNameResolution {
199    python_name_resolution_at_in_functions_bounded(name, reference, source, functions, || true)
200        .expect("unbounded function binding lookup completes")
201}
202
203fn python_name_resolution_at_in_functions_bounded(
204    name: &str,
205    reference: Node<'_>,
206    source: &str,
207    functions: Vec<Node<'_>>,
208    mut scope_step: impl FnMut() -> bool,
209) -> Option<PythonLexicalNameResolution> {
210    for function in functions {
211        if !scope_step() {
212            return None;
213        }
214        let mut parameter_names = Vec::new();
215        if let Some(parameters) = function.child_by_field_name("parameters") {
216            let mut cursor = parameters.walk();
217            for parameter in parameters.named_children(&mut cursor) {
218                if !scope_step() {
219                    return None;
220                }
221                if let Some(name) = crate::syntax::python_parameter_name_bounded(
222                    parameter,
223                    source,
224                    &mut scope_step,
225                )? {
226                    parameter_names.push(name);
227                }
228            }
229        }
230        let inventory = PythonLexicalScopeInventory::collect_bounded(
231            function,
232            source,
233            parameter_names,
234            &mut scope_step,
235        )?;
236        let resolution = inventory.name_resolution_at_bounded(name, reference, &mut scope_step)?;
237        match resolution {
238            PythonLexicalNameResolution::Global
239            | PythonLexicalNameResolution::Local
240            | PythonLexicalNameResolution::Nonlocal => return Some(resolution),
241            PythonLexicalNameResolution::Unbound => {}
242        }
243    }
244    Some(PythonLexicalNameResolution::Unbound)
245}
246
247/// The grammar places alias formals inside the alias's left-hand generic type.
248/// All binder consumers use this same structured interpretation.
249pub(crate) fn python_type_parameters(owner: Node<'_>) -> Option<Node<'_>> {
250    owner.child_by_field_name("type_parameters").or_else(|| {
251        if owner.kind() != "type_alias_statement" {
252            return None;
253        }
254        let left = owner.child_by_field_name("left")?;
255        let generic = left.named_child(0)?;
256        (generic.kind() == "generic_type")
257            .then(|| named_children_iter(generic).find(|node| node.kind() == "type_parameter"))
258            .flatten()
259    })
260}
261
262/// Whether this identifier is the binder (rather than a bound/constraint use)
263/// of one structured PEP 695 type parameter.
264pub fn python_is_type_parameter_binder(node: Node<'_>) -> bool {
265    if node.kind() != "identifier" {
266        return false;
267    }
268    let mut current = node;
269    while let Some(parent) = current.parent() {
270        if matches!(
271            parent.kind(),
272            "class_definition" | "function_definition" | "type_alias_statement"
273        ) && let Some(parameters) = python_type_parameters(parent)
274            && parameters.start_byte() <= node.start_byte()
275            && node.end_byte() <= parameters.end_byte()
276        {
277            let mut cursor = parameters.walk();
278            return parameters.named_children(&mut cursor).any(|parameter| {
279                let binder = python_type_parameter_binder_node(parameter);
280                binder.is_some_and(|binder| binder.id() == node.id())
281            });
282        }
283        if matches!(
284            parent.kind(),
285            "module" | "class_definition" | "function_definition" | "type_alias_statement"
286        ) {
287            return false;
288        }
289        current = parent;
290    }
291    false
292}
293
294pub(crate) fn python_type_parameter_binder_node(parameter: Node<'_>) -> Option<Node<'_>> {
295    if parameter.kind() == "identifier" {
296        Some(parameter)
297    } else {
298        first_identifier_bounded(parameter, &mut || true).flatten()
299    }
300}
301
302#[derive(Clone, Copy, Debug)]
303pub struct PythonDirectScopeBinding<'tree> {
304    pub declaration: Node<'tree>,
305    pub kind: PythonDirectScopeBindingKind,
306}
307
308#[derive(Clone, Debug)]
309struct PythonLocalBinding<'tree> {
310    name: Box<str>,
311    declaration: Node<'tree>,
312}
313
314#[derive(Clone, Copy, Debug, PartialEq, Eq)]
315enum PythonLocalBindingKind {
316    FunctionOnly,
317    ClassOnly,
318    ImportOnly,
319    Other,
320}
321
322#[derive(Clone, Debug)]
323struct PythonComprehensionBinding {
324    parent: Option<usize>,
325    start_byte: usize,
326    end_byte: usize,
327    enclosing_iterable_ranges: Vec<(usize, usize)>,
328}
329
330/// Function-scope Python bindings discovered from tree-sitter structure.
331///
332/// The inventory models Python's whole-function symbol-table behavior while
333/// retaining the implicit scope of comprehension targets. Construction is
334/// iterative and every inspected node is gated by `scope_step`; `None` means
335/// the caller stopped discovery and must conservatively avoid module fallback.
336pub struct PythonLexicalScopeInventory<'tree> {
337    binding_nodes: Vec<Node<'tree>>,
338    locals: Vec<PythonLocalBinding<'tree>>,
339    bindings: PythonLexicalScopeBindings,
340}
341
342/// Completed function binding facts without borrowed tree-sitter nodes.
343/// Retain these only under the identity of the exact source that produced them.
344pub struct PythonLexicalScopeBindings {
345    parameters: HashSet<Box<str>>,
346    local_names: HashMap<Box<str>, PythonLocalBindingKind>,
347    binding_writes: HashSet<Box<str>>,
348    // Real binding events retained before global declarations leave locals.
349    global_binding_events: HashSet<Box<str>>,
350    globals: HashSet<Box<str>>,
351    nonlocals: HashSet<Box<str>>,
352    comprehensions: HashMap<Box<str>, Vec<PythonComprehensionBinding>>,
353}
354
355impl PythonLexicalScopeBindings {
356    pub fn name_resolution_at(
357        &self,
358        name: &str,
359        reference: Node<'_>,
360    ) -> PythonLexicalNameResolution {
361        self.name_resolution_at_bounded(name, reference, || true)
362            .expect("unbounded lexical name lookup completes")
363    }
364
365    /// Resolve a read while charging every comprehension binding and iterable
366    /// range inspected. Exhaustion is distinct from an unbound name.
367    pub fn name_resolution_at_bounded(
368        &self,
369        name: &str,
370        reference: Node<'_>,
371        mut scope_step: impl FnMut() -> bool,
372    ) -> Option<PythonLexicalNameResolution> {
373        if !scope_step() {
374            return None;
375        }
376        if self.comprehension_binds_name_at_bounded(name, reference, &mut scope_step)? {
377            return Some(PythonLexicalNameResolution::Local);
378        }
379        Some(if self.nonlocals.contains(name) {
380            PythonLexicalNameResolution::Nonlocal
381        } else if self.globals.contains(name) {
382            PythonLexicalNameResolution::Global
383        } else if self.parameters.contains(name) || self.local_names.contains_key(name) {
384            PythonLexicalNameResolution::Local
385        } else {
386            PythonLexicalNameResolution::Unbound
387        })
388    }
389
390    fn comprehension_binds_name_at_bounded(
391        &self,
392        name: &str,
393        reference: Node<'_>,
394        mut scope_step: impl FnMut() -> bool,
395    ) -> Option<bool> {
396        if !scope_step() {
397            return None;
398        }
399        let Some(bindings) = self.comprehensions.get(name) else {
400            return Some(false);
401        };
402        let reference_byte = reference.start_byte();
403        let mut completed = true;
404        let end = bindings.partition_point(|binding| {
405            completed &= scope_step();
406            binding.start_byte <= reference_byte
407        });
408        if !completed {
409            return None;
410        }
411        let mut index = end.checked_sub(1);
412        while let Some(current) = index {
413            if !scope_step() {
414                return None;
415            }
416            let binding = &bindings[current];
417            if reference_byte < binding.end_byte {
418                let mut in_outer_iterable = false;
419                for (start, end) in &binding.enclosing_iterable_ranges {
420                    if !scope_step() {
421                        return None;
422                    }
423                    in_outer_iterable |= *start <= reference_byte && reference_byte < *end;
424                }
425                if !in_outer_iterable {
426                    return Some(true);
427                }
428            }
429            // Ranges are laminar. Skip completed siblings directly to the
430            // enclosing same-name comprehension, rather than scanning them.
431            index = binding.parent;
432        }
433        Some(false)
434    }
435
436    /// A directive alone is not an event. Declarations, imports, assignments,
437    /// and every other collected binder/delete count, without value inference.
438    pub fn has_global_binding_event(&self, name: &str) -> bool {
439        self.global_binding_events.contains(name)
440    }
441
442    /// All actual global binding events, before any read-time filtering.
443    /// Callers that copy this set must charge their own bounded iteration.
444    pub fn global_binding_events(&self) -> impl Iterator<Item = &str> {
445        self.global_binding_events.iter().map(|name| name.as_ref())
446    }
447
448    pub fn resolves_to_local_function_bounded(
449        &self,
450        name: &str,
451        reference: Node<'_>,
452        mut scope_step: impl FnMut() -> bool,
453    ) -> Option<bool> {
454        if !scope_step() {
455            return None;
456        }
457        Some(
458            !self.parameters.contains(name)
459                && !self.comprehension_binds_name_at_bounded(name, reference, &mut scope_step)?
460                && self.local_names.get(name) == Some(&PythonLocalBindingKind::FunctionOnly),
461        )
462    }
463
464    /// Whether the active callable obtains `name` from a runtime binding
465    /// rather than an untouched function or import declaration.
466    pub fn has_runtime_callable_binding_at(&self, name: &str, reference: Node<'_>) -> bool {
467        self.has_runtime_callable_binding_at_bounded(name, reference, || true)
468            .expect("unbounded runtime binding lookup completes")
469    }
470
471    pub fn has_runtime_callable_binding_at_bounded(
472        &self,
473        name: &str,
474        reference: Node<'_>,
475        mut scope_step: impl FnMut() -> bool,
476    ) -> Option<bool> {
477        if !scope_step() {
478            return None;
479        }
480        Some(
481            self.parameters.contains(name)
482                || self.binding_writes.contains(name)
483                || self.comprehension_binds_name_at_bounded(name, reference, &mut scope_step)?,
484        )
485    }
486}
487
488/// Binding events in an executing class namespace at one reference. Only a
489/// proved static superclass path precedes that class statement's name binding.
490/// Lazy type-parameter expressions and other header contexts keep that event.
491/// Other events retain the existing whole-scope conservative interpretation.
492pub struct PythonClassReferenceScope<'tree> {
493    scope: Node<'tree>,
494    pending_name: Option<Node<'tree>>,
495}
496
497impl<'tree> PythonClassReferenceScope<'tree> {
498    pub fn new_bounded(
499        scope: Node<'tree>,
500        reference: Node<'tree>,
501        mut scope_step: impl FnMut() -> bool,
502    ) -> Option<Self> {
503        assert_eq!(scope.kind(), "class_definition");
504        let mut current = reference;
505        let mut pending_name = None;
506        while current != scope {
507            if !scope_step() {
508                return None;
509            }
510            if current.kind() == "class_definition"
511                && let Some(superclasses) = current.child_by_field_name("superclasses")
512            {
513                for expression in named_children_iter(superclasses) {
514                    if !scope_step() {
515                        return None;
516                    }
517                    if expression.start_byte() <= reference.start_byte()
518                        && reference.end_byte() <= expression.end_byte()
519                        && let Some(path) = crate::syntax::python_static_value_path_bounded(
520                            expression,
521                            &mut scope_step,
522                        )?
523                        && (path.first().copied() == Some(reference) || expression == reference)
524                    {
525                        pending_name = Some(current.child_by_field_name("name")?);
526                    }
527                }
528            }
529            current = current.parent()?;
530        }
531        Some(Self {
532            scope,
533            pending_name,
534        })
535    }
536
537    fn includes_binding(&self, declaration: Node<'tree>) -> bool {
538        Some(declaration) != self.pending_name
539    }
540
541    pub fn collect_bounded(
542        &self,
543        source: &str,
544        scope_step: impl FnMut() -> bool,
545    ) -> Option<PythonLexicalScopeInventory<'tree>> {
546        PythonLexicalScopeInventory::collect_with_declaration_filter_bounded(
547            self.scope,
548            source,
549            std::iter::empty::<String>(),
550            |declaration| self.includes_binding(declaration),
551            scope_step,
552        )
553    }
554
555    pub fn binds_name_bounded(
556        &self,
557        name: &str,
558        source: &str,
559        scope_step: impl FnMut() -> bool,
560    ) -> Option<bool> {
561        python_scope_binds_name_with_filter_bounded(
562            self.scope,
563            name,
564            source,
565            |declaration| self.includes_binding(declaration),
566            scope_step,
567        )
568    }
569}
570
571impl<'tree> PythonLexicalScopeInventory<'tree> {
572    /// `parameter_names` is the callable's formal-parameter name stream. The
573    /// layout it comes from is resolved by `analyzer/lexical_definitions.rs`,
574    /// which dispatches through the analysis-side language registry and so
575    /// cannot be named here; `analyzer/python/lexical_scope.rs` in
576    /// `brokk-bifrost-analysis` is the one caller that computes it, under the
577    /// same `scope_step` meter this walk uses.
578    pub fn collect_bounded(
579        callable: Node<'tree>,
580        source: &str,
581        parameter_names: impl IntoIterator<Item = String>,
582        scope_step: impl FnMut() -> bool,
583    ) -> Option<Self> {
584        Self::collect_with_declaration_filter_bounded(
585            callable,
586            source,
587            parameter_names,
588            |_| true,
589            scope_step,
590        )
591    }
592
593    fn collect_with_declaration_filter_bounded(
594        callable: Node<'tree>,
595        source: &str,
596        parameter_names: impl IntoIterator<Item = String>,
597        include_declaration: impl Fn(Node<'tree>) -> bool,
598        mut scope_step: impl FnMut() -> bool,
599    ) -> Option<Self> {
600        let mut inventory = Self {
601            binding_nodes: Vec::new(),
602            locals: Vec::new(),
603            bindings: PythonLexicalScopeBindings {
604                parameters: parameter_names.into_iter().map(Box::<str>::from).collect(),
605                local_names: HashMap::default(),
606                binding_writes: HashSet::default(),
607                global_binding_events: HashSet::default(),
608                globals: HashSet::default(),
609                nonlocals: HashSet::default(),
610                comprehensions: HashMap::default(),
611            },
612        };
613        // Recovery can replace the module grammar node with an ERROR root.
614        // Its declarations still belong to the source file's module scope.
615        let module_scope = callable.parent().is_none();
616        let body = if module_scope {
617            callable
618        } else if let Some(body) = callable.child_by_field_name("body") {
619            body
620        } else {
621            return Some(inventory);
622        };
623        let mut stack = vec![body];
624
625        while let Some(node) = stack.pop() {
626            if !scope_step() {
627                return None;
628            }
629            let nested_scope = node != body
630                && matches!(
631                    node.kind(),
632                    "function_definition" | "lambda" | "class_definition"
633                );
634            if nested_scope {
635                if matches!(node.kind(), "function_definition" | "class_definition")
636                    && let Some(name) = node.child_by_field_name("name")
637                    && include_declaration(name)
638                {
639                    inventory.record_local_node(name, source);
640                }
641                // Defaults, annotations, bases, and type-parameter expressions
642                // execute in an enclosing scope. Keep scanning those headers
643                // for walrus/comprehension bindings while pruning the nested
644                // callable or class body itself.
645                push_nested_scope_header_children(&mut stack, node, &mut scope_step)?;
646                continue;
647            }
648
649            match node.kind() {
650                "global_statement" => {
651                    if module_scope {
652                        continue;
653                    }
654                    collect_direct_identifier_names(node, source, &mut scope_step, |name| {
655                        inventory.bindings.globals.insert(name.into());
656                    })?;
657                    continue;
658                }
659                "nonlocal_statement" => {
660                    collect_direct_identifier_names(node, source, &mut scope_step, |name| {
661                        inventory.bindings.nonlocals.insert(name.into());
662                    })?;
663                    continue;
664                }
665                "import_statement" | "import_from_statement" => {
666                    collect_import_bindings(node, &mut scope_step, |binding| {
667                        inventory.record_local_kind(
668                            node_text(binding, source),
669                            binding,
670                            PythonLocalBindingKind::ImportOnly,
671                        )
672                    })?;
673                    continue;
674                }
675                "assignment" | "augmented_assignment" => {
676                    if let Some(target) = node.child_by_field_name("left") {
677                        collect_binding_targets(
678                            target,
679                            source,
680                            &mut scope_step,
681                            |name, declaration| {
682                                inventory.record_binding_write(name, declaration);
683                            },
684                        )?;
685                    }
686                }
687                "type_alias_statement" => {
688                    if let Some(target) = node.child_by_field_name("left")
689                        && let Some(binding) = first_identifier_bounded(target, &mut scope_step)?
690                    {
691                        inventory.record_local_node(binding, source);
692                    }
693                }
694                "named_expression" => {
695                    // PEP 572 binds a comprehension walrus in the containing
696                    // non-comprehension scope, so this remains a function local.
697                    if let Some(target) = node.child_by_field_name("name") {
698                        collect_binding_targets(
699                            target,
700                            source,
701                            &mut scope_step,
702                            |name, declaration| {
703                                inventory.record_binding_write(name, declaration);
704                            },
705                        )?;
706                    }
707                }
708                "for_statement" => {
709                    if let Some(target) = node.child_by_field_name("left") {
710                        collect_binding_targets(
711                            target,
712                            source,
713                            &mut scope_step,
714                            |name, declaration| {
715                                inventory.record_binding_write(name, declaration);
716                            },
717                        )?;
718                    }
719                }
720                "for_in_clause" => {
721                    // These occur inside comprehensions and belong to their
722                    // implicit scope. The enclosing comprehension records them.
723                }
724                "delete_statement" => {
725                    for target in named_children_bounded(node, &mut scope_step)? {
726                        collect_binding_targets(
727                            target,
728                            source,
729                            &mut scope_step,
730                            |name, declaration| {
731                                inventory.record_binding_write(name, declaration);
732                            },
733                        )?;
734                    }
735                    continue;
736                }
737                "as_pattern" => {
738                    if let Some(alias) = node.child_by_field_name("alias") {
739                        collect_binding_targets(
740                            alias,
741                            source,
742                            &mut scope_step,
743                            |name, declaration| {
744                                inventory.record_binding_write(name, declaration);
745                            },
746                        )?;
747                        push_named_children_except(&mut stack, node, alias, &mut scope_step)?;
748                        continue;
749                    }
750                }
751                "except_clause" => {
752                    // Older grammar shapes expose the alias directly. Current
753                    // tree-sitter-python nests it in an `as_pattern`, handled
754                    // above when the clause's children are scanned.
755                    if let Some(alias) = node.child_by_field_name("alias") {
756                        collect_binding_targets(
757                            alias,
758                            source,
759                            &mut scope_step,
760                            |name, declaration| {
761                                inventory.record_binding_write(name, declaration);
762                            },
763                        )?;
764                    }
765                }
766                "case_clause" => {
767                    let children = named_children_bounded(node, &mut scope_step)?;
768                    for child in children.iter().copied() {
769                        if child.kind() == "case_pattern" {
770                            collect_match_pattern_bindings(
771                                child,
772                                source,
773                                &mut scope_step,
774                                |name, declaration| {
775                                    inventory.record_binding_write(name, declaration);
776                                },
777                            )?;
778                        }
779                    }
780                    for child in children.into_iter().rev() {
781                        if child.kind() != "case_pattern" {
782                            stack.push(child);
783                        }
784                    }
785                    continue;
786                }
787                kind if is_comprehension(kind) => {
788                    let range = (node.start_byte(), node.end_byte());
789                    let children = named_children_bounded(node, &mut scope_step)?;
790                    let enclosing_iterable_ranges = if let Some(first_clause) = children
791                        .iter()
792                        .copied()
793                        .find(|child| child.kind() == "for_in_clause")
794                    {
795                        children_by_field_name_bounded(first_clause, "right", &mut scope_step)?
796                            .into_iter()
797                            .map(|iterable| (iterable.start_byte(), iterable.end_byte()))
798                            .collect()
799                    } else {
800                        Vec::new()
801                    };
802                    for clause in children
803                        .iter()
804                        .copied()
805                        .filter(|child| child.kind() == "for_in_clause")
806                    {
807                        if let Some(target) = clause.child_by_field_name("left") {
808                            let mut names = Vec::new();
809                            collect_binding_targets(target, source, &mut scope_step, |name, _| {
810                                names.push(name.to_owned());
811                            })?;
812                            for name in names {
813                                if !scope_step() {
814                                    return None;
815                                }
816                                let bindings = inventory
817                                    .bindings
818                                    .comprehensions
819                                    .entry(name.into())
820                                    .or_default();
821                                if bindings.last().is_some_and(|previous| {
822                                    (previous.start_byte, previous.end_byte) == range
823                                }) {
824                                    continue;
825                                }
826                                // Inventory traversal is source-order preorder.
827                                debug_assert!(
828                                    bindings
829                                        .last()
830                                        .is_none_or(|previous| previous.start_byte <= range.0)
831                                );
832                                let mut parent = bindings.len().checked_sub(1);
833                                while let Some(index) = parent {
834                                    if !scope_step() {
835                                        return None;
836                                    }
837                                    if bindings[index].end_byte > range.0 {
838                                        debug_assert!(bindings[index].end_byte >= range.1);
839                                        break;
840                                    }
841                                    parent = bindings[index].parent;
842                                }
843                                bindings.push(PythonComprehensionBinding {
844                                    parent,
845                                    start_byte: range.0,
846                                    end_byte: range.1,
847                                    enclosing_iterable_ranges: enclosing_iterable_ranges.clone(),
848                                });
849                            }
850                        }
851                    }
852                    for child in children.into_iter().rev() {
853                        stack.push(child);
854                    }
855                    continue;
856                }
857                _ => {}
858            }
859
860            push_named_children(&mut stack, node, &mut scope_step)?;
861        }
862
863        // Preserve all real global binding events before pruning semantic
864        // locals, including def/class/import declarations that intentionally
865        // do not belong to the runtime-callable-value predicate.
866        for name in inventory.bindings.local_names.keys() {
867            if !scope_step() {
868                return None;
869            }
870            if inventory.bindings.globals.contains(name.as_ref()) {
871                inventory
872                    .bindings
873                    .global_binding_events
874                    .insert(name.clone());
875            }
876        }
877
878        // `global` and `nonlocal` are whole-function directives regardless of
879        // source order. Neither declaration may become a semantic local.
880        inventory.locals.retain(|binding| {
881            !inventory.bindings.globals.contains(binding.name.as_ref())
882                && !inventory.bindings.nonlocals.contains(binding.name.as_ref())
883        });
884        inventory.bindings.local_names.retain(|name, _| {
885            !inventory.bindings.globals.contains(name.as_ref())
886                && !inventory.bindings.nonlocals.contains(name.as_ref())
887        });
888        Some(inventory)
889    }
890
891    pub fn into_bindings(self) -> PythonLexicalScopeBindings {
892        self.bindings
893    }
894
895    pub fn name_resolution_at(
896        &self,
897        name: &str,
898        reference: Node<'_>,
899    ) -> PythonLexicalNameResolution {
900        self.bindings.name_resolution_at(name, reference)
901    }
902
903    pub fn name_resolution_at_bounded(
904        &self,
905        name: &str,
906        reference: Node<'_>,
907        scope_step: impl FnMut() -> bool,
908    ) -> Option<PythonLexicalNameResolution> {
909        self.bindings
910            .name_resolution_at_bounded(name, reference, scope_step)
911    }
912
913    pub(crate) fn comprehension_binds_name_at_bounded(
914        &self,
915        name: &str,
916        reference: Node<'_>,
917        scope_step: impl FnMut() -> bool,
918    ) -> Option<bool> {
919        self.bindings
920            .comprehension_binds_name_at_bounded(name, reference, scope_step)
921    }
922
923    pub fn has_runtime_callable_binding_at(&self, name: &str, reference: Node<'_>) -> bool {
924        self.bindings
925            .has_runtime_callable_binding_at(name, reference)
926    }
927
928    pub fn has_runtime_callable_binding_at_bounded(
929        &self,
930        name: &str,
931        reference: Node<'_>,
932        scope_step: impl FnMut() -> bool,
933    ) -> Option<bool> {
934        self.bindings
935            .has_runtime_callable_binding_at_bounded(name, reference, scope_step)
936    }
937
938    pub fn local_function_declaration(
939        &self,
940        name: &str,
941        reference: Node<'_>,
942    ) -> Option<Node<'tree>> {
943        self.local_function_declaration_bounded(name, reference, || true)
944    }
945
946    pub fn local_function_declaration_bounded(
947        &self,
948        name: &str,
949        reference: Node<'_>,
950        mut scope_step: impl FnMut() -> bool,
951    ) -> Option<Node<'tree>> {
952        if !self
953            .bindings
954            .resolves_to_local_function_bounded(name, reference, &mut scope_step)?
955        {
956            return None;
957        }
958        for binding in &self.locals {
959            if !scope_step() {
960                return None;
961            }
962            if binding.name.as_ref() == name {
963                return binding
964                    .declaration
965                    .parent()
966                    .filter(|declaration| declaration.kind() == "function_definition");
967            }
968        }
969        None
970    }
971
972    /// A single untouched local class declaration, not an inferred instance
973    /// type. Statement ordering/containment is checked at the selected use.
974    pub fn local_class_declaration_bounded(
975        &self,
976        name: &str,
977        reference: Node<'_>,
978        mut scope_step: impl FnMut() -> bool,
979    ) -> Option<Node<'tree>> {
980        if self.name_resolution_at_bounded(name, reference, &mut scope_step)?
981            != PythonLexicalNameResolution::Local
982            || self.bindings.has_runtime_callable_binding_at_bounded(
983                name,
984                reference,
985                &mut scope_step,
986            )?
987            || self.bindings.local_names.get(name) != Some(&PythonLocalBindingKind::ClassOnly)
988        {
989            return None;
990        }
991        for binding in &self.locals {
992            if !scope_step() {
993                return None;
994            }
995            if binding.name.as_ref() == name {
996                return binding
997                    .declaration
998                    .parent()
999                    .filter(|node| node.kind() == "class_definition");
1000            }
1001        }
1002        None
1003    }
1004
1005    /// The import must be the only binding event, not merely the first
1006    /// retained token. Competing imports, def/class names and writes collapse
1007    /// ImportOnly to Other during collection, even when import metadata is absent.
1008    pub fn unique_import_declaration_bounded(
1009        &self,
1010        name: &str,
1011        reference: Node<'_>,
1012        mut scope_step: impl FnMut() -> bool,
1013    ) -> Option<Option<Node<'tree>>> {
1014        if self.name_resolution_at_bounded(name, reference, &mut scope_step)?
1015            != PythonLexicalNameResolution::Local
1016            || self.bindings.has_runtime_callable_binding_at_bounded(
1017                name,
1018                reference,
1019                &mut scope_step,
1020            )?
1021            || self.bindings.local_names.get(name) != Some(&PythonLocalBindingKind::ImportOnly)
1022        {
1023            return Some(None);
1024        }
1025        for binding in &self.locals {
1026            if !scope_step() {
1027                return None;
1028            }
1029            if binding.name.as_ref() == name {
1030                return Some(Some(binding.declaration));
1031            }
1032        }
1033        unreachable!("ImportOnly is constructed with its declaration token")
1034    }
1035
1036    /// All binding tokens, including repeated and globally redirected writes.
1037    /// The native producer attributes these after the whole scope inventory exists.
1038    pub fn binding_nodes(&self) -> impl Iterator<Item = Node<'tree>> + '_ {
1039        self.binding_nodes.iter().copied()
1040    }
1041
1042    pub fn global_names(&self) -> impl Iterator<Item = &str> {
1043        self.bindings.globals.iter().map(AsRef::as_ref)
1044    }
1045
1046    pub fn nonlocal_names(&self) -> impl Iterator<Item = &str> {
1047        self.bindings.nonlocals.iter().map(AsRef::as_ref)
1048    }
1049
1050    pub fn local_bindings(&self) -> impl Iterator<Item = (&str, Node<'tree>)> + '_ {
1051        self.locals
1052            .iter()
1053            .map(|binding| (binding.name.as_ref(), binding.declaration))
1054    }
1055
1056    fn record_local_node(&mut self, node: Node<'tree>, source: &str) {
1057        let name = node_text(node, source);
1058        self.record_local(name, node);
1059    }
1060
1061    fn record_local(&mut self, name: &str, declaration: Node<'tree>) {
1062        if name.is_empty() {
1063            return;
1064        }
1065        let binding_kind = if is_function_declaration_name(declaration) {
1066            PythonLocalBindingKind::FunctionOnly
1067        } else if declaration.parent().is_some_and(|parent| {
1068            parent.kind() == "class_definition"
1069                && brokk_bifrost_core::analyzer::tree_walk::is_field_child(
1070                    parent,
1071                    declaration,
1072                    "name",
1073                )
1074        }) {
1075            PythonLocalBindingKind::ClassOnly
1076        } else {
1077            PythonLocalBindingKind::Other
1078        };
1079        self.record_local_kind(name, declaration, binding_kind);
1080    }
1081
1082    fn record_local_kind(
1083        &mut self,
1084        name: &str,
1085        declaration: Node<'tree>,
1086        binding_kind: PythonLocalBindingKind,
1087    ) {
1088        if name.is_empty() {
1089            return;
1090        }
1091        self.binding_nodes.push(declaration);
1092        match self.bindings.local_names.entry(name.into()) {
1093            std::collections::hash_map::Entry::Vacant(entry) => {
1094                entry.insert(binding_kind);
1095                self.locals.push(PythonLocalBinding {
1096                    name: name.into(),
1097                    declaration,
1098                });
1099            }
1100            std::collections::hash_map::Entry::Occupied(mut entry) => {
1101                entry.insert(PythonLocalBindingKind::Other);
1102            }
1103        }
1104    }
1105
1106    fn record_binding_write(&mut self, name: &str, declaration: Node<'tree>) {
1107        if !name.is_empty() {
1108            self.bindings.binding_writes.insert(name.into());
1109        }
1110        self.record_local(name, declaration);
1111    }
1112}
1113
1114/// Prove that a selected `global` route has no known binding event in its
1115/// executing enclosing scopes. Outer locals are unrelated to this namespace;
1116/// an outer scope declaring the same global can still replace its identity.
1117/// Class namespaces are not captured: only explicit global events are read.
1118/// The caller has already selected `global_scope` by lexical precedence.
1119pub fn python_global_binding_is_untouched_bounded(
1120    name: &str,
1121    reference: Node<'_>,
1122    global_scope: Node<'_>,
1123    source: &str,
1124    mut scope_step: impl FnMut() -> bool,
1125) -> Option<bool> {
1126    assert!(matches!(
1127        global_scope.kind(),
1128        "function_definition" | "lambda" | "class_definition"
1129    ));
1130    let mut current = Some(global_scope);
1131    while let Some(scope) = current {
1132        if !scope_step() {
1133            return None;
1134        }
1135        if matches!(
1136            scope.kind(),
1137            "function_definition" | "lambda" | "class_definition"
1138        ) && scope.child_by_field_name("body").is_some_and(|body| {
1139            body.start_byte() <= reference.start_byte() && reference.end_byte() <= body.end_byte()
1140        }) {
1141            let inventory = if scope.kind() == "class_definition" {
1142                PythonClassReferenceScope::new_bounded(scope, reference, &mut scope_step)?
1143                    .collect_bounded(source, &mut scope_step)?
1144            } else {
1145                PythonLexicalScopeInventory::collect_bounded(
1146                    scope,
1147                    source,
1148                    std::iter::empty::<String>(),
1149                    &mut scope_step,
1150                )?
1151            };
1152            if inventory.bindings.has_global_binding_event(name) {
1153                return Some(false);
1154            }
1155        }
1156        current = scope.parent();
1157    }
1158    Some(true)
1159}
1160
1161fn is_function_declaration_name(node: Node<'_>) -> bool {
1162    node.parent().is_some_and(|parent| {
1163        parent.kind() == "function_definition"
1164            && brokk_bifrost_core::analyzer::tree_walk::is_field_child(parent, node, "name")
1165    })
1166}
1167
1168/// Collect the binders in one already-selected assignment or loop target.
1169/// Attribute/subscript operands remain reads, and exhaustion stays explicit.
1170/// Callers supply the grammar field rather than reconstructing target syntax.
1171pub fn python_binding_targets_bounded<'tree>(
1172    target: Node<'tree>,
1173    source: &str,
1174    mut scope_step: impl FnMut() -> bool,
1175) -> Option<Vec<PythonDirectScopeBinding<'tree>>> {
1176    let mut bindings = Vec::new();
1177    collect_binding_targets(target, source, &mut scope_step, |_, declaration| {
1178        bindings.push(PythonDirectScopeBinding {
1179            declaration,
1180            kind: PythonDirectScopeBindingKind::Other,
1181        });
1182    })?;
1183    Some(bindings)
1184}
1185
1186/// Return the bindings introduced directly by `node`.
1187///
1188/// Descendant traversal remains the caller's responsibility. This lets the
1189/// semantic file walk build a module binding inventory without adding a
1190/// second whole-file scan, while reusing the same structured target handling
1191/// as function symbol-table discovery.
1192pub fn python_direct_scope_bindings_bounded<'tree>(
1193    node: Node<'tree>,
1194    source: &str,
1195    mut scope_step: impl FnMut() -> bool,
1196) -> Option<Vec<PythonDirectScopeBinding<'tree>>> {
1197    let mut bindings = Vec::new();
1198
1199    match node.kind() {
1200        "function_definition" => {
1201            if let Some(name) = node.child_by_field_name("name") {
1202                bindings.push(PythonDirectScopeBinding {
1203                    declaration: name,
1204                    kind: if is_direct_module_definition_bounded(node, &mut scope_step)? {
1205                        PythonDirectScopeBindingKind::FunctionDeclaration
1206                    } else {
1207                        PythonDirectScopeBindingKind::Other
1208                    },
1209                });
1210            }
1211        }
1212        "class_definition" => {
1213            if let Some(name) = node.child_by_field_name("name") {
1214                bindings.push(PythonDirectScopeBinding {
1215                    declaration: name,
1216                    kind: if is_direct_module_definition_bounded(node, &mut scope_step)? {
1217                        PythonDirectScopeBindingKind::ClassDeclaration
1218                    } else {
1219                        PythonDirectScopeBindingKind::Other
1220                    },
1221                });
1222            }
1223        }
1224        "import_statement" | "import_from_statement" => {
1225            let module_level = is_direct_module_definition_bounded(node, &mut scope_step)?;
1226            collect_import_bindings(node, &mut scope_step, |declaration| {
1227                bindings.push(PythonDirectScopeBinding {
1228                    declaration,
1229                    kind: if module_level {
1230                        PythonDirectScopeBindingKind::Import
1231                    } else {
1232                        PythonDirectScopeBindingKind::Other
1233                    },
1234                });
1235            })?;
1236        }
1237        "assignment" | "annotated_assignment" | "augmented_assignment" => {
1238            if let Some(target) = node.child_by_field_name("left") {
1239                bindings.extend(python_binding_targets_bounded(
1240                    target,
1241                    source,
1242                    &mut scope_step,
1243                )?);
1244            }
1245        }
1246        "type_alias_statement" => {
1247            if let Some(target) = node.child_by_field_name("left")
1248                && let Some(declaration) = first_identifier_bounded(target, &mut scope_step)?
1249            {
1250                bindings.push(PythonDirectScopeBinding {
1251                    declaration,
1252                    kind: PythonDirectScopeBindingKind::Other,
1253                });
1254            }
1255        }
1256        "named_expression" => {
1257            if let Some(target) = node.child_by_field_name("name") {
1258                bindings.extend(python_binding_targets_bounded(
1259                    target,
1260                    source,
1261                    &mut scope_step,
1262                )?);
1263            }
1264        }
1265        "for_statement" | "async_for_statement" => {
1266            if let Some(target) = node.child_by_field_name("left") {
1267                bindings.extend(python_binding_targets_bounded(
1268                    target,
1269                    source,
1270                    &mut scope_step,
1271                )?);
1272            }
1273        }
1274        "with_statement" => {
1275            let mut cursor = node.walk();
1276            for item in node
1277                .named_children(&mut cursor)
1278                .filter(|item| item.kind() == "with_item")
1279            {
1280                if let Some(alias) = item.child_by_field_name("alias") {
1281                    collect_binding_targets(alias, source, &mut scope_step, |_, declaration| {
1282                        bindings.push(PythonDirectScopeBinding {
1283                            declaration,
1284                            kind: PythonDirectScopeBindingKind::Other,
1285                        });
1286                    })?;
1287                }
1288            }
1289        }
1290        "delete_statement" => {
1291            for target in named_children_bounded(node, &mut scope_step)? {
1292                bindings.extend(python_binding_targets_bounded(
1293                    target,
1294                    source,
1295                    &mut scope_step,
1296                )?);
1297            }
1298        }
1299        "as_pattern" => {
1300            if let Some(alias) = node.child_by_field_name("alias") {
1301                collect_binding_targets(alias, source, &mut scope_step, |_, declaration| {
1302                    bindings.push(PythonDirectScopeBinding {
1303                        declaration,
1304                        kind: PythonDirectScopeBindingKind::Other,
1305                    });
1306                })?;
1307            }
1308        }
1309        "except_clause" => {
1310            if let Some(alias) = node.child_by_field_name("alias") {
1311                collect_binding_targets(alias, source, &mut scope_step, |_, declaration| {
1312                    bindings.push(PythonDirectScopeBinding {
1313                        declaration,
1314                        kind: PythonDirectScopeBindingKind::Other,
1315                    });
1316                })?;
1317            }
1318        }
1319        "case_clause" => {
1320            for child in named_children_bounded(node, &mut scope_step)? {
1321                if child.kind() == "case_pattern" {
1322                    collect_match_pattern_bindings(
1323                        child,
1324                        source,
1325                        &mut scope_step,
1326                        |_, declaration| {
1327                            bindings.push(PythonDirectScopeBinding {
1328                                declaration,
1329                                kind: PythonDirectScopeBindingKind::Other,
1330                            });
1331                        },
1332                    )?;
1333                }
1334            }
1335        }
1336        _ => {}
1337    }
1338    Some(bindings)
1339}
1340
1341/// Whether a module or class execution scope binds `target_name` anywhere in
1342/// its direct scope. Nested callable and class bodies are separate scopes, but
1343/// their headers still execute in this scope. A wildcard import keeps the
1344/// name's runtime identity open even when it does not expose a static binder.
1345pub fn python_module_or_class_scope_binds_name_bounded(
1346    scope: Node<'_>,
1347    target_name: &str,
1348    source: &str,
1349    scope_step: impl FnMut() -> bool,
1350) -> Option<bool> {
1351    python_scope_binds_name_with_filter_bounded(scope, target_name, source, |_| true, scope_step)
1352}
1353
1354fn python_scope_binds_name_with_filter_bounded<'tree>(
1355    scope: Node<'tree>,
1356    target_name: &str,
1357    source: &str,
1358    include_binding: impl Fn(Node<'tree>) -> bool,
1359    mut scope_step: impl FnMut() -> bool,
1360) -> Option<bool> {
1361    assert!(matches!(scope.kind(), "module" | "class_definition"));
1362    let body = scope.child_by_field_name("body").unwrap_or(scope);
1363    let mut stack = vec![body];
1364    while let Some(node) = stack.pop() {
1365        if !scope_step() {
1366            return None;
1367        }
1368        if node.kind() == "wildcard_import" {
1369            return Some(true);
1370        }
1371        if python_direct_scope_bindings_bounded(node, source, &mut scope_step)?
1372            .into_iter()
1373            .any(|binding| {
1374                include_binding(binding.declaration)
1375                    && node_text(binding.declaration, source) == target_name
1376            })
1377        {
1378            return Some(true);
1379        }
1380        stack.extend(python_executable_scope_children(node));
1381    }
1382    Some(false)
1383}
1384
1385/// Iterate executable-scope children, skipping nested callable and class bodies.
1386pub fn python_executable_scope_children<'tree>(
1387    node: Node<'tree>,
1388) -> impl Iterator<Item = Node<'tree>> {
1389    let excluded_body = matches!(
1390        node.kind(),
1391        "class_definition" | "function_definition" | "lambda"
1392    )
1393    .then(|| node.child_by_field_name("body").map(|body| body.id()))
1394    .flatten();
1395    named_children_iter(node).filter(move |child| Some(child.id()) != excluded_body)
1396}
1397
1398pub fn python_unambiguous_module_class_binding_bounded(
1399    root: Node<'_>,
1400    source: &str,
1401    target_name: &str,
1402    scope_step: impl FnMut() -> bool,
1403) -> Option<bool> {
1404    Some(
1405        python_unambiguous_module_binding_bounded(root, source, target_name, scope_step)?
1406            == Some(PythonDirectScopeBindingKind::ClassDeclaration),
1407    )
1408}
1409
1410/// The kind of the module scope's one binding of `target_name`.
1411///
1412/// `Some(None)` says the module does not bind the name, binds it more than
1413/// once, or leaves its identity open through a wildcard import; the name is
1414/// then not a proven reference to one module-level declaration. `None` says the
1415/// bounded walk ran out of work.
1416pub fn python_unambiguous_module_binding_bounded(
1417    root: Node<'_>,
1418    source: &str,
1419    target_name: &str,
1420    scope_step: impl FnMut() -> bool,
1421) -> Option<Option<PythonDirectScopeBindingKind>> {
1422    Some(
1423        python_unambiguous_module_binding_node_bounded(root, source, target_name, scope_step)?
1424            .map(|binding| binding.kind),
1425    )
1426}
1427
1428/// The module scope's unique binding event, after the bounded proof completes.
1429///
1430/// A returned node identifies the actual binder, not a proven runtime value.
1431/// `Other` still needs the caller's syntax and visibility checks. Competing
1432/// events or a later wildcard return `Some(None)`; an interrupted proof returns
1433/// `None` and must never expose a binder found before the interruption.
1434pub fn python_unambiguous_module_binding_node_bounded<'tree>(
1435    root: Node<'tree>,
1436    source: &str,
1437    target_name: &str,
1438    mut scope_step: impl FnMut() -> bool,
1439) -> Option<Option<PythonDirectScopeBinding<'tree>>> {
1440    let mut matched = None;
1441    let mut stack = vec![root];
1442    while let Some(node) = stack.pop() {
1443        if !scope_step() {
1444            return None;
1445        }
1446        // A later unconditional declaration replaces an earlier wildcard
1447        // binding; a wildcard after it leaves its identity open.
1448        if node.kind() == "wildcard_import" && matched.is_some() {
1449            return Some(None);
1450        }
1451        for binding in python_direct_scope_bindings_bounded(node, source, &mut scope_step)? {
1452            if node_text(binding.declaration, source) != target_name {
1453                continue;
1454            }
1455            if matched.is_some() {
1456                return Some(None);
1457            }
1458            matched = Some(binding);
1459        }
1460
1461        let body = matches!(
1462            node.kind(),
1463            "function_definition" | "class_definition" | "lambda"
1464        )
1465        .then(|| node.child_by_field_name("body").map(|child| child.id()))
1466        .flatten();
1467        let name = matches!(node.kind(), "function_definition" | "class_definition")
1468            .then(|| node.child_by_field_name("name").map(|child| child.id()))
1469            .flatten();
1470        for child in named_children_bounded(node, &mut scope_step)?
1471            .into_iter()
1472            .filter(|child| Some(child.id()) != body && Some(child.id()) != name)
1473            .rev()
1474        {
1475            stack.push(child);
1476        }
1477    }
1478    Some(matched)
1479}
1480
1481fn is_direct_module_definition_bounded(
1482    node: Node<'_>,
1483    scope_step: &mut impl FnMut() -> bool,
1484) -> Option<bool> {
1485    if !scope_step() {
1486        return None;
1487    }
1488    let Some(mut parent) = node.parent() else {
1489        return Some(false);
1490    };
1491    if parent.kind() == "decorated_definition" {
1492        if !scope_step() {
1493            return None;
1494        }
1495        let Some(grandparent) = parent.parent() else {
1496            return Some(false);
1497        };
1498        parent = grandparent;
1499    }
1500    Some(parent.kind() == "module")
1501}
1502
1503fn collect_direct_identifier_names(
1504    node: Node<'_>,
1505    source: &str,
1506    scope_step: &mut impl FnMut() -> bool,
1507    mut record: impl FnMut(&str),
1508) -> Option<()> {
1509    for child in named_children_bounded(node, scope_step)? {
1510        if child.kind() == "identifier" {
1511            let name = node_text(child, source);
1512            if !name.is_empty() {
1513                record(name);
1514            }
1515        }
1516    }
1517    Some(())
1518}
1519
1520fn collect_import_bindings<'tree>(
1521    statement: Node<'tree>,
1522    scope_step: &mut impl FnMut() -> bool,
1523    mut record: impl FnMut(Node<'tree>),
1524) -> Option<()> {
1525    let mut cursor = statement.walk();
1526    let mut imports = Vec::new();
1527    for imported in statement.children_by_field_name("name", &mut cursor) {
1528        if !scope_step() {
1529            return None;
1530        }
1531        imports.push(imported);
1532    }
1533    for imported in imports {
1534        if let Some(alias) = imported.child_by_field_name("alias") {
1535            record(alias);
1536            continue;
1537        }
1538        let name = imported.child_by_field_name("name").unwrap_or(imported);
1539        let binding = if statement.kind() == "import_statement" {
1540            first_identifier_bounded(name, scope_step)?
1541        } else {
1542            last_identifier_bounded(name, scope_step)?
1543        };
1544        if let Some(binding) = binding {
1545            record(binding);
1546        }
1547    }
1548    Some(())
1549}
1550
1551fn first_identifier_bounded<'tree>(
1552    root: Node<'tree>,
1553    scope_step: &mut impl FnMut() -> bool,
1554) -> Option<Option<Node<'tree>>> {
1555    let mut stack = vec![root];
1556    while let Some(node) = stack.pop() {
1557        if !scope_step() {
1558            return None;
1559        }
1560        if node.kind() == "identifier" {
1561            return Some(Some(node));
1562        }
1563        let children = named_children_bounded(node, scope_step)?;
1564        stack.extend(children.into_iter().rev());
1565    }
1566    Some(None)
1567}
1568
1569fn last_identifier_bounded<'tree>(
1570    root: Node<'tree>,
1571    scope_step: &mut impl FnMut() -> bool,
1572) -> Option<Option<Node<'tree>>> {
1573    let mut result = None;
1574    let mut stack = vec![root];
1575    while let Some(node) = stack.pop() {
1576        if !scope_step() {
1577            return None;
1578        }
1579        if node.kind() == "identifier" {
1580            result = Some(node);
1581            continue;
1582        }
1583        let children = named_children_bounded(node, scope_step)?;
1584        stack.extend(children.into_iter().rev());
1585    }
1586    Some(result)
1587}
1588
1589pub(crate) fn collect_binding_targets<'tree>(
1590    target: Node<'tree>,
1591    source: &str,
1592    scope_step: &mut impl FnMut() -> bool,
1593    mut record: impl FnMut(&str, Node<'tree>),
1594) -> Option<()> {
1595    let mut stack = vec![target];
1596    while let Some(node) = stack.pop() {
1597        if !scope_step() {
1598            return None;
1599        }
1600        match node.kind() {
1601            // These mutate an existing object and do not bind either the
1602            // receiver or member name in the function.
1603            "attribute" | "subscript" => continue,
1604            "identifier" | "keyword_identifier" => {
1605                let name = node_text(node, source);
1606                if !name.is_empty() {
1607                    record(name, node);
1608                }
1609                continue;
1610            }
1611            _ => {}
1612        }
1613        let children = named_children_bounded(node, scope_step)?;
1614        if node.kind() == "as_pattern_target" && children.is_empty() {
1615            let name = node_text(node, source);
1616            if !name.is_empty() {
1617                record(name, node);
1618            }
1619            continue;
1620        }
1621        stack.extend(children.into_iter().rev());
1622    }
1623    Some(())
1624}
1625
1626fn collect_match_pattern_bindings<'tree>(
1627    pattern: Node<'tree>,
1628    source: &str,
1629    scope_step: &mut impl FnMut() -> bool,
1630    mut record: impl FnMut(&str, Node<'tree>),
1631) -> Option<()> {
1632    let mut stack = vec![pattern];
1633    while let Some(node) = stack.pop() {
1634        if !scope_step() {
1635            return None;
1636        }
1637        match node.kind() {
1638            "dotted_name" => {
1639                let identifiers = named_children_bounded(node, scope_step)?
1640                    .into_iter()
1641                    .filter(|child| child.kind() == "identifier")
1642                    .collect::<Vec<_>>();
1643                if let [binding] = identifiers.as_slice() {
1644                    let name = node_text(*binding, source);
1645                    if !name.is_empty() {
1646                        record(name, *binding);
1647                    }
1648                }
1649                continue;
1650            }
1651            "splat_pattern" => {
1652                for child in named_children_bounded(node, scope_step)? {
1653                    if child.kind() == "identifier" {
1654                        let name = node_text(child, source);
1655                        if !name.is_empty() {
1656                            record(name, child);
1657                        }
1658                    }
1659                }
1660                continue;
1661            }
1662            "class_pattern" => {
1663                let mut children = named_children_bounded(node, scope_step)?;
1664                if children
1665                    .first()
1666                    .is_some_and(|child| child.kind() == "dotted_name")
1667                {
1668                    children.remove(0);
1669                }
1670                stack.extend(children.into_iter().rev());
1671                continue;
1672            }
1673            "keyword_pattern" => {
1674                let mut children = named_children_bounded(node, scope_step)?;
1675                if children
1676                    .first()
1677                    .is_some_and(|child| child.kind() == "identifier")
1678                {
1679                    children.remove(0);
1680                }
1681                stack.extend(children.into_iter().rev());
1682                continue;
1683            }
1684            "dict_pattern" => {
1685                let key_ids = children_by_field_name_bounded(node, "key", scope_step)?
1686                    .into_iter()
1687                    .map(|key| key.id())
1688                    .collect::<HashSet<_>>();
1689                let children = named_children_bounded(node, scope_step)?;
1690                stack.extend(
1691                    children
1692                        .into_iter()
1693                        .filter(|child| !key_ids.contains(&child.id()))
1694                        .rev(),
1695                );
1696                continue;
1697            }
1698            "as_pattern" => {
1699                if let Some(alias) = node.child_by_field_name("alias") {
1700                    collect_binding_targets(alias, source, scope_step, &mut record)?;
1701                    let children = named_children_bounded(node, scope_step)?;
1702                    stack.extend(
1703                        children
1704                            .into_iter()
1705                            .filter(|child| child.id() != alias.id())
1706                            .rev(),
1707                    );
1708                    continue;
1709                }
1710                let mut children = named_children_bounded(node, scope_step)?;
1711                if let Some(alias) = children
1712                    .last()
1713                    .copied()
1714                    .filter(|child| child.kind() == "identifier")
1715                {
1716                    let name = node_text(alias, source);
1717                    if !name.is_empty() {
1718                        record(name, alias);
1719                    }
1720                    children.pop();
1721                }
1722                stack.extend(children.into_iter().rev());
1723                continue;
1724            }
1725            "identifier" => {
1726                // Direct identifiers are match `as` aliases handled by their
1727                // parent. Keyword names and class heads are likewise skipped.
1728                continue;
1729            }
1730            kind if is_pattern_literal(kind) => continue,
1731            _ => {}
1732        }
1733        let children = named_children_bounded(node, scope_step)?;
1734        stack.extend(children.into_iter().rev());
1735    }
1736    Some(())
1737}
1738
1739fn push_named_children<'tree>(
1740    stack: &mut Vec<Node<'tree>>,
1741    node: Node<'tree>,
1742    scope_step: &mut impl FnMut() -> bool,
1743) -> Option<()> {
1744    let children = named_children_bounded(node, scope_step)?;
1745    push_bounded_children(stack, children.into_iter());
1746    Some(())
1747}
1748
1749fn push_named_children_except<'tree>(
1750    stack: &mut Vec<Node<'tree>>,
1751    node: Node<'tree>,
1752    excluded: Node<'tree>,
1753    scope_step: &mut impl FnMut() -> bool,
1754) -> Option<()> {
1755    let children = named_children_bounded(node, scope_step)?;
1756    push_bounded_children(
1757        stack,
1758        children
1759            .into_iter()
1760            .filter(|child| child.id() != excluded.id()),
1761    );
1762    Some(())
1763}
1764
1765fn push_nested_scope_header_children<'tree>(
1766    stack: &mut Vec<Node<'tree>>,
1767    node: Node<'tree>,
1768    scope_step: &mut impl FnMut() -> bool,
1769) -> Option<()> {
1770    let body = node.child_by_field_name("body").map(|child| child.id());
1771    let name = node.child_by_field_name("name").map(|child| child.id());
1772    // Prune execution boundaries before charging or visiting their bodies.
1773    // Only the header belongs to the enclosing scope's collector walk.
1774    let mut cursor = node.walk();
1775    let children = node
1776        .named_children(&mut cursor)
1777        .filter(|child| Some(child.id()) != body);
1778    let mut headers = Vec::new();
1779    push_bounded_nodes(children, &mut headers, scope_step).then_some(())?;
1780    push_bounded_children(
1781        stack,
1782        headers.into_iter().filter(|child| Some(child.id()) != name),
1783    );
1784    Some(())
1785}
1786
1787fn push_bounded_children<'tree>(
1788    stack: &mut Vec<Node<'tree>>,
1789    children: impl DoubleEndedIterator<Item = Node<'tree>>,
1790) {
1791    for child in children.rev() {
1792        stack.push(child);
1793    }
1794}
1795
1796fn named_children_bounded<'tree>(
1797    node: Node<'tree>,
1798    scope_step: &mut impl FnMut() -> bool,
1799) -> Option<Vec<Node<'tree>>> {
1800    let mut cursor = node.walk();
1801    let mut children = Vec::new();
1802    push_bounded_nodes(node.named_children(&mut cursor), &mut children, scope_step)
1803        .then_some(children)
1804}
1805
1806fn children_by_field_name_bounded<'tree>(
1807    node: Node<'tree>,
1808    field: &str,
1809    scope_step: &mut impl FnMut() -> bool,
1810) -> Option<Vec<Node<'tree>>> {
1811    let mut cursor = node.walk();
1812    let mut children = Vec::new();
1813    push_bounded_nodes(
1814        node.children_by_field_name(field, &mut cursor),
1815        &mut children,
1816        scope_step,
1817    )
1818    .then_some(children)
1819}
1820
1821pub(crate) fn is_comprehension(kind: &str) -> bool {
1822    matches!(
1823        kind,
1824        "list_comprehension"
1825            | "set_comprehension"
1826            | "dictionary_comprehension"
1827            | "generator_expression"
1828    )
1829}
1830
1831fn is_pattern_literal(kind: &str) -> bool {
1832    matches!(
1833        kind,
1834        "string"
1835            | "concatenated_string"
1836            | "integer"
1837            | "float"
1838            | "complex_pattern"
1839            | "true"
1840            | "false"
1841            | "none"
1842    )
1843}
1844
1845#[cfg(test)]
1846mod tests {
1847    use brokk_bifrost_test_macros::hardwon;
1848
1849    #[test]
1850    fn only_the_first_comprehension_iterable_uses_the_enclosing_scope() {
1851        let source = "def run(first, second):\n    return [second for first in first for second in second]\n";
1852        let mut parser = tree_sitter::Parser::new();
1853        parser
1854            .set_language(&tree_sitter_python::LANGUAGE.into())
1855            .unwrap();
1856        let tree = parser.parse(source, None).unwrap();
1857        let mut stack = vec![tree.root_node()];
1858        let comprehension = loop {
1859            let node = stack.pop().expect("fixture contains a comprehension");
1860            if node.kind() == "list_comprehension" {
1861                break node;
1862            }
1863            let mut cursor = node.walk();
1864            stack.extend(node.named_children(&mut cursor));
1865        };
1866        let mut cursor = comprehension.walk();
1867        let clauses = comprehension
1868            .named_children(&mut cursor)
1869            .filter(|node| node.kind() == "for_in_clause")
1870            .collect::<Vec<_>>();
1871        let outer = clauses[0].child_by_field_name("right").unwrap();
1872        let inner = clauses[1].child_by_field_name("right").unwrap();
1873        assert!(!super::python_comprehension_binds_name_at(
1874            "first", outer, source
1875        ));
1876        assert!(super::python_comprehension_binds_name_at(
1877            "second", inner, source
1878        ));
1879    }
1880
1881    #[test]
1882    #[hardwon(
1883        "#5044+#5511+#5751: bounded lexical proofs bypassed stops, lazy bindings or competing events"
1884    )]
1885    fn bounded_comprehension_lookup_preserves_exhaustion() {
1886        let source = "def run(xs):\n    class Base:\n        pass\n    def helper():\n        pass\n    class Derived(Base):\n        pass\n    helper()\n    return [target for target in xs]\n";
1887        let tree = crate::declarations::parse_python_tree(source).unwrap();
1888        let function = tree.root_node().named_child(0).unwrap();
1889        let inventory = super::PythonLexicalScopeInventory::collect_bounded(
1890            function,
1891            source,
1892            ["xs".to_owned()],
1893            || true,
1894        )
1895        .unwrap();
1896        let mut stack = vec![function];
1897        let comprehension = loop {
1898            let node = stack.pop().expect("fixture contains a comprehension");
1899            if node.kind() == "list_comprehension" {
1900                break node;
1901            }
1902            stack.extend(brokk_bifrost_core::analyzer::tree_walk::named_children_iter(node));
1903        };
1904        let reference = comprehension.named_child(0).unwrap();
1905        for mut remaining in [0_usize, 1] {
1906            assert_eq!(
1907                inventory.name_resolution_at_bounded("target", reference, || {
1908                    let available = remaining > 0;
1909                    remaining = remaining.saturating_sub(1);
1910                    available
1911                }),
1912                None
1913            );
1914        }
1915        assert_eq!(
1916            inventory.name_resolution_at_bounded("target", reference, || true),
1917            Some(super::PythonLexicalNameResolution::Local)
1918        );
1919        let body = function.child_by_field_name("body").unwrap();
1920        let derived = brokk_bifrost_core::analyzer::tree_walk::named_children_iter(body)
1921            .find(|node| node.child_by_field_name("superclasses").is_some())
1922            .unwrap();
1923        let base_reference = derived
1924            .child_by_field_name("superclasses")
1925            .unwrap()
1926            .named_child(0)
1927            .unwrap();
1928        let call = brokk_bifrost_core::analyzer::tree_walk::named_children_iter(body)
1929            .filter(|node| node.kind() == "expression_statement")
1930            .find_map(|node| node.named_child(0).filter(|node| node.kind() == "call"))
1931            .unwrap();
1932        let helper_reference = call.child_by_field_name("function").unwrap();
1933        // Collection has completed, but every later lookup must still charge
1934        // retained comprehension facts. One step cannot finish that scan.
1935        let one_step = || {
1936            let mut available = true;
1937            move || std::mem::take(&mut available)
1938        };
1939        assert!(
1940            inventory
1941                .has_runtime_callable_binding_at_bounded("helper", helper_reference, one_step())
1942                .is_none()
1943        );
1944        assert!(
1945            inventory
1946                .local_function_declaration_bounded("helper", helper_reference, one_step())
1947                .is_none()
1948        );
1949        assert!(
1950            inventory
1951                .local_class_declaration_bounded("Base", base_reference, one_step())
1952                .is_none()
1953        );
1954        assert_eq!(
1955            inventory
1956                .local_function_declaration_bounded("helper", helper_reference, || true)
1957                .unwrap()
1958                .kind(),
1959            "function_definition"
1960        );
1961        assert_eq!(
1962            inventory
1963                .local_class_declaration_bounded("Base", base_reference, || true)
1964                .unwrap()
1965                .kind(),
1966            "class_definition"
1967        );
1968        let bindings = inventory.into_bindings();
1969        assert_eq!(
1970            bindings.name_resolution_at_bounded("missing", reference, one_step()),
1971            None,
1972            "stopped lookup must not manufacture Unbound"
1973        );
1974        assert_eq!(
1975            bindings.name_resolution_at_bounded("missing", reference, || true),
1976            Some(super::PythonLexicalNameResolution::Unbound)
1977        );
1978        assert_eq!(
1979            bindings.resolves_to_local_function_bounded("helper", helper_reference, one_step()),
1980            None
1981        );
1982        assert_eq!(
1983            bindings.resolves_to_local_function_bounded("helper", helper_reference, || true),
1984            Some(true)
1985        );
1986        assert_eq!(
1987            super::python_comprehension_binds_name_at_bounded(
1988                "target",
1989                reference,
1990                source,
1991                one_step()
1992            ),
1993            None
1994        );
1995        assert_eq!(
1996            super::python_comprehension_binds_name_at_bounded("target", reference, source, || true),
1997            Some(true)
1998        );
1999        let clause = brokk_bifrost_core::analyzer::tree_walk::named_children_iter(comprehension)
2000            .find(|node| node.kind() == "for_in_clause")
2001            .unwrap();
2002        let targets = super::python_binding_targets_bounded(
2003            clause.child_by_field_name("left").unwrap(),
2004            source,
2005            || true,
2006        )
2007        .unwrap();
2008        assert_eq!(targets.len(), 1);
2009        assert_eq!(
2010            Some(targets[0].declaration),
2011            clause.child_by_field_name("left")
2012        );
2013
2014        // An assignment binder is positive evidence only after later events
2015        // and executable headers have been checked. Body-local writes do not
2016        // compete, but header walrus writes and later wildcards do.
2017        use super::PythonDirectScopeBindingKind::{ClassDeclaration, Other};
2018        for (source, expected_kind) in [
2019            ("Alias = Base\ntrailing = None\n", Some(Other)),
2020            ("Alias = Base\nAlias = Other\n", None),
2021            ("Alias = Base\ndel Alias\n", None),
2022            ("Alias = Base\nfrom pkg import Target as Alias\n", None),
2023            ("Alias = Base\nfrom pkg import *\n", None),
2024            ("from pkg import *\nAlias = Base\n", Some(Other)),
2025            (
2026                "Alias = Base\ndef inner():\n    Alias = Other\nclass Container:\n    Alias = Other\n",
2027                Some(Other),
2028            ),
2029            (
2030                "Alias = Base\ndef inner(value=(Alias := Other)):\n    pass\n",
2031                None,
2032            ),
2033            ("class Alias:\n    pass\n", Some(ClassDeclaration)),
2034            (
2035                "from pkg import *\nclass Alias:\n    pass\n",
2036                Some(ClassDeclaration),
2037            ),
2038            ("class Alias:\n    pass\nfrom pkg import *\n", None),
2039            ("Other = Base\n", None),
2040        ] {
2041            let tree = crate::declarations::parse_python_tree(source).unwrap();
2042            let root = tree.root_node();
2043            assert!(!root.has_error(), "{source}");
2044            let mut steps = 0_usize;
2045            let binding = super::python_unambiguous_module_binding_node_bounded(
2046                root,
2047                source,
2048                "Alias",
2049                || {
2050                    steps += 1;
2051                    true
2052                },
2053            )
2054            .expect("uninterrupted binding proof completes");
2055            assert_eq!(
2056                binding.map(|binding| binding.kind),
2057                expected_kind,
2058                "{source}"
2059            );
2060            if let Some(binding) = binding {
2061                assert_eq!(binding.declaration.kind(), "identifier");
2062                assert_eq!(super::node_text(binding.declaration, source), "Alias");
2063                let parent = binding.declaration.parent().unwrap();
2064                let field = if binding.kind == ClassDeclaration {
2065                    "name"
2066                } else {
2067                    "left"
2068                };
2069                assert_eq!(parent.child_by_field_name(field), Some(binding.declaration));
2070                let statement = if binding.kind == ClassDeclaration {
2071                    parent
2072                } else {
2073                    parent.parent().unwrap()
2074                };
2075                assert_eq!(statement.parent(), Some(root), "exact module-owned binder");
2076            }
2077            assert_eq!(
2078                super::python_unambiguous_module_binding_bounded(root, source, "Alias", || true),
2079                Some(expected_kind),
2080                "kind-only consumers retain the same positive requirement: {source}"
2081            );
2082            assert_eq!(
2083                super::python_unambiguous_module_class_binding_bounded(
2084                    root,
2085                    source,
2086                    "Alias",
2087                    || true
2088                ),
2089                Some(expected_kind == Some(ClassDeclaration))
2090            );
2091            for mut remaining in 0..steps {
2092                assert!(
2093                    super::python_unambiguous_module_binding_node_bounded(
2094                        root,
2095                        source,
2096                        "Alias",
2097                        || {
2098                            let available = remaining > 0;
2099                            remaining = remaining.saturating_sub(1);
2100                            available
2101                        },
2102                    )
2103                    .is_none(),
2104                    "a stopped proof cannot publish its early binder: {source}"
2105                );
2106            }
2107        }
2108
2109        // The same spelling is an immediate base root and a lazy bound root.
2110        // Generic hierarchy refusal cannot test this shared binding distinction.
2111        let source = "import ns_source as ns\nclass Outer:\n    class ns[T: ns.Target]((ns.Target)):\n        pass\n";
2112        let tree = crate::declarations::parse_python_tree(source).unwrap();
2113        assert!(!tree.root_node().has_error());
2114        let outer = brokk_bifrost_core::analyzer::tree_walk::first_named_child_of_kind(
2115            tree.root_node(),
2116            "class_definition",
2117        )
2118        .unwrap();
2119        let inner = brokk_bifrost_core::analyzer::tree_walk::first_named_child_of_kind(
2120            outer.child_by_field_name("body").unwrap(),
2121            "class_definition",
2122        )
2123        .unwrap();
2124        let base = inner
2125            .child_by_field_name("superclasses")
2126            .unwrap()
2127            .named_child(0)
2128            .unwrap();
2129        let immediate = crate::syntax::python_static_value_path_bounded(base, || true)
2130            .unwrap()
2131            .unwrap()[0];
2132        let bound =
2133            brokk_bifrost_core::analyzer::tree_walk::first_named_descendant_of_kind_inclusive(
2134                inner.child_by_field_name("type_parameters").unwrap(),
2135                "attribute",
2136            )
2137            .unwrap()
2138            .child_by_field_name("object")
2139            .unwrap();
2140        for (reference, resolution, binds) in [
2141            (
2142                immediate,
2143                super::PythonLexicalNameResolution::Unbound,
2144                false,
2145            ),
2146            (bound, super::PythonLexicalNameResolution::Local, true),
2147        ] {
2148            assert!(
2149                super::PythonClassReferenceScope::new_bounded(outer, reference, || false).is_none()
2150            );
2151            let scope =
2152                super::PythonClassReferenceScope::new_bounded(outer, reference, || true).unwrap();
2153            let inventory = scope.collect_bounded(source, || true).unwrap();
2154            assert_eq!(
2155                inventory.name_resolution_at_bounded("ns", reference, || true),
2156                Some(resolution)
2157            );
2158            assert_eq!(scope.binds_name_bounded("ns", source, || true), Some(binds));
2159        }
2160    }
2161}