1use brokk_bifrost_core::analyzer::query_token::QueryToken;
15use brokk_bifrost_core::analyzer::usages::local_inference::LocalBindingsSnapshot;
16use brokk_bifrost_core::analyzer::usages::model::{
17 ExportEntry, ExportIndex, ImportBinder, ImportBinding, ImportKind,
18};
19use brokk_bifrost_core::analyzer::usages::{ImportEdge, ImportEdgeKind};
20use brokk_bifrost_core::analyzer::{CodeUnit, Language, ProjectFile};
21use brokk_bifrost_core::hash::{HashMap, HashSet};
22use std::collections::{BTreeSet, VecDeque};
23use std::sync::{Arc, Mutex};
24
25use crate::declarations::python_module_name;
26use crate::graph_support::{
27 PythonModuleSpellings, PythonSource, PythonUsageSource, export_index_from_file_facts,
28 import_binder_from_imports, import_bindings_from_imports, python_module_file_under_source_root,
29 retain_modules_for_importer,
30};
31use crate::imports::{
32 literal_importlib_modules, module_replacement_of, resolve_python_relative_module,
33};
34
35#[derive(Debug, Default)]
37pub struct PythonUsageIndex {
38 module_index: HashMap<String, Vec<ProjectFile>>,
39 module_spellings: Arc<PythonModuleSpellings>,
40 exports_by_file: HashMap<ProjectFile, Arc<ExportIndex>>,
41 reexport_edges: HashMap<(ProjectFile, String), Vec<(ProjectFile, String)>>,
42 star_reexports: HashMap<ProjectFile, Vec<ProjectFile>>,
43 importer_reverse: HashMap<ProjectFile, Vec<ImportEdge>>,
44 literal_importlib_importers: HashMap<ProjectFile, Vec<ProjectFile>>,
45 module_binding_timelines: Mutex<HashMap<ProjectFile, Arc<ModuleBindingTimeline>>>,
46 scope_facts_by_file: Mutex<HashMap<ProjectFile, Arc<PythonScopeFacts>>>,
47}
48
49pub type ModuleBindingTimeline = HashMap<String, Vec<ModuleBindingEvent>>;
50pub type PythonScopeFacts = HashMap<CodeUnit, LocalBindingsSnapshot<String>>;
51
52#[derive(Clone, Debug)]
53pub struct ModuleBindingEvent {
54 pub visible_from: usize,
55 pub conditional: bool,
56 pub kind: ModuleBindingEventKind,
57}
58
59#[derive(Clone, Debug)]
60pub enum ModuleBindingEventKind {
61 ImportModule {
62 module: String,
63 consumed_attributes: usize,
64 },
65 FromImport {
66 module: String,
67 imported_name: String,
68 },
69 Other,
70}
71
72fn resolve_module(
76 module_index: &HashMap<String, Vec<ProjectFile>>,
77 module_spellings: &PythonModuleSpellings,
78 importing_file: &ProjectFile,
79 module_specifier: &str,
80) -> Vec<ProjectFile> {
81 let resolved_module = if module_specifier.starts_with('.') {
82 resolve_python_relative_module(importing_file, module_specifier)
83 } else {
84 Some(module_specifier.to_string())
85 };
86 let Some(resolved_module) = resolved_module else {
87 return Vec::new();
88 };
89 let mut files = module_index
90 .get(&resolved_module)
91 .cloned()
92 .unwrap_or_default();
93 retain_modules_for_importer(importing_file, &mut files, |file| file);
96 if files.is_empty() {
97 files.extend(python_module_file_under_source_root(
100 module_spellings,
101 importing_file,
102 &resolved_module,
103 ));
104 }
105 files
106}
107
108fn is_sys_namespace_binding(binding: &ImportBinding) -> bool {
109 binding.kind == ImportKind::Namespace
110 && binding
111 .namespace_imported_module
112 .as_deref()
113 .unwrap_or(&binding.module_specifier)
114 == "sys"
115}
116
117fn is_importlib_namespace_binding(binding: &ImportBinding) -> bool {
118 binding.kind == ImportKind::Namespace
119 && binding
120 .namespace_imported_module
121 .as_deref()
122 .unwrap_or(&binding.module_specifier)
123 == "importlib"
124}
125
126impl PythonUsageIndex {
127 pub fn build(python: &dyn PythonSource, token: QueryToken<'_>) -> Self {
131 let _scope = brokk_bifrost_core::profiling::scope("PythonUsageIndex::build");
132 let mut files: Vec<ProjectFile> = python
133 .project()
134 .analyzable_files(Language::Python)
135 .map(|set| set.into_iter().collect())
136 .unwrap_or_default();
137 files.sort();
138 files.dedup();
139
140 let module_spellings = python.module_spellings();
141 let mut module_index: HashMap<String, Vec<ProjectFile>> = HashMap::default();
142 let mut exports_by_file: HashMap<ProjectFile, Arc<ExportIndex>> = HashMap::default();
143 let mut binders_by_file: HashMap<ProjectFile, Arc<ImportBinder>> = HashMap::default();
144 let mut import_bindings_by_file: HashMap<ProjectFile, Vec<(String, ImportBinding)>> =
145 HashMap::default();
146 let mut literal_importlib_modules_by_file: HashMap<ProjectFile, HashSet<String>> =
147 HashMap::default();
148 let mut replacement_modules: HashMap<ProjectFile, String> = HashMap::default();
149 python.visit_file_facts(&files, &mut |file, facts| {
150 let module_name = facts
151 .and_then(|facts| {
152 facts
153 .top_level_declarations()
154 .iter()
155 .find(|unit| unit.is_module())
156 })
157 .map(|unit| unit.fq_name().to_string())
158 .unwrap_or_else(|| python_module_name(file));
159 module_index
160 .entry(module_name.clone())
161 .or_default()
162 .push(file.clone());
163 if let Some(facts) = facts {
164 let import_bindings = import_bindings_from_imports(python, file, facts.imports());
165 let binder = Arc::new(import_binder_from_imports(python, file, facts.imports()));
166 if binder.bindings.values().any(is_importlib_namespace_binding) {
167 literal_importlib_modules_by_file.insert(
168 file.clone(),
169 literal_importlib_modules(facts.source(), &binder.bindings),
170 );
171 }
172 if binder.bindings.values().any(is_sys_namespace_binding)
173 && let Some(replacement) = module_replacement_of(python, file, facts.source())
174 {
175 replacement_modules.insert(file.clone(), replacement.target_module);
176 }
177 exports_by_file.insert(
178 file.clone(),
179 Arc::new(export_index_from_file_facts(
180 python,
181 file,
182 facts,
183 &module_name,
184 &binder,
185 )),
186 );
187 import_bindings_by_file.insert(file.clone(), import_bindings);
188 binders_by_file.insert(file.clone(), binder);
189 } else {
190 exports_by_file.insert(file.clone(), python.export_index_of(file));
191 let binder = python.import_binder_of(file);
192 if let Ok(source) = python.project().read_source(file) {
193 if binder.bindings.values().any(is_importlib_namespace_binding) {
194 literal_importlib_modules_by_file.insert(
195 file.clone(),
196 literal_importlib_modules(&source, &binder.bindings),
197 );
198 }
199 if binder.bindings.values().any(is_sys_namespace_binding)
200 && let Some(replacement) = module_replacement_of(python, file, &source)
201 {
202 replacement_modules.insert(file.clone(), replacement.target_module);
203 }
204 }
205 let imports = python.import_info_of(token, file);
206 import_bindings_by_file.insert(
207 file.clone(),
208 import_bindings_from_imports(python, file, &imports),
209 );
210 binders_by_file.insert(file.clone(), binder);
211 }
212 });
213 for resolved in module_index.values_mut() {
214 resolved.sort();
215 resolved.dedup();
216 }
217
218 let mut raw_replacements: HashMap<ProjectFile, ProjectFile> = HashMap::default();
219 for (file, target_module) in replacement_modules {
220 let mut targets =
221 resolve_module(&module_index, &module_spellings, &file, &target_module);
222 if targets.len() != 1 {
223 continue;
224 }
225 let target = targets.pop().expect("one module replacement target");
226 if target != file {
227 raw_replacements.insert(file, target);
228 }
229 }
230
231 let mut canonical_replacements: HashMap<ProjectFile, ProjectFile> = HashMap::default();
232 for file in raw_replacements.keys() {
233 if let Some(target) = canonical_module_replacement(file, &raw_replacements) {
234 canonical_replacements.insert(file.clone(), target);
235 }
236 }
237 for resolved in module_index.values_mut() {
238 let mut seen = HashSet::default();
239 resolved.retain_mut(|file| {
240 if let Some(canonical) = canonical_replacements.get(file) {
241 *file = canonical.clone();
242 }
243 seen.insert(file.clone())
244 });
245 }
246
247 let mut reexport_edges: HashMap<(ProjectFile, String), Vec<(ProjectFile, String)>> =
248 HashMap::default();
249 let mut star_reexports: HashMap<ProjectFile, Vec<ProjectFile>> = HashMap::default();
250 for (file, exports) in &exports_by_file {
251 for (exported_name, entry) in &exports.exports_by_name {
252 match entry {
253 ExportEntry::Local { local_name } => {
254 let Some(binder) = binders_by_file.get(file) else {
255 continue;
256 };
257 let Some(binding) = binder.bindings.get(local_name) else {
258 continue;
259 };
260 let Some(imported_name) = binding.imported_name.as_ref() else {
261 continue;
262 };
263 for resolved_file in resolve_module(
264 &module_index,
265 &module_spellings,
266 file,
267 &binding.module_specifier,
268 ) {
269 reexport_edges
270 .entry((resolved_file, imported_name.clone()))
271 .or_default()
272 .push((file.clone(), exported_name.clone()));
273 }
274 }
275 ExportEntry::Default { .. } | ExportEntry::ReexportedModule { .. } => {}
278 ExportEntry::ReexportedNamed {
279 module_specifier,
280 imported_name,
281 } => {
282 for resolved_file in
283 resolve_module(&module_index, &module_spellings, file, module_specifier)
284 {
285 reexport_edges
286 .entry((resolved_file, imported_name.clone()))
287 .or_default()
288 .push((file.clone(), exported_name.clone()));
289 }
290 }
291 }
292 }
293 for star in &exports.reexport_stars {
294 for resolved_file in resolve_module(
295 &module_index,
296 &module_spellings,
297 file,
298 &star.module_specifier,
299 ) {
300 star_reexports
301 .entry(resolved_file)
302 .or_default()
303 .push(file.clone());
304 }
305 }
306 }
307
308 let importer_reverse = build_importer_reverse(
309 &module_index,
310 &module_spellings,
311 &files,
312 &import_bindings_by_file,
313 &exports_by_file,
314 );
315 let mut literal_importlib_importers: HashMap<ProjectFile, Vec<ProjectFile>> =
316 HashMap::default();
317 for (importer, modules) in literal_importlib_modules_by_file {
318 for module in modules {
319 for target_file in
320 resolve_module(&module_index, &module_spellings, &importer, &module)
321 {
322 literal_importlib_importers
323 .entry(target_file.clone())
324 .or_default()
325 .push(importer.clone());
326 }
327 }
328 }
329 for importers in literal_importlib_importers.values_mut() {
330 importers.sort();
331 importers.dedup();
332 }
333
334 Self {
335 module_index,
336 module_spellings,
337 exports_by_file,
338 reexport_edges,
339 star_reexports,
340 importer_reverse,
341 literal_importlib_importers,
342 module_binding_timelines: Mutex::new(HashMap::default()),
343 scope_facts_by_file: Mutex::new(HashMap::default()),
344 }
345 }
346
347 pub fn seeds_for_target(
348 &self,
349 target_file: &ProjectFile,
350 target_short: &str,
351 ) -> BTreeSet<(ProjectFile, String)> {
352 let mut seeds: BTreeSet<(ProjectFile, String)> = BTreeSet::new();
353
354 if let Some(exports) = self.exports_by_file.get(target_file) {
355 for (exported_name, entry) in &exports.exports_by_name {
356 let local = match entry {
357 ExportEntry::Local { local_name } => Some(local_name.as_str()),
358 ExportEntry::Default { local_name } => local_name.as_deref(),
359 ExportEntry::ReexportedNamed { .. } | ExportEntry::ReexportedModule { .. } => {
360 None
361 }
362 };
363 if let Some(local_name) = local
364 && local_name == target_short
365 {
366 seeds.insert((target_file.clone(), exported_name.clone()));
367 }
368 }
369 }
370
371 let mut frontier: VecDeque<(ProjectFile, String)> = seeds.iter().cloned().collect();
372 while let Some(seed) = frontier.pop_front() {
373 if let Some(reexports) = self.reexport_edges.get(&seed) {
374 for next in reexports {
375 if seeds.insert(next.clone()) {
376 frontier.push_back(next.clone());
377 }
378 }
379 }
380 if !seed.1.starts_with('_')
381 && let Some(star_files) = self.star_reexports.get(&seed.0)
382 {
383 for star_file in star_files {
384 let next = (star_file.clone(), seed.1.clone());
385 if seeds.insert(next.clone()) {
386 frontier.push_back(next);
387 }
388 }
389 }
390 }
391
392 seeds
393 }
394
395 pub fn matching_edges_for_importer(
396 &self,
397 importer: &ProjectFile,
398 seeds: &BTreeSet<(ProjectFile, String)>,
399 ) -> Vec<ImportEdge> {
400 let mut matches = Vec::new();
401 for (target_file, _) in seeds {
402 let Some(edges) = self.importer_reverse.get(target_file) else {
403 continue;
404 };
405 matches.extend(
406 edges
407 .iter()
408 .filter(|edge| &edge.importer == importer && edge_matches_seed(edge, seeds))
409 .cloned(),
410 );
411 }
412 matches
413 }
414
415 pub fn importer_files_for_seeds(
416 &self,
417 seeds: &BTreeSet<(ProjectFile, String)>,
418 ) -> HashSet<ProjectFile> {
419 let mut importers = HashSet::default();
420 for (target_file, _) in seeds {
421 if let Some(edges) = self.importer_reverse.get(target_file) {
422 importers.extend(
423 edges
424 .iter()
425 .filter(|edge| edge_matches_seed(edge, seeds))
426 .map(|edge| edge.importer.clone()),
427 );
428 }
429 if let Some(dynamic_importers) = self.literal_importlib_importers.get(target_file) {
430 importers.extend(dynamic_importers.iter().cloned());
431 }
432 }
433 importers
434 }
435
436 pub fn resolve_module_files(
437 &self,
438 importing_file: &ProjectFile,
439 module_specifier: &str,
440 ) -> Vec<ProjectFile> {
441 resolve_module(
442 &self.module_index,
443 &self.module_spellings,
444 importing_file,
445 module_specifier,
446 )
447 }
448
449 pub fn module_binding_timeline(
450 &self,
451 file: &ProjectFile,
452 build: impl FnOnce() -> ModuleBindingTimeline,
453 ) -> Arc<ModuleBindingTimeline> {
454 if let Some(cached) = self
455 .module_binding_timelines
456 .lock()
457 .expect("Python module-binding timeline cache mutex poisoned")
458 .get(file)
459 .cloned()
460 {
461 return cached;
462 }
463
464 let timeline = Arc::new(build());
465 self.module_binding_timelines
466 .lock()
467 .expect("Python module-binding timeline cache mutex poisoned")
468 .entry(file.clone())
469 .or_insert_with(|| timeline.clone())
470 .clone()
471 }
472
473 pub fn scope_facts(
474 &self,
475 file: &ProjectFile,
476 build: impl FnOnce() -> PythonScopeFacts,
477 ) -> Arc<PythonScopeFacts> {
478 if let Some(cached) = self
479 .scope_facts_by_file
480 .lock()
481 .expect("Python scope-facts cache mutex poisoned")
482 .get(file)
483 .cloned()
484 {
485 return cached;
486 }
487
488 let facts = Arc::new(build());
489 self.scope_facts_by_file
490 .lock()
491 .expect("Python scope-facts cache mutex poisoned")
492 .entry(file.clone())
493 .or_insert_with(|| facts.clone())
494 .clone()
495 }
496}
497
498fn edge_matches_seed(edge: &ImportEdge, seeds: &BTreeSet<(ProjectFile, String)>) -> bool {
499 match &edge.kind {
500 ImportEdgeKind::Named(name) => seeds.contains(&(edge.target_file.clone(), name.clone())),
501 ImportEdgeKind::Default => {
502 seeds.contains(&(edge.target_file.clone(), "default".to_string()))
503 }
504 ImportEdgeKind::Namespace => seeds.iter().any(|(file, _)| file == &edge.target_file),
505 ImportEdgeKind::CommonJsRequire(export_name) => {
506 seeds.contains(&(edge.target_file.clone(), export_name.clone()))
507 }
508 }
509}
510
511fn canonical_module_replacement(
512 file: &ProjectFile,
513 replacements: &HashMap<ProjectFile, ProjectFile>,
514) -> Option<ProjectFile> {
515 let mut seen = BTreeSet::new();
516 let mut current = file.clone();
517 while let Some(target) = replacements.get(¤t) {
518 if !seen.insert(current) {
519 return None;
520 }
521 current = target.clone();
522 }
523 Some(current)
524}
525
526fn build_importer_reverse(
527 module_index: &HashMap<String, Vec<ProjectFile>>,
528 module_spellings: &PythonModuleSpellings,
529 files: &[ProjectFile],
530 bindings_by_file: &HashMap<ProjectFile, Vec<(String, ImportBinding)>>,
531 exports_by_file: &HashMap<ProjectFile, Arc<ExportIndex>>,
532) -> HashMap<ProjectFile, Vec<ImportEdge>> {
533 let mut reverse: HashMap<ProjectFile, Vec<ImportEdge>> = HashMap::default();
534 for file in files {
535 let Some(bindings) = bindings_by_file.get(file) else {
536 continue;
537 };
538 for (local_name, binding) in bindings {
539 let imported_module = binding
540 .namespace_imported_module
541 .as_deref()
542 .unwrap_or(&binding.module_specifier);
543 for target_file in resolve_module(module_index, module_spellings, file, imported_module)
544 {
545 if matches!(binding.kind, ImportKind::Glob) {
548 let Some(exports) = exports_by_file.get(&target_file) else {
549 continue;
550 };
551 for export_name in exports.exports_by_name.keys() {
552 if export_name.starts_with('_') {
553 continue;
554 }
555 reverse
556 .entry(target_file.clone())
557 .or_default()
558 .push(ImportEdge {
559 importer: file.clone(),
560 local_name: export_name.clone(),
561 target_file: target_file.clone(),
562 kind: ImportEdgeKind::Named(export_name.clone()),
563 });
564 }
565 continue;
566 }
567 let kind = match (binding.kind, binding.imported_name.as_deref()) {
568 (ImportKind::Default, _) => ImportEdgeKind::Default,
569 (ImportKind::Namespace, _) => ImportEdgeKind::Namespace,
570 (ImportKind::Named, Some(name)) => ImportEdgeKind::Named(name.to_string()),
571 (ImportKind::Named, None) => ImportEdgeKind::Named(local_name.clone()),
572 (ImportKind::CommonJsRequire, _) | (ImportKind::Glob, _) => continue,
574 };
575 reverse
576 .entry(target_file.clone())
577 .or_default()
578 .push(ImportEdge {
579 importer: file.clone(),
580 local_name: local_name.clone(),
581 target_file,
582 kind,
583 });
584 }
585 }
586 }
587 reverse
588}
589
590pub fn usage_seeds(
592 python: &dyn PythonUsageSource,
593 target_file: &ProjectFile,
594 target_short: &str,
595) -> BTreeSet<(ProjectFile, String)> {
596 python
597 .usage_index()
598 .seeds_for_target(target_file, target_short)
599}
600
601pub fn usage_matching_edges(
603 python: &dyn PythonUsageSource,
604 importer: &ProjectFile,
605 seeds: &BTreeSet<(ProjectFile, String)>,
606) -> Vec<ImportEdge> {
607 python
608 .usage_index()
609 .matching_edges_for_importer(importer, seeds)
610}
611
612pub fn usage_importer_files(
613 python: &dyn PythonUsageSource,
614 seeds: &BTreeSet<(ProjectFile, String)>,
615) -> HashSet<ProjectFile> {
616 python.usage_index().importer_files_for_seeds(seeds)
617}
618
619pub fn usage_resolve_module_files(
620 python: &dyn PythonUsageSource,
621 importing_file: &ProjectFile,
622 module_specifier: &str,
623) -> Vec<ProjectFile> {
624 python
625 .usage_index()
626 .resolve_module_files(importing_file, module_specifier)
627}
628
629pub fn usage_module_binding_timeline(
630 python: &dyn PythonUsageSource,
631 file: &ProjectFile,
632 build: impl FnOnce() -> ModuleBindingTimeline,
633) -> Arc<ModuleBindingTimeline> {
634 python.usage_index().module_binding_timeline(file, build)
635}
636
637pub fn usage_scope_facts(
638 python: &dyn PythonUsageSource,
639 file: &ProjectFile,
640 build: impl FnOnce() -> PythonScopeFacts,
641) -> Arc<PythonScopeFacts> {
642 python.usage_index().scope_facts(file, build)
643}
644
645#[cfg(test)]
646mod tests {
647 use super::*;
648
649 #[test]
650 fn module_replacement_chains_canonicalize_and_cycles_are_rejected() {
651 let root = tempfile::tempdir().expect("temporary project root");
652 let first = ProjectFile::new(root.path(), "first.py");
653 let second = ProjectFile::new(root.path(), "second.py");
654 let canonical = ProjectFile::new(root.path(), "canonical.py");
655 let chain = HashMap::from_iter([
656 (first.clone(), second.clone()),
657 (second.clone(), canonical.clone()),
658 ]);
659
660 assert_eq!(
661 canonical_module_replacement(&first, &chain),
662 Some(canonical)
663 );
664
665 let cycle = HashMap::from_iter([(first.clone(), second.clone()), (second, first.clone())]);
666 assert_eq!(canonical_module_replacement(&first, &cycle), None);
667 }
668
669 #[test]
670 fn module_binding_timeline_is_reused_within_index_generation() {
671 let root = tempfile::tempdir().expect("temporary project root");
672 let file = ProjectFile::new(root.path(), "consumer.py");
673 let index = PythonUsageIndex::default();
674 let first = index.module_binding_timeline(&file, || {
675 ModuleBindingTimeline::from_iter([(
676 "target".to_string(),
677 vec![ModuleBindingEvent {
678 visible_from: 12,
679 conditional: false,
680 kind: ModuleBindingEventKind::Other,
681 }],
682 )])
683 });
684 let second = index.module_binding_timeline(&file, || {
685 panic!("cached timeline should avoid rebuilding the file")
686 });
687
688 assert!(Arc::ptr_eq(&first, &second));
689
690 let first_facts = index.scope_facts(&file, PythonScopeFacts::default);
691 let second_facts = index.scope_facts(&file, || {
692 panic!("cached scope facts should avoid rebuilding the file")
693 });
694 assert!(Arc::ptr_eq(&first_facts, &second_facts));
695 }
696}