1use crate::bindings::PythonLexicalScopeInventory;
4use brokk_bifrost_core::analyzer::ProjectFile;
5use brokk_bifrost_core::analyzer::Range;
6use brokk_bifrost_core::analyzer::python_facts::PythonSourceFacts;
7use brokk_bifrost_core::analyzer::query_token::QueryToken;
8use brokk_bifrost_core::analyzer::source_facts::SourceFactRows;
9use std::collections::{HashMap, HashSet};
10use std::mem::size_of;
11use std::sync::Arc;
12use tree_sitter::Node;
13
14mod hazards;
15pub(crate) use hazards::PythonDynamicHazards;
16
17#[derive(Debug, Clone, Default)]
25pub struct PythonModuleGlobalSourceFacts {
26 bindings: HashMap<Box<str>, PythonModuleGlobalBindingFact>,
27 global_declarations: HashSet<Box<str>>,
28 wildcard_import_offsets: Vec<usize>,
29 has_dynamic_write: bool,
30 has_exec: bool,
31}
32
33#[derive(Debug, Clone, Default)]
34struct PythonModuleGlobalBindingFact {
35 statements: u32,
36 initializer: Option<Range>,
37 initializer_statement_end: usize,
38}
39
40impl PythonModuleGlobalSourceFacts {
41 pub fn module_binds_name(&self, name: &str) -> bool {
43 self.bindings.contains_key(name)
44 }
45
46 pub fn initializer_range(&self, name: &str) -> Option<Range> {
48 if self.has_dynamic_write || self.has_exec || self.global_declarations.contains(name) {
49 return None;
50 }
51 let binding = self.bindings.get(name)?;
52 if binding.statements != 1 {
53 return None;
54 }
55 if self
56 .wildcard_import_offsets
57 .iter()
58 .any(|offset| *offset > binding.initializer_statement_end)
59 {
60 return None;
61 }
62 binding.initializer
63 }
64
65 pub fn estimated_retained_bytes(&self) -> usize {
67 size_of::<Self>()
68 + self
69 .bindings
70 .keys()
71 .map(|name| name.len() + size_of::<PythonModuleGlobalBindingFact>())
72 .sum::<usize>()
73 + self
74 .global_declarations
75 .iter()
76 .map(|name| name.len() + size_of::<Box<str>>())
77 .sum::<usize>()
78 + self.wildcard_import_offsets.len() * size_of::<usize>()
79 }
80}
81
82#[derive(Debug)]
83enum PythonModuleMutationHazard {
84 Global(Vec<Box<str>>),
85 Exec,
86 ReflectiveWrite,
87}
88
89fn python_module_mutation_hazard_bounded(
92 node: Node<'_>,
93 source: &str,
94 hazards: &PythonDynamicHazards,
95 mut scope_step: impl FnMut() -> bool,
96) -> Option<Option<PythonModuleMutationHazard>> {
97 if !scope_step() {
98 return None;
99 }
100 if node.kind() == "global_statement" {
101 let mut names = Vec::new();
102 let mut cursor = node.walk();
103 for child in node.named_children(&mut cursor) {
104 if !scope_step() {
105 return None;
106 }
107 if child.kind() == "identifier" {
108 names.push(child.utf8_text(source.as_bytes()).ok()?.into());
109 }
110 }
111 return Some(Some(PythonModuleMutationHazard::Global(names)));
112 }
113 if hazards.contains(node) {
114 return Some(Some(PythonModuleMutationHazard::Exec));
115 }
116 if node.kind() != "call" {
117 return Some(None);
118 }
119 if node
124 .child_by_field_name("function")
125 .is_some_and(|function| {
126 function.kind() == "identifier"
127 && function.utf8_text(source.as_bytes()).ok() == Some("exec")
128 })
129 {
130 return Some(Some(PythonModuleMutationHazard::Exec));
131 }
132 Some(
133 module_globals_write_call_bounded(node, source, &mut scope_step)?
134 .then_some(PythonModuleMutationHazard::ReflectiveWrite),
135 )
136}
137
138pub(crate) fn python_module_dynamic_write_candidate(
142 node: Node<'_>,
143 source: &str,
144 hazards: &PythonDynamicHazards,
145) -> bool {
146 matches!(
147 python_module_mutation_hazard_bounded(node, source, hazards, || true),
148 Some(Some(
149 PythonModuleMutationHazard::Exec | PythonModuleMutationHazard::ReflectiveWrite
150 ))
151 )
152}
153
154#[derive(Debug)]
160pub struct PythonModuleMutationFacts {
161 global_binding_events: HashSet<Box<str>>,
162 dynamic_hazards: Vec<Range>,
163}
164
165impl brokk_bifrost_core::retention_budget::RetainedBytes for PythonModuleMutationFacts {
166 fn retained_bytes(&self) -> usize {
168 use brokk_bifrost_core::allocation_size::allocation_size;
169 use brokk_bifrost_core::domain_memo::hash_table_allocation_bytes;
170 std::mem::size_of::<Self>()
171 + hash_table_allocation_bytes(
172 self.global_binding_events.capacity(),
173 std::mem::size_of::<Box<str>>(),
174 )
175 + self
176 .global_binding_events
177 .iter()
178 .map(|name| allocation_size(name.len()))
179 .sum::<usize>()
180 + allocation_size(self.dynamic_hazards.capacity() * std::mem::size_of::<Range>())
181 }
182}
183
184impl PythonModuleMutationFacts {
185 pub fn collect_bounded(
188 root: Node<'_>,
189 source: &str,
190 mut scope_step: impl FnMut() -> bool,
191 ) -> Option<Self> {
192 use brokk_bifrost_core::analyzer::tree_walk::{
193 WalkControl, node_range, try_walk_named_tree_preorder,
194 };
195 if !scope_step() || root.kind() != "module" || root.has_error() {
196 return None;
197 }
198 let hazards = PythonDynamicHazards::collect_bounded(root, source, &mut scope_step)?;
199 let mut facts = Self {
200 global_binding_events: HashSet::new(),
201 dynamic_hazards: Vec::new(),
202 };
203 let mut checked_global_scopes = HashSet::new();
204 try_walk_named_tree_preorder(root, true, |node| {
205 if !scope_step() {
206 return Err(());
207 }
208 match python_module_mutation_hazard_bounded(node, source, &hazards, &mut scope_step)
209 .ok_or(())?
210 {
211 Some(PythonModuleMutationHazard::Global(_)) => {
212 let mut current = node.parent();
215 while let Some(scope) = current {
216 if !scope_step() {
217 return Err(());
218 }
219 if scope.kind() == "module" {
220 break;
223 }
224 if matches!(
225 scope.kind(),
226 "function_definition" | "lambda" | "class_definition"
227 ) {
228 if !checked_global_scopes.contains(&scope.id()) {
229 let bindings = PythonLexicalScopeInventory::collect_bounded(
232 scope,
233 source,
234 std::iter::empty::<String>(),
235 &mut scope_step,
236 )
237 .ok_or(())?
238 .into_bindings();
239 for name in bindings.global_binding_events() {
242 if !scope_step() {
243 return Err(());
244 }
245 facts.global_binding_events.insert(name.into());
246 }
247 checked_global_scopes.insert(scope.id());
248 }
249 break;
250 }
251 current = scope.parent();
252 }
253 }
254 Some(
255 PythonModuleMutationHazard::Exec | PythonModuleMutationHazard::ReflectiveWrite,
256 ) => {
257 facts.dynamic_hazards.push(node_range(node));
258 }
259 None => {}
260 }
261 Ok(WalkControl::Continue)
262 })
263 .ok()?;
264 scope_step().then_some(facts)
265 }
266
267 pub fn binding_unmutated_at_bounded(
273 &self,
274 root: Node<'_>,
275 name: &str,
276 reference: Node<'_>,
277 mut scope_step: impl FnMut() -> bool,
278 ) -> Option<bool> {
279 use brokk_bifrost_core::analyzer::tree_walk::node_range;
280 use brokk_bifrost_core::analyzer::usages::reference_site::smallest_named_node_covering_with_scope;
281 if !scope_step() {
282 return None;
283 }
284 if root.kind() != "module" || root.has_error() {
285 return scope_step().then_some(false);
286 }
287 let deferred = crate::syntax::python_reference_is_deferred_function_body_bounded(
288 reference,
289 &mut scope_step,
290 )?;
291 let read_range = node_range(reference);
292 let mut unmutated = !self.global_binding_events.contains(name);
293 if unmutated {
294 for hazard in &self.dynamic_hazards {
295 if !scope_step() {
296 return None;
297 }
298 let node = smallest_named_node_covering_with_scope(
299 root,
300 hazard.start_byte,
301 hazard.end_byte,
302 &mut scope_step,
303 )?;
304 if node.start_byte() != hazard.start_byte || node.end_byte() != hazard.end_byte {
305 return None;
306 }
307 if deferred
310 || crate::runtime_values::python_hazard_can_precede_bounded(
311 *hazard,
312 read_range,
313 node,
314 &mut scope_step,
315 )?
316 {
317 unmutated = false;
318 break;
319 }
320 }
321 }
322 scope_step().then_some(unmutated)
325 }
326
327 pub fn export_unmutated_bounded(
330 &self,
331 name: &str,
332 mut scope_step: impl FnMut() -> bool,
333 ) -> Option<bool> {
334 if !scope_step() {
335 return None;
336 }
337 let unmutated =
338 !self.global_binding_events.contains(name) && self.dynamic_hazards.is_empty();
339 scope_step().then_some(unmutated)
340 }
341}
342
343pub fn python_module_binding_unmutated_at_bounded(
345 root: Node<'_>,
346 source: &str,
347 name: &str,
348 reference: Node<'_>,
349 mut scope_step: impl FnMut() -> bool,
350) -> Option<bool> {
351 PythonModuleMutationFacts::collect_bounded(root, source, &mut scope_step)?
352 .binding_unmutated_at_bounded(root, name, reference, scope_step)
353}
354
355pub fn python_module_export_unmutated_bounded(
357 root: Node<'_>,
358 source: &str,
359 name: &str,
360 mut scope_step: impl FnMut() -> bool,
361) -> Option<bool> {
362 PythonModuleMutationFacts::collect_bounded(root, source, &mut scope_step)?
363 .export_unmutated_bounded(name, scope_step)
364}
365
366pub fn python_module_global_source_facts(
373 root: Node<'_>,
374 source: &str,
375 max_nodes: usize,
376 mut keep_going: impl FnMut() -> bool,
377) -> Option<PythonModuleGlobalSourceFacts> {
378 if root.kind() != "module" || root.has_error() {
379 return None;
380 }
381 let mut remaining = max_nodes;
382 let mut facts = PythonModuleGlobalSourceFacts::default();
383 let mut stack = vec![(root, true)];
384 while let Some((node, initializer_path)) = stack.pop() {
385 if remaining == 0 || !keep_going() {
386 return None;
387 }
388 remaining -= 1;
389
390 if node.kind() == "wildcard_import" {
391 facts.wildcard_import_offsets.push(node.start_byte());
392 }
393
394 let mut bound_names = HashSet::<String>::new();
395 if matches!(
396 node.kind(),
397 "function_definition"
398 | "class_definition"
399 | "import_statement"
400 | "import_from_statement"
401 | "assignment"
402 | "augmented_assignment"
403 | "annotated_assignment"
404 | "named_expression"
405 | "for_statement"
406 | "delete_statement"
407 | "as_pattern"
408 | "except_clause"
409 | "case_clause"
410 ) {
411 let mut steps = || {
412 if remaining == 0 || !keep_going() {
413 false
414 } else {
415 remaining -= 1;
416 true
417 }
418 };
419 for binding in
420 crate::bindings::python_direct_scope_bindings_bounded(node, source, &mut steps)?
421 {
422 if binding.declaration.kind() == "identifier" {
423 bound_names.insert(
424 binding
425 .declaration
426 .utf8_text(source.as_bytes())
427 .ok()?
428 .to_owned(),
429 );
430 }
431 }
432 }
433 if node.kind() == "annotated_assignment"
434 && let Some(target) = node.child_by_field_name("left")
435 {
436 module_target_names(
437 target,
438 source,
439 &mut bound_names,
440 &mut remaining,
441 &mut keep_going,
442 )?;
443 }
444 if node.kind() == "with_statement" {
445 let mut cursor = node.walk();
446 for child in node.named_children(&mut cursor) {
447 if child.kind() == "with_clause" {
448 let mut with_stack = vec![child];
449 while let Some(item) = with_stack.pop() {
450 if remaining == 0 || !keep_going() {
451 return None;
452 }
453 remaining -= 1;
454 if item.kind() == "as_pattern"
455 && let Some(alias) = item.child_by_field_name("alias")
456 {
457 module_target_names(
458 alias,
459 source,
460 &mut bound_names,
461 &mut remaining,
462 &mut keep_going,
463 )?;
464 }
465 with_stack.extend(item.named_children(&mut item.walk()));
466 }
467 }
468 }
469 }
470
471 if !bound_names.is_empty() {
472 let assignment_initializer = (node.kind() == "assignment"
473 && initializer_path
474 && node.parent().is_some_and(|parent| {
475 matches!(parent.kind(), "module" | "block" | "expression_statement")
476 })
477 && node.child_by_field_name("type").is_none()
478 && node.child_by_field_name("annotation").is_none()
479 && node
480 .child_by_field_name("left")
481 .is_some_and(|left| left.kind() == "identifier")
482 && bound_names.len() == 1)
483 .then(|| node.child_by_field_name("right"))
484 .flatten();
485 for name in bound_names {
486 let binding = facts.bindings.entry(name.into_boxed_str()).or_default();
487 binding.statements = binding.statements.saturating_add(1);
488 if let Some(value) = assignment_initializer {
489 binding.initializer = Some(node_range(value, source));
490 binding.initializer_statement_end = node.end_byte();
491 } else {
492 binding.initializer = None;
493 binding.initializer_statement_end = node.end_byte();
494 }
495 }
496 }
497
498 let allowed_block = matches!(
499 node.kind(),
500 "if_statement"
501 | "try_statement"
502 | "with_statement"
503 | "for_statement"
504 | "block"
505 | "except_clause"
506 | "else_clause"
507 | "finally_clause"
508 | "expression_statement"
509 );
510 let scope_body = matches!(
511 node.kind(),
512 "function_definition" | "class_definition" | "lambda"
513 )
514 .then(|| node.child_by_field_name("body").map(|body| body.id()))
515 .flatten();
516 let name_node = matches!(node.kind(), "function_definition" | "class_definition")
517 .then(|| node.child_by_field_name("name").map(|name| name.id()))
518 .flatten();
519 let mut cursor = node.walk();
520 let children = node.named_children(&mut cursor).collect::<Vec<_>>();
521 for child in children.into_iter().rev() {
522 if Some(child.id()) == scope_body || Some(child.id()) == name_node {
523 continue;
524 }
525 let child_initializer_path =
526 if matches!(node.kind(), "module" | "block" | "expression_statement") {
527 initializer_path
528 } else if matches!(
529 node.kind(),
530 "except_clause" | "else_clause" | "finally_clause"
531 ) {
532 initializer_path && child.kind() == "block"
533 } else if allowed_block {
534 if node.kind() == "try_statement" {
535 initializer_path
536 && matches!(
537 child.kind(),
538 "block" | "except_clause" | "else_clause" | "finally_clause"
539 )
540 } else if matches!(node.kind(), "if_statement" | "for_statement")
541 && child.kind() == "else_clause"
542 {
543 initializer_path
544 } else {
545 initializer_path
546 && child.kind() == "block"
547 && (node
548 .child_by_field_name("body")
549 .is_some_and(|body| body.id() == child.id())
550 || node
551 .child_by_field_name("consequence")
552 .is_some_and(|body| body.id() == child.id())
553 || node
554 .child_by_field_name("alternative")
555 .is_some_and(|body| body.id() == child.id()))
556 }
557 } else {
558 false
559 };
560 if matches!(
561 node.kind(),
562 "list_comprehension"
563 | "set_comprehension"
564 | "dictionary_comprehension"
565 | "generator_expression"
566 ) && child.kind() == "for_in_clause"
567 {
568 let target = child.child_by_field_name("left");
569 let mut clause_cursor = child.walk();
570 for clause_child in child.named_children(&mut clause_cursor) {
571 if target.is_some_and(|target| target.id() == clause_child.id()) {
572 continue;
573 }
574 stack.push((clause_child, false));
575 }
576 continue;
577 }
578 stack.push((child, child_initializer_path));
579 }
580 }
581
582 remaining = max_nodes;
586 let mut pending = vec![root];
587 while let Some(node) = pending.pop() {
588 if remaining == 0 || !keep_going() {
589 return None;
590 }
591 remaining -= 1;
592 let mut cursor = node.walk();
593 pending.extend(node.named_children(&mut cursor));
594 }
595 let hazards = PythonDynamicHazards::collect_bounded(root, source, &mut keep_going)?;
596 remaining = max_nodes;
597 let mut stack = vec![root];
598 while let Some(node) = stack.pop() {
599 if remaining == 0 || !keep_going() {
600 return None;
601 }
602 remaining -= 1;
603 match python_module_mutation_hazard_bounded(node, source, &hazards, || true)? {
606 Some(PythonModuleMutationHazard::Global(names)) => {
607 facts.global_declarations.extend(names);
608 }
609 Some(PythonModuleMutationHazard::Exec) => facts.has_exec = true,
610 Some(PythonModuleMutationHazard::ReflectiveWrite) => facts.has_dynamic_write = true,
611 None => {}
612 }
613 let mut cursor = node.walk();
614 stack.extend(node.named_children(&mut cursor));
615 }
616 facts.wildcard_import_offsets.sort_unstable();
617 Some(facts)
618}
619
620fn node_range(node: Node<'_>, source: &str) -> Range {
621 let start_byte = node.start_byte();
622 let end_byte = node.end_byte();
623 let start_line = source.as_bytes()[..start_byte]
624 .iter()
625 .filter(|byte| **byte == b'\n')
626 .count()
627 + 1;
628 let end_line = source.as_bytes()[..end_byte]
629 .iter()
630 .filter(|byte| **byte == b'\n')
631 .count()
632 + 1;
633 Range {
634 start_byte,
635 end_byte,
636 start_line,
637 end_line,
638 }
639}
640
641fn module_target_names(
642 root: Node<'_>,
643 source: &str,
644 names: &mut HashSet<String>,
645 remaining: &mut usize,
646 keep_going: &mut impl FnMut() -> bool,
647) -> Option<()> {
648 let mut stack = vec![root];
649 while let Some(node) = stack.pop() {
650 if *remaining == 0 || !keep_going() {
651 return None;
652 }
653 *remaining -= 1;
654 match node.kind() {
655 "identifier" => {
656 names.insert(node.utf8_text(source.as_bytes()).ok()?.to_owned());
657 }
658 "attribute" | "subscript" | "call" | "string" | "integer" => {}
659 _ => {
660 let mut cursor = node.walk();
661 stack.extend(node.named_children(&mut cursor));
662 }
663 }
664 }
665 Some(())
666}
667
668fn module_globals_write_call_bounded(
669 call: Node<'_>,
670 source: &str,
671 mut scope_step: impl FnMut() -> bool,
672) -> Option<bool> {
673 if !scope_step() {
674 return None;
675 }
676 let function = call.child_by_field_name("function");
677 let Some(function) = function else {
678 return Some(false);
679 };
680 if function.kind() == "attribute" {
681 let method = function.child_by_field_name("attribute");
682 let object = function.child_by_field_name("object");
683 if method.is_some_and(|method| {
684 method
685 .utf8_text(source.as_bytes())
686 .ok()
687 .is_some_and(|name| {
688 matches!(name, "update" | "setdefault" | "pop" | "popitem" | "clear")
689 })
690 }) && object.is_some_and(|object| is_module_mapping_call(object, source))
691 {
692 return Some(true);
693 }
694 }
695 if !is_module_mapping_call(call, source) {
696 return Some(false);
697 }
698 let mut current = call;
699 while let Some(parent) = current.parent() {
700 if !scope_step() {
701 return None;
702 }
703 match parent.kind() {
704 "assignment" | "augmented_assignment" | "annotated_assignment" => {
705 return Some(parent.child_by_field_name("left").is_some_and(|left| {
706 left.start_byte() <= call.start_byte() && call.end_byte() <= left.end_byte()
707 }));
708 }
709 "delete_statement" => return Some(true),
710 "subscript" | "attribute" => current = parent,
711 _ => return Some(false),
712 }
713 }
714 Some(false)
715}
716
717fn is_module_mapping_call(node: Node<'_>, source: &str) -> bool {
718 if node.kind() != "call"
719 || !node
720 .child_by_field_name("arguments")
721 .is_some_and(|arguments| {
722 let mut cursor = arguments.walk();
723 arguments.named_children(&mut cursor).next().is_none()
724 })
725 {
726 return false;
727 }
728 node.child_by_field_name("function")
729 .is_some_and(|function| {
730 function.kind() == "identifier"
731 && function
732 .utf8_text(source.as_bytes())
733 .ok()
734 .is_some_and(|name| matches!(name, "globals" | "vars"))
735 })
736}
737
738#[derive(Debug, Clone)]
739pub struct PythonFileSourceFacts {
740 pub occurrences: SourceFactRows,
741 pub facts: PythonSourceFacts,
742}
743
744impl PythonFileSourceFacts {
745 pub fn callable_return_for_range(
747 &self,
748 start: usize,
749 end: usize,
750 keep_going: &dyn Fn() -> bool,
751 ) -> Option<&brokk_bifrost_core::analyzer::python_facts::PythonCallableReturnFact> {
752 for fact in &self.facts.callable_returns {
753 if !keep_going() {
754 return None;
755 }
756 let declaration = self.occurrences.declaration(fact.declaration);
757 let range = self.occurrences.occurrence(declaration.occurrence).range;
758 if range.start_byte == start && range.end_byte == end {
759 return Some(fact);
760 }
761 }
762 None
763 }
764
765 pub fn estimated_retained_bytes(&self) -> usize {
766 self.occurrences
767 .estimated_bytes()
768 .saturating_add(self.facts.estimated_retained_bytes())
769 }
770}
771
772pub trait PythonSourceFactProvider: Send + Sync {
773 fn python_source_facts(
776 &self,
777 token: QueryToken<'_>,
778 file: &ProjectFile,
779 keep_going: &dyn Fn() -> bool,
780 ) -> Option<Arc<PythonFileSourceFacts>>;
781}
782
783#[cfg(test)]
784mod tests {
785 use super::*;
786 use brokk_bifrost_test_macros::hardwon;
787
788 fn module_facts(source: &str) -> PythonModuleGlobalSourceFacts {
789 let mut parser = tree_sitter::Parser::new();
790 parser
791 .set_language(&tree_sitter_python::LANGUAGE.into())
792 .expect("Python grammar");
793 let tree = parser.parse(source, None).expect("parse fixture");
794 python_module_global_source_facts(tree.root_node(), source, 100_000, || true)
795 .expect("complete Python module facts")
796 }
797
798 fn initializer<'a>(
799 facts: &PythonModuleGlobalSourceFacts,
800 source: &'a str,
801 name: &str,
802 ) -> Option<&'a str> {
803 let range = facts.initializer_range(name)?;
804 source.get(range.start_byte..range.end_byte)
805 }
806
807 #[test]
808 #[brokk_bifrost_test_macros::hardwon(
809 "#12323: alias propagation must not publish partial clean facts when stopped"
810 )]
811 fn dynamic_alias_collection_exhaustion_refuses_partial_facts() {
812 let source = "run = exec\nother = run\nrun = other\nother(payload)\nimport types\ncheck = another\nanother = check\ncheck(payload, (types.FunctionType,))\n";
813 let tree = crate::declarations::parse_python_tree(source).unwrap();
814 let mut visits = 0_usize;
815 let facts = PythonModuleMutationFacts::collect_bounded(tree.root_node(), source, || {
816 visits += 1;
817 true
818 })
819 .unwrap();
820 assert!(!facts.dynamic_hazards.is_empty());
821 for allowance in 0..visits {
822 let mut remaining = allowance;
823 assert!(
824 PythonModuleMutationFacts::collect_bounded(tree.root_node(), source, || {
825 let allowed = remaining > 0;
826 remaining = remaining.saturating_sub(1);
827 allowed
828 })
829 .is_none(),
830 "allowance={allowance}"
831 );
832 }
833 }
834
835 #[test]
836 #[hardwon(
837 "#12323: comprehension lookups multiplied parsing work and consumed the node allowance"
838 )]
839 fn dynamic_hazard_comprehensions_preserve_scaling_and_node_budget() {
840 for statement in [
841 "values = [item for item in items]\n",
842 "unrelated = 1\nvalue = eval\n",
843 "v = vars\nvars = v\n",
844 ] {
845 let mut previous_work = None;
846 for count in [128, 256] {
847 let mut source = String::from("sentinel = 1\neval = object\n");
848 for _ in 0..count {
849 source.push_str(statement);
850 }
851 let tree = crate::declarations::parse_python_tree(&source).unwrap();
852 let root = tree.root_node();
853 let mut work = 0_usize;
854 let hazards = PythonDynamicHazards::collect_bounded(root, &source, || {
855 work += 1;
856 true
857 })
858 .unwrap();
859 assert!(!hazards.contains(root));
860 if let Some(previous) = previous_work {
861 assert!(
862 work < previous * 3,
863 "doubling {statement:?}: {previous} -> {work}"
864 );
865 }
866 previous_work = Some(work);
867 let mut nodes = 0_usize;
868 let mut stack = vec![root];
869 while let Some(node) = stack.pop() {
870 nodes += 1;
871 let mut cursor = node.walk();
872 stack.extend(node.named_children(&mut cursor));
873 }
874 let facts = python_module_global_source_facts(root, &source, nodes * 4, || true)
877 .expect("ordinary source within its node allowance");
878 assert_eq!(Some("1"), initializer(&facts, &source, "sentinel"));
879 assert!(
880 python_module_global_source_facts(root, &source, nodes - 1, || true).is_none()
881 );
882 assert!(
883 python_module_global_source_facts(root, &source, nodes * 4, || false).is_none()
884 );
885 }
886 }
887 }
888
889 #[test]
890 fn qs6_initializer_range_grammar_boundary() {
891 for source in [
892 "value = 1\n",
893 "value = (\n 1,\n 2\n)\n",
894 "value = '''a\nb'''\n",
895 "# \u{e9}\r\nvalue = (\r\n 1\r\n)\r\n",
896 ] {
897 let tree = crate::declarations::parse_python_tree(source).unwrap();
898 let root = tree.root_node();
899 let mut cursor = root.walk();
900 let statement = root
901 .named_children(&mut cursor)
902 .find(|n| n.kind() == "expression_statement")
903 .unwrap();
904 let rhs = statement
905 .named_child(0)
906 .unwrap()
907 .child_by_field_name("right")
908 .unwrap();
909 let range = module_facts(source).initializer_range("value").unwrap();
910 assert_eq!(
911 (
912 range.start_byte,
913 range.end_byte,
914 range.start_line,
915 range.end_line
916 ),
917 (
918 rhs.start_byte(),
919 rhs.end_byte(),
920 rhs.start_position().row + 1,
921 rhs.end_position().row + 1
922 ),
923 "{source}"
924 );
925 }
926 }
927
928 #[test]
929 fn qs6_module_binding_and_mutation_shapes() {
930 for target in [
932 "item",
933 "(item, other)",
934 "container.attr",
935 "container[index]",
936 ] {
937 let source =
938 format!("container = factory()\nindex = 0\nwith manager() as {target}:\n pass\n");
939 let facts = module_facts(&source);
940 assert_eq!(
941 initializer(&facts, &source, "container"),
942 Some("factory()"),
943 "{target}"
944 );
945 assert_eq!(initializer(&facts, &source, "index"), Some("0"), "{target}");
946 assert_eq!(
947 facts.module_binds_name("item"),
948 target == "item" || target == "(item, other)"
949 );
950 }
951 for mapping in ["globals", "vars"] {
952 for (call, mutates) in [
953 ("update(value=2)", true),
954 ("setdefault('value', 2)", true),
955 ("pop('value')", true),
956 ("clear()", true),
957 ("get('value')", false),
958 ] {
959 let source = format!("value = 1\n{mapping}().{call}\n");
960 assert_eq!(
961 module_facts(&source).initializer_range("value").is_none(),
962 mutates,
963 "{source}"
964 );
965 }
966 }
967 }
968
969 #[test]
970 #[hardwon(
971 "6b123df7cc68: quicksilver round 6 on brokk-bifrost-python: popitem can delete a module binding"
972 )]
973 fn qs6_popitem_invalidates_initializer() {
974 let source = "value = 1\nglobals().popitem()\n";
975 assert!(module_facts(source).initializer_range("value").is_none());
976 }
977
978 #[test]
979 fn qs6_final_cancellation_boundary() {
980 for source in [
981 "value = 1\nvalue\n",
982 "value = 1\ndef change():\n global value\n value = 2\nvalue\n",
983 ] {
984 let tree = crate::declarations::parse_python_tree(source).unwrap();
985 let root = tree.root_node();
986 let reference = root
987 .named_child(root.named_child_count() - 1)
988 .unwrap()
989 .named_child(0)
990 .unwrap();
991 let facts = PythonModuleMutationFacts::collect_bounded(root, source, || true).unwrap();
992 let mut parent_count = 0;
993 let mut current = reference;
994 while let Some(parent) = current.parent() {
995 parent_count += 1;
996 current = parent;
997 }
998 let mut remaining: usize = 1 + parent_count;
1001 assert_eq!(
1002 facts.binding_unmutated_at_bounded(root, "value", reference, || {
1003 let admitted = remaining > 0;
1004 remaining = remaining.saturating_sub(1);
1005 admitted
1006 }),
1007 None
1008 );
1009 }
1010 }
1011
1012 #[test]
1013 #[hardwon(
1014 "#4622+#5745: module mutation and stopped scans cannot prove unchanged initializer classes"
1015 )]
1016 fn module_global_source_fact_requires_a_single_safe_assignment() {
1017 let source = "class Target: pass\n\
1018safe = Target()\n\
1019items = [safe for safe in ()]\n\
1020if True:\n nested_safe = Target()\n";
1021 let facts = module_facts(source);
1022 assert_eq!(
1023 Some("Target()"),
1024 initializer(&facts, source, "safe"),
1025 "{facts:#?}"
1026 );
1027 assert_eq!(Some("Target()"), initializer(&facts, source, "nested_safe"));
1028
1029 let source = "class Target: pass\n\
1030global_write = Target()\n\
1031def change():\n global global_write\n global_write = None\n";
1032 assert_eq!(
1033 None,
1034 initializer(&module_facts(source), source, "global_write")
1035 );
1036
1037 let source = "class Target: pass\n\
1038twice = Target()\n\
1039twice = Target()\n";
1040 assert_eq!(None, initializer(&module_facts(source), source, "twice"));
1041
1042 let source = "class Target: pass\n\
1043dynamic = Target()\n\
1044globals()[\"dynamic\"] = None\n";
1045 assert_eq!(None, initializer(&module_facts(source), source, "dynamic"));
1046
1047 let source = "class Target: pass\n\
1048dynamic = Target()\n\
1049vars().update(dynamic=None)\n";
1050 assert_eq!(None, initializer(&module_facts(source), source, "dynamic"));
1051
1052 let source = "class Target: pass\n\
1053dynamic = Target()\n\
1054exec(\"dynamic = None\")\n";
1055 assert_eq!(None, initializer(&module_facts(source), source, "dynamic"));
1056
1057 let deferred_exec =
1058 "class Target: pass\nvalue = Target()\ndef later():\n exec('value = None')\n";
1059 assert_eq!(
1060 None,
1061 initializer(&module_facts(deferred_exec), deferred_exec, "value")
1062 );
1063
1064 let bounded_source =
1067 "class Base: pass\nclass D(Base): pass\ndef later():\n exec('Base = object')\n";
1068 let mut parser = tree_sitter::Parser::new();
1069 parser
1070 .set_language(&tree_sitter_python::LANGUAGE.into())
1071 .expect("Python grammar");
1072 let tree = parser.parse(bounded_source, None).expect("parse fixture");
1073 let root = tree.root_node();
1074 let reference = root
1075 .named_child(1)
1076 .unwrap()
1077 .child_by_field_name("superclasses")
1078 .unwrap()
1079 .named_child(0)
1080 .unwrap();
1081 let mut visits = 0_usize;
1082 assert_eq!(
1083 Some(true),
1084 python_module_binding_unmutated_at_bounded(
1085 root,
1086 bounded_source,
1087 "Base",
1088 reference,
1089 || {
1090 visits += 1;
1091 true
1092 },
1093 )
1094 );
1095 for allowance in 0..visits {
1096 let mut remaining = allowance;
1097 assert_eq!(
1098 None,
1099 python_module_binding_unmutated_at_bounded(
1100 root,
1101 bounded_source,
1102 "Base",
1103 reference,
1104 || {
1105 let allowed = remaining > 0;
1106 remaining = remaining.saturating_sub(1);
1107 allowed
1108 },
1109 ),
1110 "stopping after {allowance} of {visits} visits cannot admit Base"
1111 );
1112 }
1113 assert_eq!(
1114 Some(false),
1115 python_module_export_unmutated_bounded(root, bounded_source, "Base", || true)
1116 );
1117
1118 let multi_source = "class A: pass\nclass B: pass\nclass C: pass\nclass ReadOnly: pass\nclass Sibling: pass\nclass D(A, B, C, ReadOnly, Sibling): pass\ndef writer():\n global A\n global B, C\n global ReadOnly\n A = None\n class B(B): pass\n del C\n return ReadOnly\ndef sibling():\n global Sibling\n from elsewhere import Sibling\n";
1121 let tree = parser
1122 .parse(multi_source, None)
1123 .expect("parse all-name events");
1124 let root = tree.root_node();
1125 assert!(!root.has_error());
1126 let arguments = root
1127 .named_child(5)
1128 .unwrap()
1129 .child_by_field_name("superclasses")
1130 .unwrap();
1131 let mut collection_visits = 0_usize;
1132 let mutation = PythonModuleMutationFacts::collect_bounded(root, multi_source, || {
1133 collection_visits += 1;
1134 true
1135 })
1136 .expect("complete mutation inventory");
1137 for allowance in 0..collection_visits {
1138 let mut remaining = allowance;
1139 assert!(
1140 PythonModuleMutationFacts::collect_bounded(root, multi_source, || {
1141 let allowed = remaining > 0;
1142 remaining = remaining.saturating_sub(1);
1143 allowed
1144 })
1145 .is_none(),
1146 "partial collection at {allowance} must not publish facts"
1147 );
1148 }
1149 for (index, name, expected) in [
1150 (0, "A", false),
1151 (1, "B", false),
1152 (2, "C", false),
1153 (3, "ReadOnly", true),
1154 (4, "Sibling", false),
1155 ] {
1156 let reference = arguments.named_child(index).unwrap();
1157 let mut read_visits = 0_usize;
1158 assert_eq!(
1159 Some(expected),
1160 mutation.binding_unmutated_at_bounded(root, name, reference, || {
1161 read_visits += 1;
1162 true
1163 }),
1164 "all-name inventory: {name}"
1165 );
1166 assert!(
1167 read_visits < collection_visits,
1168 "a reused name read must not recollect the module"
1169 );
1170 assert_eq!(
1171 None,
1172 mutation.binding_unmutated_at_bounded(root, name, reference, || false),
1173 "completed facts cannot override a stopped reader"
1174 );
1175 for allowance in 0..read_visits {
1176 let mut remaining = allowance;
1177 assert_eq!(
1178 None,
1179 mutation.binding_unmutated_at_bounded(root, name, reference, || {
1180 let allowed = remaining > 0;
1181 remaining = remaining.saturating_sub(1);
1182 allowed
1183 }),
1184 "{name}: stopped read including final check at {allowance}"
1185 );
1186 }
1187 let mut export_visits = 0_usize;
1188 assert_eq!(
1189 Some(expected),
1190 mutation.export_unmutated_bounded(name, || {
1191 export_visits += 1;
1192 true
1193 })
1194 );
1195 for allowance in 0..export_visits {
1196 let mut remaining = allowance;
1197 assert_eq!(
1198 None,
1199 mutation.export_unmutated_bounded(name, || {
1200 let allowed = remaining > 0;
1201 remaining = remaining.saturating_sub(1);
1202 allowed
1203 }),
1204 "{name}: stopped export including final check at {allowance}"
1205 );
1206 }
1207 }
1208
1209 for (label, source, container_index, expected, export_expected) in [
1210 (
1211 "empty inventory still checks the final stop",
1212 "class Base: pass\nclass D(Base): pass\n",
1213 1,
1214 true,
1215 true,
1216 ),
1217 (
1218 "later exec is irrelevant to immediate read",
1219 bounded_source,
1220 1,
1221 true,
1222 false,
1223 ),
1224 (
1225 "deferred read includes later exec",
1226 "class Base: pass\ndef load():\n class D(Base): pass\ndef later():\n exec('Base = object')\n",
1227 1,
1228 false,
1229 false,
1230 ),
1231 (
1232 "later loop hazard can precede next read",
1233 "class Base: pass\nfor item in (1, 2):\n class D(Base): pass\n exec('Base = object')\n",
1234 1,
1235 false,
1236 false,
1237 ),
1238 (
1239 "earlier callable remains a possible writer",
1240 "class Base: pass\ndef earlier():\n exec('Base = object')\nclass D(Base): pass\n",
1241 2,
1242 false,
1243 false,
1244 ),
1245 (
1246 "later reflective call is irrelevant to immediate read",
1247 "class Base: pass\nclass D(Base): pass\nglobals().update(Base=object)\n",
1248 1,
1249 true,
1250 false,
1251 ),
1252 ] {
1253 let tree = parser.parse(source, None).expect("parse hazard ordering");
1254 let root = tree.root_node();
1255 assert!(!root.has_error(), "{label}");
1256 let container = root.named_child(container_index).unwrap();
1257 let class = if container.kind() == "class_definition" {
1258 container
1259 } else {
1260 container
1261 .child_by_field_name("body")
1262 .unwrap()
1263 .named_child(0)
1264 .unwrap()
1265 };
1266 assert_eq!(class.kind(), "class_definition");
1267 let reference = class
1268 .child_by_field_name("superclasses")
1269 .unwrap()
1270 .named_child(0)
1271 .unwrap();
1272 let mutation =
1273 PythonModuleMutationFacts::collect_bounded(root, source, || true).unwrap();
1274 let mut read_visits = 0_usize;
1275 assert_eq!(
1276 Some(expected),
1277 mutation.binding_unmutated_at_bounded(root, "Base", reference, || {
1278 read_visits += 1;
1279 true
1280 }),
1281 "{label}"
1282 );
1283 assert_eq!(
1284 Some(export_expected),
1285 mutation.export_unmutated_bounded("Base", || true),
1286 "{label}: completed exports include all hazards"
1287 );
1288 for allowance in 0..read_visits {
1289 let mut remaining = allowance;
1290 assert_eq!(
1291 None,
1292 mutation.binding_unmutated_at_bounded(root, "Base", reference, || {
1293 let allowed = remaining > 0;
1294 remaining = remaining.saturating_sub(1);
1295 allowed
1296 }),
1297 "{label}: recovery/ancestry/final stop at {allowance}"
1298 );
1299 }
1300 }
1301
1302 let original_tree = parser.parse(bounded_source, None).unwrap();
1306 let mutation = PythonModuleMutationFacts::collect_bounded(
1307 original_tree.root_node(),
1308 bounded_source,
1309 || true,
1310 )
1311 .unwrap();
1312 let changed_source = "class Base: pass\nclass D(Base): pass\ndef later():\n longer_call('a longer structured expression at the previous hazard site')\n";
1313 let changed_tree = parser.parse(changed_source, None).unwrap();
1314 let changed_root = changed_tree.root_node();
1315 let changed_reference = changed_root
1316 .named_child(1)
1317 .unwrap()
1318 .child_by_field_name("superclasses")
1319 .unwrap()
1320 .named_child(0)
1321 .unwrap();
1322 assert_eq!(
1323 None,
1324 mutation
1325 .binding_unmutated_at_bounded(changed_root, "Base", changed_reference, || true,)
1326 );
1327
1328 let read_only_initializer = "class Target: pass\nvalue = Target()\ndef read_only():\n global value\n return value\n";
1331 assert_eq!(
1332 None,
1333 initializer(
1334 &module_facts(read_only_initializer),
1335 read_only_initializer,
1336 "value"
1337 )
1338 );
1339 for (label, suffix, expected) in [
1340 (
1341 "read-only directives and unrelated local writer",
1342 "def read_only():\n global Base\n global Base\n return Base\ndef local():\n Base = 0\n",
1343 true,
1344 ),
1345 ("module directive is inert", "", true),
1346 (
1347 "sibling global assignment",
1348 "def read_only():\n global Base\n return Base\ndef change():\n global Base\n Base = 0\n",
1349 false,
1350 ),
1351 (
1352 "pending global class binding",
1353 "class Outer:\n global Base\n class Base(Base):\n pass\n",
1354 false,
1355 ),
1356 (
1357 "global function declaration",
1358 "def change():\n global Base\n def Base():\n pass\n",
1359 false,
1360 ),
1361 (
1362 "global import binding",
1363 "def change():\n global Base\n from elsewhere import Base\n",
1364 false,
1365 ),
1366 (
1367 "global delete binding",
1368 "def change():\n global Base\n del Base\n",
1369 false,
1370 ),
1371 (
1372 "nested directive uses nearest class owner",
1373 "def outer():\n Base = 0\n class ReadOnly:\n global Base\n value = Base\n",
1374 true,
1375 ),
1376 ] {
1377 let source = format!("global Base\nclass Base: pass\nclass D(Base): pass\n{suffix}");
1380 let tree = parser
1381 .parse(&source, None)
1382 .expect("parse global event fixture");
1383 let root = tree.root_node();
1384 assert!(!root.has_error(), "{label}: {source}");
1385 let reference = root
1386 .named_child(2)
1387 .unwrap()
1388 .child_by_field_name("superclasses")
1389 .unwrap()
1390 .named_child(0)
1391 .unwrap();
1392 let mut visits = 0_usize;
1393 assert_eq!(
1394 Some(expected),
1395 python_module_binding_unmutated_at_bounded(
1396 root,
1397 &source,
1398 "Base",
1399 reference,
1400 || {
1401 visits += 1;
1402 true
1403 }
1404 ),
1405 "{label}"
1406 );
1407 assert_eq!(
1408 Some(expected),
1409 python_module_export_unmutated_bounded(root, &source, "Base", || true),
1410 "{label}: complete-module export uses the same event proof"
1411 );
1412 for allowance in 0..visits {
1413 let mut remaining = allowance;
1414 assert_eq!(
1415 None,
1416 python_module_binding_unmutated_at_bounded(
1417 root,
1418 &source,
1419 "Base",
1420 reference,
1421 || {
1422 let allowed = remaining > 0;
1423 remaining = remaining.saturating_sub(1);
1424 allowed
1425 },
1426 ),
1427 "{label}: stop after {allowance} of {visits} visits cannot prove no writer"
1428 );
1429 }
1430 }
1431
1432 let source = "class Target: pass\n\
1433wild = Target()\n\
1434from elsewhere import *\n";
1435 assert_eq!(None, initializer(&module_facts(source), source, "wild"));
1436
1437 let source = "class Target: pass\n\
1438annotated: object = Target()\n\
1439augmented = Target()\n\
1440augmented += Target()\n\
1441deleted = Target()\n\
1442del deleted\n\
1443for loop_target in ():\n pass\n\
1444with manager as with_target:\n pass\n\
1445walrus = None\n\
1446(walrus := Target())\n\
1447import pathlib as imported\n\
1448from os import path as from_imported\n\
1449def declared():\n pass\n\
1450class Declared: pass\n";
1451 let facts = module_facts(source);
1452 for name in [
1453 "annotated",
1454 "augmented",
1455 "deleted",
1456 "loop_target",
1457 "with_target",
1458 "walrus",
1459 "imported",
1460 "from_imported",
1461 "declared",
1462 "Declared",
1463 ] {
1464 assert_eq!(
1465 None,
1466 initializer(&facts, source, name),
1467 "{name}: {facts:#?}"
1468 );
1469 }
1470 }
1471}