cobraphp 0.1.0.dev4__tar.gz → 0.1.0.dev5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. {cobraphp-0.1.0.dev4/src/cobraphp.egg-info → cobraphp-0.1.0.dev5}/PKG-INFO +8 -8
  2. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/README.md +5 -5
  3. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/pyproject.toml +7 -5
  4. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/__init__.py +8 -4
  5. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_call_builder.py +3 -2
  6. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_callee_index.py +4 -2
  7. cobraphp-0.1.0.dev5/src/cobraphp/analysis/_database_write_reach.py +208 -0
  8. cobraphp-0.1.0.dev5/src/cobraphp/analysis/_database_writes.py +1455 -0
  9. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_defuse_builder.py +4 -5
  10. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_file_filter.py +1 -1
  11. cobraphp-0.1.0.dev5/src/cobraphp/analysis/_node_order.py +41 -0
  12. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_semgrep_runner.py +103 -52
  13. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_taint_propagator.py +8 -4
  14. cobraphp-0.1.0.dev5/src/cobraphp/analysis/database_writes.toml +490 -0
  15. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5/src/cobraphp.egg-info}/PKG-INFO +8 -8
  16. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp.egg-info/SOURCES.txt +2 -0
  17. cobraphp-0.1.0.dev5/src/cobraphp.egg-info/requires.txt +4 -0
  18. cobraphp-0.1.0.dev4/src/cobraphp/analysis/_database_writes.py +0 -708
  19. cobraphp-0.1.0.dev4/src/cobraphp/analysis/database_writes.toml +0 -120
  20. cobraphp-0.1.0.dev4/src/cobraphp.egg-info/requires.txt +0 -4
  21. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/LICENSE +0 -0
  22. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/setup.cfg +0 -0
  23. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/__init__.py +0 -0
  24. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/_backend.py +0 -0
  25. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/_placeholder.py +0 -0
  26. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_ast_types.py +0 -0
  27. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_call_graph.py +0 -0
  28. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_call_graph_nodes.py +0 -0
  29. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_errors.py +0 -0
  30. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_project_root.py +0 -0
  31. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_records.py +0 -0
  32. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_source_kinds.py +0 -0
  33. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_taint_graph.py +0 -0
  34. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/_taint_rules.py +0 -0
  35. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/frameworks.toml +0 -0
  36. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/php_ast_types.toml +0 -0
  37. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/rules/database_taint.yaml +0 -0
  38. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/analysis/rules/user_input_taint.yaml +0 -0
  39. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/config.py +0 -0
  40. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/entries.py +0 -0
  41. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/errors.py +0 -0
  42. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/graphs.py +0 -0
  43. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/project.py +0 -0
  44. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/py.typed +0 -0
  45. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp/results.py +0 -0
  46. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp.egg-info/dependency_links.txt +0 -0
  47. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/src/cobraphp.egg-info/top_level.txt +0 -0
  48. {cobraphp-0.1.0.dev4 → cobraphp-0.1.0.dev5}/tests/test_interface.py +0 -0
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cobraphp
3
- Version: 0.1.0.dev4
3
+ Version: 0.1.0.dev5
4
4
  Summary: Placeholder for the Python interface of CobraPHP, a static taint analyzer for PHP projects.
5
5
  License-Expression: GPL-2.0-only
6
6
  Requires-Python: >=3.11
7
7
  Description-Content-Type: text/markdown
8
8
  License-File: LICENSE
9
- Requires-Dist: cpg2py>=1.2.0
10
- Requires-Dist: php-parser-py>=2.0.3
9
+ Requires-Dist: cpg2py==1.2.2
10
+ Requires-Dist: php-parser-py==2.1.0
11
11
  Requires-Dist: semgrep==1.85.0
12
12
  Requires-Dist: setuptools<82
13
13
  Dynamic: license-file
