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