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