@@ -30,7 +30,7 @@ From a checkout, with [uv](https://docs.astral.sh/uv/):
30
30
  uv sync
31
31
  ```
32
32
 
33
- `uv sync` installs the package, its dependencies at the versions of `uv.lock` and the check tools. Run commands through `uv run` so that the programs the dependencies install are on `PATH`.
33
+ `uv sync` installs the package, its dependencies at the versions of `uv.lock` and the check tools. The analysis starts the `semgrep` program of the scripts directory of the running Python environment, and the first one on `PATH` only when that directory lacks it, so the caller's `PATH` need not hold that directory.
34
34
 
35
35
  The planned release wheel will bundle the CobraPHP jar. Which Java runtime it uses is undecided ([open gaps](docs/design.md#open-gaps)). Python 3.11 or later.
36
36
 
@@ -75,14 +75,14 @@ for node_id in flow.tainted[USER_INPUT]:
75
75
  print(node_id, backward_slice(flow, node_id, max_depth=3))
76
76
  ```
77
77
 
78
- Find the database writes the value of a data-flow node reaches; an empty result means that no path to a recognised write was found, not that the value is never stored:
78
+ Find the database writes the value of a data-flow node reaches; an empty result means that no path to a recognised write was found, not that the value is never stored. `DatabaseWriteReach` derives the steps of the walk once, for many queries; `reached_database_writes(ast, flow, writes, node_id)` answers one:
79
79
 
80
80
  ```python
81
- from cobraphp.analysis import find_database_writes, reached_database_writes
81
+ from cobraphp.analysis import DatabaseWriteReach, find_database_writes
82
82
 
83
- writes = find_database_writes(ast)
83
+ reach = DatabaseWriteReach(ast, flow, find_database_writes(ast))
84
84
  for node_id in flow.tainted[USER_INPUT]:
85
- for write in reached_database_writes(ast, flow, writes, node_id):
85
+ for write in reach.reached_database_writes(node_id):
86
86
  print(node_id, write.file, write.line, write.kind, write.table)
87
87
  ```
88
88
 
@@ -16,7 +16,7 @@ From a checkout, with [uv](https://docs.astral.sh/uv/):
16
16
  uv sync
17
17
  ```
18
18
 
19
- `uv sync` installs the package, its dependencies at the versions of `uv.lock` and the check tools. Run commands through `uv run` so that the programs the dependencies install are on `PATH`.
19
+ `uv sync` installs the package, its dependencies at the versions of `uv.lock` and the check tools. The analysis starts the `semgrep` program of the scripts directory of the running Python environment, and the first one on `PATH` only when that directory lacks it, so the caller's `PATH` need not hold that directory.
20
20
 
21
21
  The planned release wheel will bundle the CobraPHP jar. Which Java runtime it uses is undecided ([open gaps](docs/design.md#open-gaps)). Python 3.11 or later.
22
22
 
@@ -61,14 +61,14 @@ for node_id in flow.tainted[USER_INPUT]:
61
61
  print(node_id, backward_slice(flow, node_id, max_depth=3))
62
62
  ```
63
63
 
64
- Find the database writes the value of a data-flow node reaches; an empty result means that no path to a recognised write was found, not that the value is never stored:
64
+ Find the database writes the value of a data-flow node reaches; an empty result means that no path to a recognised write was found, not that the value is never stored. `DatabaseWriteReach` derives the steps of the walk once, for many queries; `reached_database_writes(ast, flow, writes, node_id)` answers one:
65
65
 
66
66
  ```python
67
- from cobraphp.analysis import find_database_writes, reached_database_writes
67
+ from cobraphp.analysis import DatabaseWriteReach, find_database_writes
68
68
 
69
- writes = find_database_writes(ast)
69
+ reach = DatabaseWriteReach(ast, flow, find_database_writes(ast))
70
70
  for node_id in flow.tainted[USER_INPUT]:
71
- for write in reached_database_writes(ast, flow, writes, node_id):
71
+ for write in reach.reached_database_writes(node_id):
72
72
  print(node_id, write.file, write.line, write.kind, write.table)
73
73
  ```
74
74
 
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
5
5
 
6
6
  [project]
7
7
  name = "cobraphp"
8
- version = "0.1.0.dev4"
8
+ version = "0.1.0.dev5"
9
9
  description = "Placeholder for the Python interface of CobraPHP, a static taint analyzer for PHP projects."
10
10
  readme = "README.md"
11
11
  license = "GPL-2.0-only"
@@ -14,11 +14,13 @@ license-files = ["LICENSE"]
14
14
  # oldest CPython release that still receives upstream security fixes. The Python floor of JPype is unverified.
15
15
  requires-python = ">=3.11"
16
16
  # Planned runtime dependency of the jar interface, not declared until that implementation exists: JPype1
17
- # (in-process JVM bridge). The others are those of `cobraphp.analysis`. Semgrep is pinned so that the
18
- # expressions its rules match stay the same; Semgrep 1.85 imports `pkg_resources`, which setuptools 82 removes.
17
+ # (in-process JVM bridge). The others are those of `cobraphp.analysis`. php-parser-py is pinned so that the
18
+ # AST of every target PHP version, 5.6 included, stays the one the analysis is tested on; cpg2py is pinned so
19
+ # that the graph interface the analysis queries stays the same; Semgrep is pinned so that the expressions its
20
+ # rules match stay the same; Semgrep 1.85 imports `pkg_resources`, which setuptools 82 removes.
19
21
  dependencies = [
20
- "cpg2py>=1.2.0",
21
- "php-parser-py>=2.0.3",
22
+ "cpg2py==1.2.2",
23
+ "php-parser-py==2.1.0",
22
24
  "semgrep==1.85.0",
23
25
  "setuptools<82",
24
26
  ]
@@ -10,7 +10,8 @@ from __future__ import annotations
10
10
  from php_parser_py import AST
11
11
 
12
12
  from ._call_builder import CallBuilder
13
- from ._database_writes import DatabaseWrite, find_database_writes, reached_database_writes
13
+ from ._database_write_reach import DatabaseWriteReach, reached_database_writes
14
+ from ._database_writes import DatabaseWrite, find_database_writes
14
15
  from ._errors import AnalysisTimeoutError, StaticAnalysisError
15
16
  from ._file_filter import app_file_filter, framework_excluded_dirs, make_app_file_filter
16
17
  from ._records import DataFlowGraph, backward_slice, call_graph_export, data_flow_graph
@@ -37,10 +38,12 @@ def build_data_flow(
37
38
 
38
39
  Semgrep finds the expressions each Source kind's rule matches; def-use edges inside each function,
39
40
  argument and return edges over the call graph, then a breadth-first walk from those expressions mark the
40
- reached nodes. `timeout_seconds` bounds each Semgrep run; `target_files` (project-relative) restricts
41
- Semgrep to those files, and when none of them exists Semgrep does not run.
41
+ reached nodes. Semgrep scans exactly the files of `project_ast`, from the project root, whatever the
42
+ caller's working directory. `timeout_seconds` bounds the Semgrep run of each Source kind; `target_files`
43
+ (project-relative) restricts Semgrep to those files, and when none of them exists Semgrep does not run.
42
44
 
43
- Raises `DependencyUnavailableError` when the `semgrep` program is not on PATH, `AnalysisTimeoutError`
45
+ Raises `DependencyUnavailableError` when the `semgrep` program is neither in the scripts directory of the
46
+ running Python environment nor on PATH, `AnalysisTimeoutError`
44
47
  when a Semgrep run exceeds `timeout_seconds`, and `StaticAnalysisError` when Semgrep fails, its output is
45
48
  malformed or the AST is malformed.
46
49
  """
@@ -55,6 +58,7 @@ __all__ = [
55
58
  "AnalysisTimeoutError",
56
59
  "DataFlowGraph",
57
60
  "DatabaseWrite",
61
+ "DatabaseWriteReach",
58
62
  "StaticAnalysisError",
59
63
  "app_file_filter",
60
64
  "backward_slice",
@@ -7,6 +7,7 @@ from php_parser_py import AST, Node, NodeNotInFileError
7
7
  from ._errors import StaticAnalysisError
8
8
  from ._call_graph import CallGraph
9
9
  from ._callee_index import CALL_SITE_TYPES, NAMED_CALLABLE_TYPES, CalleeIndex
10
+ from ._node_order import nodes_in_path_order
10
11
 
11
12
  # PHP AST node types of anonymous callables; with the named ones, every callable declaration.
12
13
  CLOSURE_TYPE = "Expr_Closure"
@@ -45,7 +46,7 @@ class CallBuilder:
45
46
  resolution targets.
46
47
  """
47
48
  callee_index = CalleeIndex(self._ast)
48
- for callable_node in self._ast.nodes(lambda n: n.node_type in CALLABLE_DECL_TYPES):
49
+ for callable_node in nodes_in_path_order(self._ast, lambda n: n.node_type in CALLABLE_DECL_TYPES):
49
50
  callable_name = self._register_callable(call_graph, callable_node)
50
51
  if callable_node.node_type in NAMED_CALLABLE_TYPES:
51
52
  callee_index.add(callable_node, callable_name)
@@ -100,7 +101,7 @@ class CallBuilder:
100
101
 
101
102
  def _build_call_sites(self, call_graph: CallGraph, callee_index: CalleeIndex) -> None:
102
103
  """Extract call sites and link to callees."""
103
- call_site_nodes = list(self._ast.nodes(lambda n: n.node_type in CALL_SITE_TYPES))
104
+ call_site_nodes = nodes_in_path_order(self._ast, lambda n: n.node_type in CALL_SITE_TYPES)
104
105
 
105
106
  for call_site_node in call_site_nodes:
106
107
  try:
@@ -32,8 +32,10 @@ class CalleeIndex:
32
32
  self, and static denote the enclosing class and a literal class name
33
33
  denotes that class by short name. With no receiver class (parent, a
34
34
  variable, an expression) or no such method in it, the call resolves to
35
- the first method of that name in AST order. A call whose name is an
36
- expression has no callee. For every key, the first declaration wins.
35
+ the first method of that name. A call whose name is an expression has
36
+ no callee. For every key, the first declaration wins, with declarations
37
+ taken in files sorted by POSIX relative path and in source order within
38
+ a file.
37
39
  """
38
40
 
39
41
  def __init__(self, ast: AST) -> None:
@@ -0,0 +1,208 @@
1
+ """The database writes the value of a data-flow node reaches (docs/design-analysis-subpackage.md).
2
+
3
+ `DatabaseWriteReach` derives the steps of the walk once from a project AST and a data-flow graph: the
4
+ successor lists of the graph, the step from a node to the expression that holds its value, and the step from
5
+ a closure's `use` variable to the variables of that name in the closure. A query then walks only the steps
6
+ within `max_depth` of its node.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import threading
12
+ import weakref
13
+
14
+ from php_parser_py import AST, Node
15
+
16
+ from ._database_writes import _INTERPOLATED_TYPE, _SCOPE_TYPES, _VARIABLE_TYPE, DatabaseWrite, _name
17
+ from ._node_order import nodes_in_path_order
18
+ from ._records import DataFlowGraph
19
+
20
+ # Expressions whose value is computed from the value of each child: casts, unary and binary operators
21
+ # (concatenation and null coalescing among them) and interpolated strings. An array literal holds the values
22
+ # of its items' children. A ternary's result is its second and third child; its condition is not part of the
23
+ # result, except in the short form `a ?: b`, whose first child is also the result.
24
+ _CAST_PREFIX = "Expr_Cast_"
25
+ _BINARY_PREFIX = "Expr_BinaryOp_"
26
+ _UNARY_TYPES = frozenset({"Expr_UnaryMinus", "Expr_UnaryPlus", "Expr_BitwiseNot", "Expr_BooleanNot"})
27
+ _ARRAY_TYPE = "Expr_Array"
28
+ _ARRAY_ITEM_TYPE = "ArrayItem"
29
+ _TERNARY_TYPE = "Expr_Ternary"
30
+ _CLOSURE_USE_TYPE = "ClosureUse"
31
+ _CLOSURE_TYPE = "Expr_Closure"
32
+
33
+
34
+ class DatabaseWriteReach:
35
+ """The steps of the reach walk over one project AST and data-flow graph, with the writes to test.
36
+
37
+ The constructor reads `project_ast` and `graph` once and keeps its own copy of every step, so a later
38
+ change to either does not change the results of this object; it keeps no reference to them.
39
+ """
40
+
41
+ __slots__ = ("_steps", "_writes", "_operand_writes")
42
+
43
+ def __init__(self, project_ast: AST, graph: DataFlowGraph, writes: tuple[DatabaseWrite, ...]) -> None:
44
+ self._steps = _walk_steps(project_ast, graph)
45
+ self._writes, self._operand_writes = _write_index(writes)
46
+
47
+ @classmethod
48
+ def _with_steps(cls, steps: dict[str, tuple[str, ...]], writes: tuple[DatabaseWrite, ...]) -> DatabaseWriteReach:
49
+ reach = cls.__new__(cls)
50
+ reach._steps = steps
51
+ reach._writes, reach._operand_writes = _write_index(writes)
52
+ return reach
53
+
54
+ def reached_database_writes(self, node_id: str, *, max_depth: int = 10) -> tuple[DatabaseWrite, ...]:
55
+ """The writes that the value of `node_id` reaches within `max_depth` steps, in the order of `writes`.
56
+
57
+ The reached nodes are `node_id` itself and the nodes a breadth-first walk reaches within `max_depth`
58
+ steps; a negative `max_depth` counts as 0, and a node outside the graph and the AST reaches only
59
+ itself. A write is reached when one of its `operand_ids` is a reached node. An empty result means that
60
+ no path within `max_depth` steps leads to a recognised write, not that the value is never stored.
61
+ """
62
+ steps = self._steps
63
+ visited = {node_id}
64
+ frontier = [node_id]
65
+ for _ in range(max_depth):
66
+ following: list[str] = []
67
+ for current in frontier:
68
+ for step in steps.get(current, ()):
69
+ if step not in visited:
70
+ visited.add(step)
71
+ following.append(step)
72
+ if not following:
73
+ break
74
+ frontier = following
75
+ operand_writes = self._operand_writes
76
+ indices = {index for node in visited for index in operand_writes.get(node, ())}
77
+ return tuple(self._writes[index] for index in sorted(indices))
78
+
79
+
80
+ def reached_database_writes(
81
+ project_ast: AST,
82
+ graph: DataFlowGraph,
83
+ writes: tuple[DatabaseWrite, ...],
84
+ node_id: str,
85
+ *,
86
+ max_depth: int = 10,
87
+ ) -> tuple[DatabaseWrite, ...]:
88
+ """The `writes` that the value of `node_id` reaches within `max_depth` steps.
89
+
90
+ Equal to `DatabaseWriteReach(project_ast, graph, writes).reached_database_writes(node_id, max_depth=...)`.
91
+ The steps of the most recent call are kept and reused while the call passes the same `project_ast` object
92
+ and a `graph` whose `predecessors` equal the ones the steps were derived from; any other call derives
93
+ them again.
94
+ """
95
+ return _reach_for(project_ast, graph, writes).reached_database_writes(node_id, max_depth=max_depth)
96
+
97
+
98
+ class _CacheEntry:
99
+ __slots__ = ("ast", "predecessors", "reach", "writes")
100
+
101
+ def __init__(
102
+ self,
103
+ ast: weakref.ref[AST],
104
+ predecessors: dict[str, tuple[str, ...]],
105
+ writes: tuple[DatabaseWrite, ...],
106
+ reach: DatabaseWriteReach,
107
+ ) -> None:
108
+ self.ast = ast
109
+ self.predecessors = predecessors
110
+ self.writes = writes
111
+ self.reach = reach
112
+
113
+
114
+ # The steps of the most recent `reached_database_writes` call, replaced as a whole under the lock. The entry
115
+ # refers to the AST weakly and holds a copy of the graph's `predecessors`, which a later call compares with.
116
+ _cache: list[_CacheEntry] = []
117
+ _cache_lock = threading.Lock()
118
+
119
+
120
+ def _reach_for(ast: AST, graph: DataFlowGraph, writes: tuple[DatabaseWrite, ...]) -> DatabaseWriteReach:
121
+ with _cache_lock:
122
+ entry = _cache[0] if _cache else None
123
+ if entry is None or entry.ast() is not ast or entry.predecessors != graph.predecessors:
124
+ predecessors = {node: tuple(ids) for node, ids in graph.predecessors.items()}
125
+ reach = DatabaseWriteReach(ast, graph, writes)
126
+ _cache[:] = [_CacheEntry(weakref.ref(ast), predecessors, writes, reach)]
127
+ return reach
128
+ if entry.writes is not writes and entry.writes != writes:
129
+ entry.reach = DatabaseWriteReach._with_steps(entry.reach._steps, writes)
130
+ entry.writes = writes
131
+ return entry.reach
132
+
133
+
134
+ def _write_index(writes: tuple[DatabaseWrite, ...]) -> tuple[tuple[DatabaseWrite, ...], dict[str, tuple[int, ...]]]:
135
+ lists: dict[str, list[int]] = {}
136
+ for index, write in enumerate(writes):
137
+ for operand in write.operand_ids:
138
+ indices = lists.setdefault(operand, [])
139
+ if not indices or indices[-1] != index:
140
+ indices.append(index)
141
+ return tuple(writes), {operand: tuple(indices) for operand, indices in lists.items()}
142
+
143
+
144
+ # Every step of the walk: the graph's successor lists (the reverse of `predecessors`), then the step from each
145
+ # AST node to the expression that holds its value, and from each closure `use` variable to the variables of
146
+ # that name in the closure's own scope.
147
+ def _walk_steps(ast: AST, graph: DataFlowGraph) -> dict[str, tuple[str, ...]]:
148
+ lists: dict[str, list[str]] = {}
149
+ for node_id, predecessors in graph.predecessors.items():
150
+ for predecessor in predecessors:
151
+ lists.setdefault(predecessor, []).append(node_id)
152
+ for node in nodes_in_path_order(ast, lambda n: _holds_values(n.node_type)):
153
+ for child, targets in _holding_steps(ast, node):
154
+ lists.setdefault(child, []).extend(targets)
155
+ return {node_id: tuple(ids) for node_id, ids in lists.items()}
156
+
157
+
158
+ def _holds_values(node_type: str) -> bool:
159
+ return (
160
+ node_type in (_ARRAY_TYPE, _TERNARY_TYPE, _CLOSURE_TYPE, _INTERPOLATED_TYPE)
161
+ or node_type in _UNARY_TYPES
162
+ or node_type.startswith((_CAST_PREFIX, _BINARY_PREFIX))
163
+ )
164
+
165
+
166
+ # (child id, target ids) for the children of `node` whose value `node` holds, or for a closure the variables
167
+ # of its `use` list.
168
+ def _holding_steps(ast: AST, node: Node) -> list[tuple[str, list[str]]]:
169
+ node_type = node.node_type
170
+ if node_type == _ARRAY_TYPE:
171
+ return [
172
+ (child.id, [node.id])
173
+ for item in ast.succ(node)
174
+ if item.node_type == _ARRAY_ITEM_TYPE
175
+ for child in ast.succ(item)
176
+ ]
177
+ if node_type == _CLOSURE_TYPE:
178
+ uses = [
179
+ variable
180
+ for use in ast.succ(node)
181
+ if use.node_type == _CLOSURE_USE_TYPE
182
+ for variable in ast.succ(use)
183
+ if variable.node_type == _VARIABLE_TYPE
184
+ ]
185
+ if not uses:
186
+ return []
187
+ scope = _scope_variables(ast, node)
188
+ return [(variable.id, scope.get(_name(variable), [])) for variable in uses]
189
+ children = list(ast.succ(node))
190
+ if node_type == _TERNARY_TYPE and len(children) == 3:
191
+ children = children[1:]
192
+ return [(child.id, [node.id]) for child in children]
193
+
194
+
195
+ # Variable nodes of a closure's own scope by name: its body and its nested arrow functions, and the `use`
196
+ # variables of closures nested in it, which read this scope.
197
+ def _scope_variables(ast: AST, closure: Node) -> dict[str, list[str]]:
198
+ variables: dict[str, list[str]] = {}
199
+ pending = [child for child in ast.succ(closure) if child.node_type != _CLOSURE_USE_TYPE]
200
+ while pending:
201
+ node = pending.pop()
202
+ if node.node_type in _SCOPE_TYPES:
203
+ pending.extend(child for child in ast.succ(node) if child.node_type == _CLOSURE_USE_TYPE)
204
+ continue
205
+ if node.node_type == _VARIABLE_TYPE and _name(node):
206
+ variables.setdefault(_name(node), []).append(node.id)
207
+ pending.extend(ast.succ(node))
208
+ return variables