1use crate::bindings::{
6 PythonLexicalNameResolution, python_comprehension_binds_name_at, python_name_resolution_at,
7 python_type_parameter_binds_name_at,
8};
9use crate::graph::PythonGraphSource;
10use crate::graph::hits::{
11 record_hit, record_import_hit, record_self_receiver_hit, record_unproven_hit,
12};
13use crate::graph::resolver::{
14 annotation_class_qualifier_sites, annotation_reference_candidates, member_name,
15 normalized_receiver_type, receiver_annotation_matches_target,
16 resolve_callable_parameter_default_types, resolve_constructor_types, resolve_receiver_type,
17 resolve_visible_named_import_candidates, resolved_member_declarations, target_owner_code_unit,
18 top_level_identifier,
19};
20use crate::graph_support::{PythonSource, PythonUsageSource};
21use crate::imports::{
22 PythonImportBinding, PythonImportDetails, imported_module_assignment_at,
23 python_function_scoped_import_binding, python_import_bindings_from_imports,
24 python_import_details, python_imports_by_statement, resolve_fqn_candidates,
25 resolve_python_module_specifier,
26};
27use crate::syntax::{
28 attribute_chain, is_declaration_identifier, leftmost_identifier, python_plain_string_literal,
29 python_reference_is_deferred_function_body,
30};
31use crate::usage_index::{
32 ModuleBindingEvent, ModuleBindingEventKind, ModuleBindingTimeline, PythonScopeFacts,
33 usage_matching_edges, usage_module_binding_timeline, usage_resolve_module_files,
34 usage_scope_facts,
35};
36pub use brokk_bifrost_core::analyzer::common::node_source_text as slice;
37use brokk_bifrost_core::analyzer::common::nonempty_node_source_text as non_empty_node_text;
38use brokk_bifrost_core::analyzer::model::ImportInfo;
39use brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path;
40use brokk_bifrost_core::analyzer::tree_walk::parent_if_field;
41use brokk_bifrost_core::analyzer::usages::local_inference::{
42 LocalBindingsSnapshot, LocalInferenceConfig, LocalInferenceEngine, SymbolResolution,
43};
44use brokk_bifrost_core::analyzer::usages::model::{ImportKind, UsageHit};
45use brokk_bifrost_core::analyzer::usages::{ImportEdge, ImportEdgeKind};
46use brokk_bifrost_core::analyzer::{CodeUnit, CodeUnitIndex, Language, ProjectFile, Range};
47use brokk_bifrost_core::cancellation::CancellationToken;
48use brokk_bifrost_core::hash::{HashMap, HashSet};
49use brokk_bifrost_core::text_utils::compute_line_starts;
50use std::collections::BTreeSet;
51use std::sync::Arc;
52use tree_sitter::{Node, Parser, Tree};
53
54pub struct ParsedFile {
55 pub source: Arc<String>,
56 pub tree: Tree,
57}
58
59pub struct PythonProjectGraph {
60 parsed: HashMap<ProjectFile, ParsedFile>,
61}
62
63pub fn build_python_graph(
64 candidate_files: &HashSet<ProjectFile>,
65 target_file: &ProjectFile,
66 cancellation: Option<&CancellationToken>,
67) -> PythonProjectGraph {
68 let parser_language = tree_sitter_python::LANGUAGE.into();
69 let files: HashSet<ProjectFile> = candidate_files
70 .iter()
71 .cloned()
72 .chain(std::iter::once(target_file.clone()))
73 .collect();
74 let mut parsed = HashMap::default();
75
76 for file in files {
77 if cancellation.is_some_and(CancellationToken::is_cancelled) {
78 break;
79 }
80 let Ok(source) = file.read_to_string() else {
81 continue;
82 };
83 if cancellation.is_some_and(CancellationToken::is_cancelled) {
84 break;
85 }
86 if source.is_empty() {
87 continue;
88 }
89 let mut parser = Parser::new();
90 if parser.set_language(&parser_language).is_err() {
91 continue;
92 }
93 let Some(tree) = parser.parse(source.as_str(), None) else {
94 continue;
95 };
96 if cancellation.is_some_and(CancellationToken::is_cancelled) {
97 break;
98 }
99 parsed.insert(
100 file,
101 ParsedFile {
102 source: Arc::new(source),
103 tree,
104 },
105 );
106 }
107
108 PythonProjectGraph { parsed }
109}
110
111pub struct PythonScanTarget<'a> {
113 target: &'a CodeUnit,
114 target_short: String,
115 target_member: Option<String>,
116 target_owner: Option<CodeUnit>,
117 member_unique_in_target_file: bool,
118}
119
120impl<'a> PythonScanTarget<'a> {
121 pub fn new(index: &dyn CodeUnitIndex, target: &'a CodeUnit) -> Self {
123 let target_member = member_name(index, target);
124 let member_unique_in_target_file = target_member.as_deref().is_some_and(|member| {
128 let owners: HashSet<CodeUnit> = index
129 .declarations(target.source())
130 .into_iter()
131 .filter(|decl| {
132 decl.identifier() == member && target_owner_code_unit(index, decl).is_some()
133 })
134 .filter_map(|decl| target_owner_code_unit(index, &decl))
135 .collect();
136 owners.len() == 1
137 });
138 Self {
139 target,
140 target_short: top_level_identifier(index, target),
141 target_member,
142 target_owner: target_owner_code_unit(index, target),
143 member_unique_in_target_file,
144 }
145 }
146}
147
148pub type PythonSeedScan<'a> = (
150 &'a PythonGraphSource<'a>,
151 &'a PythonScanTarget<'a>,
152 &'a BTreeSet<(ProjectFile, String)>,
153);
154
155pub fn scan_file_for_seed_batch(
157 graph: &PythonGraphSource<'_>,
158 python: &dyn PythonUsageSource,
159 project_graph: &PythonProjectGraph,
160 file: &ProjectFile,
161 targets: &[PythonSeedScan<'_>],
162 cancellation: Option<&CancellationToken>,
163) -> Vec<Result<ScanResult, ProjectFile>> {
164 let empty = || {
165 (0..targets.len())
166 .map(|_| Ok(ScanResult::default()))
167 .collect()
168 };
169 let parser_language = tree_sitter_python::LANGUAGE.into();
170 if cancellation.is_some_and(CancellationToken::is_cancelled) {
171 return empty();
172 }
173 let owned_source: Option<Arc<String>>;
174 let owned_tree: Option<Tree>;
175 let (source_str, tree_ref) = {
176 let _scope = brokk_bifrost_core::profiling::scope("python_graph::read_or_parse_candidate");
177 if let Some(parsed) = project_graph.parsed.get(file) {
178 (parsed.source.as_str(), &parsed.tree)
179 } else {
180 let Ok(source) = file.read_to_string() else {
181 return empty();
182 };
183 if source.is_empty() {
184 return empty();
185 }
186 let mut parser = Parser::new();
187 if parser.set_language(&parser_language).is_err() {
188 return empty();
189 }
190 let Some(tree) = parser.parse(source.as_str(), None) else {
191 return empty();
192 };
193 owned_source = Some(Arc::new(source));
194 owned_tree = Some(tree);
195 (
196 owned_source.as_deref().unwrap().as_str(),
197 owned_tree.as_ref().unwrap(),
198 )
199 }
200 };
201 if cancellation.is_some_and(CancellationToken::is_cancelled) {
202 return empty();
203 }
204
205 let edges: Vec<_> = targets
206 .iter()
207 .map(|(_, _, seeds)| usage_matching_edges(python, file, seeds))
208 .collect();
209 let mut names = HashSet::default();
210 let mut has_string = false;
211 let mut stack = vec![tree_ref.root_node()];
212 while let Some(node) = stack.pop() {
213 if node.kind() == "identifier" {
214 names.insert(slice(node, source_str));
215 }
216 has_string |= node.kind() == "string";
217 let mut cursor = node.walk();
218 stack.extend(node.named_children(&mut cursor));
219 }
220 let active: Vec<_> = targets
221 .iter()
222 .zip(&edges)
223 .map(|((_, target, _), edges)| {
224 target.target.is_module()
225 || has_string
226 || names.contains(target.target_short.as_str())
227 || target
228 .target_member
229 .as_deref()
230 .is_some_and(|name| names.contains(name))
231 || edges
232 .iter()
233 .any(|edge| names.contains(edge.local_name.as_str()))
234 })
235 .collect();
236 if !active.iter().any(|active| *active) {
237 return empty();
238 }
239 let imports = python.import_info_of(graph.token, file);
240 let raw_module_bindings = {
241 let _scope = brokk_bifrost_core::profiling::scope("python_graph::module_binding_timeline");
242 usage_module_binding_timeline(python, file, || {
243 collect_module_binding_timeline(tree_ref.root_node(), source_str, &imports)
244 })
245 };
246 let module_bindings: Vec<_> = targets
247 .iter()
248 .zip(&edges)
249 .map(|((_, _, seeds), edges)| {
250 classify_module_binding_timeline(
251 python,
252 file,
253 raw_module_bindings.as_ref(),
254 seeds,
255 edges,
256 )
257 })
258 .collect();
259 let scoped_import_bindings =
260 python_import_bindings_from_imports(&imports, tree_ref.root_node(), source_str.len());
261 let scope_facts = {
262 let _scope = brokk_bifrost_core::profiling::scope("python_graph::scope_facts");
263 usage_scope_facts(python, file, || {
264 collect_scope_facts_from_parsed_source(
265 graph,
266 python,
267 file,
268 source_str,
269 tree_ref.root_node(),
270 )
271 })
272 };
273 let Some(scope_facts) = scope_facts else {
274 return active
275 .iter()
276 .map(|active| {
277 if *active {
278 Err(file.clone())
279 } else {
280 Ok(ScanResult::default())
281 }
282 })
283 .collect();
284 };
285 let scope_range_index = {
286 let _scope = brokk_bifrost_core::profiling::scope("python_graph::scope_range_index");
287 build_scope_range_index(graph, scope_facts.as_ref())
288 };
289
290 let line_starts = compute_line_starts(source_str);
291 let mut results: Vec<ScanResult> = (0..targets.len()).map(|_| ScanResult::default()).collect();
292 let mut contexts: Vec<_> = targets
293 .iter()
294 .zip(&edges)
295 .zip(&module_bindings)
296 .zip(results.iter_mut())
297 .map(
298 |((((target_graph, scan_target, seeds), edges), module_bindings), result)| {
299 let target = scan_target.target;
300 let target_self_file = file == target.source();
301 ScanCtx {
302 python,
303 file,
304 source: source_str,
305 line_starts: &line_starts,
306 graph: target_graph,
307 target,
308 target_short: &scan_target.target_short,
309 target_member: scan_target.target_member.as_deref(),
310 target_owner: scan_target.target_owner.clone(),
311 target_is_module: target.is_module(),
312 target_source: target.source(),
313 seeds,
314 edges,
315 target_self_file,
316 member_best_effort_unique: target_self_file
317 && scan_target.member_unique_in_target_file,
318 raw_module_bindings: raw_module_bindings.as_ref(),
319 module_bindings,
320 scoped_import_bindings: &scoped_import_bindings,
321 scope_facts: scope_facts.as_ref(),
322 scope_range_index: &scope_range_index,
323 hits: &mut result.hits,
324 unproven_hits: &mut result.unproven_hits,
325 }
326 },
327 )
328 .collect();
329 {
330 let _scope = brokk_bifrost_core::profiling::scope("python_graph::scan_tree");
331 scan_nodes_for_targets(
332 tree_ref.root_node(),
333 source_str,
334 graph,
335 &mut contexts,
336 &active,
337 );
338 }
339 results.into_iter().map(Ok).collect()
340}
341
342#[derive(Default)]
343pub struct ScanResult {
344 pub hits: BTreeSet<UsageHit>,
345 pub unproven_hits: BTreeSet<UsageHit>,
346}
347
348pub struct ScanCtx<'a> {
349 python: &'a dyn PythonUsageSource,
350 pub file: &'a ProjectFile,
351 pub source: &'a str,
352 pub line_starts: &'a [usize],
353 pub graph: &'a PythonGraphSource<'a>,
354 target: &'a CodeUnit,
355 target_short: &'a str,
356 target_member: Option<&'a str>,
357 target_owner: Option<CodeUnit>,
358 target_is_module: bool,
359 target_source: &'a ProjectFile,
360 seeds: &'a BTreeSet<(ProjectFile, String)>,
361 edges: &'a [ImportEdge],
362 target_self_file: bool,
363 member_best_effort_unique: bool,
369 raw_module_bindings: &'a ModuleBindingTimeline,
370 module_bindings: &'a HashMap<String, Vec<ClassifiedModuleBindingEvent>>,
371 scoped_import_bindings: &'a [PythonImportBinding],
372 scope_facts: &'a HashMap<CodeUnit, LocalBindingsSnapshot<String>>,
373 scope_range_index: &'a [ScopeRangeEntry],
374 pub hits: &'a mut BTreeSet<UsageHit>,
375 pub unproven_hits: &'a mut BTreeSet<UsageHit>,
376}
377
378struct ScopeRangeEntry {
379 range: Range,
380 scope: CodeUnit,
381 prefix_max_end: usize,
382}
383
384fn build_scope_range_index(
385 graph: &PythonGraphSource<'_>,
386 scope_facts: &HashMap<CodeUnit, LocalBindingsSnapshot<String>>,
387) -> Vec<ScopeRangeEntry> {
388 let mut entries = scope_facts
389 .keys()
390 .flat_map(|scope| {
391 graph
392 .index
393 .ranges(scope)
394 .into_iter()
395 .map(|range| ScopeRangeEntry {
396 range,
397 scope: scope.clone(),
398 prefix_max_end: 0,
399 })
400 })
401 .collect::<Vec<_>>();
402 entries.sort_by(|left, right| {
403 left.range
404 .start_byte
405 .cmp(&right.range.start_byte)
406 .then_with(|| right.range.end_byte.cmp(&left.range.end_byte))
407 .then_with(|| left.scope.cmp(&right.scope))
408 });
409 let mut max_end = 0;
410 for entry in &mut entries {
411 max_end = max_end.max(entry.range.end_byte);
412 entry.prefix_max_end = max_end;
413 }
414 entries
415}
416
417fn indexed_scope_entry<'entry, 'facts>(
418 scope_range_index: &'entry [ScopeRangeEntry],
419 scope_facts: &'facts HashMap<CodeUnit, LocalBindingsSnapshot<String>>,
420 node: Node<'_>,
421 mut skip_innermost: usize,
422) -> Option<(&'entry CodeUnit, &'facts LocalBindingsSnapshot<String>)> {
423 let mut cursor =
424 scope_range_index.partition_point(|entry| entry.range.start_byte <= node.start_byte());
425 while cursor > 0 {
426 cursor -= 1;
427 let entry = &scope_range_index[cursor];
428 if entry.prefix_max_end < node.end_byte() {
429 return None;
430 }
431 if entry.range.end_byte >= node.end_byte() {
432 if skip_innermost > 0 {
433 skip_innermost -= 1;
434 continue;
435 }
436 return scope_facts
437 .get(&entry.scope)
438 .map(|facts| (&entry.scope, facts));
439 }
440 }
441 None
442}
443
444pub fn enclosing_scope_facts<'a>(
448 index: &dyn CodeUnitIndex,
449 file: &ProjectFile,
450 scope_facts: &'a HashMap<CodeUnit, LocalBindingsSnapshot<String>>,
451 node: Node<'_>,
452) -> Option<&'a LocalBindingsSnapshot<String>> {
453 let range = Range {
454 start_byte: node.start_byte(),
455 end_byte: node.end_byte(),
456 start_line: 0,
457 end_line: 0,
458 };
459 let enclosing = index.enclosing_code_unit(file, &range)?;
460 scope_facts.get(&enclosing)
461}
462
463impl ScanCtx<'_> {
464 fn scope_entry_for_node(
465 &self,
466 node: Node<'_>,
467 ) -> Option<(&CodeUnit, &LocalBindingsSnapshot<String>)> {
468 indexed_scope_entry(
469 self.scope_range_index,
470 self.scope_facts,
471 node,
472 usize::from(function_declaration_expression_is_outer_scoped(node)),
473 )
474 }
475
476 fn scope_facts_for_node(&self, node: Node<'_>) -> Option<&LocalBindingsSnapshot<String>> {
477 self.scope_entry_for_node(node).map(|(_, facts)| facts)
478 }
479
480 fn binds_target(&self, ident: &str, node: Node<'_>) -> bool {
481 if python_comprehension_binds_name_at(ident, node, self.source)
482 || python_type_parameter_binds_name_at(ident, node, self.source)
483 {
484 return false;
485 }
486 if self.target_self_file && ident == self.target_short {
487 match python_name_resolution_at(ident, node, self.source) {
488 PythonLexicalNameResolution::Global => return true,
489 PythonLexicalNameResolution::Local | PythonLexicalNameResolution::Nonlocal => {
490 return false;
491 }
492 PythonLexicalNameResolution::Unbound => {}
493 }
494 }
495 let scope_entry = self.scope_entry_for_node(node);
496 if self.target_self_file
497 && ident == self.target_short
498 && scope_entry
499 .is_none_or(|(scope, facts)| scope.is_module() || !facts.is_shadowed(ident))
500 {
501 return true;
502 }
503 if scope_entry.is_some_and(|(scope, facts)| !scope.is_module() && facts.is_shadowed(ident))
504 {
505 return false;
506 }
507 self.module_binding_targets_query(ident, node)
508 }
509
510 fn receiver_binds_target(&self, expr: &str, node: Node<'_>) -> bool {
511 if self.binds_target(expr, node) {
512 return true;
513 }
514
515 if self.target_member.is_some() && self.import_edge_visible_for(expr, node) {
516 return true;
517 }
518
519 if matches!(expr, "self" | "cls") && self.self_receiver_matches_target(node) {
523 return true;
524 }
525
526 match enclosing_runtime_parameter_type(expr, node, self.source) {
527 EnclosingParameterType::Typed(raw_type) => {
528 return self.receiver_type_matches_target(&raw_type);
529 }
530 EnclosingParameterType::Untyped => return false,
531 EnclosingParameterType::NotDeclared => {}
532 }
533
534 let Some(scope_facts) = self.scope_facts_for_node(node) else {
535 return false;
536 };
537 let resolution = scope_facts.resolution_for(expr);
538 let Some(raw_type) = resolution
539 .as_precise()
540 .and_then(|targets| targets.iter().next())
541 else {
542 return false;
543 };
544 self.receiver_type_matches_target(raw_type)
545 }
546
547 fn importlib_assignment_targets_query(&self, receiver: Node<'_>, node: Node<'_>) -> bool {
548 if receiver.kind() != "identifier" {
549 return false;
550 }
551 let local = slice(receiver, self.source);
552 let Some(module) =
553 imported_module_assignment_at(node, local, self.source, |importlib_local| {
554 self.importlib_binding_visible(importlib_local, node)
555 })
556 else {
557 return false;
558 };
559 self.graph
560 .index
561 .parent_of(self.target)
562 .filter(CodeUnit::is_module)
563 .is_some_and(|owner| {
564 owner.fq_name() == module
565 || resolve_fqn_candidates(self.python, Some(self.file), &module, |name| {
566 self.graph.index.definitions(name).collect()
567 })
568 .into_iter()
569 .any(|candidate| candidate.is_module() && candidate == owner)
570 })
571 || module_contains_seed(self.python, self.file, &module, self.seeds)
572 }
573
574 fn importlib_binding_visible(&self, local: &str, node: Node<'_>) -> bool {
575 if let Some(binding) = self.scoped_import_bindings.iter().rev().find(|binding| {
576 binding.start_byte <= node.start_byte()
577 && binding.scope_start_byte <= node.start_byte()
578 && node.end_byte() <= binding.scope_end_byte
579 && binding.local_name == local
580 }) {
581 if binding.is_function_scoped() {
582 return binding.qualified_name == "importlib";
583 }
584 if self
585 .scope_facts_for_node(node)
586 .is_some_and(|facts| facts.is_shadowed(local))
587 {
588 return false;
589 }
590 return binding.qualified_name == "importlib";
591 }
592 if self
593 .scope_facts_for_node(node)
594 .is_some_and(|facts| facts.is_shadowed(local))
595 {
596 return false;
597 }
598 self.python
599 .import_binder_of(self.file)
600 .bindings
601 .get(local)
602 .is_some_and(|binding| {
603 binding.kind == ImportKind::Namespace
604 && binding
605 .namespace_imported_module
606 .as_deref()
607 .unwrap_or(&binding.module_specifier)
608 == "importlib"
609 })
610 }
611
612 fn node_directly_in_owner_class_body(&self, node: Node<'_>) -> bool {
618 let Some(target_owner) = self.target_owner.as_ref() else {
619 return false;
620 };
621 let range = Range {
622 start_byte: node.start_byte(),
623 end_byte: node.end_byte(),
624 start_line: 0,
625 end_line: 0,
626 };
627 let Some(enclosing) = self.graph.index.enclosing_code_unit(self.file, &range) else {
628 return false;
629 };
630 if &enclosing == target_owner {
631 return true;
632 }
633 if enclosing.is_function() {
634 return target_owner_code_unit(self.graph.index, &enclosing).as_ref()
635 == Some(target_owner)
636 && function_declaration_expression_is_outer_scoped(node);
637 }
638 target_owner_code_unit(self.graph.index, &enclosing).as_ref() == Some(target_owner)
639 }
640
641 fn receiver_type_is_unknown(&self, expr: &str, node: Node<'_>) -> bool {
645 match enclosing_runtime_parameter_type(expr, node, self.source) {
646 EnclosingParameterType::Typed(_) => return false,
647 EnclosingParameterType::Untyped => return true,
648 EnclosingParameterType::NotDeclared => {}
649 }
650 match self.scope_facts_for_node(node) {
651 Some(facts) => facts.resolution_for(expr).is_unknown(),
652 None => true,
653 }
654 }
655
656 fn import_edge_visible_for(&self, ident: &str, node: Node<'_>) -> bool {
657 if let Some(scope_facts) = self.scope_facts_for_node(node)
658 && scope_facts.is_shadowed(ident)
659 {
660 return false;
661 }
662 self.module_binding_targets_query(ident, node)
663 }
664
665 fn module_binding_targets_query(&self, ident: &str, node: Node<'_>) -> bool {
666 if self.target_member.is_some() {
672 return self.module_binding_targets_symbol(ident, node);
673 }
674 if self.target_is_module
675 && imported_module_bindings(self, node, node)
676 .into_iter()
677 .flat_map(|binding| {
678 usage_resolve_module_files(self.python, self.file, &binding.module)
679 })
680 .any(|resolved| &resolved == self.target_source)
681 {
682 return true;
687 }
688 if let Some(matches) = self.function_import_binding_targets_query(ident, node) {
689 return matches;
690 }
691 self.module_binding_matches_query(ident, node, true, |kind| {
692 kind != ModuleBindingKind::Other
693 })
694 }
695
696 fn module_binding_targets_symbol(&self, ident: &str, node: Node<'_>) -> bool {
697 if let Some(matches) = self.function_import_binding_targets_query(ident, node) {
698 return matches;
699 }
700 let unclassified_named_import = self.edges.iter().any(|edge| {
701 edge.local_name == ident && !matches!(edge.kind, ImportEdgeKind::Namespace)
702 });
703 self.module_binding_matches_query(ident, node, unclassified_named_import, |kind| {
704 kind == ModuleBindingKind::TargetSymbolImport
705 })
706 }
707
708 fn function_import_binding_targets_query(&self, ident: &str, node: Node<'_>) -> Option<bool> {
713 let binding =
714 python_function_scoped_import_binding(self.scoped_import_bindings, ident, node)?;
715 let qualified_name = resolve_python_module_specifier(
716 self.python.project(),
717 self.file,
718 &binding.qualified_name,
719 )
720 .unwrap_or_else(|| binding.qualified_name.clone());
721 let candidates =
722 resolve_fqn_candidates(self.python, Some(self.file), &qualified_name, |name| {
723 self.graph.index.definitions(name).collect()
724 });
725 let imported_target = self.target_owner.as_ref().unwrap_or(self.target);
726 Some(
727 candidates
728 .iter()
729 .any(|candidate| candidate == imported_target),
730 )
731 }
732
733 fn module_binding_matches_query(
734 &self,
735 ident: &str,
736 node: Node<'_>,
737 unclassified: bool,
738 matches: impl Fn(ModuleBindingKind) -> bool,
739 ) -> bool {
740 if !self.edges.iter().any(|edge| edge.local_name == ident) {
741 return false;
742 }
743 let Some(events) = self.module_bindings.get(ident) else {
744 return unclassified;
745 };
746 let cutoff = if python_reference_is_deferred_function_body(node) {
747 usize::MAX
748 } else {
749 node.start_byte()
750 };
751 let visible: Vec<_> = events
752 .iter()
753 .filter(|event| event.visible_from <= cutoff)
754 .collect();
755 let start = visible
756 .iter()
757 .rposition(|event| !event.conditional)
758 .unwrap_or(0);
759 visible[start..].iter().any(|event| matches(event.kind))
760 }
761
762 fn module_binding_is_local_at(&self, ident: &str, node: Node<'_>) -> bool {
763 self.module_binding_matches_query(ident, node, false, |kind| {
764 kind == ModuleBindingKind::Other
765 })
766 }
767
768 fn module_binding_targets_module(&self, ident: &str, node: Node<'_>) -> bool {
769 self.module_binding_matches_query(ident, node, false, |kind| {
770 kind == ModuleBindingKind::TargetModuleImport
771 })
772 }
773
774 fn bare_read_binds_target(&self, ident: &str, node: Node<'_>) -> bool {
788 if self.module_binding_targets_symbol(ident, node) {
789 return true;
790 }
791 self.module_binding_is_local_at(ident, node)
792 && !self.module_binding_targets_module(ident, node)
793 }
794
795 fn self_receiver_matches_target(&self, node: Node<'_>) -> bool {
799 let Some(target_owner) = self.target_owner.as_ref() else {
800 return false;
801 };
802 let range = Range {
803 start_byte: node.start_byte(),
804 end_byte: node.end_byte(),
805 start_line: 0,
806 end_line: 0,
807 };
808 let Some(enclosing) = self.graph.index.enclosing_code_unit(self.file, &range) else {
809 return false;
810 };
811 let enclosing_class = if enclosing.is_class() {
812 enclosing
813 } else {
814 match target_owner_code_unit(self.graph.index, &enclosing) {
815 Some(class) => class,
816 None => return false,
817 }
818 };
819 self.receiver_unit_matches_target(&enclosing_class, target_owner)
820 }
821
822 fn receiver_type_matches_target(&self, raw_type: &str) -> bool {
823 let Some(target_owner) = self.target_owner.as_ref() else {
824 return false;
825 };
826 if let Some(receiver_type) = resolve_receiver_type(
827 self.graph,
828 self.python,
829 self.file,
830 raw_type,
831 self.target_self_file,
832 ) {
833 return self.receiver_unit_matches_target(&receiver_type, target_owner);
834 }
835
836 receiver_annotation_matches_target(
841 raw_type,
842 self.edges,
843 self.target_short,
844 self.target_self_file,
845 )
846 }
847
848 fn receiver_unit_matches_target(
849 &self,
850 receiver_type: &CodeUnit,
851 target_owner: &CodeUnit,
852 ) -> bool {
853 if let Some(member) = self.target_member {
854 return resolved_member_declarations(self.graph, receiver_type, member)
855 .iter()
856 .any(|candidate| candidate == self.target);
857 }
858 receiver_type == target_owner
859 || self
860 .graph
861 .hierarchy
862 .map(|provider| provider.get_ancestors(receiver_type).definite().to_vec())
863 .unwrap_or_default()
864 .into_iter()
865 .any(|ancestor| ancestor == *target_owner)
866 }
867}
868
869pub(crate) fn function_declaration_expression_is_outer_scoped(node: Node<'_>) -> bool {
870 let site_start = node.start_byte();
871 let site_end = node.end_byte();
872 let mut current = node;
873 while let Some(parent) = current.parent() {
874 if parent.kind() == "function_definition" {
875 if parent
876 .child_by_field_name("body")
877 .is_some_and(|body| body.start_byte() <= site_start && site_end <= body.end_byte())
878 {
879 return false;
880 }
881 if parent
882 .child_by_field_name("name")
883 .is_some_and(|name| name.id() == node.id())
884 {
885 return false;
886 }
887 if let Some(parameters) = parent.child_by_field_name("parameters")
888 && parameters.start_byte() <= site_start
889 && site_end <= parameters.end_byte()
890 {
891 let mut parameter = node;
892 while parameter.parent() != Some(parameters) {
893 let Some(next) = parameter.parent() else {
894 return false;
895 };
896 parameter = next;
897 }
898 let binder = if parameter.kind() == "identifier" {
899 Some(parameter)
900 } else {
901 parameter.child_by_field_name("name").or_else(|| {
902 parameter
903 .named_child(0)
904 .filter(|child| child.kind() == "identifier")
905 })
906 };
907 return binder.is_none_or(|binder| binder.id() != node.id());
908 }
909 return true;
910 }
911 if parent.kind() == "decorated_definition" {
912 return current.kind() == "decorator";
913 }
914 if parent.kind() == "class_definition" {
915 break;
916 }
917 current = parent;
918 }
919 false
920}
921
922fn scan_nodes_for_targets(
923 root: Node<'_>,
924 source: &str,
925 graph: &PythonGraphSource<'_>,
926 contexts: &mut [ScanCtx<'_>],
927 active: &[bool],
928) {
929 let mut by_terminal: HashMap<String, Vec<usize>> = HashMap::default();
933 let mut broad = Vec::new();
934 for (index, ctx) in contexts
935 .iter()
936 .enumerate()
937 .filter(|(index, _)| active[*index])
938 {
939 if ctx.target_is_module || ctx.target_member == Some("__init__") {
940 broad.push(index);
941 }
942 let mut names = HashSet::default();
943 names.insert(ctx.target_short);
944 names.extend(ctx.target_member);
945 names.extend(ctx.seeds.iter().map(|(_, name)| name.as_str()));
946 names.extend(ctx.edges.iter().map(|edge| edge.local_name.as_str()));
947 if ctx.target_member.is_none() {
948 names.extend(ctx.module_bindings.iter().filter_map(|(name, events)| {
949 events
950 .iter()
951 .any(|event| event.kind != ModuleBindingKind::Other)
952 .then_some(name.as_str())
953 }));
954 }
955 for name in names {
956 by_terminal.entry(name.to_owned()).or_default().push(index);
957 }
958 }
959 let python = contexts[0].python;
960 let file = contexts[0].file;
961 let has_self = contexts
962 .iter()
963 .enumerate()
964 .any(|(index, ctx)| active[index] && ctx.target_self_file);
965 let has_foreign = contexts
966 .iter()
967 .enumerate()
968 .any(|(index, ctx)| active[index] && !ctx.target_self_file);
969 let has_class = contexts
970 .iter()
971 .enumerate()
972 .any(|(index, ctx)| active[index] && ctx.target.is_class());
973 let mut consumed_until = vec![0; contexts.len()];
974 let mut stack = vec![root];
975 while let Some(node) = stack.pop() {
976 let kind = node.kind();
977 if matches!(kind, "import_statement" | "import_from_statement") {
978 for (_, ctx) in contexts
979 .iter_mut()
980 .enumerate()
981 .filter(|(index, _)| active[*index] && node.start_byte() >= consumed_until[*index])
982 {
983 handle_import_candidate(node, ctx);
984 }
985 continue;
986 }
987 if matches!(
988 kind,
989 "identifier" | "attribute" | "string_content" | "keyword_argument"
990 ) {
991 let mut selected = if kind == "string_content" {
992 Vec::new()
993 } else {
994 broad.clone()
995 };
996 let terminal = match kind {
997 "attribute" => node.child_by_field_name("attribute"),
998 "keyword_argument" => node.child_by_field_name("name"),
999 "identifier" => Some(node),
1000 _ => None,
1001 };
1002 if let Some(indices) = terminal.and_then(|node| by_terminal.get(slice(node, source))) {
1003 selected.extend(indices);
1004 }
1005 if kind == "attribute"
1006 && let Some(object) = node.child_by_field_name("object")
1007 && let Some(indices) = by_terminal.get(slice(object, source))
1008 {
1009 selected.extend(indices);
1010 }
1011 selected.sort_unstable();
1012 selected.dedup();
1013
1014 let annotation_node = kind != "keyword_argument"
1018 && crate::syntax::python_node_is_in_annotation(node)
1019 && active
1020 .iter()
1021 .enumerate()
1022 .any(|(index, active)| *active && node.start_byte() >= consumed_until[index]);
1023 let own = if annotation_node && has_self {
1024 annotation_reference_candidates(graph, python, file, source, node, true)
1025 } else {
1026 None
1027 };
1028 let foreign = if annotation_node && has_foreign {
1029 annotation_reference_candidates(graph, python, file, source, node, false)
1030 } else {
1031 None
1032 };
1033 if own.is_some() || foreign.is_some() {
1034 let qualifiers: Vec<_> = if has_class {
1035 annotation_class_qualifier_sites(graph, python, file, source, node).collect()
1036 } else {
1037 Vec::new()
1038 };
1039 for (index, ctx) in contexts.iter_mut().enumerate() {
1040 if !active[index] || node.start_byte() < consumed_until[index] {
1041 continue;
1042 }
1043 let candidates = if ctx.target_self_file { &own } else { &foreign }
1044 .as_deref()
1045 .expect("every active annotation target has its binding variant");
1046 let consumed =
1047 handle_annotation_reference_candidate(node, ctx, candidates, &qualifiers);
1048 if consumed {
1049 if kind == "attribute" {
1050 consumed_until[index] = node.end_byte();
1051 }
1052 } else if selected.binary_search(&index).is_ok() {
1053 debug_assert_eq!(
1054 kind, "attribute",
1055 "only attribute annotations fall through"
1056 );
1057 handle_attribute_candidate(node, ctx);
1058 }
1059 }
1060 } else {
1061 let constructors = if kind == "identifier"
1064 && parent_if_field(node, "call", "function").is_some()
1065 && selected.iter().any(|&index| {
1066 contexts[index].target_member == Some("__init__")
1067 && node.start_byte() >= consumed_until[index]
1068 }) {
1069 resolve_constructor_types(graph, python, file, source, node)
1070 } else {
1071 Vec::new()
1072 };
1073 for index in selected {
1074 if node.start_byte() < consumed_until[index] {
1075 continue;
1076 }
1077 let ctx = &mut contexts[index];
1078 match kind {
1079 "identifier" => handle_identifier_candidate(node, ctx, &constructors),
1080 "attribute" => handle_attribute_candidate(node, ctx),
1081 "keyword_argument" => handle_keyword_argument_candidate(node, ctx),
1082 "string_content" => {}
1084 _ => unreachable!(),
1085 }
1086 }
1087 }
1088 }
1089 if kind == "keyword_argument" {
1090 if let Some(value) = node.child_by_field_name("value") {
1091 stack.push(value);
1092 }
1093 continue;
1094 }
1095 let mut cursor = node.walk();
1096 let mut children: Vec<_> = node.named_children(&mut cursor).collect();
1097 children.reverse();
1098 stack.extend(children);
1099 }
1100}
1101
1102fn handle_annotation_reference_candidate(
1103 node: Node<'_>,
1104 ctx: &mut ScanCtx<'_>,
1105 candidates: &[CodeUnit],
1106 qualifiers: &[(Node<'_>, CodeUnit)],
1107) -> bool {
1108 if node.kind() == "attribute"
1113 && ctx.target.is_field()
1114 && let Some(root) = leftmost_identifier(node)
1115 && ctx.target_member == Some(slice(root, ctx.source))
1116 && ctx.node_directly_in_owner_class_body(root)
1117 {
1118 record_hit(root, ctx);
1119 }
1120
1121 if (ctx.target.is_class() || ctx.target.is_field() || ctx.target_member.is_none())
1122 && candidates.iter().all(|candidate| *candidate == *ctx.target)
1123 && candidates.iter().any(|candidate| *candidate == *ctx.target)
1124 {
1125 let site = if node.kind() == "attribute" {
1126 node.child_by_field_name("attribute").unwrap_or(node)
1127 } else {
1128 node
1129 };
1130 record_hit(site, ctx);
1131 }
1132
1133 if ctx.target.is_class()
1134 && let Some((site, _)) = qualifiers.iter().find(|(_, owner)| owner == ctx.target)
1135 {
1136 record_hit(*site, ctx);
1137 }
1138
1139 if node.kind() == "attribute" && (candidates.is_empty() || ctx.target_is_module) {
1145 return false;
1146 }
1147
1148 true
1149}
1150
1151fn handle_keyword_argument_candidate(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
1152 let (Some(target_member), Some(name), Some(arguments)) = (
1153 ctx.target_member,
1154 node.child_by_field_name("name"),
1155 node.parent(),
1156 ) else {
1157 return;
1158 };
1159 if name.kind() != "identifier"
1160 || slice(name, ctx.source) != target_member
1161 || arguments.kind() != "argument_list"
1162 {
1163 return;
1164 }
1165 let Some(call) = arguments.parent().filter(|parent| parent.kind() == "call") else {
1166 return;
1167 };
1168 let Some(function) = call.child_by_field_name("function") else {
1169 return;
1170 };
1171 if function.kind() == "identifier" && slice(function, ctx.source) == "cls" {
1172 if ctx.self_receiver_matches_target(function) {
1173 record_hit(name, ctx);
1174 }
1175 return;
1176 }
1177 let Some(target_owner) = ctx.target_owner.as_ref() else {
1178 return;
1179 };
1180 let scoped_callee_matches = if function.kind() == "identifier" {
1181 ctx.scope_facts_for_node(function)
1182 .and_then(|facts| {
1183 facts
1184 .resolution_for(slice(function, ctx.source))
1185 .as_precise()
1186 .and_then(|targets| targets.iter().next().cloned())
1187 })
1188 .is_some_and(|raw_type| ctx.receiver_type_matches_target(&raw_type))
1189 } else {
1190 false
1191 };
1192 let default_callee_matches = if function.kind() == "identifier" {
1193 resolve_callable_parameter_default_types(
1194 ctx.graph,
1195 ctx.python,
1196 ctx.file,
1197 ctx.source,
1198 function,
1199 slice(function, ctx.source),
1200 )
1201 .into_iter()
1202 .any(|class| constructed_class_matches_target_owner(ctx, &class, target_owner))
1203 } else {
1204 false
1205 };
1206 let root_shadowed = leftmost_identifier(function).is_some_and(|root| {
1207 ctx.scope_facts_for_node(function)
1208 .is_some_and(|facts| facts.is_shadowed(slice(root, ctx.source)))
1209 });
1210 let named_import_callee_matches = if !root_shadowed && function.kind() == "identifier" {
1211 let cutoff = if python_reference_is_deferred_function_body(function) {
1212 usize::MAX
1213 } else {
1214 function.start_byte()
1215 };
1216 resolve_visible_named_import_candidates(
1217 ctx.graph,
1218 ctx.python,
1219 ctx.file,
1220 ctx.raw_module_bindings,
1221 slice(function, ctx.source),
1222 cutoff,
1223 )
1224 .into_iter()
1225 .any(|class| constructed_class_matches_target_owner(ctx, &class, target_owner))
1226 } else {
1227 false
1228 };
1229 if root_shadowed
1230 && !scoped_callee_matches
1231 && !default_callee_matches
1232 && !named_import_callee_matches
1233 {
1234 return;
1235 }
1236 let matches = scoped_callee_matches
1237 || default_callee_matches
1238 || named_import_callee_matches
1239 || (!root_shadowed
1240 && resolve_constructor_types(ctx.graph, ctx.python, ctx.file, ctx.source, function)
1241 .into_iter()
1242 .any(|class| constructed_class_matches_target_owner(ctx, &class, target_owner)));
1243 if matches {
1244 record_hit(name, ctx);
1245 }
1246}
1247
1248fn handle_import_candidate(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
1254 if ctx.target_member.is_some() {
1255 return;
1256 }
1257 if !ctx
1258 .edges
1259 .iter()
1260 .any(|edge| edge.local_name == ctx.target_short)
1261 {
1262 return;
1263 }
1264 let mut stack = vec![node];
1265 while let Some(node) = stack.pop() {
1266 if node.kind() == "identifier" && slice(node, ctx.source) == ctx.target_short {
1267 record_import_hit(node, ctx);
1268 return;
1269 }
1270 let mut cursor = node.walk();
1271 for child in node.named_children(&mut cursor) {
1272 stack.push(child);
1273 }
1274 }
1275}
1276
1277fn handle_identifier_candidate(node: Node<'_>, ctx: &mut ScanCtx<'_>, constructors: &[CodeUnit]) {
1278 if node
1279 .parent()
1280 .is_some_and(|parent| parent.kind() == "attribute")
1281 {
1282 return;
1283 }
1284 let text = slice(node, ctx.source);
1285 if text.is_empty() || is_declaration_identifier(node) || decorates_the_target(node, ctx) {
1286 return;
1287 }
1288 if let Some(member) = ctx.target_member {
1289 if member == "__init__" && parent_if_field(node, "call", "function").is_some() {
1292 let Some(target_owner) = ctx.target_owner.as_ref() else {
1293 return;
1294 };
1295 if constructors
1296 .iter()
1297 .any(|class| constructed_class_matches_target_owner(ctx, class, target_owner))
1298 {
1299 record_hit(node, ctx);
1300 }
1301 return;
1302 }
1303 if text == member && ctx.node_directly_in_owner_class_body(node) {
1306 record_hit(node, ctx);
1307 }
1308 return;
1309 }
1310 if !ctx.binds_target(text, node) {
1311 return;
1312 }
1313 let dynamic_getattr = dynamic_getattr_receiver(node, ctx);
1314 if !ctx.target_is_module && imported_root_targets_module(ctx, node, node) && !dynamic_getattr {
1319 return;
1320 }
1321 if !ctx.target_is_module
1322 && ctx.edges.iter().any(|edge| edge.local_name == text)
1323 && !ctx.bare_read_binds_target(text, node)
1324 && !dynamic_getattr
1325 {
1326 return;
1327 }
1328 if dynamic_getattr && !(ctx.target_is_module && imported_root_targets_module(ctx, node, node)) {
1329 record_unproven_hit(node, ctx);
1330 } else {
1331 record_hit(node, ctx);
1332 }
1333}
1334
1335fn constructed_class_matches_target_owner(
1336 ctx: &ScanCtx<'_>,
1337 constructed: &CodeUnit,
1338 target_owner: &CodeUnit,
1339) -> bool {
1340 constructed == target_owner
1341 || ctx
1342 .graph
1343 .hierarchy
1344 .map(|provider| provider.get_ancestors(constructed).definite().to_vec())
1345 .unwrap_or_default()
1346 .into_iter()
1347 .any(|ancestor| &ancestor == target_owner)
1348}
1349
1350fn dynamic_getattr_receiver(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
1354 let Some(arguments) = node
1355 .parent()
1356 .filter(|parent| parent.kind() == "argument_list")
1357 else {
1358 return false;
1359 };
1360 let Some(call) = arguments.parent().filter(|parent| parent.kind() == "call") else {
1361 return false;
1362 };
1363 let Some(function) = call.child_by_field_name("function") else {
1364 return false;
1365 };
1366 if function.kind() != "identifier"
1367 || slice(function, ctx.source) != "getattr"
1368 || !ctx
1369 .scope_facts_for_node(function)
1370 .is_some_and(|facts| !facts.is_shadowed("getattr"))
1371 {
1372 return false;
1373 }
1374
1375 let mut object = None;
1376 let mut name = None;
1377 let mut positional = 0;
1378 let mut cursor = arguments.walk();
1379 for argument in arguments.named_children(&mut cursor) {
1380 if argument.kind() == "keyword_argument" {
1381 let Some(label) = argument.child_by_field_name("name") else {
1382 return false;
1383 };
1384 let Some(value) = argument.child_by_field_name("value") else {
1385 return false;
1386 };
1387 match slice(label, ctx.source) {
1388 "object" => object = Some(value),
1389 "name" => name = Some(value),
1390 _ => {}
1391 }
1392 } else if matches!(argument.kind(), "list_splat" | "dictionary_splat") {
1393 return false;
1394 } else {
1395 match positional {
1396 0 => object = Some(argument),
1397 1 => name = Some(argument),
1398 _ => {}
1399 }
1400 positional += 1;
1401 }
1402 }
1403 let Some(object) = object else {
1404 return false;
1405 };
1406 let Some(name) = name else {
1407 return false;
1408 };
1409 object.start_byte() == node.start_byte()
1410 && object.end_byte() == node.end_byte()
1411 && python_plain_string_literal(name, ctx.source).is_none()
1412}
1413
1414fn decorates_the_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
1422 if ctx.file != ctx.target_source {
1423 return false;
1424 }
1425 let mut current = node;
1426 while let Some(parent) = current.parent() {
1427 if parent.kind() == "decorated_definition" && current.kind() == "decorator" {
1428 let Some(definition) = parent.child_by_field_name("definition") else {
1429 return false;
1430 };
1431 return ctx.graph.index.ranges(ctx.target).iter().any(|range| {
1432 range.start_byte <= definition.start_byte()
1433 && definition.end_byte() <= range.end_byte
1434 });
1435 }
1436 current = parent;
1437 }
1438 false
1439}
1440
1441fn handle_attribute_candidate(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
1442 let Some(object) = node.child_by_field_name("object") else {
1443 return;
1444 };
1445 let Some(attribute) = node.child_by_field_name("attribute") else {
1446 return;
1447 };
1448 let object_text = slice(object, ctx.source);
1449 let attribute_text = slice(attribute, ctx.source);
1450 if ctx.target_member.is_none()
1451 && !ctx.target_is_module
1452 && attribute_text == ctx.target_short
1453 && ctx.importlib_assignment_targets_query(object, node)
1454 {
1455 record_hit(attribute, ctx);
1456 }
1457 if let Some(member) = ctx.target_member
1458 && attribute_text == member
1459 {
1460 let is_same_owner_receiver =
1465 matches!(object_text, "self" | "cls") && ctx.self_receiver_matches_target(node);
1466 if is_same_owner_receiver {
1467 record_self_receiver_hit(attribute, ctx);
1468 } else if ctx.receiver_binds_target(object_text, node)
1469 || (object.kind() == "call" && call_result_matches_target(object, ctx))
1470 {
1471 record_hit(attribute, ctx);
1472 } else if member_receiver_match_is_unproven(object, object_text, node, ctx) {
1473 record_unproven_hit(attribute, ctx);
1474 }
1475 }
1476
1477 let object_binds_target = if ctx.target_is_module {
1478 imported_root_targets_module(ctx, object, node)
1479 } else {
1480 ctx.binds_target(object_text, node)
1481 };
1482 if object.kind() == "identifier"
1483 && object_binds_target
1484 && (ctx.target_is_module
1485 || (ctx.target_member.is_none()
1486 && !ctx.edges.iter().any(|edge| {
1487 matches!(edge.kind, ImportEdgeKind::Namespace) && edge.local_name == object_text
1488 })))
1489 {
1490 record_hit(object, ctx);
1491 }
1492
1493 if ctx.target_is_module
1494 && let Some(module_qualifier) = module_attribute_target_hit(node, ctx)
1495 {
1496 record_hit(module_qualifier, ctx);
1497 }
1498
1499 if let Some(member) = ctx.target_member
1503 && object.kind() == "identifier"
1504 && object_text == member
1505 && ctx.node_directly_in_owner_class_body(object)
1506 {
1507 record_hit(object, ctx);
1508 }
1509
1510 if ctx.member_best_effort_unique
1516 && let Some(member) = ctx.target_member
1517 && attribute_text == member
1518 && object.kind() == "identifier"
1519 && !matches!(object_text, "self" | "cls")
1520 && !ctx.receiver_binds_target(object_text, node)
1521 && ctx.receiver_type_is_unknown(object_text, node)
1522 {
1523 record_hit(attribute, ctx);
1524 }
1525
1526 if let Some(module_binding_target) = module_binding_attribute_target_hit(node, ctx) {
1527 record_hit(module_binding_target, ctx);
1528 }
1529}
1530
1531fn module_binding_attribute_target_hit<'a>(node: Node<'a>, ctx: &ScanCtx<'_>) -> Option<Node<'a>> {
1543 if ctx.target_member.is_some() {
1544 return None;
1545 }
1546 let (root, attributes) = attribute_chain(node)?;
1547 let terminal = *attributes.last()?;
1548 let terminal_name = slice(terminal, ctx.source);
1549 if terminal_name.is_empty()
1550 || !ctx
1551 .seeds
1552 .iter()
1553 .any(|(_, seed_name)| seed_name == terminal_name)
1554 {
1555 return None;
1556 }
1557
1558 for binding in imported_module_bindings(ctx, root, node) {
1559 let mut written_module = binding.module.clone();
1560 for attribute in attributes
1561 [binding.consumed_attributes.min(attributes.len() - 1)..attributes.len() - 1]
1562 .iter()
1563 {
1564 let segment = slice(*attribute, ctx.source);
1565 if segment.is_empty() {
1566 return None;
1567 }
1568 written_module.push('.');
1569 written_module.push_str(segment);
1570 }
1571 if usage_resolve_module_files(ctx.python, ctx.file, &written_module)
1572 .iter()
1573 .any(|resolved| {
1574 ctx.seeds
1575 .contains(&(resolved.clone(), terminal_name.to_string()))
1576 })
1577 {
1578 return Some(terminal);
1579 }
1580
1581 let mut written_fqn = binding.module;
1582 for attribute in attributes.iter().skip(binding.consumed_attributes) {
1583 let segment = slice(*attribute, ctx.source);
1584 if segment.is_empty() {
1585 return None;
1586 }
1587 written_fqn.push('.');
1588 written_fqn.push_str(segment);
1589 }
1590 if resolve_fqn_candidates(ctx.python, Some(ctx.file), &written_fqn, |name| {
1591 ctx.graph.index.definitions(name).collect()
1592 })
1593 .into_iter()
1594 .any(|candidate| &candidate == ctx.target)
1595 {
1596 return Some(terminal);
1597 }
1598 }
1599 None
1600}
1601
1602fn imported_root_targets_module(ctx: &ScanCtx<'_>, root: Node<'_>, reference: Node<'_>) -> bool {
1603 imported_module_bindings(ctx, root, reference)
1604 .into_iter()
1605 .any(|binding| {
1606 usage_resolve_module_files(ctx.python, ctx.file, &binding.module)
1607 .into_iter()
1608 .any(|resolved_file| &resolved_file == ctx.target_source)
1609 })
1610}
1611
1612fn module_attribute_target_hit<'a>(node: Node<'a>, ctx: &ScanCtx<'_>) -> Option<Node<'a>> {
1613 let (root, attributes) = attribute_chain(node)?;
1614 if attributes.is_empty() {
1615 return None;
1616 }
1617 for binding in imported_module_bindings(ctx, root, node) {
1618 let mut module_fqn = binding.module;
1619 for attribute in attributes.iter().skip(binding.consumed_attributes) {
1620 let segment = slice(*attribute, ctx.source);
1621 if segment.is_empty() {
1622 return None;
1623 }
1624 if module_fqn.ends_with('.') {
1625 module_fqn.push_str(segment);
1626 } else {
1627 module_fqn.push('.');
1628 module_fqn.push_str(segment);
1629 }
1630 let resolved = usage_resolve_module_files(ctx.python, ctx.file, &module_fqn);
1631 if resolved.is_empty() {
1632 break;
1633 }
1634 if resolved
1635 .iter()
1636 .any(|resolved_file| resolved_file == ctx.target_source)
1637 {
1638 return Some(*attribute);
1639 }
1640 }
1641 }
1642 None
1643}
1644
1645fn call_result_matches_target(call: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
1646 let Some(target_owner) = ctx.target_owner.as_ref() else {
1647 return false;
1648 };
1649 let scope_facts = ctx.scope_facts_for_node(call);
1650 call_result_types(
1651 ctx.graph,
1652 ctx.python,
1653 ctx.file,
1654 ctx.source,
1655 call,
1656 scope_facts,
1657 )
1658 .into_iter()
1659 .any(|class| {
1660 &class == target_owner
1661 || ctx
1662 .graph
1663 .hierarchy
1664 .map(|provider| provider.get_ancestors(&class).definite().to_vec())
1665 .unwrap_or_default()
1666 .into_iter()
1667 .any(|ancestor| &ancestor == target_owner)
1668 })
1669}
1670
1671pub fn call_result_types(
1672 graph: &PythonGraphSource<'_>,
1673 python: &dyn PythonUsageSource,
1674 file: &ProjectFile,
1675 source: &str,
1676 call: Node<'_>,
1677 scope_facts: Option<&LocalBindingsSnapshot<String>>,
1678) -> Vec<CodeUnit> {
1679 let Some(function) = call.child_by_field_name("function") else {
1680 return Vec::new();
1681 };
1682 let constructed = resolve_constructor_types(graph, python, file, source, function);
1683 if !constructed.is_empty() {
1684 return constructed;
1685 }
1686 let callable_fqns = resolve_callable_fqns(graph, python, file, source, function, scope_facts);
1687 if callable_fqns.is_empty() {
1688 return Vec::new();
1689 }
1690 let callables = callable_fqns
1691 .into_iter()
1692 .flat_map(|callable_fqn| {
1693 resolve_fqn_candidates(python, Some(file), &callable_fqn, |name| {
1694 graph.index.definitions(name).collect()
1695 })
1696 })
1697 .collect::<Vec<_>>();
1698 let mut classes = Vec::new();
1699 for callable in callables.into_iter().filter(CodeUnit::is_function) {
1700 let raw_type = callable_return_type_name(graph, python, &callable).or_else(|| {
1701 if callable.source() != file {
1702 return None;
1703 }
1704 let prepared = python.prepared_syntax(graph.token, file)?;
1705 let key = factory_function_key(graph, &callable);
1706 let facts = python.python_source_facts(graph.token, file, &|| true)?;
1707 collect_factory_return_types_from_root(
1708 prepared.tree().root_node(),
1709 prepared.source(),
1710 &facts,
1711 )?
1712 .remove(&key)
1713 });
1714 let Some(raw_type) = raw_type else {
1715 continue;
1716 };
1717 if let Some(class) =
1718 resolve_receiver_type(graph, python, callable.source(), &raw_type, true)
1719 {
1720 classes.push(class);
1721 }
1722 }
1723 classes.sort();
1724 classes.dedup();
1725 classes
1726}
1727
1728fn resolve_callable_fqns(
1729 graph: &PythonGraphSource<'_>,
1730 python: &dyn PythonUsageSource,
1731 file: &ProjectFile,
1732 source: &str,
1733 function: Node<'_>,
1734 scope_facts: Option<&LocalBindingsSnapshot<String>>,
1735) -> Vec<String> {
1736 match function.kind() {
1737 "identifier" => {
1738 resolve_identifier_callable_fqns(graph, python, file, source, function, scope_facts)
1739 }
1740 "attribute" => {
1741 resolve_attribute_callable_fqns(graph, python, file, source, function, scope_facts)
1742 }
1743 _ => Vec::new(),
1744 }
1745}
1746
1747fn resolve_identifier_callable_fqns(
1748 graph: &PythonGraphSource<'_>,
1749 python: &dyn PythonUsageSource,
1750 file: &ProjectFile,
1751 source: &str,
1752 function: Node<'_>,
1753 scope_facts: Option<&LocalBindingsSnapshot<String>>,
1754) -> Vec<String> {
1755 let local = slice(function, source);
1756 if local.is_empty() || scope_facts.is_some_and(|facts| facts.is_shadowed(local)) {
1757 return Vec::new();
1758 }
1759 let binder = python.import_binder_of(file);
1760 match binder.bindings.get(local) {
1761 Some(binding) if binding.kind == ImportKind::Named => binding
1762 .imported_name
1763 .as_ref()
1764 .map(|imported| vec![format!("{}.{}", binding.module_specifier, imported)])
1765 .unwrap_or_default(),
1766 _ => graph
1767 .index
1768 .declarations(file)
1769 .into_iter()
1770 .find(|unit| unit.is_function() && unit.identifier() == local)
1771 .map(|unit| vec![unit.fq_name()])
1772 .unwrap_or_default(),
1773 }
1774}
1775
1776fn resolve_attribute_callable_fqns(
1777 graph: &PythonGraphSource<'_>,
1778 python: &dyn PythonUsageSource,
1779 file: &ProjectFile,
1780 source: &str,
1781 function: Node<'_>,
1782 scope_facts: Option<&LocalBindingsSnapshot<String>>,
1783) -> Vec<String> {
1784 let Some(receiver) = function.child_by_field_name("object") else {
1785 return Vec::new();
1786 };
1787 let Some(method) = function.child_by_field_name("attribute") else {
1788 return Vec::new();
1789 };
1790 let method = slice(method, source);
1791 if method.is_empty() {
1792 return Vec::new();
1793 }
1794 let mut fqns = attribute_receiver_classes(graph, python, file, source, receiver, scope_facts)
1795 .into_iter()
1796 .map(|class| format!("{}.{}", class.fq_name(), method))
1797 .collect::<Vec<_>>();
1798 fqns.sort();
1799 fqns.dedup();
1800 fqns
1801}
1802
1803fn attribute_receiver_classes(
1804 graph: &PythonGraphSource<'_>,
1805 python: &dyn PythonUsageSource,
1806 file: &ProjectFile,
1807 source: &str,
1808 receiver: Node<'_>,
1809 scope_facts: Option<&LocalBindingsSnapshot<String>>,
1810) -> Vec<CodeUnit> {
1811 let mut classes = match receiver.kind() {
1812 "identifier" => {
1813 identifier_receiver_classes(graph, python, file, source, receiver, scope_facts)
1814 }
1815 "attribute" => {
1816 if let Some(root) = leftmost_identifier(receiver)
1817 && scope_facts.is_some_and(|facts| facts.is_shadowed(slice(root, source)))
1818 {
1819 Vec::new()
1820 } else {
1821 resolve_constructor_types(graph, python, file, source, receiver)
1822 }
1823 }
1824 _ => Vec::new(),
1825 };
1826 classes.sort();
1827 classes.dedup();
1828 classes
1829}
1830
1831fn identifier_receiver_classes(
1832 graph: &PythonGraphSource<'_>,
1833 python: &dyn PythonUsageSource,
1834 file: &ProjectFile,
1835 source: &str,
1836 receiver: Node<'_>,
1837 scope_facts: Option<&LocalBindingsSnapshot<String>>,
1838) -> Vec<CodeUnit> {
1839 let ident = slice(receiver, source);
1840 if ident.is_empty() {
1841 return Vec::new();
1842 }
1843 if matches!(ident, "self" | "cls")
1844 && let Some(class) = enclosing_class_for_node(graph, file, receiver)
1845 {
1846 return vec![class];
1847 }
1848 if let Some(facts) = scope_facts {
1849 if let Some(raw_type) = facts
1850 .resolution_for(ident)
1851 .as_precise()
1852 .and_then(|targets| targets.iter().next())
1853 && let Some(class) = resolve_receiver_type(graph, python, file, raw_type, false)
1854 {
1855 return vec![class];
1856 }
1857 if facts.is_shadowed(ident) {
1858 return Vec::new();
1859 }
1860 }
1861 resolve_receiver_type(graph, python, file, ident, false)
1862 .into_iter()
1863 .collect()
1864}
1865
1866fn enclosing_class_for_node(
1867 graph: &PythonGraphSource<'_>,
1868 file: &ProjectFile,
1869 node: Node<'_>,
1870) -> Option<CodeUnit> {
1871 let range = Range {
1872 start_byte: node.start_byte(),
1873 end_byte: node.end_byte(),
1874 start_line: 0,
1875 end_line: 0,
1876 };
1877 let enclosing = graph.index.enclosing_code_unit(file, &range)?;
1878 brokk_bifrost_core::analyzer::usages::common::enclosing_owner_chain(enclosing, |unit| {
1884 graph.index.parent_of(unit)
1885 })
1886 .take(2)
1887 .find(|unit| unit.is_class() && unit.source() == file)
1888}
1889
1890struct ImportedModuleBinding {
1891 module: String,
1892 consumed_attributes: usize,
1893}
1894
1895fn imported_module_bindings(
1896 ctx: &ScanCtx<'_>,
1897 root: Node<'_>,
1898 reference: Node<'_>,
1899) -> Vec<ImportedModuleBinding> {
1900 let root_text = slice(root, ctx.source);
1901 if root_text.is_empty() || import_root_shadowed(ctx, root_text, root, reference) {
1902 return Vec::new();
1903 }
1904
1905 if let Some(binding) = ctx.scoped_import_bindings.iter().rev().find(|binding| {
1906 binding.is_function_scoped()
1907 && binding.start_byte <= reference.start_byte()
1908 && binding.scope_start_byte <= reference.start_byte()
1909 && reference.end_byte() <= binding.scope_end_byte
1910 && binding.local_name == root_text
1911 }) {
1912 let qualified_name = resolve_python_module_specifier(
1913 ctx.python.project(),
1914 ctx.file,
1915 &binding.qualified_name,
1916 )
1917 .unwrap_or_else(|| binding.qualified_name.clone());
1918 return if usage_resolve_module_files(ctx.python, ctx.file, &qualified_name).is_empty() {
1919 Vec::new()
1920 } else {
1921 vec![ImportedModuleBinding {
1922 module: qualified_name,
1923 consumed_attributes: binding.consumed_attributes,
1924 }]
1925 };
1926 }
1927
1928 let Some(events) = ctx.raw_module_bindings.get(root_text) else {
1929 return Vec::new();
1930 };
1931 let cutoff = if python_reference_is_deferred_function_body(reference) {
1932 usize::MAX
1933 } else {
1934 reference.start_byte()
1935 };
1936 let visible: Vec<_> = events
1937 .iter()
1938 .filter(|event| event.visible_from <= cutoff)
1939 .collect();
1940 let start = visible
1945 .iter()
1946 .rposition(|event| {
1947 if event.conditional {
1948 return false;
1949 }
1950 match &event.kind {
1951 ModuleBindingEventKind::ImportModule {
1952 module,
1953 consumed_attributes,
1954 } => *consumed_attributes == 0 && module != root_text,
1955 ModuleBindingEventKind::FromImport { .. } | ModuleBindingEventKind::Other => true,
1956 }
1957 })
1958 .unwrap_or(0);
1959 let mut modules = visible[start..]
1960 .iter()
1961 .filter_map(|event| match &event.kind {
1962 ModuleBindingEventKind::ImportModule {
1963 module,
1964 consumed_attributes,
1965 } => {
1966 let mut segments = parse_symbol_path(Language::Python, module);
1967 segments.truncate(segments.len().saturating_sub(*consumed_attributes));
1968 Some(ImportedModuleBinding {
1969 module: segments.join("."),
1970 consumed_attributes: 0,
1971 })
1972 }
1973 ModuleBindingEventKind::FromImport {
1974 module,
1975 imported_name,
1976 } => {
1977 let submodule = if module.ends_with('.') {
1978 format!("{module}{imported_name}")
1979 } else {
1980 format!("{module}.{imported_name}")
1981 };
1982 (!usage_resolve_module_files(ctx.python, ctx.file, &submodule).is_empty())
1983 .then_some(ImportedModuleBinding {
1984 module: submodule,
1985 consumed_attributes: 0,
1986 })
1987 }
1988 ModuleBindingEventKind::Other => None,
1989 })
1990 .collect::<Vec<_>>();
1991 modules.sort_by(|left, right| {
1992 left.module
1993 .cmp(&right.module)
1994 .then_with(|| left.consumed_attributes.cmp(&right.consumed_attributes))
1995 });
1996 modules.dedup_by(|left, right| {
1997 left.module == right.module && left.consumed_attributes == right.consumed_attributes
1998 });
1999 modules
2000}
2001
2002fn import_root_shadowed(
2003 ctx: &ScanCtx<'_>,
2004 root_text: &str,
2005 root: Node<'_>,
2006 reference: Node<'_>,
2007) -> bool {
2008 ctx.scope_entry_for_node(root)
2009 .or_else(|| ctx.scope_entry_for_node(reference))
2010 .is_some_and(|(scope, facts)| !scope.is_module() && facts.is_shadowed(root_text))
2011 || enclosing_parameters_shadow(root_text, reference, ctx.source)
2012}
2013
2014fn enclosing_parameters_shadow(root_text: &str, reference: Node<'_>, source: &str) -> bool {
2015 let mut current = reference;
2016 while let Some(parent) = current.parent() {
2017 if matches!(parent.kind(), "function_definition" | "lambda") {
2018 let Some(parameters) = parent.child_by_field_name("parameters") else {
2019 return false;
2020 };
2021 let mut cursor = parameters.walk();
2022 return parameters.named_children(&mut cursor).any(|parameter| {
2023 parameter_symbol(parameter, source).as_deref() == Some(root_text)
2024 });
2025 }
2026 current = parent;
2027 }
2028 false
2029}
2030
2031enum EnclosingParameterType {
2032 NotDeclared,
2033 Untyped,
2034 Typed(String),
2035}
2036
2037fn enclosing_runtime_parameter_type(
2038 name: &str,
2039 reference: Node<'_>,
2040 source: &str,
2041) -> EnclosingParameterType {
2042 let site_start = reference.start_byte();
2043 let site_end = reference.end_byte();
2044 let mut current = reference;
2045 while let Some(parent) = current.parent() {
2046 if matches!(parent.kind(), "function_definition" | "lambda")
2047 && parent
2048 .child_by_field_name("body")
2049 .is_some_and(|body| body.start_byte() <= site_start && site_end <= body.end_byte())
2050 && let Some(parameters) = parent.child_by_field_name("parameters")
2051 {
2052 let mut cursor = parameters.walk();
2053 for parameter in parameters.named_children(&mut cursor) {
2054 if parameter_symbol(parameter, source).as_deref() != Some(name) {
2055 continue;
2056 }
2057 return parameter
2058 .child_by_field_name("type")
2059 .and_then(|annotation| normalized_receiver_type(slice(annotation, source)))
2060 .map_or(EnclosingParameterType::Untyped, |raw_type| {
2061 EnclosingParameterType::Typed(raw_type)
2062 });
2063 }
2064 }
2065 current = parent;
2066 }
2067 EnclosingParameterType::NotDeclared
2068}
2069
2070fn member_receiver_match_is_unproven(
2071 object: Node<'_>,
2072 object_text: &str,
2073 node: Node<'_>,
2074 ctx: &ScanCtx<'_>,
2075) -> bool {
2076 if matches!(object_text, "self" | "cls") {
2077 return false;
2078 }
2079 match object.kind() {
2080 "identifier" => {
2081 ctx.receiver_type_is_unknown(object_text, node) && !ctx.member_best_effort_unique
2082 }
2083 "attribute" => true,
2084 _ => false,
2085 }
2086}
2087
2088#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2089enum ModuleBindingKind {
2090 TargetSymbolImport,
2091 TargetModuleImport,
2092 Other,
2093}
2094
2095#[derive(Clone, Copy, Debug)]
2096struct ClassifiedModuleBindingEvent {
2097 visible_from: usize,
2098 conditional: bool,
2099 kind: ModuleBindingKind,
2100}
2101
2102pub fn collect_module_binding_timeline(
2103 root: Node<'_>,
2104 source: &str,
2105 imports: &[ImportInfo],
2106) -> ModuleBindingTimeline {
2107 let mut timeline = ModuleBindingTimeline::default();
2108 let imports_by_statement = python_imports_by_statement(imports);
2109 let mut stack = vec![root];
2110 while let Some(node) = stack.pop() {
2111 match node.kind() {
2112 "function_definition" | "class_definition" => {
2113 if let Some(name) = node.child_by_field_name("name") {
2114 record_module_binding(
2115 &mut timeline,
2116 slice(name, source),
2117 node.end_byte(),
2118 binding_is_conditional(node),
2119 ModuleBindingEventKind::Other,
2120 );
2121 }
2122 continue;
2123 }
2124 "import_statement" | "import_from_statement" => {
2125 if let Some(statement_imports) = imports_by_statement.get(&node.start_byte()) {
2126 collect_import_binding_events(node, statement_imports, &mut timeline);
2127 }
2128 continue;
2129 }
2130 "assignment" | "augmented_assignment" | "named_expression" => {
2131 if let Some(left) = node.child_by_field_name("left") {
2132 record_local_binding_targets(
2133 left,
2134 source,
2135 node.end_byte(),
2136 binding_is_conditional(node),
2137 &mut timeline,
2138 );
2139 }
2140 continue;
2141 }
2142 "for_statement" => {
2143 if let Some(left) = node.child_by_field_name("left") {
2144 record_local_binding_targets(
2145 left,
2146 source,
2147 left.end_byte(),
2148 true,
2149 &mut timeline,
2150 );
2151 }
2152 }
2153 _ => {}
2154 }
2155
2156 let mut cursor = node.walk();
2157 let mut children: Vec<Node<'_>> = node.named_children(&mut cursor).collect();
2158 children.reverse();
2159 stack.extend(children);
2160 }
2161 for events in timeline.values_mut() {
2162 events.sort_by_key(|event| event.visible_from);
2163 }
2164 timeline
2165}
2166
2167fn collect_import_binding_events(
2168 node: Node<'_>,
2169 imports: &[ImportInfo],
2170 timeline: &mut ModuleBindingTimeline,
2171) {
2172 for import in imports {
2173 let Some(details) = python_import_details(import) else {
2174 continue;
2175 };
2176 match details {
2177 PythonImportDetails::Import { module, alias } => {
2178 let Some(local) = import.local_name() else {
2179 continue;
2180 };
2181 let consumed_attributes = if alias.is_some() {
2182 0
2183 } else {
2184 import
2185 .path
2186 .as_ref()
2187 .map(|path| path.segments.len().saturating_sub(1))
2188 .unwrap_or(0)
2189 };
2190 record_module_binding(
2191 timeline,
2192 local,
2193 node.end_byte(),
2194 binding_is_conditional(node),
2195 ModuleBindingEventKind::ImportModule {
2196 module,
2197 consumed_attributes,
2198 },
2199 );
2200 }
2201 PythonImportDetails::FromImport {
2202 module,
2203 name,
2204 wildcard,
2205 ..
2206 } => {
2207 if wildcard {
2208 continue;
2209 }
2210 let Some(local) = import.local_name() else {
2211 continue;
2212 };
2213 record_module_binding(
2214 timeline,
2215 local,
2216 node.end_byte(),
2217 binding_is_conditional(node),
2218 ModuleBindingEventKind::FromImport {
2219 module,
2220 imported_name: name,
2221 },
2222 );
2223 }
2224 }
2225 }
2226}
2227
2228fn classify_module_binding_timeline(
2229 python: &dyn PythonUsageSource,
2230 file: &ProjectFile,
2231 timeline: &ModuleBindingTimeline,
2232 seeds: &BTreeSet<(ProjectFile, String)>,
2233 edges: &[ImportEdge],
2234) -> HashMap<String, Vec<ClassifiedModuleBindingEvent>> {
2235 let mut classified = HashMap::default();
2236 let mut module_targets: HashMap<String, bool> = HashMap::default();
2237 let relevant_locals: HashSet<&str> =
2238 edges.iter().map(|edge| edge.local_name.as_str()).collect();
2239 for (local, events) in timeline {
2240 if !relevant_locals.contains(local.as_str()) {
2241 continue;
2242 }
2243 let classified_events = events
2244 .iter()
2245 .map(|event| {
2246 let kind = match &event.kind {
2247 ModuleBindingEventKind::ImportModule { module, .. } => {
2248 if *module_targets
2249 .entry(module.clone())
2250 .or_insert_with(|| module_contains_seed(python, file, module, seeds))
2251 {
2252 ModuleBindingKind::TargetModuleImport
2253 } else {
2254 ModuleBindingKind::Other
2255 }
2256 }
2257 ModuleBindingEventKind::FromImport {
2258 module,
2259 imported_name,
2260 } => {
2261 let direct = usage_resolve_module_files(python, file, module).iter().any(
2262 |resolved| seeds.contains(&(resolved.clone(), imported_name.clone())),
2263 );
2264 let submodule = if module.ends_with('.') {
2265 format!("{module}{imported_name}")
2266 } else {
2267 format!("{module}.{imported_name}")
2268 };
2269 let imports_target_module =
2270 *module_targets.entry(submodule.clone()).or_insert_with(|| {
2271 module_contains_seed(python, file, &submodule, seeds)
2272 });
2273 if direct {
2274 ModuleBindingKind::TargetSymbolImport
2275 } else if imports_target_module {
2276 ModuleBindingKind::TargetModuleImport
2277 } else {
2278 ModuleBindingKind::Other
2279 }
2280 }
2281 ModuleBindingEventKind::Other => ModuleBindingKind::Other,
2282 };
2283 ClassifiedModuleBindingEvent {
2284 visible_from: event.visible_from,
2285 conditional: event.conditional,
2286 kind,
2287 }
2288 })
2289 .collect();
2290 classified.insert(local.clone(), classified_events);
2291 }
2292 classified
2293}
2294
2295fn module_contains_seed(
2296 python: &dyn PythonUsageSource,
2297 file: &ProjectFile,
2298 module: &str,
2299 seeds: &BTreeSet<(ProjectFile, String)>,
2300) -> bool {
2301 usage_resolve_module_files(python, file, module)
2302 .iter()
2303 .any(|resolved| seeds.iter().any(|(seed_file, _)| seed_file == resolved))
2304}
2305
2306fn record_module_binding(
2307 timeline: &mut ModuleBindingTimeline,
2308 name: &str,
2309 visible_from: usize,
2310 conditional: bool,
2311 kind: ModuleBindingEventKind,
2312) {
2313 let name = name.trim();
2314 if name.is_empty() {
2315 return;
2316 }
2317 timeline
2318 .entry(name.to_string())
2319 .or_default()
2320 .push(ModuleBindingEvent {
2321 visible_from,
2322 conditional,
2323 kind,
2324 });
2325}
2326
2327fn record_local_binding_targets(
2328 target: Node<'_>,
2329 source: &str,
2330 visible_from: usize,
2331 conditional: bool,
2332 timeline: &mut ModuleBindingTimeline,
2333) {
2334 let mut stack = vec![target];
2335 while let Some(node) = stack.pop() {
2336 if node.kind() == "identifier" {
2337 record_module_binding(
2338 timeline,
2339 slice(node, source),
2340 visible_from,
2341 conditional,
2342 ModuleBindingEventKind::Other,
2343 );
2344 continue;
2345 }
2346 if matches!(node.kind(), "attribute" | "subscript") {
2347 continue;
2348 }
2349 let mut cursor = node.walk();
2350 let mut children: Vec<Node<'_>> = node.named_children(&mut cursor).collect();
2351 children.reverse();
2352 stack.extend(children);
2353 }
2354}
2355
2356fn binding_is_conditional(mut node: Node<'_>) -> bool {
2357 while let Some(parent) = node.parent() {
2358 if matches!(
2359 parent.kind(),
2360 "if_statement"
2361 | "try_statement"
2362 | "except_clause"
2363 | "match_statement"
2364 | "case_clause"
2365 | "for_statement"
2366 | "while_statement"
2367 ) {
2368 return true;
2369 }
2370 if matches!(
2371 parent.kind(),
2372 "module" | "function_definition" | "class_definition"
2373 ) {
2374 return false;
2375 }
2376 node = parent;
2377 }
2378 false
2379}
2380
2381pub fn collect_assigned_identifiers(node: Node<'_>, source: &str, out: &mut HashSet<String>) {
2387 let mut stack = vec![node];
2388 while let Some(node) = stack.pop() {
2389 match node.kind() {
2390 "attribute" | "subscript" | "call" => continue,
2391 "identifier" => {
2392 let text = slice(node, source).trim();
2393 if !text.is_empty() {
2394 out.insert(text.to_string());
2395 }
2396 continue;
2397 }
2398 _ => {}
2399 }
2400
2401 let mut cursor = node.walk();
2402 let mut children: Vec<Node<'_>> = node.named_children(&mut cursor).collect();
2403 children.reverse();
2404 stack.extend(children);
2405 }
2406}
2407
2408pub fn collect_scope_facts_from_parsed_source(
2409 graph: &PythonGraphSource<'_>,
2410 python: &dyn PythonUsageSource,
2411 file: &ProjectFile,
2412 source: &str,
2413 root: Node<'_>,
2414) -> Option<PythonScopeFacts> {
2415 let facts = python.python_source_facts(graph.token, file, &|| true)?;
2416 let mut factory_return_types = collect_factory_return_types_from_root(root, source, &facts)?;
2417 collect_imported_factory_return_types(graph, python, file, &mut factory_return_types);
2418 Some(collect_scope_facts_with_factory_returns(
2419 graph,
2420 file,
2421 source,
2422 root,
2423 &factory_return_types,
2424 ))
2425}
2426
2427fn collect_imported_factory_return_types(
2428 graph: &PythonGraphSource<'_>,
2429 python: &dyn PythonUsageSource,
2430 file: &ProjectFile,
2431 factory_return_types: &mut HashMap<String, String>,
2432) {
2433 let binder = python.import_binder_of(file);
2434 for (local, binding) in &binder.bindings {
2435 if !matches!(binding.kind, ImportKind::Named) {
2436 continue;
2437 }
2438 let Some(imported) = binding.imported_name.as_deref() else {
2439 continue;
2440 };
2441 let fqn = format!("{}.{}", binding.module_specifier, imported);
2442 let units = resolve_fqn_candidates(python, Some(file), &fqn, |name| {
2443 graph.index.definitions(name).collect()
2444 });
2445 for unit in units {
2446 if unit.is_function() {
2447 if let Some(return_type) = callable_return_type_name(graph, python, &unit) {
2448 let return_type =
2449 resolve_receiver_type(graph, python, unit.source(), &return_type, true)
2450 .map(|unit| unit.fq_name())
2451 .unwrap_or(return_type);
2452 factory_return_types
2453 .entry(local.clone())
2454 .or_insert(return_type);
2455 }
2456 continue;
2457 }
2458 if !unit.is_class() {
2459 continue;
2460 }
2461 factory_return_types
2462 .entry(local.clone())
2463 .or_insert_with(|| unit.identifier().to_string());
2464 collect_imported_class_method_return_types(
2465 graph,
2466 python,
2467 local,
2468 &unit,
2469 factory_return_types,
2470 );
2471 }
2472 }
2473}
2474
2475fn collect_imported_class_method_return_types(
2476 graph: &PythonGraphSource<'_>,
2477 python: &dyn PythonSource,
2478 local_class_name: &str,
2479 class_unit: &CodeUnit,
2480 factory_return_types: &mut HashMap<String, String>,
2481) {
2482 for member in graph.index.direct_children(class_unit) {
2483 if !member.is_function() {
2484 continue;
2485 }
2486 let Some(return_type) = callable_return_type_name(graph, python, &member) else {
2487 continue;
2488 };
2489 factory_return_types
2490 .entry(format!("{}.{}", local_class_name, member.identifier()))
2491 .or_insert(return_type);
2492 }
2493}
2494
2495fn callable_return_type_name(
2496 graph: &PythonGraphSource<'_>,
2497 python: &dyn PythonSource,
2498 callable: &CodeUnit,
2499) -> Option<String> {
2500 let metadata = graph.index.signature_metadata(callable);
2501 let first = metadata.first()?;
2502 #[cfg(any(test, feature = "test-support"))]
2503 note_callable_return_type_lookup_for_test(first.return_type_text().is_some());
2504 if first.return_type_text().is_some() {
2505 return first
2506 .return_type_identity()?
2507 .nominal_name()
2508 .map(|name| name.path().join("."));
2509 }
2510 let prepared = python.prepared_syntax(graph.token, callable.source())?;
2514 callable_return_type_name_in_tree(
2515 graph,
2516 callable,
2517 prepared.source(),
2518 prepared.tree().root_node(),
2519 )
2520}
2521
2522#[cfg(any(test, feature = "test-support"))]
2527#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
2528pub struct CallableReturnTypeLookupCounts {
2529 pub canonical: usize,
2531 pub body: usize,
2533}
2534
2535#[cfg(any(test, feature = "test-support"))]
2536thread_local! {
2537 static CALLABLE_RETURN_TYPE_LOOKUPS_FOR_TEST: std::cell::Cell<CallableReturnTypeLookupCounts> =
2538 const { std::cell::Cell::new(CallableReturnTypeLookupCounts { canonical: 0, body: 0 }) };
2539}
2540
2541#[cfg(any(test, feature = "test-support"))]
2542fn note_callable_return_type_lookup_for_test(from_canonical_metadata: bool) {
2543 CALLABLE_RETURN_TYPE_LOOKUPS_FOR_TEST.with(|counts| {
2544 let mut observed = counts.get();
2545 if from_canonical_metadata {
2546 observed.canonical += 1;
2547 } else {
2548 observed.body += 1;
2549 }
2550 counts.set(observed);
2551 });
2552}
2553
2554#[cfg(any(test, feature = "test-support"))]
2557pub fn with_callable_return_type_lookup_counter_for_test<T>(
2558 body: impl FnOnce() -> T,
2559) -> (T, CallableReturnTypeLookupCounts) {
2560 CALLABLE_RETURN_TYPE_LOOKUPS_FOR_TEST.with(|counts| {
2561 counts.set(CallableReturnTypeLookupCounts::default());
2562 let result = body();
2563 let observed = counts.get();
2564 counts.set(CallableReturnTypeLookupCounts::default());
2565 (result, observed)
2566 })
2567}
2568
2569fn callable_return_type_name_in_tree(
2571 graph: &PythonGraphSource<'_>,
2572 callable: &CodeUnit,
2573 source: &str,
2574 root: Node<'_>,
2575) -> Option<String> {
2576 let mut ranges = graph.index.ranges(callable);
2577 ranges.sort_by_key(|range| range.start_byte);
2578 ranges.into_iter().find_map(|range| {
2579 let declaration = root.descendant_for_byte_range(range.start_byte, range.end_byte)?;
2580 let function = python_first_function_definition(declaration)?;
2581 inferred_factory_return_type(function, source, None, &HashMap::default())
2582 })
2583}
2584
2585fn factory_function_key(graph: &PythonGraphSource<'_>, callable: &CodeUnit) -> String {
2586 graph
2587 .index
2588 .parent_of(callable)
2589 .filter(CodeUnit::is_class)
2590 .map(|owner| format!("{}.{}", owner.identifier(), callable.identifier()))
2591 .unwrap_or_else(|| callable.identifier().to_string())
2592}
2593
2594pub fn python_first_function_definition(root: Node<'_>) -> Option<Node<'_>> {
2595 let mut stack = vec![root];
2596 while let Some(node) = stack.pop() {
2597 if node.kind() == "function_definition" {
2598 return Some(node);
2599 }
2600 let mut cursor = node.walk();
2601 let mut children: Vec<Node<'_>> = node.named_children(&mut cursor).collect();
2602 children.reverse();
2603 stack.extend(children);
2604 }
2605 None
2606}
2607
2608fn collect_scope_facts_with_factory_returns(
2609 graph: &PythonGraphSource<'_>,
2610 file: &ProjectFile,
2611 source: &str,
2612 root: Node<'_>,
2613 factory_return_types: &HashMap<String, String>,
2614) -> PythonScopeFacts {
2615 let declarations = graph.index.declarations(file);
2616 let mut class_facts_by_name: HashMap<String, LocalBindingsSnapshot<String>> =
2617 HashMap::default();
2618 for declaration in declarations
2619 .iter()
2620 .filter(|declaration| declaration.is_class())
2621 {
2622 let facts = collect_declaration_scope_facts(
2623 graph,
2624 declaration,
2625 root,
2626 source,
2627 ScopeFactTraversal::Class,
2628 true,
2629 Some(declaration.short_name()),
2630 factory_return_types,
2631 );
2632 class_facts_by_name.insert(
2633 declaration.short_name().to_string(),
2634 facts.filtered_visible_bindings(|symbol, _| symbol.starts_with("self.")),
2635 );
2636 }
2637
2638 let mut scope_facts = HashMap::default();
2639 for declaration in declarations
2640 .iter()
2641 .filter(|declaration| declaration.is_function())
2642 {
2643 let owner = declaration
2648 .short_name()
2649 .rsplit_once('.')
2650 .map(|(owner, _)| owner);
2651 let mut facts = collect_declaration_scope_facts(
2652 graph,
2653 declaration,
2654 root,
2655 source,
2656 ScopeFactTraversal::Function,
2657 false,
2658 owner,
2659 factory_return_types,
2660 );
2661 if let Some(owner) = owner
2662 && let Some(class_facts) = class_facts_by_name.get(owner)
2663 {
2664 facts = facts.merged_with_visible(class_facts);
2665 }
2666 scope_facts.insert(declaration.clone(), facts);
2667 }
2668
2669 for declaration in declarations.iter().filter(|d| d.is_module()) {
2674 let facts = collect_declaration_scope_facts(
2675 graph,
2676 declaration,
2677 root,
2678 source,
2679 ScopeFactTraversal::Module,
2680 false,
2681 None,
2682 factory_return_types,
2683 );
2684 scope_facts.insert(declaration.clone(), facts);
2685 }
2686 scope_facts
2687}
2688
2689#[allow(clippy::too_many_arguments)]
2690fn collect_declaration_scope_facts(
2691 graph: &PythonGraphSource<'_>,
2692 declaration: &CodeUnit,
2693 root: Node<'_>,
2694 source: &str,
2695 traversal: ScopeFactTraversal,
2696 allow_self_receivers: bool,
2697 current_class: Option<&str>,
2698 factory_return_types: &HashMap<String, String>,
2699) -> LocalBindingsSnapshot<String> {
2700 let mut events = Vec::new();
2701 let mut ranges = graph.index.ranges(declaration);
2702 ranges.sort_by_key(|range| range.start_byte);
2703 for range in ranges {
2704 if let Some(node) = root.descendant_for_byte_range(range.start_byte, range.end_byte) {
2705 collect_scope_fact_events_from_node(node, source, traversal, &mut events);
2706 }
2707 }
2708 collect_scope_facts_from_events(
2709 &events,
2710 allow_self_receivers,
2711 current_class,
2712 factory_return_types,
2713 )
2714}
2715
2716pub fn collect_function_scope_facts_from_node(
2717 function: Node<'_>,
2718 source: &str,
2719) -> LocalBindingsSnapshot<String> {
2720 let mut events = Vec::new();
2721 if function.kind() == "lambda" {
2722 if let Some(parameters) = function.child_by_field_name("parameters") {
2723 collect_parameter_events(parameters, source, &mut events);
2724 }
2725 } else {
2726 collect_scope_fact_events_from_node(
2727 function,
2728 source,
2729 ScopeFactTraversal::Function,
2730 &mut events,
2731 );
2732 }
2733 collect_scope_facts_from_events(&events, false, None, &HashMap::default())
2734}
2735
2736fn collect_scope_facts_from_events(
2737 events: &[ScopeFactEvent],
2738 allow_self_receivers: bool,
2739 current_class: Option<&str>,
2740 factory_return_types: &HashMap<String, String>,
2741) -> LocalBindingsSnapshot<String> {
2742 let mut engine = LocalInferenceEngine::new(LocalInferenceConfig::default());
2743 let globals: HashSet<&str> = events
2744 .iter()
2745 .filter_map(|event| match event {
2746 ScopeFactEvent::Global { symbol } => Some(symbol.as_str()),
2747 _ => None,
2748 })
2749 .collect();
2750 let nonlocals: HashSet<&str> = events
2751 .iter()
2752 .filter_map(|event| match event {
2753 ScopeFactEvent::Nonlocal { symbol } => Some(symbol.as_str()),
2754 _ => None,
2755 })
2756 .collect();
2757 for symbol in &nonlocals {
2758 engine.declare_shadow((*symbol).to_string());
2759 }
2760 for event in events {
2761 if let ScopeFactEvent::Parameter { symbol, .. } = event
2762 && !globals.contains(symbol.as_str())
2763 && !nonlocals.contains(symbol.as_str())
2764 && !engine.is_shadowed(symbol)
2765 {
2766 engine.declare_shadow(symbol.clone());
2767 }
2768 }
2769 let merged = merged_assignment_symbols(events, current_class, factory_return_types);
2770
2771 let mut changed = true;
2772 while changed {
2773 changed = false;
2774 let mut aliases = Vec::new();
2775 for event in events {
2776 match event {
2777 ScopeFactEvent::Parameter {
2778 symbol,
2779 annotation: Some(annotation),
2780 }
2781 | ScopeFactEvent::Annotation { symbol, annotation } => {
2782 if globals.contains(symbol.as_str()) || nonlocals.contains(symbol.as_str()) {
2783 continue;
2784 }
2785 apply_annotation_event(
2786 symbol,
2787 annotation,
2788 allow_self_receivers,
2789 &mut engine,
2790 &mut changed,
2791 );
2792 }
2793 ScopeFactEvent::Parameter {
2794 annotation: None, ..
2795 } => {}
2796 ScopeFactEvent::Assignment { lhs, rhs } => {
2797 if globals.contains(lhs.as_str()) {
2798 continue;
2799 }
2800 if !engine.is_shadowed(lhs) {
2801 engine.declare_shadow(lhs.clone());
2802 }
2803 if lhs.starts_with("self.") && !allow_self_receivers {
2804 continue;
2805 }
2806 if merged.contains(lhs.as_str()) {
2813 continue;
2814 }
2815
2816 match rhs {
2817 AssignmentRhs::Call(callee) => {
2818 if !engine.is_shadowed(callee) {
2819 if let Some(receiver_type) = factory_return_type_for_callee(
2820 callee,
2821 current_class,
2822 factory_return_types,
2823 ) && engine.resolve_symbol(lhs).is_unknown()
2824 {
2825 engine.seed_symbol(lhs.clone(), receiver_type.clone());
2826 changed = true;
2827 continue;
2828 }
2829
2830 if let Some(receiver_type) = normalized_receiver_type(callee)
2831 && engine.resolve_symbol(lhs).is_unknown()
2832 {
2833 engine.seed_symbol(lhs.clone(), receiver_type);
2834 changed = true;
2835 continue;
2836 }
2837 }
2838 }
2839 AssignmentRhs::Symbol(rhs_symbol) => {
2840 if !engine.is_shadowed(rhs_symbol)
2841 && let Some(receiver_type) = normalized_receiver_type(rhs_symbol)
2842 && engine.resolve_symbol(lhs).is_unknown()
2843 {
2844 engine.seed_symbol(lhs.clone(), receiver_type);
2845 changed = true;
2846 continue;
2847 }
2848
2849 if let SymbolResolution::Precise(targets) =
2850 engine.resolve_symbol(rhs_symbol)
2851 && !targets.is_empty()
2852 {
2853 aliases.push((lhs.clone(), rhs_symbol.clone()));
2854 }
2855 }
2856 AssignmentRhs::Unknown => {}
2857 }
2858 }
2859 ScopeFactEvent::Global { .. } | ScopeFactEvent::Nonlocal { .. } => {}
2860 }
2861 }
2862 let before = engine.snapshot();
2863 engine.apply_aliases_until_stable(aliases);
2864 if engine.snapshot() != before {
2865 changed = true;
2866 }
2867 }
2868
2869 engine.snapshot()
2870}
2871
2872fn merged_assignment_symbols<'events>(
2884 events: &'events [ScopeFactEvent],
2885 current_class: Option<&str>,
2886 factory_return_types: &HashMap<String, String>,
2887) -> HashSet<&'events str> {
2888 let mut seen: HashMap<&str, String> = HashMap::default();
2889 let mut merged = HashSet::default();
2890 for event in events {
2891 let ScopeFactEvent::Assignment { lhs, rhs } = event else {
2892 continue;
2893 };
2894 let Some(assigned_type) = direct_assignment_type(rhs, current_class, factory_return_types)
2895 else {
2896 continue;
2897 };
2898 match seen.get(lhs.as_str()) {
2899 Some(first) if first == &assigned_type => {}
2900 Some(_) => {
2901 merged.insert(lhs.as_str());
2902 }
2903 None => {
2904 seen.insert(lhs.as_str(), assigned_type);
2905 }
2906 }
2907 }
2908 merged
2909}
2910
2911fn direct_assignment_type(
2914 rhs: &AssignmentRhs,
2915 current_class: Option<&str>,
2916 factory_return_types: &HashMap<String, String>,
2917) -> Option<String> {
2918 match rhs {
2919 AssignmentRhs::Call(callee) => {
2920 factory_return_type_for_callee(callee, current_class, factory_return_types)
2921 .cloned()
2922 .or_else(|| normalized_receiver_type(callee))
2923 }
2924 AssignmentRhs::Symbol(symbol) => normalized_receiver_type(symbol),
2925 AssignmentRhs::Unknown => None,
2926 }
2927}
2928
2929fn factory_return_type_for_callee<'a>(
2930 callee: &str,
2931 current_class: Option<&str>,
2932 factory_return_types: &'a HashMap<String, String>,
2933) -> Option<&'a String> {
2934 if let Some(receiver_type) = factory_return_types.get(callee) {
2935 return Some(receiver_type);
2936 }
2937 let class_name = current_class?;
2938 let method = callee
2939 .strip_prefix("self.")
2940 .or_else(|| callee.strip_prefix("cls."))?;
2941 factory_return_types.get(&format!("{class_name}.{method}"))
2942}
2943
2944fn apply_annotation_event(
2945 symbol: &str,
2946 annotation: &str,
2947 allow_self_receivers: bool,
2948 engine: &mut LocalInferenceEngine<String>,
2949 changed: &mut bool,
2950) {
2951 if symbol.starts_with("self.") && !allow_self_receivers {
2952 return;
2953 }
2954 if let Some(receiver_type) = normalized_receiver_type(annotation)
2955 && engine.resolve_symbol(symbol).is_unknown()
2956 {
2957 engine.seed_symbol(symbol.to_string(), receiver_type);
2958 *changed = true;
2959 }
2960}
2961
2962enum ScopeFactEvent {
2963 Global {
2964 symbol: String,
2965 },
2966 Nonlocal {
2967 symbol: String,
2968 },
2969 Parameter {
2970 symbol: String,
2971 annotation: Option<String>,
2972 },
2973 Annotation {
2974 symbol: String,
2975 annotation: String,
2976 },
2977 Assignment {
2978 lhs: String,
2979 rhs: AssignmentRhs,
2980 },
2981}
2982
2983enum AssignmentRhs {
2984 Symbol(String),
2985 Call(String),
2986 Unknown,
2987}
2988
2989#[derive(Clone, Copy)]
2990enum ScopeFactTraversal {
2991 Module,
2992 Function,
2993 Class,
2994}
2995
2996fn collect_scope_fact_events_from_node(
2997 root: Node<'_>,
2998 source: &str,
2999 traversal: ScopeFactTraversal,
3000 events: &mut Vec<ScopeFactEvent>,
3001) {
3002 let mut stack = vec![(root, false)];
3003 while let Some((node, inside_function)) = stack.pop() {
3004 let next_inside_function = match traversal {
3005 ScopeFactTraversal::Module => {
3006 if matches!(
3007 node.kind(),
3008 "function_definition" | "class_definition" | "lambda"
3009 ) {
3010 continue;
3011 }
3012 false
3013 }
3014 ScopeFactTraversal::Function => match node.kind() {
3015 "function_definition" if inside_function => continue,
3016 "function_definition" => true,
3017 "class_definition" | "lambda" => continue,
3018 _ => inside_function,
3019 },
3020 ScopeFactTraversal::Class => inside_function,
3021 };
3022 if matches!(traversal, ScopeFactTraversal::Function) && !next_inside_function {
3023 let mut cursor = node.walk();
3024 let mut children: Vec<Node<'_>> = node.named_children(&mut cursor).collect();
3025 children.reverse();
3026 stack.extend(children.into_iter().map(|child| (child, false)));
3027 continue;
3028 }
3029 match node.kind() {
3030 "global_statement" => collect_scope_directive_events(node, source, events, |symbol| {
3031 ScopeFactEvent::Global { symbol }
3032 }),
3033 "nonlocal_statement" => {
3034 collect_scope_directive_events(node, source, events, |symbol| {
3035 ScopeFactEvent::Nonlocal { symbol }
3036 })
3037 }
3038 "parameters" | "lambda_parameters" => collect_parameter_events(node, source, events),
3039 "assignment" => collect_assignment_events(node, source, events),
3040 _ => {}
3041 }
3042
3043 let mut cursor = node.walk();
3044 let mut children: Vec<Node<'_>> = node.named_children(&mut cursor).collect();
3045 children.reverse();
3046 stack.extend(
3047 children
3048 .into_iter()
3049 .map(|child| (child, next_inside_function)),
3050 );
3051 }
3052}
3053
3054fn collect_scope_directive_events(
3055 node: Node<'_>,
3056 source: &str,
3057 events: &mut Vec<ScopeFactEvent>,
3058 make_event: impl Fn(String) -> ScopeFactEvent,
3059) {
3060 let mut cursor = node.walk();
3061 for identifier in node
3062 .named_children(&mut cursor)
3063 .filter(|child| child.kind() == "identifier")
3064 {
3065 let Some(symbol) = non_empty_node_text(identifier, source) else {
3066 continue;
3067 };
3068 events.push(make_event(symbol));
3069 }
3070}
3071
3072fn collect_parameter_events(node: Node<'_>, source: &str, events: &mut Vec<ScopeFactEvent>) {
3073 let mut cursor = node.walk();
3074 for child in node.named_children(&mut cursor) {
3075 if child.kind() == "type_parameter" {
3076 continue;
3077 }
3078 let Some(symbol) = parameter_symbol(child, source) else {
3079 continue;
3080 };
3081 if matches!(symbol.as_str(), "self" | "cls" | "/") {
3082 continue;
3083 }
3084 let annotation = child
3085 .child_by_field_name("type")
3086 .map(|annotation| slice(annotation, source).trim().to_string())
3087 .filter(|annotation| !annotation.is_empty());
3088 events.push(ScopeFactEvent::Parameter { symbol, annotation });
3089 }
3090}
3091
3092fn parameter_symbol(node: Node<'_>, source: &str) -> Option<String> {
3093 if node.kind() == "identifier" {
3094 return non_empty_node_text(node, source);
3095 }
3096 if let Some(name) = node.child_by_field_name("name") {
3097 return non_empty_node_text(name, source);
3098 }
3099 let mut cursor = node.walk();
3100 node.named_children(&mut cursor)
3101 .find(|child| child.kind() == "identifier")
3102 .and_then(|identifier| non_empty_node_text(identifier, source))
3103}
3104
3105fn collect_assignment_events(node: Node<'_>, source: &str, events: &mut Vec<ScopeFactEvent>) {
3106 let Some(left) = node.child_by_field_name("left") else {
3107 return;
3108 };
3109 let Some(lhs) = receiver_symbol(left, source) else {
3110 return;
3111 };
3112
3113 if let Some(annotation) = node
3114 .child_by_field_name("type")
3115 .map(|annotation| slice(annotation, source).trim().to_string())
3116 .filter(|annotation| !annotation.is_empty())
3117 {
3118 events.push(ScopeFactEvent::Annotation {
3119 symbol: lhs,
3120 annotation,
3121 });
3122 return;
3123 }
3124
3125 let rhs = node
3126 .child_by_field_name("right")
3127 .and_then(|right| rhs_symbol(right, source))
3128 .unwrap_or(AssignmentRhs::Unknown);
3129 events.push(ScopeFactEvent::Assignment { lhs, rhs });
3130}
3131
3132fn receiver_symbol(node: Node<'_>, source: &str) -> Option<String> {
3133 match node.kind() {
3134 "identifier" | "attribute" => non_empty_node_text(node, source),
3135 _ => None,
3136 }
3137}
3138
3139fn rhs_symbol(node: Node<'_>, source: &str) -> Option<AssignmentRhs> {
3140 match node.kind() {
3141 "identifier" | "attribute" => non_empty_node_text(node, source).map(AssignmentRhs::Symbol),
3142 "call" => node
3143 .child_by_field_name("function")
3144 .or_else(|| node.named_child(0))
3145 .and_then(|callee| receiver_symbol(callee, source))
3146 .map(AssignmentRhs::Call),
3147 _ => None,
3148 }
3149}
3150
3151fn collect_factory_return_types_from_root(
3152 root: Node<'_>,
3153 source: &str,
3154 source_facts: &crate::source_facts::PythonFileSourceFacts,
3155) -> Option<HashMap<String, String>> {
3156 let returns_by_range: HashMap<_, _> = source_facts
3157 .facts
3158 .callable_returns
3159 .iter()
3160 .map(|fact| {
3161 let declaration = source_facts.occurrences.declaration(fact.declaration);
3162 let range = source_facts
3163 .occurrences
3164 .occurrence(declaration.occurrence)
3165 .range;
3166 ((range.start_byte, range.end_byte), fact)
3167 })
3168 .collect();
3169 let mut returns = HashMap::default();
3170 let mut functions = Vec::new();
3171 let mut stack = vec![(root, None::<String>)];
3172 while let Some((node, class_name)) = stack.pop() {
3173 match node.kind() {
3174 "class_definition" => {
3175 let next_class = node
3176 .child_by_field_name("name")
3177 .and_then(|name| non_empty_node_text(name, source))
3178 .or(class_name);
3179 push_factory_index_children(node, next_class, &mut stack);
3180 }
3181 "function_definition" => {
3182 if let Some(name) = node
3183 .child_by_field_name("name")
3184 .and_then(|name| non_empty_node_text(name, source))
3185 {
3186 let key = class_name
3187 .as_ref()
3188 .map(|class| format!("{class}.{name}"))
3189 .unwrap_or(name);
3190 let declaration = node
3191 .parent()
3192 .filter(|parent| parent.kind() == "decorated_definition")
3193 .unwrap_or(node);
3194 let fact = *returns_by_range
3195 .get(&(declaration.start_byte(), declaration.end_byte()))?;
3196 if let Some(return_type) = factory_return_type_with_known(
3197 node,
3198 source,
3199 fact,
3200 None,
3201 &HashMap::default(),
3202 ) {
3203 returns.insert(key.clone(), return_type);
3204 }
3205 functions.push((key, class_name, node, fact));
3206 }
3207 }
3208 _ => push_factory_index_children(node, class_name, &mut stack),
3209 }
3210 }
3211 for _ in 0..functions.len() {
3217 let mut changed = false;
3218 for (key, class_name, function, fact) in &functions {
3219 let Some(return_type) = factory_return_type_with_known(
3220 *function,
3221 source,
3222 fact,
3223 class_name.as_deref(),
3224 &returns,
3225 ) else {
3226 continue;
3227 };
3228 if returns.get(key) != Some(&return_type) {
3229 returns.insert(key.clone(), return_type);
3230 changed = true;
3231 }
3232 }
3233 if !changed {
3234 break;
3235 }
3236 }
3237 Some(returns)
3238}
3239
3240fn push_factory_index_children<'tree>(
3241 node: Node<'tree>,
3242 class_name: Option<String>,
3243 stack: &mut Vec<(Node<'tree>, Option<String>)>,
3244) {
3245 let mut cursor = node.walk();
3246 let mut children: Vec<Node<'tree>> = node.named_children(&mut cursor).collect();
3247 children.reverse();
3248 stack.extend(
3249 children
3250 .into_iter()
3251 .map(|child| (child, class_name.clone())),
3252 );
3253}
3254
3255fn factory_return_type_with_known(
3256 function: Node<'_>,
3257 source: &str,
3258 fact: &brokk_bifrost_core::analyzer::python_facts::PythonCallableReturnFact,
3259 current_class: Option<&str>,
3260 known: &HashMap<String, String>,
3261) -> Option<String> {
3262 if fact.return_annotation.is_some() {
3263 return fact
3264 .runtime_type
3265 .as_ref()?
3266 .nominal_name()
3267 .map(|name| name.path().join("."));
3268 }
3269
3270 inferred_factory_return_type(function, source, current_class, known)
3271}
3272
3273fn inferred_factory_return_type(
3274 function: Node<'_>,
3275 source: &str,
3276 current_class: Option<&str>,
3277 known: &HashMap<String, String>,
3278) -> Option<String> {
3279 let body = function.child_by_field_name("body")?;
3280 let mut candidates = HashSet::default();
3281 let mut saw_return = false;
3282 let mut saw_unknown_return = false;
3283 let mut stack = vec![body];
3284 while let Some(node) = stack.pop() {
3285 if node != body && matches!(node.kind(), "function_definition" | "class_definition") {
3286 continue;
3287 }
3288 if node.kind() == "return_statement" {
3289 saw_return = true;
3290 match node
3291 .named_child(0)
3292 .and_then(|value| returned_receiver_type(value, source))
3293 {
3294 Some(returned_type) => {
3295 candidates.insert(
3296 canonical_factory_return(&returned_type, current_class, known)
3297 .unwrap_or(returned_type),
3298 );
3299 }
3300 None => saw_unknown_return = true,
3301 }
3302 }
3303 let mut cursor = node.walk();
3304 let mut children: Vec<Node<'_>> = node.named_children(&mut cursor).collect();
3305 children.reverse();
3306 stack.extend(children);
3307 }
3308 if !saw_return || saw_unknown_return {
3309 return None;
3310 }
3311 (candidates.len() == 1)
3312 .then(|| candidates.into_iter().next())
3313 .flatten()
3314}
3315
3316fn canonical_factory_return(
3317 raw: &str,
3318 current_class: Option<&str>,
3319 known: &HashMap<String, String>,
3320) -> Option<String> {
3321 let mut current = raw;
3322 let mut seen = HashSet::default();
3323 while let Some(next) = factory_return_type_for_callee(current, current_class, known) {
3324 if !seen.insert(current.to_string()) {
3325 return None;
3326 }
3327 current = next;
3328 }
3329 Some(current.to_string())
3330}
3331
3332fn returned_receiver_type(node: Node<'_>, source: &str) -> Option<String> {
3333 let raw = match node.kind() {
3334 "identifier" => non_empty_node_text(node, source),
3335 "call" => node
3336 .child_by_field_name("function")
3337 .or_else(|| node.named_child(0))
3338 .filter(|callee| callee.kind() == "identifier")
3339 .and_then(|callee| non_empty_node_text(callee, source)),
3340 _ => None,
3341 }?;
3342 normalized_receiver_type(&raw)
3343}
3344
3345#[cfg(test)]
3346mod tests {
3347 use super::*;
3348 use brokk_bifrost_test_macros::hardwon;
3349
3350 #[test]
3351 #[hardwon("#1225: a lambda parameter failed to shadow the enclosing receiver name")]
3352 fn lambda_scope_facts_preserve_untyped_parameter_shadowing() {
3353 let source = "shadowed = lambda method: method.signature\n";
3354 let mut parser = Parser::new();
3355 parser
3356 .set_language(&tree_sitter_python::LANGUAGE.into())
3357 .unwrap();
3358 let tree = parser.parse(source, None).unwrap();
3359 let mut nodes = vec![tree.root_node()];
3360 let lambda = loop {
3361 let node = nodes.pop().unwrap();
3362 if node.kind() == "lambda" {
3363 break node;
3364 }
3365 let mut cursor = node.walk();
3366 nodes.extend(node.named_children(&mut cursor));
3367 };
3368
3369 let facts = collect_function_scope_facts_from_node(lambda, source);
3370
3371 assert!(facts.is_shadowed("method"));
3372 assert!(facts.resolution_for("method").is_unknown());
3373 }
3374}