codecop 0.1.0__py3-none-any.whl

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 (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1671 @@
1
+ """Loops above a query: `loop_context`.
2
+
3
+ `in_loop` on a site says the loop is in the same function as the query. A query that runs once per item is
4
+ more often called from a loop in a caller. This module looks for those loops in the call graph `origins`
5
+ builds, and says what each one is.
6
+
7
+ Two passes:
8
+
9
+ scan every source file once: its loops, the callbacks of iterator methods (`xs.map(x => ...)`,
10
+ `.for_each(|x| ...)`, `.forEach(x -> ...)`), and every call made inside one, by the name called.
11
+ An edge caller -> callee of the call graph is "in a loop" when the caller calls that name inside
12
+ a loop of its own body.
13
+ detail only for the loops a site's paths pass through: the loop's kind, what it iterates over and where
14
+ that comes from (another query's result is the N+1 signature), and whether anything derived from
15
+ the loop variable reaches the query (names followed through assignments and call arguments).
16
+
17
+ Per site: `loop_context` (every loop found within `loop_depth` caller hops, nearest first, `loop_count` the
18
+ full number, `loop_depth` the deepest nesting on one path), and on each listed origin the loops its own path
19
+ passes through. `in_loop` keeps its meaning.
20
+
21
+ What is read is syntax. A kind is told from the shape of the loop and the words in it, so it is a label with
22
+ a basis, not a proof: `kind_basis` says which rule gave it.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import bisect
28
+ import re
29
+ import sys
30
+ import time
31
+ from collections import Counter, OrderedDict, defaultdict, deque
32
+ from dataclasses import dataclass, fields, replace
33
+
34
+ from tree_sitter import Node, Parser, Query, QueryCursor
35
+
36
+
37
+ @dataclass
38
+ class Settings:
39
+ """Limits of the loop search. Each is a key of `[discover.origins]` (or `[discover]`) in codecop.toml."""
40
+
41
+ loops: int = 1 # 0 turns the whole pass off
42
+ loop_depth: int = 10 # caller hops searched for a loop (the walk itself stops at `max_depth`)
43
+ max_loops: int = 12 # loops listed per site (`loop_count` has the full number)
44
+ loop_driver_depth: int = 4 # hops down from the call that feeds a loop to the query behind it
45
+ loop_driver_nodes: int = 300 # functions visited on that way down
46
+ loop_parse_cache: int = 64 # parsed files kept while loops are described
47
+ loop_text_chars: int = 120 # length of the source excerpts in the output
48
+ max_origins: int = 5 # read from the origins settings: paths are kept for the origins listed
49
+
50
+ @classmethod
51
+ def of(cls, value) -> "Settings":
52
+ if isinstance(value, cls):
53
+ return value
54
+ if value is None:
55
+ return cls()
56
+ if not isinstance(value, dict):
57
+ value = {f.name: getattr(value, f.name) for f in fields(cls) if hasattr(value, f.name)}
58
+ known = {f.name for f in fields(cls)}
59
+ return replace(cls(), **{k: int(v) for k, v in value.items() if k in known and v is not None})
60
+
61
+
62
+ # What a loop above a query most likely means for the query, most relevant first: a per-item loop, a chunk loop,
63
+ # a walk through time windows, a fixed count; a retry or polling loop and a loop of unknown kind say least and
64
+ # come last. Within a class the nearest loop first, and at the same distance the one whose collection is another
65
+ # query's result (the N+1 shape). The nearest per-item loop comes before a query-driven one further up because
66
+ # it is the one that multiplies the query directly: putting every query-driven loop first can rank a loop several
67
+ # guessed calls away in front of the real one, one call up.
68
+ def relevance(loop: dict) -> int:
69
+ return {"per-item": 0, "chunk": 1, "time-window": 2, "fixed": 3}.get(loop.get("kind"), 4)
70
+
71
+
72
+ def by_relevance(loop: dict) -> tuple:
73
+ return relevance(loop), loop.get("hop", 0), 0 if loop.get("source") == "query" else 1
74
+
75
+
76
+ def loop_summary(first: dict, kinds: Counter, total: int, driven: int = 0) -> dict:
77
+ """The most relevant loop of a site in a few fields, and how many loops of each kind are above it (all of
78
+ them, listed or not). `query_per_item` is true only for a per-item loop: a retry or polling wrapper never is."""
79
+ out = {"kind": first.get("kind", "unknown"), "hop": first.get("hop", 0), "file": first.get("file", ""), "line": first.get("line", 0),
80
+ "driver": first.get("driver"), "uses_loop_var": first.get("uses_loop_var"), "verified": first.get("verified", True),
81
+ "query_per_item": first.get("kind") == "per-item", "loops": total,
82
+ "driven_by_query": driven, # loops above the site, of any kind, whose collection is a query's result
83
+ "by_kind": {k: n for k, n in sorted(kinds.items(), key=lambda kv: (relevance({"kind": kv[0]}), kv[0]))}}
84
+ return out
85
+
86
+
87
+ # --------------------------------------------------------------------------- per-language syntax
88
+
89
+ _ITER_TS = {"map", "forEach", "flatMap", "filter", "reduce", "some", "every", "each", "eachSeries", "mapSeries",
90
+ "eachLimit", "mapLimit", "pMap", "pmap", "forEachAsync", "mapAsync", "find", "findIndex", "reduceRight"}
91
+ SPECS: dict[str, dict] = {
92
+ "go": {
93
+ "loops": ("for_statement",),
94
+ "closures": ("func_literal",),
95
+ "funcs": ("function_declaration", "method_declaration", "func_literal"),
96
+ "calls": ("call_expression",),
97
+ "assigns": {"short_var_declaration": ("left", "right"), "assignment_statement": ("left", "right"),
98
+ "var_spec": ("name", "value"), "range_clause": ("left", "right")},
99
+ "iter_always": {"ForEach", "ForEachWhile"}, "iter_guarded": {"Map", "FilterMap", "FlatMap", "Filter"},
100
+ "guard": re.compile(r"^(lo|slices|iter|xslices)$"),
101
+ "refs": ("identifier", "selector_expression"),
102
+ },
103
+ "python": {
104
+ "loops": ("for_statement", "while_statement", "list_comprehension", "set_comprehension",
105
+ "dictionary_comprehension", "generator_expression"),
106
+ "closures": ("lambda",),
107
+ "funcs": ("function_definition", "lambda"),
108
+ "calls": ("call",),
109
+ "assigns": {"assignment": ("left", "right"), "augmented_assignment": ("left", "right"),
110
+ "for_statement": ("left", "right"), "for_in_clause": ("left", "right"),
111
+ "named_expression": ("name", "value")},
112
+ "iter_always": {"imap", "imap_unordered", "starmap"}, "iter_guarded": {"map"},
113
+ "guard": re.compile(r"^$|pool|executor|Pool|Executor"),
114
+ "refs": ("identifier", "attribute"),
115
+ },
116
+ "rust": {
117
+ "loops": ("for_expression", "while_expression", "loop_expression"),
118
+ "closures": ("closure_expression",),
119
+ "funcs": ("function_item", "closure_expression"),
120
+ "calls": ("call_expression",),
121
+ "assigns": {"let_declaration": ("pattern", "value"), "assignment_expression": ("left", "right"),
122
+ "compound_assignment_expr": ("left", "right"), "for_expression": ("pattern", "value"),
123
+ "let_condition": ("pattern", "value")},
124
+ "iter_always": {"for_each", "try_for_each", "for_each_concurrent", "try_for_each_concurrent"},
125
+ "iter_guarded": {"map", "filter_map", "flat_map", "then", "filter", "any", "all", "fold", "find_map", "inspect",
126
+ "and_then", "try_fold"},
127
+ "guard": re.compile(r"\.(?:iter|into_iter|iter_mut|par_iter|into_par_iter|chunks|drain|keys|values|into_values|"
128
+ r"enumerate|windows|zip|lines|chars|bytes|rev|skip|take)\(|stream::iter|\bstream\b"),
129
+ "refs": ("identifier", "scoped_identifier", "field_expression"),
130
+ },
131
+ "java": {
132
+ "loops": ("for_statement", "enhanced_for_statement", "while_statement", "do_statement"),
133
+ "closures": ("lambda_expression",),
134
+ "funcs": ("method_declaration", "constructor_declaration", "lambda_expression"),
135
+ "calls": ("method_invocation", "object_creation_expression"),
136
+ "assigns": {"variable_declarator": ("name", "value"), "assignment_expression": ("left", "right"),
137
+ "enhanced_for_statement": ("name", "value")},
138
+ "iter_always": {"forEach", "forEachOrdered", "forEachRemaining"},
139
+ "iter_guarded": {"map", "flatMap", "filter", "mapToObj", "peek", "anyMatch", "allMatch", "noneMatch", "mapToInt",
140
+ "mapToLong", "reduce", "collect"},
141
+ "guard": re.compile(r"[sS]tream\b|\.entrySet\(|\.values\(|\.keySet\("),
142
+ "refs": ("identifier", "method_reference", "field_access"),
143
+ },
144
+ "typescript": {
145
+ "loops": ("for_statement", "for_in_statement", "while_statement", "do_statement"),
146
+ "closures": ("arrow_function", "function_expression", "function", "generator_function"),
147
+ "funcs": ("function_declaration", "generator_function_declaration", "method_definition", "arrow_function",
148
+ "function_expression", "function", "generator_function"),
149
+ "calls": ("call_expression", "new_expression"),
150
+ "assigns": {"variable_declarator": ("name", "value"), "assignment_expression": ("left", "right"),
151
+ "augmented_assignment_expression": ("left", "right"), "for_in_statement": ("left", "right")},
152
+ "iter_always": _ITER_TS, "iter_guarded": set(), "guard": re.compile(r"$^"),
153
+ "refs": ("identifier", "member_expression"),
154
+ },
155
+ }
156
+ # the call of a method by name, with the name captured as @m: only iterator methods are asked for
157
+ _ITER_PATTERNS = {
158
+ "go": ["(call_expression function: (selector_expression field: (field_identifier) @m))"],
159
+ "python": ["(call function: (attribute attribute: (identifier) @m))", "(call function: (identifier) @m)"],
160
+ "rust": ["(call_expression function: (field_expression field: (field_identifier) @m))",
161
+ "(call_expression function: (generic_function function: (field_expression field: (field_identifier) @m)))"],
162
+ "java": ["(method_invocation name: (identifier) @m)"],
163
+ "typescript": ["(call_expression function: (member_expression property: (property_identifier) @m))"],
164
+ }
165
+
166
+ _IDENT = re.compile(r"[A-Za-z_$][\w$]*")
167
+ _KEYWORDS = {"const", "let", "var", "mut", "ref", "final", "await", "async", "range", "in", "of", "for", "if", "else",
168
+ "return", "new", "true", "false", "nil", "null", "None", "True", "False", "undefined", "self", "this", "_",
169
+ "int", "string", "bool", "float", "i32", "i64", "u32", "u64", "usize", "str", "String", "Some", "Ok", "Err"}
170
+ _CTOR_NAMES = {"__init__", "constructor", "<init>", "__new__"}
171
+ _MUTATORS = {"push", "append", "add", "put", "set", "insert", "extend", "update", "where", "and", "or", "bind", "push_bind",
172
+ "arg", "args", "param", "setParameter", "addValue", "setdefault", "addAll", "putAll", "Where", "And", "Or",
173
+ "Set", "Add", "Append", "push_str", "write", "andWhere", "orWhere", "values", "setString", "setLong",
174
+ "setInt", "setObject", "addBatch", "filter"}
175
+
176
+ TIME_WORDS = {"window", "windows", "bucket", "buckets", "interval", "intervals", "period", "periods", "day", "days",
177
+ "date", "dates", "hour", "hours", "week", "weeks", "month", "months", "year", "years", "minute", "minutes",
178
+ "timerange", "daterange", "since", "until", "timeslot", "timeslots"}
179
+ CHUNK_WORDS = {"chunk", "chunks", "chunked", "batch", "batches", "batched", "page", "pages", "partition", "partitions",
180
+ "paginate", "paginated", "pagination"}
181
+ TIME_PLURALS = {w for w in TIME_WORDS if w.endswith("s")} | {"timerange", "daterange"}
182
+ CHUNK_PLURALS = {"chunks", "batches", "pages", "partitions"}
183
+ # names of a loop that pages through a result, matched inside identifiers with `_` removed and lower-cased
184
+ _PAGING = re.compile(r"cursor|offset|hasmore|nexttoken|nextpage|pagetoken|continuation|lastid|startafter|lastkey|"
185
+ r"lastseen|\bpage\b|pageno|pagenum|\bmarker\b|\bafter(?:id|key|tenant|ts|time|seq)\w*")
186
+ # `if len(page) < pageSize { break }`, `if (rows.length === 0) break`, `if not rows: break`
187
+ _SHORT_PAGE = re.compile(r"if\s*\(?\s*(?:len\(\s*\w+\s*\)\s*(?:<|==)\s*[\w.]+|\w+\.(?:length|size\(\)|len\(\))\s*(?:<|===?)\s*[\w.]+|"
188
+ r"not\s+\w+|!\s*\w+(?:\.length)?|\w+\.(?:isEmpty|is_empty)\(\))\s*\)?\s*[:{]?\s*(?:\n\s*)?(?:break|return)\b")
189
+ _DRAIN = re.compile(r"^\(?\s*(?:len\(\s*[\w.]+\s*\)\s*(?:>|!=)\s*0|[\w.]+\.(?:length|size\(\))\s*(?:>|!==?)\s*0|"
190
+ r"!\s*[\w.]+\.(?:isEmpty|is_empty|empty)\(\)|\w*(?:queue|stack|pending|todo|worklist|remaining|frontier)\w*|"
191
+ r"not\s+[\w.]+\.empty\(\))\s*\)?$", re.I)
192
+ RETRY_WORDS = {"retry", "retries", "attempt", "attempts", "tries", "backoff", "poll", "polling", "tick", "ticker",
193
+ "heartbeat", "retrying"}
194
+ _SLEEP = re.compile(r"\b(?:[sS]leep|sleep_ms|sleep_until|setTimeout|delay|Tick|NewTicker|ticker|interval\.tick|"
195
+ r"wait_for|time\.After|backoff|Backoff|wait_timeout)\b|\bselect\s*\{")
196
+ # A counted loop whose body leaves on success or goes round again on failure is a retry wrapper, whatever it is called.
197
+ _RETRY_BODY = re.compile(
198
+ r"except\b[^\n]*:\s*\n(?:[^\n]*\n){0,4}?\s*continue\b|catch\s*(?:\([^)]*\))?\s*\{[^{}]*\bcontinue\b|"
199
+ r"if\s+err\s*==\s*nil\s*\{\s*(?:return|break)\b|if\s+err\s*!=\s*nil\s*\{[^{}]*\bcontinue\b|"
200
+ r"Err\([^)]*\)\s*=>\s*\{?[^{}]*\bcontinue\b|\.is_ok\(\)\s*\{\s*(?:return|break)\b")
201
+ # What an ORM translator writes on a site in a method that a framework calls once per row of a list.
202
+ _PER_ROW_NOTE = re.compile(r"once per row the serializer or resolver handles|of the row a serializer or resolver handles")
203
+ _CURSOR = re.compile(r"\.((?:try_|has_?|get_?)?(?:[nN]ext|recv|pop|poll|fetchone|read|[sS]can|shift|dequeue|take)\w*)\(")
204
+ _TIME_OPS = re.compile(r"\.(Before|After|Add|AddDate|plusDays|plusHours|plusMonths|plusMinutes|plusWeeks|isBefore|"
205
+ r"isAfter|add_days)\(|timedelta|Duration|chrono::|addDays|addHours|addMonths|setDate\(|"
206
+ r"relativedelta|date_range|dayjs|moment\(")
207
+ _CHUNK_CALL = re.compile(r"\b(chunks?|Chunk|chunked|batched|batch|partition|each_slice|chunks_exact|array_chunk|"
208
+ r"splitEvery|inBatches|in_batches|iter_chunks|chunkify|paginate|iter_pages)\w*\s*\(")
209
+ _WRAPPERS = re.compile(
210
+ r"^(?:range\s+|await\s+|&mut\s+|&|\*)+|"
211
+ r"\.(?:items|iteritems|values|keys|iter|into_iter|iter_mut|entrySet|keySet|stream|parallelStream|entries|all|"
212
+ r"into_values|into_keys|par_iter|clone|cloned|copied|enumerate|rev|toList|collect|to_vec|as_slice|unwrap)\(\)$")
213
+ _WRAP_CALL = re.compile(r"^(?:enumerate|list|sorted|reversed|tuple|set|iter|tqdm|Object\.entries|Object\.keys|"
214
+ r"Object\.values|Array\.from|std::iter::IntoIterator::into_iter)\((.*)\)$", re.S)
215
+ _LITERAL = re.compile(
216
+ r"^(?:&?(?:\[[\d.\s]*\]|map\[[^\]]+\])[\w.*\[\]]*\s*\{|&?\[|\(|\{|vec!\s*\[|"
217
+ r"(?:List|Set|Arrays|ImmutableList|ImmutableSet|EnumSet|Lists|Sets|Stream|Map)\.(?:of|asList|newArrayList|newHashSet)\s*\(|"
218
+ r"new\s+[\w.<>]+\s*\[\s*\]\s*\{|frozenset\(\s*[\[({]|tuple\(\s*[\[(])")
219
+ _EMPTY = re.compile(r"(?:\[\]|\{\}|nil|null|None|Vec::new\(\)|vec!\[\]|list\(\)|dict\(\)|set\(\)|make\(.*\)|"
220
+ r"new\s+[\w.]+(?:<[^>]*>)?\(\d*\)|\[\][\w.*\[\]]+\{\}|Vec::with_capacity\(.*\)|\[\]\s+as\s+.+)$")
221
+
222
+
223
+ def _debug() -> bool:
224
+ from . import origins
225
+ return origins.DEBUG
226
+
227
+
228
+ def _words(text: str) -> set[str]:
229
+ out = set()
230
+ for ident in _IDENT.findall(text):
231
+ for part in re.split(r"_+|(?<=[a-z0-9])(?=[A-Z])|\$", ident):
232
+ if part:
233
+ out.add(part.lower())
234
+ return out
235
+
236
+
237
+ def _names(text: str) -> list[str]:
238
+ return [n for n in _IDENT.findall(text) if n not in _KEYWORDS and not n[0].isupper()] or \
239
+ [n for n in _IDENT.findall(text) if n not in _KEYWORDS]
240
+
241
+
242
+ def _t(node: Node | None) -> str:
243
+ return node.text.decode("utf-8", "replace") if node is not None else ""
244
+
245
+
246
+ def _mentions(text: str, names) -> bool:
247
+ if not names or not text:
248
+ return False
249
+ for n in names:
250
+ if n in text and re.search(r"(?<![\w.$])" + re.escape(n) + r"(?![\w$])", text):
251
+ return True
252
+ return False
253
+
254
+
255
+ def _top_level_items(text: str) -> int | None:
256
+ """Elements of a bracketed literal: the commas at depth 1, plus one. None when the text is not one closed
257
+ literal or holds a spread (`...xs`, `*xs`)."""
258
+ m = _LITERAL.match(text)
259
+ if m is None:
260
+ return None
261
+ depth, items, quote, seen_any, i, n = 0, 0, "", False, m.end() - 1, len(text)
262
+ while i < n:
263
+ c = text[i]
264
+ if quote:
265
+ if c == "\\":
266
+ i += 1
267
+ elif c == quote:
268
+ quote = ""
269
+ elif c in "\"'`":
270
+ quote, seen_any = c, True
271
+ elif c in "[({":
272
+ depth += 1
273
+ if depth > 1:
274
+ seen_any = True
275
+ elif c in "])}":
276
+ depth -= 1
277
+ if depth == 0:
278
+ if text[i + 1:].strip().rstrip(")").strip():
279
+ return None
280
+ return items + 1 if seen_any else 0
281
+ elif c == "," and depth == 1:
282
+ if text[i + 1:].strip()[:1] not in ("]", ")", "}"): # not a trailing comma
283
+ items += 1
284
+ elif not c.isspace():
285
+ if depth == 1 and (text.startswith("...", i) or (c == "*" and text[i - 1] in "[(, \n")):
286
+ return None
287
+ seen_any = True
288
+ i += 1
289
+ return None
290
+
291
+
292
+ class _Loop:
293
+ """One loop of one file as the scan sees it: its extent, and the part of it that runs once (`ex`)."""
294
+
295
+ __slots__ = ("sb", "eb", "ex_sb", "ex_eb", "line", "callback")
296
+
297
+ def __init__(self, sb, eb, ex_sb, ex_eb, line, callback=False):
298
+ self.sb, self.eb, self.ex_sb, self.ex_eb, self.line, self.callback = sb, eb, ex_sb, ex_eb, line, callback
299
+
300
+ def holds(self, pos: int) -> bool:
301
+ return self.sb <= pos < self.eb and not (self.ex_sb <= pos < self.ex_eb)
302
+
303
+
304
+ def _once_part(lang: str, node: Node) -> Node | None:
305
+ """The part of a loop statement evaluated once: the collection of a for-each, the initializer of a counted loop."""
306
+ t = node.type
307
+ if lang == "go":
308
+ for c in node.named_children:
309
+ if c.type == "range_clause":
310
+ return c.child_by_field_name("right")
311
+ if c.type == "for_clause":
312
+ return c.child_by_field_name("initializer")
313
+ return None
314
+ if lang == "python":
315
+ if t == "for_statement":
316
+ return node.child_by_field_name("right")
317
+ if t != "while_statement":
318
+ first = next((c for c in node.named_children if c.type == "for_in_clause"), None)
319
+ return first.child_by_field_name("right") if first is not None else None
320
+ return None
321
+ if lang == "rust":
322
+ return node.child_by_field_name("value") if t == "for_expression" else None
323
+ if lang == "java":
324
+ if t == "enhanced_for_statement":
325
+ return node.child_by_field_name("value")
326
+ return node.child_by_field_name("init") if t == "for_statement" else None
327
+ if t == "for_in_statement":
328
+ return node.child_by_field_name("right")
329
+ return node.child_by_field_name("initializer") if t == "for_statement" else None
330
+
331
+
332
+ def call_parts(lang: str, node: Node) -> tuple[str, str, list[Node]]:
333
+ """(name called, receiver text, argument nodes) of a call node; name "" when it is not a plain call."""
334
+ if lang == "java":
335
+ if node.type == "object_creation_expression":
336
+ typ = _t(node.child_by_field_name("type"))
337
+ name, recv = re.sub(r"<.*", "", typ).split(".")[-1], ""
338
+ else:
339
+ name, recv = _t(node.child_by_field_name("name")), _t(node.child_by_field_name("object"))
340
+ args = node.child_by_field_name("arguments")
341
+ return name, recv, list(args.named_children) if args is not None else []
342
+ if lang == "typescript" and node.type == "new_expression":
343
+ ctor = _t(node.child_by_field_name("constructor"))
344
+ args = node.child_by_field_name("arguments")
345
+ return ctor.split(".")[-1], "", list(args.named_children) if args is not None else []
346
+ fn = node.child_by_field_name("function")
347
+ args = node.child_by_field_name("arguments")
348
+ arg_nodes: list[Node] = []
349
+ if args is not None:
350
+ if args.type in ("generator_expression", "template_string"):
351
+ arg_nodes = [args]
352
+ else:
353
+ for a in args.named_children:
354
+ if a.type == "comment":
355
+ continue
356
+ arg_nodes.append(a)
357
+ name = recv = ""
358
+ for _ in range(4):
359
+ if fn is None:
360
+ break
361
+ t = fn.type
362
+ if t in ("identifier", "field_identifier", "property_identifier"):
363
+ name = _t(fn)
364
+ break
365
+ if t in ("selector_expression", "field_expression"):
366
+ name = _t(fn.child_by_field_name("field"))
367
+ recv = _t(fn.child_by_field_name("operand") or fn.child_by_field_name("value"))
368
+ break
369
+ if t == "attribute":
370
+ name, recv = _t(fn.child_by_field_name("attribute")), _t(fn.child_by_field_name("object"))
371
+ break
372
+ if t == "member_expression":
373
+ name, recv = _t(fn.child_by_field_name("property")), _t(fn.child_by_field_name("object"))
374
+ break
375
+ if t == "scoped_identifier":
376
+ name, recv = _t(fn.child_by_field_name("name")), ""
377
+ break
378
+ if t in ("generic_function", "index_expression", "parenthesized_expression", "await_expression",
379
+ "non_null_expression", "instantiation_expression", "type_instantiation_expression"):
380
+ fn = fn.child_by_field_name("function") or fn.child_by_field_name("operand") or \
381
+ (fn.named_children[0] if fn.named_children else None)
382
+ continue
383
+ break
384
+ return name, recv, arg_nodes
385
+
386
+
387
+ def _ref_name(node: Node) -> str:
388
+ """The function a bare argument may name: `fetchOne`, `this.load`, `Repo::find`, `s.worker`."""
389
+ t = node.type
390
+ if t == "identifier":
391
+ return _t(node)
392
+ if t in ("selector_expression", "field_expression"):
393
+ return _t(node.child_by_field_name("field"))
394
+ if t == "attribute":
395
+ return _t(node.child_by_field_name("attribute"))
396
+ if t == "member_expression":
397
+ return _t(node.child_by_field_name("property"))
398
+ if t == "scoped_identifier":
399
+ return _t(node.child_by_field_name("name"))
400
+ if t == "method_reference":
401
+ return _t(node.named_children[-1]) if node.named_children else ""
402
+ return ""
403
+
404
+
405
+ def _is_bundle(src: bytes) -> bool:
406
+ """A large file of very long lines (a bundle, minified code): not scanned."""
407
+ return len(src) > 20_000 and len(src) / (src.count(b"\n") + 1) > 1000
408
+
409
+
410
+ def scan_tree(lang: str, language, tree, query) -> tuple:
411
+ """What the scan reads from one file's syntax tree, as plain values, so the tree can be let go:
412
+ (language name, loops, functions handed to iterator methods as (byte, name, line), the calls inside the
413
+ loops in source order as (byte, name, ((argument byte, name of a function handed over), ...))).
414
+ `query(language, lang, which)` gives the compiled queries."""
415
+ spec = SPECS[lang]
416
+ root = tree.root_node
417
+ caps = QueryCursor(query(language, lang, "scan")).captures(root)
418
+ loops: list[_Loop] = []
419
+ for node in caps.get("loop", ()):
420
+ once = _once_part(lang, node)
421
+ loops.append(_Loop(node.start_byte, node.end_byte, once.start_byte if once is not None else -1,
422
+ once.end_byte if once is not None else -1, node.start_point[0] + 1))
423
+ always, guard, closures, ref_types = spec["iter_always"], spec["guard"], spec["closures"], spec["refs"]
424
+ refs: list[tuple[int, str, int]] = []
425
+ for node in caps.get("iter", ()):
426
+ name, recv, args = call_parts(lang, node)
427
+ if name not in always and not (name in spec["iter_guarded"] and guard.search(recv)):
428
+ continue
429
+ for a in args:
430
+ if a.type in closures:
431
+ loops.append(_Loop(a.start_byte, a.end_byte, -1, -1, node.start_point[0] + 1, True))
432
+ elif a.type in ref_types:
433
+ refs.append((a.start_byte, _ref_name(a), node.start_point[0] + 1))
434
+ # the calls inside loops: asked for one outermost loop at a time, so a file's other calls cost nothing
435
+ calls: dict[int, Node] = {}
436
+ if loops:
437
+ calls_q = query(language, lang, "calls")
438
+ end = -1
439
+ for lp in sorted(loops, key=lambda lp: (lp.sb, -lp.eb)):
440
+ if lp.sb < end or lp.eb - lp.sb < 2:
441
+ continue
442
+ end = lp.eb
443
+ cur = QueryCursor(calls_q)
444
+ cur.set_byte_range(lp.sb, lp.eb)
445
+ for node in cur.captures(root).get("call", ()):
446
+ calls[node.start_byte * 4 + (1 if node.type.startswith(("new", "object")) else 0)] = node
447
+ out = []
448
+ for node in sorted(calls.values(), key=lambda c: c.start_byte):
449
+ name, _, args = call_parts(lang, node)
450
+ # the same few names over and over: one string object for each
451
+ out.append((node.start_byte, sys.intern(name), tuple((a.start_byte, sys.intern(_ref_name(a))) for a in args if a.type in ref_types)))
452
+ return lang, loops, refs, out
453
+
454
+
455
+ class Prescan:
456
+ """The scan's reading of each file, taken while the call graph has the file's tree (`origins.TREE_HOOK`),
457
+ so that the tracker does not parse every file a second time. A file without a reading here is read and
458
+ parsed by the tracker as before."""
459
+
460
+ def __init__(self) -> None:
461
+ self.files: dict[str, tuple] = {}
462
+ self._queries: dict[tuple[int, str], Query] = {}
463
+ self.errors = 0
464
+
465
+ def add(self, lang: str, language, rel: str, src: bytes, tree) -> None:
466
+ if lang not in SPECS or language is None or _is_bundle(src):
467
+ return
468
+ try:
469
+ self.files[rel] = scan_tree(lang, language, tree, lambda *a: Tracker._query(self, *a))
470
+ except Exception:
471
+ if _debug():
472
+ raise
473
+ self.errors += 1 # the tracker reads the file itself, and counts the error if it fails again
474
+
475
+
476
+ # --------------------------------------------------------------------------- the tracker
477
+
478
+ class Tracker:
479
+ """Built once per run, after the call graph. `origins.annotate` calls `walked`, `keep`, `attach`, `site`
480
+ and `summary`; everything else is internal."""
481
+
482
+ def __init__(self, root, ix, langs, callers, entries, sites, settings=None, prescan: "Prescan | None" = None):
483
+ self.cfg = Settings.of(settings)
484
+ self._pre: dict[str, tuple] = prescan.files if prescan is not None else {}
485
+ self.root, self.ix, self.langs, self.callers, self.entries = root, ix, langs, callers, entries
486
+ self.on = bool(self.cfg.loops)
487
+ self.seconds = 0.0
488
+ self.file_loops: dict[str, list[_Loop]] = {}
489
+ self.calls: dict[tuple, list[tuple]] = defaultdict(list) # (owner id, name) -> [(call byte, loop indexes)]
490
+ self._edge: dict[tuple[int, int], tuple] = {}
491
+ self._hits: dict[int, list] = {}
492
+ self._parsed: OrderedDict[str, tuple] = OrderedDict()
493
+ self._parsers: dict[int, Parser] = {}
494
+ self._queries: dict[tuple[int, str], Query] = {}
495
+ self._fn_node: dict[int, object] = {}
496
+ self._assigns: dict[int, list] = {}
497
+ self._params: dict[int, tuple] = {}
498
+ self._fn_calls: dict[int, list] = {}
499
+ self._loop_info: dict[tuple[str, int], dict] = {}
500
+ self._callees: dict[int, list[int]] | None = None
501
+ self._below: dict[int, tuple] = {}
502
+ self._ref_hop: dict[tuple[int, int], bool] = {}
503
+ self._line_starts: dict[str, list[int]] = {}
504
+ self.fn_sites: dict[int, list[dict]] = defaultdict(list)
505
+ self.scan_errors = 0
506
+ if not self.on:
507
+ return
508
+ started = time.monotonic()
509
+ for s in sites:
510
+ if s.get("kind") == "sql_file":
511
+ continue
512
+ fn = ix.at_line(s["file"], s["line"])
513
+ if fn is not None:
514
+ self.fn_sites[fn.id].append(s)
515
+ names = {f.name for f in ix.fns}
516
+ names.update(re.split(r"\.|::", f.container)[-1] for f in ix.fns if f.container)
517
+ self._known = names
518
+ for rel in list(ix.by_file):
519
+ try:
520
+ self._scan(rel)
521
+ except Exception:
522
+ if _debug():
523
+ raise
524
+ self.scan_errors += 1
525
+ self.seconds += time.monotonic() - started
526
+
527
+ # ---- languages --------------------------------------------------------------------
528
+ def _language(self, lang: str, rel: str):
529
+ if lang == "typescript":
530
+ from .typescript import language_for
531
+ return language_for(rel)
532
+ return getattr(self.langs.get(lang), "language", None)
533
+
534
+ def _parser(self, language) -> Parser:
535
+ p = self._parsers.get(id(language))
536
+ if p is None:
537
+ p = self._parsers[id(language)] = Parser(language)
538
+ return p
539
+
540
+ def _query(self, language, lang: str, which: str) -> Query:
541
+ q = self._queries.get((id(language), which))
542
+ if q is None:
543
+ spec = SPECS[lang]
544
+ if which == "scan": # loops, and the calls of iterator methods (the rest of the calls are not read)
545
+ names = " ".join(f'"{n}"' for n in sorted(spec["iter_always"] | spec["iter_guarded"]))
546
+ parts = [f"({t}) @loop" for t in spec["loops"]]
547
+ parts += [f"({p} (#any-of? @m {names})) @iter" for p in _ITER_PATTERNS[lang]]
548
+ else:
549
+ parts = [f"({t}) @call" for t in spec["calls"]]
550
+ if which == "detail":
551
+ parts += [f"({t}) @assign" for t in spec["assigns"]]
552
+ q = self._queries[(id(language), which)] = Query(language, " ".join(parts))
553
+ return q
554
+
555
+ def _read(self, rel: str) -> bytes | None:
556
+ from .origins import _read_source
557
+ return _read_source(self.root, rel)
558
+
559
+ # ---- scan -------------------------------------------------------------------------
560
+ def _scan(self, rel: str) -> None:
561
+ fns = self.ix.by_file.get(rel)
562
+ if not fns:
563
+ return
564
+ lang = fns[0].lang
565
+ spec = SPECS.get(lang)
566
+ language = self._language(lang, rel) if spec else None
567
+ if language is None:
568
+ return
569
+ pre = self._pre.pop(rel, None) if self._pre else None
570
+ if pre is None or pre[0] != lang:
571
+ src = self._read(rel)
572
+ if src is None or _is_bundle(src):
573
+ return
574
+ pre = scan_tree(lang, language, self._parser(language).parse(src), self._query)
575
+ _, found, refs, calls = pre
576
+ loops: list[_Loop] = list(found)
577
+ ref_types = spec["refs"]
578
+ # (byte, name, line) of a function handed to an iterator method
579
+ ref_hits: list[tuple[int, str, int]] = [r for r in refs if r[1] in self._known]
580
+ if not loops and not ref_hits:
581
+ self.file_loops[rel] = []
582
+ return
583
+ for pos, ref, line in ref_hits: # `xs.map(fetchOne)`: a loop with no body of its own in this file
584
+ loops.append(_Loop(pos, pos + 1, -1, -1, line, True))
585
+ loops.sort(key=lambda lp: (lp.sb, -lp.eb))
586
+ self.file_loops[rel] = loops
587
+ at_byte, known = self.ix.at_byte, self._known
588
+ for pos, ref, _ in ref_hits:
589
+ owner = at_byte(rel, pos)
590
+ if owner is not None:
591
+ inside = self._holding(loops, pos)
592
+ self.calls[(owner.id, ref)].append((pos, tuple(inside)))
593
+ stack: list[int] = []
594
+ li, n = 0, len(loops)
595
+ for pos, name, arg_refs in calls:
596
+ while li < n and loops[li].sb <= pos:
597
+ stack.append(li)
598
+ li += 1
599
+ while stack and loops[stack[-1]].eb <= pos:
600
+ stack.pop()
601
+ if not stack:
602
+ continue
603
+ stack[:] = [i for i in stack if loops[i].eb > pos]
604
+ inside = [i for i in reversed(stack) if loops[i].holds(pos)]
605
+ if not inside:
606
+ continue
607
+ owner = None
608
+ if name in known:
609
+ owner = at_byte(rel, pos)
610
+ if owner is not None:
611
+ self.calls[(owner.id, name)].append((pos, tuple(inside)))
612
+ for a_pos, ref in arg_refs:
613
+ if ref in known and ref != name:
614
+ owner = owner or at_byte(rel, pos)
615
+ if owner is not None:
616
+ self.calls[(owner.id, ref)].append((a_pos, tuple(inside)))
617
+
618
+ @staticmethod
619
+ def _holding(loops: list[_Loop], pos: int) -> list[int]:
620
+ """Indexes of the loops that hold a byte, innermost first."""
621
+ out = []
622
+ for i, lp in enumerate(loops):
623
+ if lp.sb > pos:
624
+ break
625
+ if lp.holds(pos):
626
+ out.append(i)
627
+ out.reverse()
628
+ return out
629
+
630
+ # ---- edges ------------------------------------------------------------------------
631
+ def _own(self, fn, rel: str, idxs) -> tuple:
632
+ """Of some loops of a file, those that belong to a function's own body (a loop that is the whole
633
+ function is the callback loop around an inline function, and belongs to its parent)."""
634
+ loops = self.file_loops.get(rel) or ()
635
+ return tuple(i for i in idxs if loops[i].sb >= fn.sb and loops[i].eb <= fn.eb
636
+ and not (loops[i].sb == fn.sb and loops[i].eb == fn.eb))
637
+
638
+ def _call_names(self, f) -> list[str]:
639
+ names = [f.name]
640
+ if f.container:
641
+ simple = re.split(r"\.|::", f.container)[-1]
642
+ if f.name in _CTOR_NAMES or f.name == simple or (f.lang == "rust" and f.name == "new"):
643
+ names.append(simple)
644
+ return names
645
+
646
+ def chains(self, caller: int, callee: int) -> tuple:
647
+ """The loops of `caller` that its calls to `callee` sit in: one chain per distinct place, each
648
+ ((file, loop index), ...) innermost first. Empty when no call to it is in a loop."""
649
+ key = (caller, callee)
650
+ got = self._edge.get(key)
651
+ if got is not None:
652
+ return got
653
+ fns = self.ix.fns
654
+ c, f = fns[caller], fns[callee]
655
+ found: dict[tuple, None] = {}
656
+ for name in self._call_names(f):
657
+ for _, idxs in self.calls.get((caller, name), ()):
658
+ own = self._own(c, c.file, idxs)
659
+ if own:
660
+ found[own] = None
661
+ if f.lex is c and f.file == c.file and (f.inline or not found):
662
+ loops = self.file_loops.get(c.file)
663
+ if loops:
664
+ # the closure itself may be the callback of an iterator method: that loop starts where it does
665
+ own = self._own(c, c.file, self._holding(loops, f.sb))
666
+ if own:
667
+ found[own] = None
668
+ got = self._edge[key] = tuple(tuple((c.file, i) for i in chain) for chain in found)
669
+ return got
670
+
671
+ def edge(self, caller: int, callee: int) -> tuple:
672
+ """Every loop of `caller` around a call to `callee`, each once, inner before outer."""
673
+ chains = self.chains(caller, callee)
674
+ if len(chains) == 1:
675
+ return chains[0]
676
+ return tuple(dict.fromkeys(ref for chain in chains for ref in chain))
677
+
678
+ # ---- the walk ---------------------------------------------------------------------
679
+ def walked(self, fid: int, seen: dict, parent: dict) -> None:
680
+ """Called by `origins.reach` with its finished walk from one function: every caller edge it looked at
681
+ that sits in a loop becomes a hit (hops, path of function ids from the site up, loops, guessed)."""
682
+ if not self.on or fid in self._hits:
683
+ return
684
+ started = time.monotonic()
685
+ callers, guessed, depth_max = self.callers, self.ix.guessed, self.cfg.loop_depth
686
+ hits: dict[tuple, tuple] = {}
687
+ edge, fns = self.edge, self.ix.fns
688
+ start_test = fns[fid].test
689
+ for state, depth in seen.items():
690
+ if depth >= depth_max:
691
+ continue
692
+ f, g = state
693
+ for c in callers.get(f, ()):
694
+ loops = edge(c, f)
695
+ if not loops or (fns[c].test and not start_test):
696
+ continue # a loop in a test says nothing about how the application runs the query
697
+ unsure = bool(g or guessed.get((f, c), 0))
698
+ for ref in loops:
699
+ old = hits.get(ref)
700
+ if old is None or (old[2], old[0]) > (unsure, depth + 1):
701
+ hits[ref] = (depth + 1, state, unsure, c)
702
+ out = []
703
+ for ref, (hop, state, unsure, c) in hits.items():
704
+ path, cur = [], state
705
+ while cur in parent:
706
+ path.append(cur[0])
707
+ cur = parent[cur][0]
708
+ path.append(cur[0])
709
+ path.reverse()
710
+ path.append(c)
711
+ out.append((hop, unsure, ref, tuple(path)))
712
+ out.sort(key=lambda h: (h[0], h[1], h[2]))
713
+ self._hits[fid] = out
714
+ self.seconds += time.monotonic() - started
715
+
716
+ def keep(self, found: dict, states: dict) -> set:
717
+ """Entry points whose path `reach` should record: the ones `annotate` can list for a site."""
718
+ if not self.on or not found:
719
+ return set()
720
+ from .origins import KIND_ORDER, TEST_KINDS
721
+ ranked = []
722
+ for e, hops in found.items():
723
+ ent = self.entries[e]
724
+ ranked.append((ent.kind in TEST_KINDS, bool(states[e][1]), hops, KIND_ORDER.get(ent.kind, 9), ent.name, ent.kind,
725
+ ent.file, ent.line, e))
726
+ ranked.sort()
727
+ k = self.cfg.max_origins
728
+ return {r[8] for r in ranked[:k]} | {r[8] for r in [r for r in ranked if not r[0]][:k]}
729
+
730
+ # ---- detail: parsed files ---------------------------------------------------------
731
+ def _tree(self, rel: str):
732
+ got = self._parsed.get(rel)
733
+ if got is not None:
734
+ self._parsed.move_to_end(rel)
735
+ return got
736
+ fns = self.ix.by_file.get(rel)
737
+ lang = fns[0].lang if fns else ""
738
+ language = self._language(lang, rel) if lang in SPECS else None
739
+ src = self._read(rel) if language is not None else None
740
+ got = (None, None, lang, None) if src is None else (src, self._parser(language).parse(src), lang, language)
741
+ self._parsed[rel] = got
742
+ while len(self._parsed) > max(2, self.cfg.loop_parse_cache):
743
+ old, _ = self._parsed.popitem(last=False)
744
+ for fid in [f.id for f in self.ix.by_file.get(old, ())]:
745
+ self._fn_node.pop(fid, None)
746
+ return got
747
+
748
+ def _node_at(self, rel: str, sb: int, types) -> Node | None:
749
+ src, tree, _, _ = self._tree(rel)
750
+ if tree is None:
751
+ return None
752
+ n = tree.root_node.descendant_for_byte_range(sb, sb)
753
+ while n is not None and n.start_byte >= sb:
754
+ if n.start_byte == sb and n.type in types:
755
+ return n
756
+ n = n.parent
757
+ return None
758
+
759
+ def _line_byte(self, rel: str, line: int) -> int:
760
+ starts = self._line_starts.get(rel)
761
+ if starts is None:
762
+ src = self._tree(rel)[0] or b""
763
+ starts = [0] + [m.end() for m in re.finditer(b"\n", src)]
764
+ if len(self._line_starts) > 4 * max(2, self.cfg.loop_parse_cache):
765
+ self._line_starts.clear()
766
+ self._line_starts[rel] = starts
767
+ return starts[min(max(line - 1, 0), len(starts) - 1)]
768
+
769
+ def _fn_def(self, fn) -> Node | None:
770
+ """The definition node of a function of the index (None for a module)."""
771
+ if fn.module:
772
+ return None
773
+ src, tree, lang, _ = self._tree(fn.file)
774
+ if tree is None:
775
+ return None
776
+ funcs = SPECS[lang]["funcs"]
777
+ n = tree.root_node.descendant_for_byte_range(fn.sb, max(fn.sb, fn.eb - 1))
778
+ if n is None:
779
+ return None
780
+ if n.type in funcs:
781
+ return n
782
+ todo = deque([n])
783
+ steps = 0
784
+ while todo and steps < 200:
785
+ cur = todo.popleft()
786
+ steps += 1
787
+ for c in cur.named_children:
788
+ if c.end_byte <= fn.sb or c.start_byte >= fn.eb:
789
+ continue
790
+ if c.type in funcs:
791
+ return c
792
+ todo.append(c)
793
+ return None
794
+
795
+ def params(self, fn) -> tuple[list[list[str]], str]:
796
+ """Parameter names by position (a destructured parameter has several), and the receiver's name."""
797
+ got = self._params.get(fn.id)
798
+ if got is not None:
799
+ return got
800
+ node = self._fn_def(fn)
801
+ lang = fn.lang
802
+ out: list[list[str]] = []
803
+ recv = {"python": "self", "typescript": "this", "java": "this", "rust": "self"}.get(lang, "")
804
+ if node is not None:
805
+ if lang == "go":
806
+ r = node.child_by_field_name("receiver")
807
+ if r is not None:
808
+ names = _names(_t(r).split(" ")[0].strip("("))
809
+ recv = names[0] if names else ""
810
+ plist = node.child_by_field_name("parameters")
811
+ for p in (plist.named_children if plist is not None else ()):
812
+ ns = [_t(c) for c in p.children_by_field_name("name")]
813
+ out.extend([[n] for n in ns] or [[]])
814
+ elif lang == "python":
815
+ plist = node.child_by_field_name("parameters")
816
+ for i, p in enumerate(plist.named_children if plist is not None else ()):
817
+ text = _t(p)
818
+ if p.type in ("keyword_separator", "positional_separator"):
819
+ continue
820
+ name = re.match(r"\*{0,2}\s*([A-Za-z_]\w*)", text)
821
+ name = name.group(1) if name else ""
822
+ if i == 0 and name in ("self", "cls") and fn.container:
823
+ recv = name
824
+ continue
825
+ out.append([name] if name else [])
826
+ elif lang == "rust":
827
+ plist = node.child_by_field_name("parameters")
828
+ for p in (plist.named_children if plist is not None else ()):
829
+ if p.type == "self_parameter":
830
+ continue
831
+ pat = p.child_by_field_name("pattern") or p
832
+ out.append(_names(_t(pat).split(":")[0]))
833
+ elif lang == "java":
834
+ plist = node.child_by_field_name("parameters")
835
+ if plist is not None and plist.type == "identifier":
836
+ out.append([_t(plist)])
837
+ else:
838
+ for p in (plist.named_children if plist is not None else ()):
839
+ nm = p.child_by_field_name("name")
840
+ out.append([_t(nm)] if nm is not None else _names(_t(p))[-1:])
841
+ else:
842
+ single = node.child_by_field_name("parameter")
843
+ plist = node.child_by_field_name("parameters")
844
+ if single is not None:
845
+ out.append([_t(single)])
846
+ for p in (plist.named_children if plist is not None else ()):
847
+ if p.type in ("comment", "decorator"):
848
+ continue
849
+ pat = p.child_by_field_name("pattern") or p.child_by_field_name("left") or p
850
+ text = _t(pat)
851
+ if p.type not in ("required_parameter", "optional_parameter"):
852
+ text = text.split("=")[0]
853
+ if text.strip() == "this":
854
+ continue
855
+ out.append(_names(text))
856
+ got = self._params[fn.id] = (out, recv)
857
+ return got
858
+
859
+ def _detail(self, fn) -> tuple[list, list]:
860
+ """(assignments, calls) of one function's own body. An assignment is (byte, names bound, source text);
861
+ a call is (byte, name, receiver text, argument texts, keyword names)."""
862
+ got = self._assigns.get(fn.id)
863
+ if got is not None:
864
+ return got, self._fn_calls[fn.id]
865
+ src, tree, lang, language = self._tree(fn.file)
866
+ assigns: list[tuple] = []
867
+ calls: list[tuple] = []
868
+ if tree is not None:
869
+ spec = SPECS[lang]
870
+ cur = QueryCursor(self._query(language, lang, "detail"))
871
+ cur.set_byte_range(fn.sb, fn.eb)
872
+ caps = cur.captures(tree.root_node)
873
+ at_byte = self.ix.at_byte
874
+ fields_of = spec["assigns"]
875
+ for node in caps.get("assign", ()):
876
+ if not (fn.sb <= node.start_byte < fn.eb):
877
+ continue
878
+ lf, rf = fields_of[node.type]
879
+ left, right = node.child_by_field_name(lf), node.child_by_field_name(rf)
880
+ if left is None or right is None:
881
+ continue
882
+ ltext = _t(left)
883
+ if re.match(r"\s*(?:self|this)\b", ltext):
884
+ continue
885
+ names = _names(ltext)
886
+ if ("." in ltext or "[" in ltext) and not ltext.lstrip().startswith(("[", "(", "{")):
887
+ names = names[:1] # `state.cursor = x`, `out[k] = x`: the object changes
888
+ if names:
889
+ assigns.append((node.start_byte, names, _t(right)))
890
+ closures = spec["closures"]
891
+ for node in caps.get("call", ()):
892
+ if not (fn.sb <= node.start_byte < fn.eb):
893
+ continue
894
+ name, recv, args = call_parts(lang, node)
895
+ texts, kws = [], []
896
+ for a in args:
897
+ if a.type == "keyword_argument":
898
+ kws.append(_t(a.child_by_field_name("name")))
899
+ texts.append(_t(a.child_by_field_name("value")))
900
+ else:
901
+ kws.append("")
902
+ texts.append(_t(a))
903
+ if a.type in closures: # a callback's parameters carry what the call was made on
904
+ ps = a.child_by_field_name("parameters") or a.child_by_field_name("parameter")
905
+ pnames = _names(_t(ps)) if ps is not None else []
906
+ if pnames:
907
+ assigns.append((a.start_byte, pnames, recv + " " + " ".join(_t(x) for x in args if x.type not in closures)))
908
+ if name in _MUTATORS and recv and texts:
909
+ root = _IDENT.match(recv)
910
+ if root and root.group(0) not in ("self", "this"):
911
+ assigns.append((node.start_byte, [root.group(0)], " ".join(texts)))
912
+ owner = at_byte(fn.file, node.start_byte)
913
+ if name and (owner is fn or (owner is not None and owner.inline)):
914
+ calls.append((node.start_byte, name, recv, texts, kws))
915
+ self._assigns[fn.id], self._fn_calls[fn.id] = assigns, calls
916
+ if len(self._assigns) > 20000:
917
+ for k in list(self._assigns)[:5000]:
918
+ self._assigns.pop(k, None)
919
+ self._fn_calls.pop(k, None)
920
+ return assigns, calls
921
+
922
+ def _closure(self, fn, seed: set[str]) -> set[str]:
923
+ """Names of a function that may hold something derived from `seed` (flow-insensitive)."""
924
+ tainted = set(seed)
925
+ if not tainted:
926
+ return tainted
927
+ assigns, _ = self._detail(fn)
928
+ for _ in range(6):
929
+ grew = False
930
+ for _, names, text in assigns:
931
+ if not tainted.issuperset(names) and _mentions(text, tainted):
932
+ tainted.update(names)
933
+ grew = True
934
+ if not grew:
935
+ break
936
+ return tainted
937
+
938
+ # ---- detail: one loop -------------------------------------------------------------
939
+ def loop_info(self, rel: str, idx: int) -> dict:
940
+ key = (rel, idx)
941
+ got = self._loop_info.get(key)
942
+ if got is None:
943
+ try:
944
+ got = self._describe(rel, idx)
945
+ except Exception:
946
+ if _debug():
947
+ raise
948
+ self.scan_errors += 1
949
+ lp = self.file_loops[rel][idx]
950
+ got = {"file": rel, "line": lp.line, "kind": "unknown", "kind_basis": "not read", "form": "unknown",
951
+ "_seed": set(), "_fn": None, "_range": (lp.sb, lp.eb)}
952
+ self._loop_info[key] = got
953
+ return got
954
+
955
+ def _describe(self, rel: str, idx: int) -> dict:
956
+ lp = self.file_loops[rel][idx]
957
+ src, tree, lang, _ = self._tree(rel)
958
+ spec = SPECS[lang]
959
+ fn = self.ix.at_byte(rel, lp.sb)
960
+ if fn is not None and fn.sb == lp.sb and fn.lex is not None:
961
+ fn = fn.lex # an inline handler that is itself the callback: the loop is its parent's
962
+ cut = self.cfg.loop_text_chars
963
+ info: dict = {"file": rel, "line": lp.line, "function": fn.symbol if fn is not None else ""}
964
+ form, vars_, over, cond, update, init, body_text = "unknown", [], "", "", "", "", ""
965
+ if lp.callback:
966
+ form = "callback"
967
+ node = self._node_at(rel, lp.sb, spec["closures"])
968
+ if node is not None:
969
+ ps = node.child_by_field_name("parameters") or node.child_by_field_name("parameter")
970
+ vars_ = _names(re.sub(r":\s*[\w.<>\[\]|& ]+", "", _t(ps)))[:4] if ps is not None else []
971
+ body_text = _t(node)
972
+ call = node.parent
973
+ while call is not None and call.type not in spec["calls"]:
974
+ call = call.parent
975
+ if call is not None:
976
+ name, recv, args = call_parts(lang, call)
977
+ over = recv if recv and not spec["guard"].fullmatch(recv) else (_t(args[0]) if args and args[0] is not node else recv)
978
+ info["method"] = name
979
+ else: # a function handed over by name: `xs.map(fetchOne)`
980
+ n = tree.root_node.descendant_for_byte_range(lp.sb, lp.sb) if tree is not None else None
981
+ while n is not None and n.type not in spec["calls"]:
982
+ n = n.parent
983
+ if n is not None:
984
+ name, recv, args = call_parts(lang, n)
985
+ over = recv or (_t(args[-1]) if len(args) > 1 else "")
986
+ info["method"] = name
987
+ else:
988
+ node = self._node_at(rel, lp.sb, spec["loops"])
989
+ if node is None:
990
+ raise LookupError(rel)
991
+ t = node.type
992
+ body = node.child_by_field_name("body")
993
+ body_text = _t(body) if body is not None else _t(node)
994
+ if lang == "go":
995
+ form = "infinite"
996
+ for c in node.named_children:
997
+ if c.type == "range_clause":
998
+ form, over = "for-each", _t(c.child_by_field_name("right"))
999
+ vars_ = _names(_t(c.child_by_field_name("left")))
1000
+ elif c.type == "for_clause":
1001
+ init, cond, update = (_t(c.child_by_field_name(k)) for k in ("initializer", "condition", "update"))
1002
+ form = "counted" if (cond or init or update) else "infinite"
1003
+ vars_ = _names(init.split(":=")[0].split("=")[0]) if init else []
1004
+ elif body is None or c.id != body.id:
1005
+ form, cond = "while", _t(c)
1006
+ elif lang == "python":
1007
+ if t == "while_statement":
1008
+ cond = _t(node.child_by_field_name("condition"))
1009
+ form = "infinite" if cond.strip("() ") in ("True", "1") else "while"
1010
+ else:
1011
+ clause = node if t == "for_statement" else next((c for c in node.named_children if c.type == "for_in_clause"), None)
1012
+ form = "for-each"
1013
+ if clause is not None:
1014
+ vars_, over = _names(_t(clause.child_by_field_name("left"))), _t(clause.child_by_field_name("right"))
1015
+ if t != "for_statement":
1016
+ body_text = _t(node)
1017
+ elif lang == "rust":
1018
+ if t == "for_expression":
1019
+ form, over = "for-each", _t(node.child_by_field_name("value"))
1020
+ vars_ = _names(_t(node.child_by_field_name("pattern")))
1021
+ elif t == "while_expression":
1022
+ cond = _t(node.child_by_field_name("condition"))
1023
+ form = "infinite" if cond.strip() == "true" else "while"
1024
+ m = re.match(r"let\s+(.+?)\s*=\s*(.+)$", cond, re.S)
1025
+ if m:
1026
+ vars_ = _names(m.group(1))
1027
+ else:
1028
+ form = "infinite"
1029
+ else: # java, typescript
1030
+ if t in ("enhanced_for_statement", "for_in_statement"):
1031
+ form = "for-each"
1032
+ left = node.child_by_field_name("name" if lang == "java" else "left")
1033
+ vars_ = _names(_t(left))
1034
+ over = _t(node.child_by_field_name("value" if lang == "java" else "right"))
1035
+ elif t == "for_statement":
1036
+ init = _t(node.child_by_field_name("init" if lang == "java" else "initializer"))
1037
+ cond = _t(node.child_by_field_name("condition"))
1038
+ update = _t(node.child_by_field_name("update" if lang == "java" else "increment"))
1039
+ form = "counted" if cond.strip(" ;") else "infinite"
1040
+ vars_ = _names(re.sub(r"^\s*(?:final\s+)?(?:let|var|const|[\w.<>\[\]]+)\s+(?=\w+\s*=)", "", init).split("=")[0]) if init.strip(" ;") else []
1041
+ else:
1042
+ cond = _t(node.child_by_field_name("condition"))
1043
+ form = "infinite" if cond.strip("() ") in ("true", "1") else "while"
1044
+ vars_ = [v for v in vars_ if v != "_"]
1045
+ # a counted loop over a collection is a for-each in older clothes: `i < len(xs)`, `i < xs.length`
1046
+ if form == "counted" and not over:
1047
+ m = re.search(r"<=?\s*(?:len\(\s*([\w.]+)\s*\)|([\w.]+?)\.(?:length|size\(\)|len\(\)|Count\b|count\(\)))", cond)
1048
+ if m is None: # walked backwards: `i := len(xs) - 1; i >= 0; i--`
1049
+ m = re.search(r"=\s*(?:len\(\s*([\w.]+)\s*\)|([\w.]+?)\.(?:length|size\(\)|len\(\)))\s*-\s*1", init)
1050
+ if m:
1051
+ over = m.group(1) or m.group(2)
1052
+ else:
1053
+ m = re.search(r"<=?\s*([\w.]+)\s*$", cond.strip(" ;"))
1054
+ if m:
1055
+ info["bound"] = m.group(1)
1056
+ if form == "for-each" and lang == "python":
1057
+ m = re.match(r"range\(\s*(?:0\s*,\s*)?len\(\s*([\w.]+)\s*\)\s*(?:,\s*(.+))?\)$", over.strip())
1058
+ if m:
1059
+ info["_range_step"] = bool(m.group(2))
1060
+ seed = set(vars_)
1061
+ if form in ("while", "infinite") or (form == "counted" and not vars_):
1062
+ # nothing names the item: what changes from one pass to the next is what the body assigns
1063
+ if fn is not None:
1064
+ assigns, _ = self._detail(fn)
1065
+ for pos, names, _ in assigns:
1066
+ if lp.sb <= pos < lp.eb:
1067
+ seed.update(names)
1068
+ info.update(form=form, _seed=seed, _fn=fn, _range=(lp.sb, lp.eb))
1069
+ if vars_:
1070
+ info["vars"] = vars_[:6]
1071
+ kind, basis = self._kind(lang, form, vars_, over, cond, update, init, body_text, info)
1072
+ source = self._source(fn, over, lp.sb, info, cond if form in ("while", "infinite") else "") if fn is not None else {}
1073
+ if source.get("count") is not None and "count" not in info:
1074
+ info["count"] = source["count"]
1075
+ if kind in ("per-item", "unknown") and source.get("source") == "literal":
1076
+ kind, basis = "fixed", "iterates a literal list"
1077
+ if kind == "per-item" and source.get("source") == "constant":
1078
+ kind, basis = "fixed", "iterates a constant"
1079
+ info["kind"], info["kind_basis"] = kind, basis
1080
+ if over.strip():
1081
+ info["over"] = " ".join(over.split())[:cut]
1082
+ elif cond.strip():
1083
+ info["condition"] = " ".join(cond.split())[:cut]
1084
+ for k in ("source", "driver", "from"):
1085
+ if source.get(k) is not None:
1086
+ info[k] = source[k]
1087
+ return info
1088
+
1089
+ def _kind(self, lang, form, vars_, over, cond, update, init, body, info) -> tuple[str, str]:
1090
+ """A loop's kind and the rule that gave it. The rules read names and shapes, in this order: a retry or
1091
+ a wait, a chunk, a step through time, a fixed count, a walk over a collection."""
1092
+ last = re.findall(r"[A-Za-z_$][\w$]*", re.sub(r"\(.*", "", _WRAPPERS.sub("", over.strip())))[-1:] # `batch.Days` -> Days
1093
+ item_words = _words(" ".join(vars_)) # what one pass is handed
1094
+ coll_words = _words(" ".join(last)) # what the collection is called
1095
+ head_words = _words(" ".join((cond, update, init)))
1096
+ idents = " ".join(i.replace("_", "").lower() for i in _IDENT.findall(" ".join((cond, update, init))))
1097
+ if form in ("while", "infinite"):
1098
+ if _SLEEP.search(body) or _SLEEP.search(cond):
1099
+ return "retry-poll", "waits between passes"
1100
+ if head_words & RETRY_WORDS:
1101
+ return "retry-poll", "named as a retry"
1102
+ if lang == "go" and form == "infinite" and "select" in body and re.search(r"<-\s*[\w.]+", body):
1103
+ return "retry-poll", "waits on a channel"
1104
+ if _CURSOR.search(cond) or re.match(r"let\s+(?:Some|Ok)\s*\(", cond.strip()):
1105
+ return "per-item", "walks a cursor or iterator"
1106
+ if form == "while" and _DRAIN.search(cond.strip()):
1107
+ return "per-item", "drains a queue"
1108
+ if _TIME_OPS.search(cond):
1109
+ return "time-window", "steps through time"
1110
+ assigned = " ".join(i.replace("_", "").lower() for i in info.get("_seed") or ())
1111
+ leaves = re.search(r"\b(?:break|return)\b", body)
1112
+ if _PAGING.search(idents) or (_PAGING.search(assigned) and leaves):
1113
+ return "chunk", "pages through a result"
1114
+ if leaves and _SHORT_PAGE.search(body):
1115
+ return "chunk", "stops at a short or empty page"
1116
+ if head_words & TIME_WORDS:
1117
+ return "time-window", "steps through time"
1118
+ if form == "infinite":
1119
+ if re.search(r"\b(?:recv|Recv|accept|Accept|poll|Poll|next_message|ReadMessage|consume|Consume|receive|Receive|listen)\w*\(", body):
1120
+ return "retry-poll", "waits for the next message"
1121
+ return "retry-poll", "runs until stopped"
1122
+ return "unknown", "a condition this does not read"
1123
+ if (item_words | head_words) & RETRY_WORDS:
1124
+ return "retry-poll", "named as a retry"
1125
+ if form == "for-each" and lang == "go" and re.search(r"(?:\.C|[cC]h(?:an)?(?:nel)?|time\.Tick\(.*\))$", over.strip()):
1126
+ return ("retry-poll", "ranges over a ticker") if re.search(r"\.C$|Tick", over.strip()) else ("per-item", "ranges over a channel")
1127
+ step = re.search(r"\+=\s*(?!1\b)[\w.]+|=\s*\w+\s*\+\s*(?!1\b)[\w.(]+", update) if form == "counted" else None
1128
+ sliced = bool(vars_) and re.search(
1129
+ r"\[\s*%s\s*(?::|\.\.)|\.(?:slice|subList|substring|sublist)\(\s*%s\b" % (re.escape(vars_[0]), re.escape(vars_[0])), body)
1130
+ time_named = bool((item_words | head_words) & TIME_WORDS) or bool(coll_words & TIME_PLURALS) or \
1131
+ bool(_TIME_OPS.search(cond + " " + update + " " + over))
1132
+ if item_words & CHUNK_WORDS or coll_words & CHUNK_PLURALS:
1133
+ return "chunk", "named as a chunk or page"
1134
+ if _CHUNK_CALL.search(over):
1135
+ return "chunk", "iterates chunks"
1136
+ if (step or info.pop("_range_step", False) or re.search(r"range\([^,()]+,[^,]+,[^,]+\)$|\.step_by\(", over.strip())) and not time_named:
1137
+ return "chunk", "steps by more than one"
1138
+ if sliced and not time_named:
1139
+ return "chunk", "the body takes a slice"
1140
+ if time_named:
1141
+ return "time-window", "steps through time" if form == "counted" else "named as a time range"
1142
+ count = None
1143
+ if form == "counted":
1144
+ m = re.search(r"<(=?)\s*(\d+)\s*;?\s*$", cond.strip())
1145
+ if m:
1146
+ count = int(m.group(2)) + (1 if m.group(1) else 0)
1147
+ else:
1148
+ m = re.match(r"(?:range\(\s*(\d+)\s*\)|(?:0\s*)?\.\.(=?)\s*(\d+)|(\d+))$", over.strip())
1149
+ if m:
1150
+ count = int(m.group(1) or m.group(3) or m.group(4)) + (1 if m.group(2) else 0)
1151
+ if count is not None:
1152
+ if _RETRY_BODY.search(body): # `for i in range(3): try ... except: continue`: a pass is repeated only when it fails
1153
+ return "retry-poll", "tries again when a pass fails"
1154
+ info["count"] = count
1155
+ return "fixed", "a literal count"
1156
+ if form == "counted" and not over and not info.get("bound"):
1157
+ return "unknown", "a counted loop with no collection"
1158
+ if form == "for-each" and re.match(r"\(?\s*[\w.]*\s*\.\.|range\(\s*[\w.]+\s*(?:,\s*[\w.]+\s*)?\)$", over.strip()) \
1159
+ and not re.search(r"len\(|\.len\(\)|\.length|\.size\(\)", over):
1160
+ return "unknown", "counts to a number that is not in the source"
1161
+ return "per-item", "iterates a collection" if form != "callback" else "callback of an iterator method"
1162
+
1163
+ # ---- detail: where the collection comes from ---------------------------------------
1164
+ def _source(self, fn, over: str, before: int, info: dict, cond: str = "", depth: int = 0) -> dict:
1165
+ raw = over
1166
+ text = " ".join(over.split())
1167
+ if not text and cond:
1168
+ m = re.search(r"([A-Za-z_][\w.]*)" + _CURSOR.pattern, cond) or \
1169
+ (re.search(r"([A-Za-z_][\w.]*?)(?:\.(?:length|size|isEmpty|is_empty|empty)\b|\s*\)|\s*$)", cond.replace("len(", "").lstrip("(! "))
1170
+ if _DRAIN.search(cond.strip()) else None)
1171
+ text = m.group(1) if m else ""
1172
+ if not text and info.get("bound"):
1173
+ text = info["bound"]
1174
+ if not text:
1175
+ return {}
1176
+ for _ in range(4):
1177
+ new = _WRAPPERS.sub("", text).strip()
1178
+ m = _WRAP_CALL.match(new)
1179
+ if m:
1180
+ new = m.group(1).strip()
1181
+ if new == text:
1182
+ break
1183
+ text = new
1184
+ comp = re.match(r"[\[{(].*\bfor\b.+?\bin\b\s+(.+?)(?:\s+if\b.*)?[\]})]$", text) if fn.lang == "python" else None
1185
+ if comp: # `{r[0] for r in rows}`: the collection is what the comprehension walks
1186
+ got = self._source(fn, comp.group(1), before, {}, "", depth + 1) if depth < 3 else {}
1187
+ return got or {"source": "local"}
1188
+ if _LITERAL.match(text) and not re.match(r"\(\s*await\b", text):
1189
+ n = _top_level_items(text)
1190
+ if n == 0:
1191
+ return {"source": "local"} # an empty list or map is filled later: not a list written in the source
1192
+ if n is not None and not (text.startswith("(") and n < 2 and "," not in text):
1193
+ return {"source": "literal", "count": n}
1194
+ if re.match(r"range\(|\d+\s*\.\.|\(\s*\d", text):
1195
+ return {"source": "range"}
1196
+ ident = re.fullmatch(r"[A-Za-z_$][\w$]*", text)
1197
+ if ident:
1198
+ name = text
1199
+ params, _ = self.params(fn)
1200
+ assigns, _ = self._detail(fn)
1201
+ last = grown = None
1202
+ for pos, names, rhs in assigns:
1203
+ if pos < before and name in names:
1204
+ if not _mentions(rhs, [name]):
1205
+ last = (pos, rhs)
1206
+ elif grown is None or pos > grown:
1207
+ grown = pos
1208
+ if grown is not None and depth < 2 and (last is None or _EMPTY.match(last[1].strip())):
1209
+ # filled item by item in an earlier loop (`for rows.Next() { xs = append(xs, x) }`): where that
1210
+ # loop's items come from is where this collection comes from
1211
+ loops = self.file_loops.get(fn.file) or ()
1212
+ holder = next((i for i in self._holding(loops, grown) if loops[i].sb >= fn.sb and loops[i].eb <= fn.eb), None)
1213
+ if holder is not None and loops[holder].eb <= before:
1214
+ up = self.loop_info(fn.file, holder)
1215
+ got = {"source": up.get("source") or "local", "from": f"filled in the loop at line {loops[holder].line}"}
1216
+ if up.get("driver"):
1217
+ got["driver"] = up["driver"]
1218
+ return got
1219
+ if last is not None and depth < 3:
1220
+ got = self._source(fn, last[1], last[0], {}, "", depth + 1)
1221
+ if got.get("source") in (None, "unknown"):
1222
+ got = {"source": "local"}
1223
+ got.setdefault("from", " ".join(last[1].split())[: self.cfg.loop_text_chars])
1224
+ if got.get("source") in ("call", "query"):
1225
+ self._driver(fn, last[0], last[1], got)
1226
+ return got
1227
+ if any(name in p for p in params):
1228
+ return {"source": "parameter"}
1229
+ const = self._module_const(fn.file, name)
1230
+ if const is not None:
1231
+ n = _top_level_items(const) if _LITERAL.match(const) else None
1232
+ out = {"source": "constant", "from": const[: self.cfg.loop_text_chars]}
1233
+ if n is not None:
1234
+ out["count"] = n
1235
+ return out
1236
+ if name[:1].isupper() or name.isupper():
1237
+ return {"source": "constant"}
1238
+ return {"source": "unknown"}
1239
+ if re.search(r"\(", text):
1240
+ got = {"source": "call"}
1241
+ if depth == 0:
1242
+ self._driver(fn, before, raw, got)
1243
+ return got
1244
+ if re.fullmatch(r"[\w$]+(?:(?:\.|::|->)[\w$]+)+", text):
1245
+ last = text.split(".")[-1].split("::")[-1]
1246
+ if last.isupper() or (last[:1].isupper() and fn.lang in ("python", "rust", "java", "typescript")):
1247
+ return {"source": "constant"}
1248
+ return {"source": "field"}
1249
+ return {"source": "unknown"}
1250
+
1251
+ def _module_const(self, rel: str, name: str) -> str | None:
1252
+ src = self._tree(rel)[0]
1253
+ if src is None:
1254
+ return None
1255
+ # at the left margin (a module's own names), or a `static final` field of a class
1256
+ name_b = re.escape(name.encode())
1257
+ value = rb"\s*(?::[^=\n]+)?=\s*([^\n]+(?:\n[ \t]+[^\n]+){0,12})"
1258
+ m = re.search(rb"(?m)^(?:(?:export|pub(?:\([a-z]+\))?|public|private|protected)[ \t]+)*(?:(?:const|var|let|static|final)[ \t]+)*"
1259
+ rb"(?:[\w<>\[\],.]+[ \t]+)?" + name_b + rb"\b(?:[ \t]+[\w\[\].*]+)?" + value, src) or \
1260
+ re.search(rb"(?m)^[ \t]+(?:(?:public|private|protected)[ \t]+)?static[ \t]+final[ \t]+[\w<>\[\], .]+[ \t]+" + name_b + value, src)
1261
+ if m is None:
1262
+ return None
1263
+ return " ".join(m.group(1).decode("utf-8", "replace").split()).rstrip(";")
1264
+
1265
+ def _driver(self, fn, pos: int, text: str, out: dict) -> None:
1266
+ """When the collection is the result of a call, the query behind that call: a site in this function on
1267
+ those lines, or the nearest query below a function the call names."""
1268
+ src = self._tree(fn.file)[0] or b""
1269
+ line = src.count(b"\n", 0, pos) + 1
1270
+ end = line + text.count("\n")
1271
+ here = [s for s in self.fn_sites.get(fn.id, ()) if s["line"] <= end and s.get("end_line", s["line"]) >= line
1272
+ and s.get("statement") in ("select", "unknown", "other", None, "")]
1273
+ if here:
1274
+ out["source"] = "query"
1275
+ out["driver"] = {"site_ids": [s["id"] for s in here[:3]], "hops": 0}
1276
+ return
1277
+ called = [n for n in re.findall(r"([A-Za-z_$][\w$]*)\s*(?:::<[^>]*>)?\(", text)][::-1]
1278
+ if not called:
1279
+ return
1280
+ if self._callees is None:
1281
+ callees: dict[int, list[int]] = defaultdict(list)
1282
+ for callee, cs in self.callers.items():
1283
+ for c in cs:
1284
+ callees[c].append(callee)
1285
+ self._callees = callees
1286
+ fns = self.ix.fns
1287
+ for name in called:
1288
+ cands = [t for t in self._callees.get(fn.id, ()) if name in self._call_names(fns[t])]
1289
+ best = None
1290
+ for t in cands:
1291
+ got = self._sites_below(t)
1292
+ if got and (best is None or got[1] < best[1][1]):
1293
+ best = (t, got)
1294
+ if best is not None:
1295
+ t, (ids, hops, unsure) = best
1296
+ out["source"] = "query"
1297
+ out["driver"] = {"site_ids": ids[:3], "via": fns[t].symbol or fns[t].name, "hops": hops + 1}
1298
+ if len(ids) > 3:
1299
+ out["driver"]["site_count"] = len(ids)
1300
+ if unsure or self.ix.guessed.get((t, fn.id)) or len(cands) > 1:
1301
+ out["driver"]["verified"] = False
1302
+ return
1303
+
1304
+ def _sites_below(self, fid: int):
1305
+ """The nearest read queries at or below a function: (site ids, hops, went through a guessed call)."""
1306
+ got = self._below.get(fid)
1307
+ if got is not None:
1308
+ return got or None
1309
+ seen = {fid: (0, False)}
1310
+ todo = deque([fid])
1311
+ found: list[str] = []
1312
+ level, unsure_any = None, False
1313
+ guessed = self.ix.guessed
1314
+ while todo:
1315
+ f = todo.popleft()
1316
+ d, unsure = seen[f]
1317
+ if level is not None and d > level:
1318
+ break
1319
+ reads = [s for s in self.fn_sites.get(f, ()) if s.get("statement") in ("select", "unknown", "other", None, "")]
1320
+ if reads:
1321
+ level = d
1322
+ unsure_any = unsure_any or unsure
1323
+ found.extend(s["id"] for s in reads)
1324
+ continue
1325
+ if d >= self.cfg.loop_driver_depth or len(seen) >= self.cfg.loop_driver_nodes:
1326
+ continue
1327
+ for t in self._callees.get(f, ()):
1328
+ if t not in seen:
1329
+ seen[t] = (d + 1, unsure or bool(guessed.get((t, f))))
1330
+ todo.append(t)
1331
+ got = (found, level, unsure_any) if found else ()
1332
+ self._below[fid] = got
1333
+ return got or None
1334
+
1335
+ # ---- detail: does the loop variable reach the query --------------------------------
1336
+ def _flow(self, path, k: int, info: dict):
1337
+ """Names of path[0] (the query's function) that may derive from the loop of path[k]: a set, or None
1338
+ when a hop could not be read."""
1339
+ fns = self.ix.fns
1340
+ fk = fns[path[k]]
1341
+ seed = info.get("_seed") or set()
1342
+ top = k
1343
+ if not seed and info.get("form") == "callback" and k >= 1:
1344
+ # a function handed over by name (`xs.map(fetchOne)`): the item is its first parameter
1345
+ callee = fns[path[k - 1]]
1346
+ params, _ = self.params(callee)
1347
+ if not params or not params[0]:
1348
+ return None
1349
+ tainted, top = self._closure(callee, set(params[0])), k - 1
1350
+ elif not seed:
1351
+ return None if info.get("form") in ("unknown",) else set()
1352
+ else:
1353
+ tainted = self._closure(info.get("_fn") or fk, seed)
1354
+ lo, hi = info["_range"]
1355
+ for j in range(top, 0, -1):
1356
+ caller, callee = fns[path[j]], fns[path[j - 1]]
1357
+ if callee.lex is caller and callee.inline:
1358
+ tainted = self._closure(callee, tainted) # a closure sees its parent's names
1359
+ continue
1360
+ _, calls = self._detail(caller)
1361
+ names = self._call_names(callee)
1362
+ occ = [c for c in calls if c[1] in names]
1363
+ if j == k:
1364
+ occ = [c for c in occ if lo <= c[0] < hi] or occ
1365
+ if not occ:
1366
+ if callee.lex is caller:
1367
+ tainted = self._closure(callee, tainted)
1368
+ continue
1369
+ # handed over by name (`xs.map(fetchOne)`): the item is the first parameter
1370
+ params, _ = self.params(callee)
1371
+ if j == k and info.get("form") == "callback" and params:
1372
+ tainted = self._closure(callee, set(params[0]))
1373
+ continue
1374
+ # named but not called here (a table of functions, a callback argument): the call is somewhere
1375
+ # this does not follow, so only a parameter with the same name as a derived value is carried
1376
+ same = {n for p in params for n in p if n in tainted}
1377
+ if not same:
1378
+ return None
1379
+ tainted = self._closure(callee, same)
1380
+ continue
1381
+ params, recv_name = self.params(callee)
1382
+ nxt: set[str] = set()
1383
+ for _, _, recv, texts, kws in occ:
1384
+ shift = 0
1385
+ if callee.lang == "rust" and callee.method and not recv and len(texts) == len(params) + 1:
1386
+ shift = 1
1387
+ if _mentions(texts[0], tainted) and recv_name:
1388
+ nxt.add(recv_name)
1389
+ if recv and recv_name and _mentions(recv, tainted):
1390
+ nxt.add(recv_name)
1391
+ for i, text in enumerate(texts[shift:]):
1392
+ if not _mentions(text, tainted):
1393
+ continue
1394
+ kw = kws[i + shift]
1395
+ if kw:
1396
+ nxt.add(kw)
1397
+ elif params:
1398
+ nxt.update(params[min(i, len(params) - 1)])
1399
+ if callee.lex is caller:
1400
+ nxt |= tainted
1401
+ if not nxt:
1402
+ # at the loop's own call this is a fact (nothing of the item is handed down); further down the
1403
+ # names were lost on the way (a lookup, a field, a callback), which is not knowing
1404
+ return set() if j == top else None
1405
+ tainted = self._closure(callee, nxt)
1406
+ return tainted
1407
+
1408
+ def _site_text(self, s: dict) -> str:
1409
+ src = self._tree(s["file"])[0]
1410
+ if src is None:
1411
+ return s.get("expr") or ""
1412
+ a = self._line_byte(s["file"], s["line"])
1413
+ b = self._line_byte(s["file"], s.get("end_line", s["line"]) + 1)
1414
+ if b <= a:
1415
+ b = len(src)
1416
+ return src[a:b].decode("utf-8", "replace") + " " + (s.get("expr") or "")
1417
+
1418
+ def _site_pos(self, s: dict) -> int:
1419
+ """The byte the query's call starts at, as near as the site record says: its line, then its callee."""
1420
+ a = self._line_byte(s["file"], s["line"])
1421
+ src = self._tree(s["file"])[0]
1422
+ if src is None:
1423
+ return a
1424
+ b = self._line_byte(s["file"], s.get("end_line", s["line"]) + 1)
1425
+ if b <= a:
1426
+ b = len(src)
1427
+ line_end = src.find(b"\n", a)
1428
+ sink = (s.get("sink") or "").split("(")[0].strip()
1429
+ for needle in (sink, sink.split(".")[-1]):
1430
+ if needle:
1431
+ at = src.find(needle.encode(), a, b)
1432
+ if at >= 0:
1433
+ return at
1434
+ text = src[a: line_end if line_end >= 0 else len(src)]
1435
+ return a + (len(text) - len(text.lstrip()))
1436
+
1437
+ def _named_only(self, path, upto: int) -> int:
1438
+ """The first hop (1..upto) of a path where the caller names the function without calling it (a callback
1439
+ registered, a table of functions): 0 when every hop is a call. Such a hop says the function is reachable
1440
+ from there, not that it runs there."""
1441
+ fns = self.ix.fns
1442
+ for j in range(1, upto + 1):
1443
+ key = (path[j], path[j - 1])
1444
+ got = self._ref_hop.get(key)
1445
+ if got is None:
1446
+ caller, callee = fns[path[j]], fns[path[j - 1]]
1447
+ handed = any(self.file_loops[r[0]][r[1]].callback and self.file_loops[r[0]][r[1]].eb - self.file_loops[r[0]][r[1]].sb < 2
1448
+ for chain in self.chains(path[j], path[j - 1]) for r in chain)
1449
+ if callee.lex is caller or handed: # a closure, or `xs.map(fetchOne)`: the iterator calls it per item
1450
+ got = False
1451
+ else:
1452
+ try:
1453
+ names = self._call_names(callee)
1454
+ got = not any(c[1] in names for c in self._detail(caller)[1])
1455
+ except Exception:
1456
+ got = False
1457
+ self._ref_hop[key] = got
1458
+ if got:
1459
+ return j
1460
+ return 0
1461
+
1462
+ def _public(self, info: dict, hop: int, uses, unsure: bool, path=None) -> dict:
1463
+ out = {"hop": hop}
1464
+ out.update({k: v for k, v in info.items() if not k.startswith("_")})
1465
+ out["uses_loop_var"] = uses
1466
+ named = self._named_only(path, hop) if path is not None and hop else 0
1467
+ if named:
1468
+ out["named_not_called_at_hop"] = named
1469
+ if unsure or named:
1470
+ out["verified"] = False
1471
+ return out
1472
+
1473
+ def _uses(self, s: dict, path, k: int, info: dict, cache: dict | None = None, key=None):
1474
+ try:
1475
+ if cache is not None and key in cache:
1476
+ tainted = cache[key]
1477
+ else:
1478
+ tainted = self._flow(path, k, info)
1479
+ if cache is not None:
1480
+ cache[key] = tainted
1481
+ except Exception:
1482
+ if _debug():
1483
+ raise
1484
+ self.scan_errors += 1
1485
+ return None
1486
+ if tainted is None:
1487
+ return None
1488
+ if not tainted:
1489
+ return False
1490
+ if _mentions(self._site_text(s), tainted):
1491
+ return True
1492
+ return False if k <= 1 else None # far below the loop a miss is more often a lost name than a fact
1493
+
1494
+ def _own_loops(self, s: dict, fn) -> list[tuple[str, int]]:
1495
+ """Loops of the site's own function that hold the query, innermost first."""
1496
+ loops = self.file_loops.get(s["file"])
1497
+ if not loops or fn is None or s.get("kind") == "sql_file":
1498
+ return []
1499
+ pos = self._site_pos(s)
1500
+ if not (fn.sb <= pos < fn.eb):
1501
+ return []
1502
+ own = [(s["file"], i) for i in self._holding(loops, pos)
1503
+ if loops[i].sb >= fn.sb and loops[i].eb <= fn.eb and not (loops[i].sb == fn.sb and loops[i].eb == fn.eb)]
1504
+ if not own and s.get("in_loop") and any(lp.ex_sb <= pos < lp.ex_eb for lp in loops if lp.sb <= pos < lp.eb):
1505
+ s["loop_collection"] = True # the query is what a loop iterates over: it runs once, before the loop
1506
+ return own
1507
+
1508
+ # ---- output -----------------------------------------------------------------------
1509
+ def attach(self, s: dict, origin: dict, path) -> None:
1510
+ """`loop_context` of one listed origin: the loops of callers its path passes through (hop 1 and up), nearest first."""
1511
+ if not self.on or not path:
1512
+ return
1513
+ started = time.monotonic()
1514
+ try:
1515
+ guessed = self.ix.guessed
1516
+ out = []
1517
+ # the loops of the query's own function (hop 0) are the same on every path: they are listed once,
1518
+ # on the site, and an origin lists what its own path adds above them
1519
+ unsure = False
1520
+ for j in range(1, len(path)):
1521
+ unsure = unsure or bool(guessed.get((path[j - 1], path[j])))
1522
+ for ref in self.edge(path[j], path[j - 1]):
1523
+ info = self.loop_info(*ref)
1524
+ out.append(self._public(info, j, self._uses(s, path, j, info), unsure, path))
1525
+ if out:
1526
+ out.sort(key=by_relevance)
1527
+ if len(out) > self.cfg.max_loops: # the cap is a setting; the full number stays
1528
+ origin["loop_count"] = len(out)
1529
+ out = out[:self.cfg.max_loops]
1530
+ origin["loop_context"] = out
1531
+ except Exception:
1532
+ if _debug():
1533
+ raise
1534
+ self.scan_errors += 1
1535
+ self.seconds += time.monotonic() - started
1536
+
1537
+ def site(self, s: dict, fn, starts=()) -> None:
1538
+ """`loop_context`, `loop_count` and `loop_depth` of a site: every loop found above it, nearest first."""
1539
+ if not self.on:
1540
+ return
1541
+ started = time.monotonic()
1542
+ try:
1543
+ self._site(s, fn, starts)
1544
+ except Exception:
1545
+ if _debug():
1546
+ raise
1547
+ self.scan_errors += 1
1548
+ self.seconds += time.monotonic() - started
1549
+
1550
+ def _site(self, s: dict, fn, starts) -> None:
1551
+ fns = self.ix.fns
1552
+ out: list[dict] = []
1553
+ own: list[tuple[str, int]] = []
1554
+ seen_refs: set = set()
1555
+ framework = 0
1556
+ if fn is not None:
1557
+ own = self._own_loops(s, fn)
1558
+ for ref in own:
1559
+ info = self.loop_info(*ref)
1560
+ out.append(self._public(info, 0, self._uses(s, (fn.id,), 0, info), False))
1561
+ seen_refs.add(ref)
1562
+ if not own and _PER_ROW_NOTE.search((s.get("orm") or {}).get("notes") or ""):
1563
+ # no loop in the source: the translator saw a method a framework calls once per row of a list (a
1564
+ # serializer's field method, a GraphQL resolver). The loop is the framework's, so it is stated as a guess.
1565
+ out.append({"hop": 0, "file": s["file"], "line": s["line"], "function": s.get("symbol", ""), "kind": "per-item",
1566
+ "kind_basis": "a method the framework calls once per row", "form": "framework", "source": "framework",
1567
+ "uses_loop_var": True, "verified": False})
1568
+ framework = 1
1569
+ roots = [fn.id] if fn is not None and not fn.module else [i for i in starts if i is not None]
1570
+ if fn is not None and fn.module and fn.id in self._hits:
1571
+ roots.append(fn.id)
1572
+ hits = []
1573
+ for r in dict.fromkeys(roots):
1574
+ hits.extend(self._hits.get(r, ()))
1575
+ hits.sort(key=lambda h: (h[0], h[1], h[2]))
1576
+ total = len(own) + framework
1577
+ depth = len(own) + framework
1578
+ cache = self._flow_cache = getattr(self, "_flow_cache", {})
1579
+ # every loop above the site is described (a description is kept per loop), so that the ones listed are
1580
+ # the most relevant, not the first max_loops by distance; only the listed ones get the data-flow check
1581
+ kinds: Counter = Counter(info.get("kind", "unknown") for info in (self.loop_info(*ref) for ref in own))
1582
+ driven = sum(1 for ref in own if self.loop_info(*ref).get("source") == "query")
1583
+ if framework:
1584
+ kinds["per-item"] += 1
1585
+ found: list[tuple] = []
1586
+ for hop, unsure, ref, path in hits:
1587
+ if ref in seen_refs:
1588
+ continue
1589
+ seen_refs.add(ref)
1590
+ total += 1
1591
+ # the loops below this one on the same path: what it multiplies
1592
+ inner, nest = [], len(own) + 1
1593
+ for j in range(1, len(path)):
1594
+ chains = self.chains(path[j], path[j - 1])
1595
+ if j == len(path) - 1: # the loop's own function: only what is inside it there
1596
+ chain = next((ch for ch in chains if ref in ch), ())
1597
+ below = chain[:chain.index(ref)] if ref in chain else ()
1598
+ inner.extend(below)
1599
+ nest += len(below)
1600
+ elif chains: # two loops side by side in one function are both below, one deep
1601
+ inner.extend(dict.fromkeys(r for ch in chains for r in ch))
1602
+ nest += max(len(ch) for ch in chains)
1603
+ depth = max(depth, nest)
1604
+ info = self.loop_info(*ref)
1605
+ kinds[info.get("kind", "unknown")] += 1
1606
+ driven += info.get("source") == "query"
1607
+ found.append((relevance(info), hop, 0 if info.get("source") == "query" else 1, len(found), unsure, ref, path, inner))
1608
+ found.sort(key=lambda f: f[:4])
1609
+ # the query's own loops stay listed; the rest of the room goes to the most relevant loops of the callers
1610
+ for _, hop, _, _, unsure, ref, path, inner in found[:max(self.cfg.max_loops - len(out), 0)]:
1611
+ info = self.loop_info(*ref)
1612
+ rec = self._public(info, hop, self._uses(s, path, len(path) - 1, info, cache, (path, ref)), unsure, path)
1613
+ rec["path"] = [fns[i].symbol or fns[i].name for i in path]
1614
+ if any(fns[i].name in _CTOR_NAMES for i in path[:-1]):
1615
+ rec["note"] = "the path goes through a constructor: once per object built, which may be once per process"
1616
+ if inner or own:
1617
+ rec["inner"] = [f"{r[0]}:{self.file_loops[r[0]][r[1]].line}" for r in own + inner]
1618
+ out.append(rec)
1619
+ if len(cache) > 50000:
1620
+ cache.clear()
1621
+ if out:
1622
+ out.sort(key=by_relevance) # stable: equal loops keep the order found
1623
+ s["loop_context"] = out
1624
+ s["loop_count"] = total
1625
+ s["loop_depth"] = depth
1626
+ s["loop_summary"] = loop_summary(out[0], kinds, total, driven)
1627
+
1628
+ def summary(self, sites: list[dict]) -> dict:
1629
+ if not self.on:
1630
+ return {"enabled": False}
1631
+ live = [s for s in sites if not s.get("is_test")]
1632
+ with_ctx = [s for s in live if s.get("loop_context")]
1633
+ nearest = Counter()
1634
+ nearest_hops = Counter()
1635
+ relevant = Counter()
1636
+ any_kind = Counter()
1637
+ same_fn = Counter()
1638
+ depends = Counter()
1639
+ driven = 0
1640
+ for s in with_ctx:
1641
+ ctx = s["loop_context"] # most relevant first
1642
+ near = min(ctx, key=lambda c: c["hop"])
1643
+ nearest[near["kind"]] += 1
1644
+ nearest_hops[str(near["hop"])] += 1
1645
+ relevant[ctx[0]["kind"] + (" driven by a query" if ctx[0].get("source") == "query" else "")] += 1
1646
+ for k in {c["kind"] for c in ctx}:
1647
+ any_kind[k] += 1
1648
+ if any(c.get("driver") for c in ctx):
1649
+ driven += 1
1650
+ u = near.get("uses_loop_var")
1651
+ depends["yes" if u else ("unknown" if u is None else "no")] += 1
1652
+ for s in live:
1653
+ if s.get("in_loop"):
1654
+ own = [c for c in s.get("loop_context") or () if c["hop"] == 0]
1655
+ same_fn[own[0]["kind"] if own else ("is the loop's collection" if s.get("loop_collection") else "not located")] += 1
1656
+ return {
1657
+ "seconds": round(self.seconds, 1),
1658
+ "loops_in_source": sum(len(v) for v in self.file_loops.values()),
1659
+ "sites_with_loop_context": len(with_ctx),
1660
+ "sites_in_caller_loop_only": sum(1 for s in with_ctx if not s.get("in_loop") and min(c["hop"] for c in s["loop_context"]) > 0),
1661
+ "by_loop_depth": {str(k): v for k, v in sorted(Counter(s.get("loop_depth", 0) for s in live).items())},
1662
+ "by_nearest_hop": dict(sorted(nearest_hops.items(), key=lambda kv: int(kv[0]))),
1663
+ "by_nearest_kind": dict(nearest.most_common()),
1664
+ "by_most_relevant_kind": dict(relevant.most_common()), # what `loop_summary` and `loop_context[0]` show
1665
+ "by_kind": dict(any_kind.most_common()),
1666
+ "nearest_uses_loop_var": dict(depends.most_common()),
1667
+ "sites_driven_by_a_query": driven,
1668
+ "same_function_in_loop_by_kind": dict(same_fn.most_common()),
1669
+ "errors": self.scan_errors,
1670
+ "settings": {"loop_depth": self.cfg.loop_depth, "max_loops": self.cfg.max_loops},
1671
+ }