deixon-engine 0.2.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 (337) hide show
  1. deixon_engine/__init__.py +7 -0
  2. deixon_engine/alloy/__init__.py +0 -0
  3. deixon_engine/alloy/core.py +117 -0
  4. deixon_engine/alloy/text.py +171 -0
  5. deixon_engine/branches.py +1895 -0
  6. deixon_engine/catalogue/__init__.py +133 -0
  7. deixon_engine/catalogue/examples/access-control/bad.als +32 -0
  8. deixon_engine/catalogue/examples/access-control/good.als +40 -0
  9. deixon_engine/catalogue/examples/async-ordering/Bad.cfg +5 -0
  10. deixon_engine/catalogue/examples/async-ordering/Bad.tla +51 -0
  11. deixon_engine/catalogue/examples/async-ordering/Good.cfg +5 -0
  12. deixon_engine/catalogue/examples/async-ordering/Good.tla +52 -0
  13. deixon_engine/catalogue/examples/atomicity/Bad.cfg +4 -0
  14. deixon_engine/catalogue/examples/atomicity/Bad.tla +59 -0
  15. deixon_engine/catalogue/examples/atomicity/Good.cfg +4 -0
  16. deixon_engine/catalogue/examples/atomicity/Good.tla +59 -0
  17. deixon_engine/catalogue/examples/consensus/Bad.cfg +5 -0
  18. deixon_engine/catalogue/examples/consensus/Bad.tla +48 -0
  19. deixon_engine/catalogue/examples/consensus/Good.cfg +5 -0
  20. deixon_engine/catalogue/examples/consensus/Good.tla +47 -0
  21. deixon_engine/catalogue/examples/consistency-coherence/bad.als +22 -0
  22. deixon_engine/catalogue/examples/consistency-coherence/good.als +26 -0
  23. deixon_engine/catalogue/examples/constraint-satisfaction/bad.als +22 -0
  24. deixon_engine/catalogue/examples/constraint-satisfaction/good.als +23 -0
  25. deixon_engine/catalogue/examples/data-consistency/Bad.cfg +5 -0
  26. deixon_engine/catalogue/examples/data-consistency/Bad.tla +71 -0
  27. deixon_engine/catalogue/examples/data-consistency/Good.cfg +5 -0
  28. deixon_engine/catalogue/examples/data-consistency/Good.tla +70 -0
  29. deixon_engine/catalogue/examples/deadlock/Bad.cfg +7 -0
  30. deixon_engine/catalogue/examples/deadlock/Bad.tla +53 -0
  31. deixon_engine/catalogue/examples/deadlock/BadWaitCycle.cfg +6 -0
  32. deixon_engine/catalogue/examples/deadlock/Good.cfg +5 -0
  33. deixon_engine/catalogue/examples/deadlock/Good.tla +53 -0
  34. deixon_engine/catalogue/examples/hierarchy-containment/bad.als +21 -0
  35. deixon_engine/catalogue/examples/hierarchy-containment/good.als +25 -0
  36. deixon_engine/catalogue/examples/interleaving/Bad.cfg +5 -0
  37. deixon_engine/catalogue/examples/interleaving/Bad.tla +44 -0
  38. deixon_engine/catalogue/examples/interleaving/Good.cfg +5 -0
  39. deixon_engine/catalogue/examples/interleaving/Good.tla +39 -0
  40. deixon_engine/catalogue/examples/livelock/Bad.cfg +3 -0
  41. deixon_engine/catalogue/examples/livelock/Bad.tla +56 -0
  42. deixon_engine/catalogue/examples/livelock/Good.cfg +3 -0
  43. deixon_engine/catalogue/examples/livelock/Good.tla +57 -0
  44. deixon_engine/catalogue/examples/mutual-exclusion/Bad.cfg +4 -0
  45. deixon_engine/catalogue/examples/mutual-exclusion/Bad.tla +45 -0
  46. deixon_engine/catalogue/examples/mutual-exclusion/Good.cfg +4 -0
  47. deixon_engine/catalogue/examples/mutual-exclusion/Good.tla +40 -0
  48. deixon_engine/catalogue/examples/ordering-causality/Bad.cfg +4 -0
  49. deixon_engine/catalogue/examples/ordering-causality/Bad.tla +44 -0
  50. deixon_engine/catalogue/examples/ordering-causality/Good.cfg +4 -0
  51. deixon_engine/catalogue/examples/ordering-causality/Good.tla +44 -0
  52. deixon_engine/catalogue/examples/progress/Bad.cfg +4 -0
  53. deixon_engine/catalogue/examples/progress/Bad.tla +52 -0
  54. deixon_engine/catalogue/examples/progress/Good.cfg +4 -0
  55. deixon_engine/catalogue/examples/progress/Good.tla +50 -0
  56. deixon_engine/catalogue/examples/relational-properties/bad.als +21 -0
  57. deixon_engine/catalogue/examples/relational-properties/good.als +23 -0
  58. deixon_engine/catalogue/examples/replication/Bad.cfg +5 -0
  59. deixon_engine/catalogue/examples/replication/Bad.tla +67 -0
  60. deixon_engine/catalogue/examples/replication/Good.cfg +5 -0
  61. deixon_engine/catalogue/examples/replication/Good.tla +66 -0
  62. deixon_engine/catalogue/examples/responsiveness/Bad.cfg +6 -0
  63. deixon_engine/catalogue/examples/responsiveness/Bad.tla +58 -0
  64. deixon_engine/catalogue/examples/responsiveness/Good.cfg +6 -0
  65. deixon_engine/catalogue/examples/responsiveness/Good.tla +57 -0
  66. deixon_engine/catalogue/examples/sequential-invariant/Bad.cfg +4 -0
  67. deixon_engine/catalogue/examples/sequential-invariant/Bad.tla +51 -0
  68. deixon_engine/catalogue/examples/sequential-invariant/Good.cfg +4 -0
  69. deixon_engine/catalogue/examples/sequential-invariant/Good.tla +50 -0
  70. deixon_engine/catalogue/examples/termination/Bad.cfg +5 -0
  71. deixon_engine/catalogue/examples/termination/Bad.tla +49 -0
  72. deixon_engine/catalogue/examples/termination/Good.cfg +5 -0
  73. deixon_engine/catalogue/examples/termination/Good.tla +48 -0
  74. deixon_engine/catalogue/meta_patterns.yaml +453 -0
  75. deixon_engine/checker/__init__.py +0 -0
  76. deixon_engine/checker/alloy.py +144 -0
  77. deixon_engine/checker/apalache.py +303 -0
  78. deixon_engine/checker/graph.py +130 -0
  79. deixon_engine/checker/process.py +317 -0
  80. deixon_engine/checker/tlc.py +290 -0
  81. deixon_engine/compose/__init__.py +1 -0
  82. deixon_engine/compose/check.py +90 -0
  83. deixon_engine/compose/composition.py +152 -0
  84. deixon_engine/compose/interfaces.py +563 -0
  85. deixon_engine/confirm.py +10119 -0
  86. deixon_engine/confirm_alloy.py +505 -0
  87. deixon_engine/confirm_go.py +21 -0
  88. deixon_engine/confirm_java.py +449 -0
  89. deixon_engine/confirm_node.py +131 -0
  90. deixon_engine/datamodel/__init__.py +1 -0
  91. deixon_engine/datamodel/model.py +333 -0
  92. deixon_engine/datamodel/schema.py +311 -0
  93. deixon_engine/deploy/__init__.py +1 -0
  94. deixon_engine/deploy/answers.py +587 -0
  95. deixon_engine/deploy/blanket.py +308 -0
  96. deixon_engine/deploy/effects.py +1033 -0
  97. deixon_engine/deploy/go_build.py +223 -0
  98. deixon_engine/deploy/go_usage.py +120 -0
  99. deixon_engine/deploy/infer.py +1095 -0
  100. deixon_engine/deploy/java_build.py +446 -0
  101. deixon_engine/deploy/java_options.py +152 -0
  102. deixon_engine/deploy/java_usage.py +138 -0
  103. deixon_engine/deploy/model.py +535 -0
  104. deixon_engine/deploy/node_build.py +248 -0
  105. deixon_engine/deploy/node_usage.py +90 -0
  106. deixon_engine/deploy/options.py +628 -0
  107. deixon_engine/deploy/store.py +239 -0
  108. deixon_engine/deploy/temporal.py +349 -0
  109. deixon_engine/deploy/usage.py +437 -0
  110. deixon_engine/diagnostics/__init__.py +15 -0
  111. deixon_engine/diagnostics/bundle.py +156 -0
  112. deixon_engine/diagnostics/github.py +187 -0
  113. deixon_engine/diagnostics/redact.py +194 -0
  114. deixon_engine/diagnostics/verify.py +93 -0
  115. deixon_engine/driver/__init__.py +26 -0
  116. deixon_engine/driver/__main__.py +73 -0
  117. deixon_engine/driver/backing.py +241 -0
  118. deixon_engine/driver/decisions.py +98 -0
  119. deixon_engine/driver/envelope.py +314 -0
  120. deixon_engine/driver/identity.py +93 -0
  121. deixon_engine/driver/keys.py +60 -0
  122. deixon_engine/elicitations.py +162 -0
  123. deixon_engine/errors.py +87 -0
  124. deixon_engine/evidence.py +51 -0
  125. deixon_engine/facts/__init__.py +5 -0
  126. deixon_engine/facts/contract.py +229 -0
  127. deixon_engine/facts/go_patterns.py +215 -0
  128. deixon_engine/facts/java_patterns.py +883 -0
  129. deixon_engine/facts/pyemit.py +141 -0
  130. deixon_engine/facts/raw.py +1644 -0
  131. deixon_engine/falsify.py +306 -0
  132. deixon_engine/forge/__init__.py +1 -0
  133. deixon_engine/forge/analysis.py +258 -0
  134. deixon_engine/forge/begin.py +128 -0
  135. deixon_engine/forge/behaviour.py +292 -0
  136. deixon_engine/forge/compose.py +146 -0
  137. deixon_engine/forge/done.py +32 -0
  138. deixon_engine/forge/features.py +44 -0
  139. deixon_engine/forge/frozen.py +115 -0
  140. deixon_engine/forge/inputs.py +300 -0
  141. deixon_engine/forge/ledger.py +100 -0
  142. deixon_engine/forge/nfr.py +235 -0
  143. deixon_engine/forge/questions.py +189 -0
  144. deixon_engine/forge/readings.py +637 -0
  145. deixon_engine/forge/requirements.py +151 -0
  146. deixon_engine/forge/scenarios.py +225 -0
  147. deixon_engine/forge/slices.py +101 -0
  148. deixon_engine/gates.py +297 -0
  149. deixon_engine/gitexport.py +31 -0
  150. deixon_engine/guard/__init__.py +3 -0
  151. deixon_engine/guard/canonical.py +343 -0
  152. deixon_engine/guard/go_canonical.py +128 -0
  153. deixon_engine/guard/hook.py +437 -0
  154. deixon_engine/guard/java_canonical.py +156 -0
  155. deixon_engine/guard/jit.py +889 -0
  156. deixon_engine/guard/node_canonical.py +211 -0
  157. deixon_engine/guard/rank.py +85 -0
  158. deixon_engine/guard/tokencanon.py +139 -0
  159. deixon_engine/index/__init__.py +1 -0
  160. deixon_engine/index/concurrency.py +12705 -0
  161. deixon_engine/index/django.py +584 -0
  162. deixon_engine/index/go.py +138 -0
  163. deixon_engine/index/go_cache.py +57 -0
  164. deixon_engine/index/go_ranges.py +78 -0
  165. deixon_engine/index/go_types.py +38 -0
  166. deixon_engine/index/guards.py +442 -0
  167. deixon_engine/index/java.py +128 -0
  168. deixon_engine/index/java_cache.py +59 -0
  169. deixon_engine/index/java_ranges.py +119 -0
  170. deixon_engine/index/node.py +88 -0
  171. deixon_engine/index/node_cache.py +75 -0
  172. deixon_engine/index/node_extract.py +2996 -0
  173. deixon_engine/index/node_ranges.py +45 -0
  174. deixon_engine/index/patterns.py +3093 -0
  175. deixon_engine/index/process_sharing.py +1915 -0
  176. deixon_engine/index/py2.py +688 -0
  177. deixon_engine/index/python.py +1481 -0
  178. deixon_engine/index/rawcache.py +283 -0
  179. deixon_engine/index/signal_masks.py +679 -0
  180. deixon_engine/index/sqla.py +363 -0
  181. deixon_engine/index/srccount.py +45 -0
  182. deixon_engine/index/start_sharing.py +897 -0
  183. deixon_engine/index/structure.py +349 -0
  184. deixon_engine/index/tree.py +27 -0
  185. deixon_engine/integrations/__init__.py +3 -0
  186. deixon_engine/integrations/egm.py +257 -0
  187. deixon_engine/integrations/record.py +107 -0
  188. deixon_engine/integrations/sdd.py +92 -0
  189. deixon_engine/layout.py +472 -0
  190. deixon_engine/lints/__init__.py +0 -0
  191. deixon_engine/lints/alloy.py +142 -0
  192. deixon_engine/lints/findings.py +14 -0
  193. deixon_engine/lints/tla.py +1086 -0
  194. deixon_engine/loopdecl.py +50 -0
  195. deixon_engine/mcp/__init__.py +0 -0
  196. deixon_engine/mcp/__main__.py +3 -0
  197. deixon_engine/mcp/cli.py +263 -0
  198. deixon_engine/mcp/server.py +4232 -0
  199. deixon_engine/mcp/skills.py +60 -0
  200. deixon_engine/mcp/text_forms.py +230 -0
  201. deixon_engine/mcp/tty_prompt.py +86 -0
  202. deixon_engine/memguard.py +164 -0
  203. deixon_engine/outline.py +264 -0
  204. deixon_engine/platform/Cache_CAS.tla +34 -0
  205. deixon_engine/platform/Cache_TTL_NoCAS.tla +37 -0
  206. deixon_engine/platform/Db_AsyncReplicaRead.tla +36 -0
  207. deixon_engine/platform/Db_ReadCommitted.tla +56 -0
  208. deixon_engine/platform/Db_Serializable.tla +48 -0
  209. deixon_engine/platform/Db_SyncReplicaRead.tla +30 -0
  210. deixon_engine/platform/Deploy_Recreate.tla +25 -0
  211. deixon_engine/platform/LIBRARY.json +13 -0
  212. deixon_engine/platform/Pod_CrashRestart.tla +34 -0
  213. deixon_engine/platform/Pod_Stable.tla +30 -0
  214. deixon_engine/platform/Queue_AtLeastOnce.tla +37 -0
  215. deixon_engine/platform/Queue_AtMostOnce.tla +34 -0
  216. deixon_engine/platform/Queue_OrderedPerPartition.tla +29 -0
  217. deixon_engine/platform/Queue_Unordered.tla +28 -0
  218. deixon_engine/platform/RollingDeploy_TwoVersions.tla +25 -0
  219. deixon_engine/platform/Session_LocalMemory.tla +35 -0
  220. deixon_engine/platform/Session_Sticky.tla +32 -0
  221. deixon_engine/platform/probes/CacheLostUpdate.cfg +4 -0
  222. deixon_engine/platform/probes/CacheLostUpdate.tla +48 -0
  223. deixon_engine/platform/probes/CrashLoss.cfg +5 -0
  224. deixon_engine/platform/probes/CrashLoss.tla +47 -0
  225. deixon_engine/platform/probes/DuplicateDelivery.cfg +4 -0
  226. deixon_engine/platform/probes/DuplicateDelivery.tla +48 -0
  227. deixon_engine/platform/probes/LostSession.cfg +4 -0
  228. deixon_engine/platform/probes/LostSession.tla +39 -0
  229. deixon_engine/platform/probes/LostUpdate.cfg +4 -0
  230. deixon_engine/platform/probes/LostUpdate.tla +49 -0
  231. deixon_engine/platform/probes/MixedVersions.cfg +4 -0
  232. deixon_engine/platform/probes/MixedVersions.tla +51 -0
  233. deixon_engine/platform/probes/OutOfOrder.cfg +3 -0
  234. deixon_engine/platform/probes/OutOfOrder.tla +45 -0
  235. deixon_engine/platform/probes/StaleRead.cfg +3 -0
  236. deixon_engine/platform/probes/StaleRead.tla +43 -0
  237. deixon_engine/platform_library.py +92 -0
  238. deixon_engine/prereqs.py +34 -0
  239. deixon_engine/progress.py +392 -0
  240. deixon_engine/queries.py +1404 -0
  241. deixon_engine/registry/__init__.py +14 -0
  242. deixon_engine/registry/folder.py +277 -0
  243. deixon_engine/render.py +44 -0
  244. deixon_engine/repro.py +2778 -0
  245. deixon_engine/repro_java.py +214 -0
  246. deixon_engine/review/__init__.py +1 -0
  247. deixon_engine/review/decisions.py +117 -0
  248. deixon_engine/review/diff.py +598 -0
  249. deixon_engine/review/implications.py +213 -0
  250. deixon_engine/review/lazy.py +44 -0
  251. deixon_engine/review/preconditions.py +108 -0
  252. deixon_engine/review/report.py +79 -0
  253. deixon_engine/review/stale.py +38 -0
  254. deixon_engine/review/touched.py +185 -0
  255. deixon_engine/sharing.py +107 -0
  256. deixon_engine/skeleton/__init__.py +1 -0
  257. deixon_engine/skeleton/alloy.py +552 -0
  258. deixon_engine/skeleton/extract.py +374 -0
  259. deixon_engine/skeleton/extract_ts.py +1282 -0
  260. deixon_engine/skeleton/tagged_forms.py +409 -0
  261. deixon_engine/skeleton/tla.py +2469 -0
  262. deixon_engine/skills/alloy-authoring.md +51 -0
  263. deixon_engine/skills/bot-team.md +46 -0
  264. deixon_engine/skills/change-guard.md +96 -0
  265. deixon_engine/skills/first-look.md +494 -0
  266. deixon_engine/skills/model-slice.md +794 -0
  267. deixon_engine/skills/refine-requirements.md +268 -0
  268. deixon_engine/skills/report-issue.md +44 -0
  269. deixon_engine/skills/review-diff.md +128 -0
  270. deixon_engine/skills/start.md +58 -0
  271. deixon_engine/skills/workflow.md +80 -0
  272. deixon_engine/survey/__init__.py +1 -0
  273. deixon_engine/survey/bundles.py +274 -0
  274. deixon_engine/survey/census.py +1605 -0
  275. deixon_engine/survey/coverage.py +232 -0
  276. deixon_engine/survey/diffmap.py +86 -0
  277. deixon_engine/survey/gate.py +182 -0
  278. deixon_engine/survey/hunt.py +79 -0
  279. deixon_engine/survey/intent.py +125 -0
  280. deixon_engine/survey/markers.py +488 -0
  281. deixon_engine/survey/miner.py +217 -0
  282. deixon_engine/survey/overlay.py +46 -0
  283. deixon_engine/survey/policy.py +307 -0
  284. deixon_engine/survey/refutations.py +95 -0
  285. deixon_engine/survey/report.py +799 -0
  286. deixon_engine/survey/slices.py +3585 -0
  287. deixon_engine/survey/store.py +90 -0
  288. deixon_engine/testgen/__init__.py +1 -0
  289. deixon_engine/testgen/model_tests.py +190 -0
  290. deixon_engine/tla/__init__.py +0 -0
  291. deixon_engine/tla/cfg.py +155 -0
  292. deixon_engine/tla/text.py +308 -0
  293. deixon_engine/tla/values.py +121 -0
  294. deixon_engine/tools/AlloyRunner.java +113 -0
  295. deixon_engine/tools/PROVENANCE.md +48 -0
  296. deixon_engine/tools/dx-java-extract.jar +0 -0
  297. deixon_engine/tools/fetch.py +156 -0
  298. deixon_engine/tools/go-extract/go.mod +10 -0
  299. deixon_engine/tools/go-extract/go.sum +8 -0
  300. deixon_engine/tools/go-extract/guards.go +98 -0
  301. deixon_engine/tools/go-extract/locks.go +205 -0
  302. deixon_engine/tools/go-extract/main.go +584 -0
  303. deixon_engine/tools/go-extract/resolve.go +411 -0
  304. deixon_engine/tools/go-extract/stmts.go +452 -0
  305. deixon_engine/tools/go-extract/walk.go +423 -0
  306. deixon_engine/tools/jars.yaml +26 -0
  307. deixon_engine/trace/__init__.py +0 -0
  308. deixon_engine/trace/points.py +288 -0
  309. deixon_engine/trace/tags.py +208 -0
  310. deixon_engine/tutorial.py +308 -0
  311. deixon_engine/verdict.py +51 -0
  312. deixon_engine/workflow/__init__.py +6 -0
  313. deixon_engine/workflow/active.py +121 -0
  314. deixon_engine/workflow/archive.py +67 -0
  315. deixon_engine/workflow/binding.py +238 -0
  316. deixon_engine/workflow/bugfix.py +29 -0
  317. deixon_engine/workflow/carry.py +359 -0
  318. deixon_engine/workflow/drift.py +436 -0
  319. deixon_engine/workflow/grounding.py +221 -0
  320. deixon_engine/workflow/handoff.py +85 -0
  321. deixon_engine/workflow/hook.py +105 -0
  322. deixon_engine/workflow/questions.py +73 -0
  323. deixon_engine/workflow/recover.py +243 -0
  324. deixon_engine/workflow/resolution.py +97 -0
  325. deixon_engine/workflow/s3e.py +95 -0
  326. deixon_engine/workflow/split.py +674 -0
  327. deixon_engine/workflow/waivers.py +67 -0
  328. deixon_engine-0.2.0.dist-info/METADATA +201 -0
  329. deixon_engine-0.2.0.dist-info/RECORD +337 -0
  330. deixon_engine-0.2.0.dist-info/WHEEL +5 -0
  331. deixon_engine-0.2.0.dist-info/licenses/LICENSE +202 -0
  332. deixon_engine-0.2.0.dist-info/licenses/NOTICE +31 -0
  333. deixon_engine-0.2.0.dist-info/top_level.txt +2 -0
  334. dxshim/__init__.py +1 -0
  335. dxshim/gil.py +875 -0
  336. dxshim/loopsched.py +1031 -0
  337. dxshim/scheduler.py +895 -0
@@ -0,0 +1,1895 @@
1
+ """Branch notes and branch checks in static confirmation.
2
+
3
+ For each located step of a counterexample, the model's guard (the action's unprimed top-level conjuncts over modelled
4
+ variables, ``pc`` aside) is set beside the code's guards at the step's location (``CodeQueries.guards``). Where they
5
+ read different fields, a note says so. The notes report; they decide nothing: ``Confirmation.branch_notes`` is
6
+ outside the id hash and no verdict reads it. Shared by ``confirm`` (Python) and ``confirm_java``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+
13
+ from .index.guards import _dotted as _ast_dotted
14
+ from .tla.text import top_level_conjuncts
15
+
16
+
17
+ def _field(name: str) -> str:
18
+ """A read as a field's simple name: ``self.x``, ``this.x`` and ``x`` all name ``x``."""
19
+ return name.rsplit(".", 1)[-1]
20
+
21
+
22
+ def _mapped_fields(mod, pc_var: str) -> dict[str, set[str]]:
23
+ """Module variable -> its @code fields' simple names (non-ghost, tagged only)."""
24
+ kinds = mod.variable_kinds()
25
+ tags = mod.declaration_tags
26
+ out: dict[str, set[str]] = {}
27
+ for v in mod.variables:
28
+ if v == pc_var or kinds.get(v) == ["ghost"]:
29
+ continue
30
+ refs = tags.get(v, (0, None))[1]
31
+ names = {_field(r) for r in (refs.code if refs is not None else [])}
32
+ if names:
33
+ out[v] = names
34
+ return out
35
+
36
+
37
+ def _mapped_owner(mod, pc_var: str) -> dict[str, list[str]]:
38
+ """Field simple name -> module variables mapped to it (inverted ``_mapped_fields``)."""
39
+ owner: dict[str, list[str]] = {}
40
+ for v, fs in _mapped_fields(mod, pc_var).items():
41
+ for f in fs:
42
+ owner.setdefault(f, []).append(v)
43
+ return owner
44
+
45
+
46
+ def _spec_constrained_fields(mod, action: str, pc_var: str) -> set[str]:
47
+ """Fields an action's guard conjuncts constrain (model side)."""
48
+ fields_of = _mapped_fields(mod, pc_var)
49
+ out: set[str] = set()
50
+ for _, vs in _model_guard(mod, action, pc_var):
51
+ for v in vs:
52
+ out |= fields_of.get(v, set())
53
+ return out
54
+
55
+
56
+ def _model_guard(mod, action: str, pc_var: str) -> list[tuple[str, set[str]]]:
57
+ """(conjunct, the module variables it reads) for each guard conjunct of ``action``: unprimed, no ``pc_var``."""
58
+ d = mod.definitions.get(action)
59
+ if d is None:
60
+ return []
61
+ out = []
62
+ for part in top_level_conjuncts(d.body):
63
+ if "'" in part or "UNCHANGED" in part or re.search(rf"\b{re.escape(pc_var)}\b", part):
64
+ continue
65
+ vs = {v for v in mod.variables if re.search(rf"\b{re.escape(v)}\b", part)}
66
+ if vs:
67
+ out.append((re.sub(r"\s+", " ", part).strip(), vs))
68
+ return out
69
+
70
+
71
+ def branch_notes(q, mod, steps, located, *, pc_var: str = "pc") -> dict:
72
+ """``{"notes": [...], "located": n, "unlocated": m}``: the module docstring's notes for ``steps`` (``confirm``'s
73
+ ``_Step`` rows: ``k``, ``thread``, ``step``, ``action``), ``located(step) -> (file, line, function) | None``."""
74
+ fields_of = _mapped_fields(mod, pc_var)
75
+ modelled = set().union(*fields_of.values()) if fields_of else set()
76
+ notes, n_located, n_unlocated = [], 0, 0
77
+ seen = set()
78
+ for st in steps:
79
+ where = located(st.step)
80
+ if where is None or not hasattr(q, "guards"):
81
+ n_unlocated += 1
82
+ continue
83
+ n_located += 1
84
+ _, line, fn = where
85
+ try:
86
+ code = q.guards(fn, line)
87
+ except NotImplementedError:
88
+ n_unlocated += 1
89
+ continue
90
+ code_fields = [(g, {_field(r) for r in g.reads} & modelled) for g in code]
91
+ read_by_code = set().union(*(fs for _, fs in code_fields)) if code_fields else set()
92
+ model = _model_guard(mod, st.action, pc_var)
93
+ constrained = set()
94
+ for conj, vs in model:
95
+ for v in sorted(vs):
96
+ fs = fields_of.get(v)
97
+ if not fs:
98
+ continue
99
+ constrained |= fs
100
+ if not fs & read_by_code and (st.action, v, "model") not in seen:
101
+ seen.add((st.action, v, "model"))
102
+ notes.append({"step": st.k, "action": st.action, "status": "model-only", "variable": v,
103
+ "fields": sorted(fs), "conjunct": conj})
104
+ for g, fs in code_fields:
105
+ extra = sorted(fs - constrained)
106
+ if extra and (st.action, g.text, "code") not in seen:
107
+ seen.add((st.action, g.text, "code"))
108
+ notes.append({"step": st.k, "action": st.action, "status": "code-only", "guard": g.text,
109
+ "kind": g.kind, "fields": extra})
110
+ return {"notes": notes, "located": n_located, "unlocated": n_unlocated}
111
+
112
+
113
+ # -- refuting a branch the code cannot take ---------------------------------------------------------------
114
+
115
+ def _bool_test(text: str, names: set[str]) -> bool | None:
116
+ """The polarity of a Boolean test over one field: True when the test is the field itself (``x``, ``x == true``,
117
+ ``x is True``, ``x != false``), False when it is its negation; None for any other form."""
118
+ t = re.sub(r"\s+", " ", text.strip())
119
+ while t.startswith("(") and t.endswith(")"):
120
+ t = t[1:-1].strip()
121
+ alt = "|".join(re.escape(n) for n in sorted(names, key=len, reverse=True))
122
+ m = re.fullmatch(rf"(!\s*|not\s+)?({alt})(?:\s*(==|!=|is not|is)\s*(true|false|True|False))?", t)
123
+ if not m:
124
+ return None
125
+ pos = m.group(1) is None
126
+ if m.group(3):
127
+ lit = m.group(4).lower() == "true"
128
+ same = m.group(3) in ("==", "is")
129
+ pos = pos == (lit == same)
130
+ return pos
131
+
132
+
133
+ # integer comparisons under a domain check
134
+
135
+ _OPS = {"==": lambda a, b: a == b, "!=": lambda a, b: a != b, "<": lambda a, b: a < b,
136
+ "<=": lambda a, b: a <= b, ">": lambda a, b: a > b, ">=": lambda a, b: a >= b}
137
+ _FLIP = {"<": ">", "<=": ">=", ">": "<", ">=": "<=", "==": "==", "!=": "!="}
138
+
139
+
140
+ def _int_test(text: str, names: set[str]) -> tuple[str, int] | None:
141
+ """``(op, c)`` for an integer comparison of one field with a literal, read as ``x op c`` (a reversed
142
+ ``c op x`` is flipped); None for any other form."""
143
+ t = re.sub(r"\s+", " ", text.strip())
144
+ while t.startswith("(") and t.endswith(")"):
145
+ t = t[1:-1].strip()
146
+ alt = "|".join(re.escape(n) for n in sorted(names, key=len, reverse=True))
147
+ op = r"(==|!=|<=|>=|<|>)"
148
+ m = re.fullmatch(rf"(?:{alt}) ?{op} ?(-?\d+)", t)
149
+ if m:
150
+ return m.group(1), int(m.group(2))
151
+ m = re.fullmatch(rf"(-?\d+) ?{op} ?(?:{alt})", t)
152
+ if m:
153
+ return _FLIP[m.group(2)], int(m.group(1))
154
+ return None
155
+
156
+
157
+ def _in_domain(spec_text: str, v: str, c: int) -> bool:
158
+ """The integer comparison's domain check: the spec compares or sets ``v`` against the literal ``c``, either way round."""
159
+ op = r"(?:=<|<=|>=|/=|\\leq|\\geq|[=#<>])"
160
+ lit = re.escape(str(c))
161
+ return re.search(rf"(?<![\w']){re.escape(v)}'?\s*{op}\s*{lit}(?![\w.])", spec_text) is not None or \
162
+ re.search(rf"(?<![\w.]){lit}\s*{op}\s*{re.escape(v)}(?![\w])", spec_text) is not None
163
+
164
+
165
+ def _anchored(q, steps, located):
166
+ """(step, here, there, fn, guards) for steps anchored at a test line whose thread's next located step
167
+ is decided by guards: ``branch_checks``' shape, shared by the anchored checks without touching it."""
168
+ for i, st in enumerate(steps):
169
+ here = located(st.step)
170
+ nxt = next((s for s in steps[i + 1:] if s.thread == st.thread), None)
171
+ there = located(nxt.step) if nxt is not None else None
172
+ if here is None or there is None or here[2] != there[2] or not hasattr(q, "guards"):
173
+ continue
174
+ _, line, fn = here
175
+ try:
176
+ gs = q.guards(fn, there[1])
177
+ except NotImplementedError:
178
+ continue
179
+ yield st, here, there, fn, gs
180
+
181
+
182
+ def branch_checks(q, mod, steps, located, trace, *, pc_var: str = "pc") -> list:
183
+ """A refuted ``branch`` check for each step anchored at a Boolean guard's test line, whose thread's next
184
+ located step lies in the guarded lines, taken from a state where the test fails. It also takes an
185
+ integer comparison with a literal the spec itself compares or sets the variable against. Nothing otherwise:
186
+ every other case is left to the other checks."""
187
+ from .confirm import Check
188
+ owner = _mapped_owner(mod, pc_var)
189
+ out = []
190
+ for i, st in enumerate(steps):
191
+ here = located(st.step)
192
+ nxt = next((s for s in steps[i + 1:] if s.thread == st.thread), None)
193
+ there = located(nxt.step) if nxt is not None else None
194
+ if here is None or there is None or here[2] != there[2] or not hasattr(q, "guards"):
195
+ continue
196
+ _, line, fn = here
197
+ try:
198
+ gs = q.guards(fn, there[1])
199
+ except NotImplementedError:
200
+ continue
201
+ for g in gs:
202
+ # a read that is only another read's receiver (``self`` of ``self.closed``) is not a second name
203
+ reads = [r for r in g.reads if not any(o.startswith(r + ".") for o in g.reads)]
204
+ if g.line != line or g.calls or len(reads) != 1:
205
+ continue
206
+ fld = _field(reads[0])
207
+ vs = owner.get(fld, [])
208
+ if len(vs) != 1:
209
+ continue
210
+ spellings = {reads[0], fld, f"this.{fld}", f"self.{fld}"}
211
+ want = _bool_test(g.text, spellings)
212
+ cmp = _int_test(g.text, spellings) if want is None else None
213
+ if want is None and (cmp is None or not _in_domain(mod.code, vs[0], cmp[1])):
214
+ continue
215
+ # the state the step is taken from (its PRE-state; ``st.state`` numbers the state after it)
216
+ pre = _trace_value(trace, st)
217
+ if vs[0] not in pre:
218
+ continue
219
+ val = str(pre[vs[0]]).strip()
220
+ if want is not None:
221
+ if val not in ("TRUE", "FALSE"):
222
+ continue
223
+ holds = (val == "TRUE") == want # the test's value in that state
224
+ else:
225
+ if not re.fullmatch(r"-?\d+", val):
226
+ continue
227
+ holds = _OPS[cmp[0]](int(val), cmp[1]) # the comparison's value in that state
228
+ if holds != g.polarity:
229
+ out.append(Check("branch", "refuted",
230
+ f"step {st.k} ({st.thread} {st.action}) runs the test `{g.text}` at {here[0]}:{line} "
231
+ f"and goes on to {there[0]}:{there[1]}, which the code reaches only when the test is "
232
+ f"{g.polarity}; in the state the step is taken from, {vs[0]} = {val}, so it is "
233
+ f"{holds}: the code cannot take this step in this state",
234
+ {"step": st.k, "variable": vs[0], "guard": g.text}))
235
+ return out
236
+
237
+
238
+ # -- anchored multi-name tests (refuting, branch_checks' standard) ------------------------------------
239
+
240
+ def _strip_bool_wrapping(text: str) -> tuple[int, str]:
241
+ """Strip outer parens and leading ``not``/``!`` (counted): (negations, core)."""
242
+ t = text.strip()
243
+ while t.startswith("(") and t.endswith(")"):
244
+ t = t[1:-1].strip()
245
+ negs = 0
246
+ while True:
247
+ m = re.match(r"(?:not(?=[\s(])|!)\s*", t)
248
+ if not m:
249
+ break
250
+ negs += 1
251
+ t = t[m.end():].strip()
252
+ while t.startswith("(") and t.endswith(")"):
253
+ t = t[1:-1].strip()
254
+ return negs, t
255
+
256
+
257
+ def _split_top_and(text: str) -> tuple[int, list[str]] | None:
258
+ """Top-level ``and``/``&&`` split: (negations, parts), or None when a top-level ``or``/``||``
259
+ appears (disjunctions are out of scope: abstain). Quote- and paren-aware."""
260
+ negs, t = _strip_bool_wrapping(text)
261
+ parts, depth, cur, quote = [], 0, "", None
262
+ i = 0
263
+ while i < len(t):
264
+ ch = t[i]
265
+ if quote is not None:
266
+ cur += ch
267
+ if ch == quote and t[i - 1] != "\\":
268
+ quote = None
269
+ i += 1
270
+ continue
271
+ if ch in "\"'":
272
+ quote, cur, i = ch, cur + ch, i + 1
273
+ continue
274
+ if ch in "([{":
275
+ depth, cur, i = depth + 1, cur + ch, i + 1
276
+ continue
277
+ if ch in ")]}":
278
+ depth, cur, i = depth - 1, cur + ch, i + 1
279
+ continue
280
+ if depth == 0:
281
+ m = re.match(r"(&&|\band\b)", t[i:])
282
+ if m:
283
+ parts.append(cur)
284
+ cur, i = "", i + m.end()
285
+ continue
286
+ if re.match(r"(\|\||\bor\b)", t[i:]):
287
+ return None
288
+ cur += ch
289
+ i += 1
290
+ parts.append(cur)
291
+ return negs, [p.strip() for p in parts]
292
+
293
+
294
+ def _mapped_vars(q, fn: str, g, owner: dict) -> list:
295
+ """(read, field, var) for the guard's reads that resolve to state mapped 1:1. Locals,
296
+ parameters and unmapped names drop out here (never bare-matched to fields: a bare
297
+ `status` parameter is not the `status` field)."""
298
+ out = []
299
+ for r in _mapped_reads(q, fn, g, set(owner)):
300
+ vs = owner.get(_field(r), [])
301
+ if len(vs) == 1:
302
+ out.append((r, _field(r), vs[0]))
303
+ return out
304
+
305
+
306
+ def _conjunct_value(part: str, mapped: list, mod, pre: dict):
307
+ """(field, var, value) for one conjunct that is a decidable one-field test over the
308
+ mapped reads, else None. The field must be the only one whose spellings parse the part
309
+ (ambiguity abstains)."""
310
+ hits = []
311
+ for read, fld, var in mapped:
312
+ spellings = {read, f"this.{fld}", f"self.{fld}"}
313
+ want = _bool_test(part, spellings)
314
+ cmp = _int_test(part, spellings) if want is None else None
315
+ if want is None and (cmp is None or not _in_domain(mod.code, var, cmp[1])):
316
+ continue
317
+ if var not in pre:
318
+ return None # mapped but unvalued: the whole test abstains
319
+ val = str(pre[var]).strip()
320
+ if want is not None:
321
+ if val not in ("TRUE", "FALSE"):
322
+ return None
323
+ hits.append((fld, var, (val == "TRUE") == want))
324
+ else:
325
+ if not re.fullmatch(r"-?\d+", val):
326
+ return None
327
+ hits.append((fld, var, _OPS[cmp[0]](int(val), cmp[1])))
328
+ return hits[0] if len(hits) == 1 else None
329
+
330
+
331
+ def conjunct_checks(q, mod, steps, located, trace, *, pc_var: str = "pc") -> list:
332
+ """Like ``branch_checks``, but the anchored test is a top-level conjunction over two or more
333
+ mapped fields. Every conjunct must be a decidable one-field test; one false conjunct decides
334
+ False. Disjunctions, nested conjunctions and calls abstain."""
335
+ from .confirm import Check
336
+ owner = _mapped_owner(mod, pc_var)
337
+ out = []
338
+ for st, here, there, fn, gs in _anchored(q, steps, located):
339
+ _, line, _ = here
340
+ for g in gs:
341
+ reads = [r for r in g.reads if not any(o.startswith(r + ".") for o in g.reads)]
342
+ if g.line != line or g.calls or len(reads) < 2:
343
+ continue
344
+ split = _split_top_and(g.text)
345
+ if split is None:
346
+ continue
347
+ negs, parts = split
348
+ if len(parts) < 2:
349
+ continue
350
+ pre = _trace_value(trace, st)
351
+ mapped = _mapped_vars(q, fn, g, owner)
352
+ vals = []
353
+ for part in parts:
354
+ hit = _conjunct_value(part, mapped, mod, pre)
355
+ if hit is None:
356
+ break
357
+ vals.append(hit)
358
+ else:
359
+ value = all(v for _, _, v in vals)
360
+ if negs % 2:
361
+ value = not value
362
+ if value != g.polarity:
363
+ bad = next((p, f, x) for p, (f, x, v) in zip(parts, vals) if not v) \
364
+ if not value else None
365
+ why = f"conjunct `{bad[0]}` fails ({bad[1]} = {pre[bad[2]]})" if bad \
366
+ else f"all {len(parts)} conjuncts hold"
367
+ out.append(Check("branch", "refuted",
368
+ f"step {st.k} ({st.thread} {st.action}) runs the test `{g.text}` at "
369
+ f"{here[0]}:{line} and goes on to {there[0]}:{there[1]}, which the code "
370
+ f"reaches only when the test is {g.polarity}; {why} in the state the step "
371
+ f"is taken from: the code cannot take this step in this state",
372
+ {"step": st.k, "guard": g.text}))
373
+ continue
374
+ return out
375
+
376
+
377
+ _NUMERIC = re.compile(r"-?\d+(?:\.\d+)?")
378
+
379
+
380
+ def _comparison_value(left: str, op: str, right: str) -> bool | None:
381
+ """Two trace values compared: numeric pairs by value (``0`` equals ``0.0``), anything else by
382
+ spelling. None when either side is missing (the caller checks presence)."""
383
+ if _NUMERIC.fullmatch(left) and _NUMERIC.fullmatch(right):
384
+ eq = float(left) == float(right)
385
+ else:
386
+ eq = left == right
387
+ return eq if op == "==" else not eq
388
+
389
+
390
+ def _split_top_comparison(text: str):
391
+ """(negations, left, op, right) for a test with exactly one top-level ``==``/``!=``, else None."""
392
+ negs, t = _strip_bool_wrapping(text)
393
+ hits, depth, quote, i = [], 0, None, 0
394
+ while i < len(t):
395
+ ch = t[i]
396
+ if quote is not None:
397
+ if ch == quote and t[i - 1] != "\\":
398
+ quote = None
399
+ i += 1
400
+ continue
401
+ if ch in "\"'":
402
+ quote = ch
403
+ i += 1
404
+ continue
405
+ if ch in "([{":
406
+ depth += 1
407
+ i += 1
408
+ continue
409
+ if ch in ")]}":
410
+ depth -= 1
411
+ i += 1
412
+ continue
413
+ if depth == 0:
414
+ m = re.match(r"(==|!=)", t[i:])
415
+ if m:
416
+ hits.append((i, m.group(1)))
417
+ i += 2
418
+ continue
419
+ i += 1
420
+ if len(hits) != 1:
421
+ return None
422
+ at, op = hits[0]
423
+ left, right = t[:at].strip(), t[at + 2:].strip()
424
+ if not left or not right:
425
+ return None
426
+ return negs, left, op, right
427
+
428
+
429
+ def _resolve_field(side: str, mapped: list):
430
+ """(field, var) when the side names exactly one mapped read, else None."""
431
+ hits = [(fld, var) for read, fld, var in mapped if side == read]
432
+ return hits[0] if len(hits) == 1 else None
433
+
434
+
435
+ def comparison_checks(q, mod, steps, located, trace, *, pc_var: str = "pc") -> list:
436
+ """Like ``branch_checks``, but the anchored test compares two mapped fields (``x == y``).
437
+ Decided only when the trace values both sides (numeric pairs by value, else by spelling).
438
+ Literals stay ``branch_checks``'; ordering comparisons are out of scope."""
439
+ from .confirm import Check
440
+ owner = _mapped_owner(mod, pc_var)
441
+ out = []
442
+ for st, here, there, fn, gs in _anchored(q, steps, located):
443
+ _, line, _ = here
444
+ for g in gs:
445
+ if g.line != line or g.calls:
446
+ continue
447
+ split = _split_top_comparison(g.text)
448
+ if split is None:
449
+ continue
450
+ negs, left, op, right = split
451
+ mapped = _mapped_vars(q, fn, g, owner)
452
+ a, b = _resolve_field(left, mapped), _resolve_field(right, mapped)
453
+ if a is None or b is None:
454
+ continue
455
+ pre = _trace_value(trace, st)
456
+ if a[1] not in pre or b[1] not in pre:
457
+ continue
458
+ value = _comparison_value(str(pre[a[1]]).strip(), op, str(pre[b[1]]).strip())
459
+ if negs % 2:
460
+ value = not value
461
+ if value != g.polarity:
462
+ out.append(Check("branch", "refuted",
463
+ f"step {st.k} ({st.thread} {st.action}) runs the comparison `{g.text}` at "
464
+ f"{here[0]}:{line} and goes on to {there[0]}:{there[1]}, which the code "
465
+ f"reaches only when the test is {g.polarity}; {a[0]} = {pre[a[1]]} and "
466
+ f"{b[0]} = {pre[b[1]]} in the state the step is taken from: the code cannot "
467
+ f"take this step in this state",
468
+ {"step": st.k, "guard": g.text}))
469
+ return out
470
+
471
+
472
+ # -- call tests, callee guards, loop entries (uncertain-only) ----------------------------------------
473
+
474
+ def _resolve_callee(q, fn: str, spelling: str):
475
+ """Dotted callees that exist as function/method defs (ambiguity returns several, so the
476
+ caller abstains). ``self.m`` resolves in the current class only; a bare name in the
477
+ enclosing scope, falling back to module scope from a method; other dotted receivers
478
+ are unresolvable (their type is unknown)."""
479
+ simple = spelling.rsplit(".", 1)[-1]
480
+ parent = fn.rsplit(".", 1)[0] if "." in fn else ""
481
+ index = getattr(getattr(q, "code", None), "index", None)
482
+ if index is None or not simple or not parent:
483
+ return []
484
+ cands = []
485
+ if spelling.startswith("self."):
486
+ sym = index.symbols.get(parent)
487
+ if sym is not None and sym.kind == "class":
488
+ cands = [f"{parent}.{simple}"]
489
+ elif "." in spelling:
490
+ return []
491
+ else:
492
+ cands = [f"{parent}.{simple}"]
493
+ psym = index.symbols.get(parent)
494
+ if psym is not None and psym.kind == "class" and "." in parent:
495
+ cands.append(f"{parent.rsplit('.', 1)[0]}.{simple}")
496
+ return [c for c in cands if (s := index.symbols.get(c)) is not None
497
+ and s.kind in ("function", "method")]
498
+
499
+
500
+ def _pure_predicate(node):
501
+ """(test source, params) for a single-``return`` def with no decorators, no defaults and no
502
+ star/kwonly args (methods drop the receiver), else None."""
503
+ import ast
504
+ if node is None or getattr(node, "decorator_list", None):
505
+ return None
506
+ if len(node.body) != 1 or not isinstance(node.body[0], ast.Return) or node.body[0].value is None:
507
+ return None
508
+ args = node.args
509
+ if args.vararg is not None or args.kwarg is not None or args.kwonlyargs or args.defaults:
510
+ return None
511
+ params = [a.arg for a in (*args.posonlyargs, *args.args)]
512
+ return ast.unparse(node.body[0].value), params
513
+
514
+
515
+ def _call_args(test_src: str, spelling: str):
516
+ """Positional arg spellings of the test's one call, or None (several calls, keywords,
517
+ starred or non-name args, unparseable)."""
518
+ import ast
519
+ try:
520
+ tree = ast.parse(test_src, mode="eval")
521
+ except SyntaxError:
522
+ return None
523
+ found = []
524
+ for n in ast.walk(tree):
525
+ if not isinstance(n, ast.Call):
526
+ continue
527
+ dotted = _ast_dotted(n.func)
528
+ if dotted is None:
529
+ return None
530
+ found.append((dotted, n))
531
+ if len(found) != 1 or found[0][0] != spelling:
532
+ return None
533
+ call = found[0][1]
534
+ if call.keywords or any(isinstance(a, ast.Starred) for a in call.args):
535
+ return None
536
+ out = []
537
+ for a in call.args:
538
+ d = _ast_dotted(a)
539
+ if d is None:
540
+ return None
541
+ out.append(d)
542
+ return out
543
+
544
+
545
+ def call_checks(q, mod, steps, located, trace, *, pc_var: str = "pc") -> list:
546
+ """An anchored test calling a pure predicate is evaluated by substitution; a
547
+ failing one is an uncertain ``guard`` check, never a refute (dynamic dispatch: a subclass
548
+ may override the body we read). Anything unmodelled — several calls, unresolvable or
549
+ ambiguous callee, impure body, bad arguments, multi-field body, unvalued fields — stays
550
+ silent: doubt needs a proven failure, and unmodelled calls (len(), is_alive(), ...) would
551
+ otherwise demote every stdlib-guarded confirmation."""
552
+ from .confirm import Check
553
+ owner = _mapped_owner(mod, pc_var)
554
+ index = getattr(getattr(q, "code", None), "index", None)
555
+ out = []
556
+ for st, here, there, fn, gs in _anchored(q, steps, located):
557
+ _, line, _ = here
558
+ for g in gs:
559
+ if g.line != line or not g.calls or g.kind not in ("if", "else", "exit", "ternary"):
560
+ continue # tests only: a for-iterable with calls is not decided here
561
+ if len(g.calls) != 1:
562
+ continue
563
+ spelling = g.calls[0]
564
+ cands = _resolve_callee(q, fn, spelling)
565
+ if len(cands) != 1 or index is None:
566
+ continue
567
+ node = q._fn_node(cands[0]) if hasattr(q, "_fn_node") else None
568
+ node = node[0] if node else None
569
+ pure = _pure_predicate(node)
570
+ callee_parent = cands[0].rsplit(".", 1)[0]
571
+ psym = index.symbols.get(callee_parent) if index else None
572
+ if pure is None:
573
+ continue
574
+ test_src, params = pure
575
+ if psym is not None and psym.kind == "class" and params:
576
+ params = params[1:]
577
+ args = _call_args(g.text, spelling)
578
+ if args is None or len(args) != len(params):
579
+ continue
580
+ mapped = _mapped_vars(q, fn, g, owner)
581
+ if any(not any(a == r for r, _, _ in mapped) for a in args):
582
+ continue # an argument is no mapped read: silent
583
+ else:
584
+ sub = test_src
585
+ for p, a in sorted(zip(params, args), key=lambda t: -len(t[0])):
586
+ sub = re.sub(rf"\b{re.escape(p)}\b", a, sub)
587
+ hit = _conjunct_value(sub, mapped, mod, _trace_value(trace, st))
588
+ if hit is not None:
589
+ _, var, value = hit
590
+ if value != g.polarity:
591
+ pre = _trace_value(trace, st)
592
+ out.append(Check("guard", "uncertain",
593
+ f"step {st.k} ({st.thread} {st.action}) runs the test `{g.text}` at "
594
+ f"{here[0]}:{line}, calling pure {spelling}, which fails in the state "
595
+ f"the step is taken from ({var} = {pre[var]}); calls are never refuted",
596
+ {"step": st.k, "guard": g.text}))
597
+ return out
598
+
599
+
600
+ def callee_checks(q, mod, steps, located, trace, *, pc_var: str = "pc") -> list:
601
+ """A step in a called (non-entry) function, inside an if/else/exit/ternary
602
+ guard whose decidable test fails in the pre-state while its reads are unrefreshed. Entry
603
+ functions are ``g1_window_checks``' territory and stay out (where that check covers them, this
604
+ one's overlap ends: retire or narrow it then). Uncertain-only, never refuted."""
605
+ from .confirm import Check
606
+ owner = _mapped_owner(mod, pc_var)
607
+ lang = getattr(q, "language", "python")
608
+ entry = {}
609
+ for st in steps:
610
+ loc = located(st.step)
611
+ if loc is not None and loc[2] and st.thread not in entry:
612
+ entry[st.thread] = loc[2]
613
+ out = []
614
+ for st in steps:
615
+ here = located(st.step)
616
+ if here is None or not hasattr(q, "guards"):
617
+ continue
618
+ _, line, fn = here
619
+ if not fn or entry.get(st.thread) == fn:
620
+ continue
621
+ try:
622
+ gs = q.guards(fn, line)
623
+ except NotImplementedError:
624
+ continue
625
+ for g in gs:
626
+ if g.line == line or g.kind not in ("if", "else", "exit", "ternary"):
627
+ continue
628
+ m = _single_read_mapped(q, fn, g, owner)
629
+ if m is None:
630
+ continue
631
+ fld, var = m
632
+ pre = _trace_value(trace, st)
633
+ if var not in pre:
634
+ continue
635
+ if _window_refreshed(q, fn, [fld], g.line, line):
636
+ continue # stale reads decide nothing
637
+ holds = _guard_holds(g, var, pre, mod, lang, strict_null=True)
638
+ if holds is not None and holds != g.polarity:
639
+ out.append(Check("guard", "uncertain",
640
+ f"step {st.k} ({st.thread} {st.action}) runs in called {fn} under callee guard "
641
+ f"`{g.text}` at {here[0]}:{g.line}, which fails in the pre-state ({var} = "
642
+ f"{pre[var]}); callee guards are never refuted",
643
+ {"step": st.k, "guard": g.text}))
644
+ return out
645
+
646
+
647
+ _MODEL_EMPTY = ("<<>>", "{}", '""', "''")
648
+
649
+
650
+ def loop_entry_checks(q, mod, steps, located, trace, *, pc_var: str = "pc") -> list:
651
+ """A step inside a loop body the pre-state rules out — a ``for`` over an empty
652
+ mapped field, or a ``while`` whose decidable test is false — while the deciding reads are
653
+ unrefreshed. First-iteration shape only (never-entered); post-loop exit reasoning and
654
+ trip counts are out. Uncertain-only, never refuted."""
655
+ from .confirm import Check
656
+ owner = _mapped_owner(mod, pc_var)
657
+ lang = getattr(q, "language", "python")
658
+ out = []
659
+ for st in steps:
660
+ here = located(st.step)
661
+ if here is None or not hasattr(q, "guards"):
662
+ continue
663
+ _, line, fn = here
664
+ try:
665
+ gs = q.guards(fn, line)
666
+ except NotImplementedError:
667
+ continue
668
+ for g in gs:
669
+ if g.kind not in ("for", "while"):
670
+ continue
671
+ m = _single_read_mapped(q, fn, g, owner)
672
+ if m is None:
673
+ continue
674
+ fld, var = m
675
+ pre = _trace_value(trace, st)
676
+ if var not in pre:
677
+ continue
678
+ val = str(pre[var]).strip()
679
+ if g.kind == "for":
680
+ if val not in _MODEL_EMPTY:
681
+ continue
682
+ if _window_refreshed(q, fn, [fld], g.line, line):
683
+ continue
684
+ out.append(Check("guard", "uncertain",
685
+ f"step {st.k} ({st.thread} {st.action}) runs in a loop over {fld}, empty "
686
+ f"({val}) in the pre-state, so the loop may never be entered; loop entries "
687
+ f"are never refuted",
688
+ {"step": st.k, "guard": g.text}))
689
+ elif g.polarity is True:
690
+ holds = _guard_holds(g, var, pre, mod, lang, strict_null=True)
691
+ if holds is None or _window_refreshed(q, fn, [fld], g.line, line):
692
+ continue
693
+ if holds is False:
694
+ out.append(Check("guard", "uncertain",
695
+ f"step {st.k} ({st.thread} {st.action}) runs in a while body whose test "
696
+ f"`{g.text}` is false in the pre-state ({var} = {val}), so the loop may "
697
+ f"never be entered; loop entries are never refuted",
698
+ {"step": st.k, "guard": g.text}))
699
+ return out
700
+
701
+
702
+ # -- literal test parsing (g1, g1b and g2 checks) ----------------------------------------------------
703
+
704
+ _NULL_CLASS = {"null", "none", "nil", "undefined"}
705
+ _FALSY = {
706
+ "node": {"false", "null", "undefined", "0", "0.0", "", "nan"},
707
+ "python": {"false", "none", "0", "0.0", ""},
708
+ "go": {"false"},
709
+ "java": {"false"},
710
+ }
711
+ _LIT = r"(?:true|false|True|False|null|None|undefined|nil|NaN|-?\d+(?:\.\d+)?|\"(?:[^\"\\]|\\.)*\"|'(?:[^'\\]|\\.)*'|[A-Za-z_$#][\w$#]*(?:\.[A-Za-z_$#][\w$#]*)*)"
712
+ _NAME_LIT_KEYWORDS = {"true", "false", "null", "none", "nil", "undefined", "nan"}
713
+
714
+
715
+ def _lit_test(text: str, names: set[str]) -> tuple[str, str | None] | None:
716
+ """(op, literal) for a one-field test: bare/negated field (``truthy``/``falsy``), or
717
+ ``==``/``!=``/``===``/``!==`` (also Python ``is``/``is-not``-None) against a literal, either
718
+ way round (Yoda included; equality is symmetric). None otherwise."""
719
+ t = re.sub(r"\s+", " ", text.strip())
720
+ while t.startswith("(") and t.endswith(")"):
721
+ t = t[1:-1].strip()
722
+ alt = "|".join(re.escape(n) for n in sorted(names, key=len, reverse=True))
723
+ op = r"(===|!==|==|!=|is\s+not|is)"
724
+ m = re.fullmatch(rf"((?:!\s*)*)(not\s+)?({alt})(?:\s*{op}\s*({_LIT}))?\s*", t)
725
+ m = m or re.fullmatch(rf"({_LIT})\s*{op}\s*({alt})\s*", t)
726
+ if not m:
727
+ return None
728
+ if len(m.groups()) == 5: # name-first (possibly bare)
729
+ negs = m.group(1).count("!") + (1 if m.group(2) else 0)
730
+ if m.group(4) is None:
731
+ return ("falsy", None) if negs % 2 else ("truthy", None)
732
+ oper, lit = m.group(4), m.group(5)
733
+ else: # Yoda: literal first (symmetric by definition)
734
+ oper, lit = m.group(2), m.group(1)
735
+ negs = 0
736
+ if oper in ("is", "is not"):
737
+ if lit not in ("None", "null"):
738
+ return None # identity is only None-sound
739
+ oper = "!=" if oper == "is not" else "=="
740
+ if lit.lower() == "nan":
741
+ return None # NaN never equals, not even itself
742
+ if negs % 2:
743
+ oper = {"==": "!=", "!=": "==", "===": "!==", "!==": "==="}[oper]
744
+ return (oper, lit)
745
+
746
+
747
+ def _norm_lit(s: str) -> str:
748
+ s = s.strip()
749
+ if len(s) >= 2 and s[0] == s[-1] and s[0] in ("\"", "'"):
750
+ s = s[1:-1]
751
+ low = s.lower()
752
+ if low in ("true", "false"):
753
+ return low
754
+ if low in _NULL_CLASS:
755
+ return "null"
756
+ return s
757
+
758
+
759
+ def _holds_lit(parsed: tuple[str, str | None], value: str, lang: str, strict_null: bool = False) -> bool | None:
760
+ """A parsed literal test's value for a trace value (None when undecidable). ``strict_null`` (the
761
+ window check only): a null-class test is decided only on a null-literal value, truthiness only on a Boolean."""
762
+ op, lit = parsed
763
+ v = _norm_lit(value.strip())
764
+ if op in ("truthy", "falsy"):
765
+ if strict_null and v not in ("true", "false"):
766
+ return None # strict: no truthiness on a model's encoding
767
+ if lang in ("go", "java") and v not in ("true", "false"):
768
+ return None # no implicit truthiness: bool or undecidable
769
+ falsy = _FALSY.get(lang)
770
+ if falsy is None:
771
+ return None
772
+ if v.startswith(("[", "{", "(")):
773
+ return None # containers: emptiness undecidable here
774
+ if re.fullmatch(r"-?\d+(?:\.\d+)?", v):
775
+ try:
776
+ is_falsy = float(v) == 0.0
777
+ except ValueError:
778
+ return None
779
+ else:
780
+ is_falsy = v in falsy
781
+ return (not is_falsy) if op == "truthy" else is_falsy
782
+ assert lit is not None
783
+ if _is_name(lit) and lit.lower() not in _NAME_LIT_KEYWORDS:
784
+ return None # a name literal (enum): code-vs-code only, never trace-decided
785
+ strict, nl = op in ("===", "!=="), _norm_lit(lit)
786
+ if re.fullmatch(r"[A-Za-z_][\w$]*", v) and v.lower() not in (
787
+ "true", "false", "null", "none", "nil", "undefined", "nan"):
788
+ return None # uninterpreted model value: undecided
789
+ if strict_null and nl == "null" and v != "null":
790
+ return None # strict: a null test needs a null-literal value
791
+ if nl == "null" or v == "null":
792
+ holds = (nl == "null") == (v == "null") # null-class (loose and strict agree)
793
+ elif strict and _typeof(nl) != _typeof(v):
794
+ holds = False # strict: different types never equal
795
+ elif not strict and _typeof(nl) != _typeof(v):
796
+ return None # loose mixed-type coercion: unmodeled
797
+ elif nl in ("true", "false") or v in ("true", "false"):
798
+ holds = nl == v
799
+ elif re.fullmatch(r"-?\d+(?:\.\d+)?", nl) and re.fullmatch(r"-?\d+(?:\.\d+)?", v):
800
+ try:
801
+ holds = float(nl) == float(v)
802
+ except ValueError:
803
+ return None
804
+ else:
805
+ holds = nl == v
806
+ return (not holds) if op in ("!=", "!==") else holds
807
+
808
+
809
+ def _typeof(s: str) -> str:
810
+ if s in ("true", "false"):
811
+ return "bool"
812
+ if s == "null":
813
+ return "null"
814
+ if re.fullmatch(r"-?\d+(?:\.\d+)?", s):
815
+ return "num"
816
+ return "str"
817
+
818
+
819
+ # -- governed steps contradicted in-trace (uncertain) ----------------------------------------------------
820
+
821
+ def _trace_value(trace, st) -> dict:
822
+ """The PRE-state's values: ``st.state`` is the post-step state's number (1-based)."""
823
+ idx = getattr(st, "state", None)
824
+ if idx is None or idx - 2 < 0 or idx - 2 >= len(trace):
825
+ return {}
826
+ return trace[idx - 2].values
827
+
828
+
829
+ def _bare_is_state(q, fn: str, name: str) -> bool:
830
+ """A bare guard read names module state (a top-level ``let``/``var``/``const``), not a local
831
+ or parameter (EtcdLease: a ``let leaseBeat`` snapshot must never match the ``this.leaseBeat``
832
+ field's mapping). Unreadable files and parameters never match (silence is sound)."""
833
+ r = getattr(q, "r", None)
834
+ row = (getattr(r, "fns", {}) or {}).get(fn, {}) if r is not None else {}
835
+ for p in row.get("params", []) or []:
836
+ if (p if isinstance(p, str) else p.get("name", "")) == name:
837
+ return False
838
+ try:
839
+ text = (q.root / row.get("file", "")).read_text()
840
+ except (OSError, AttributeError, TypeError):
841
+ return False
842
+ return re.search(rf"^(?:export\s+)?(?:var|let|const)\s+{re.escape(name)}\b", text, re.M) is not None
843
+
844
+
845
+ def _guard_reads(q, fn: str, g) -> list[str]:
846
+ """A guard's pruned reads that resolve to code state (locals drop out)."""
847
+ pruned = [r for r in g.reads if not any(o.startswith(r + ".") for o in g.reads)]
848
+ return [r for r in pruned if "." in r or r.startswith("#") or _bare_is_state(q, fn, _field(r))]
849
+
850
+
851
+ def _mapped_reads(q, fn: str, g, mapped: set[str]) -> list[str]:
852
+ """A guard's state-resolving reads that name mapped fields (enum/name literals drop out)."""
853
+ return [r for r in _guard_reads(q, fn, g) if _field(r) in mapped]
854
+
855
+
856
+ def _single_read_mapped(q, fn: str, g, owner: dict) -> tuple[str, str] | None:
857
+ """(field, var) for a guard with exactly one mapped read and no calls, else None."""
858
+ reads = _mapped_reads(q, fn, g, set(owner))
859
+ if g.calls or len(reads) != 1:
860
+ return None
861
+ fld = _field(reads[0])
862
+ vs = owner.get(fld, [])
863
+ if len(vs) != 1:
864
+ return None
865
+ return fld, vs[0]
866
+
867
+
868
+ def _guard_spellings(g) -> set[str]:
869
+ out = set()
870
+ for r in g.reads:
871
+ out |= {r, _field(r), f"this.{_field(r)}", f"self.{_field(r)}"}
872
+ return out
873
+
874
+
875
+ def _parse_guard_test(g, mod, var) -> tuple | None:
876
+ """(``lit``, parsed) or (``int``, cmp) for a decidable guard test, else None."""
877
+ spellings = _guard_spellings(g)
878
+ lt = _lit_test(g.text, spellings)
879
+ if lt is not None:
880
+ return ("lit", lt)
881
+ cmp = _int_test(g.text, spellings)
882
+ if cmp is not None and _in_domain(mod.code, var, cmp[1]):
883
+ return ("int", cmp)
884
+ return None
885
+
886
+
887
+ def _guard_holds(g, var: str, pre: dict, mod, lang: str, strict_null: bool = False) -> bool | None:
888
+ """A Boolean/integer/literal guard's value in a trace state (None when undecidable). ``strict_null``
889
+ (the window check only) passes through to ``_holds_lit``; integer tests are unchanged."""
890
+ parsed = _parse_guard_test(g, mod, var)
891
+ if parsed is None:
892
+ return None
893
+ val = str(pre.get(var, "")).strip()
894
+ if parsed[0] == "lit":
895
+ return _holds_lit(parsed[1], val, lang, strict_null=strict_null)
896
+ if not re.fullmatch(r"-?\d+", val):
897
+ return None
898
+ return _OPS[parsed[1][0]](int(val), parsed[1][1])
899
+
900
+
901
+ def _caller_only(q, fn: str) -> bool:
902
+ try:
903
+ return set(q.contexts(fn)) <= {"caller"}
904
+ except (NotImplementedError, AttributeError, KeyError):
905
+ return False
906
+
907
+
908
+ def g1_checks(q, mod, steps, located, trace, *, pc_var: str = "pc") -> list:
909
+ """An uncertain check for each located step governed by a guard on a mapped field
910
+ whose test fails in the step's trace state (fresh: no same-function write, await, or
911
+ unknown-callee call between test and step; caller-only functions, so no worker preemption
912
+ can refresh the value). Disjoint from ``branch_checks`` by construction (govs exclude test lines)."""
913
+ from .confirm import Check
914
+ if getattr(q, "language", "") not in ("node", "go") or not hasattr(q, "guards"):
915
+ return []
916
+ if not hasattr(q, "write_sites"):
917
+ return []
918
+ owner = _mapped_owner(mod, pc_var)
919
+ out = []
920
+ for i, st in enumerate(steps):
921
+ here = located(st.step)
922
+ if here is None:
923
+ continue
924
+ _, line, fn = here
925
+ try:
926
+ gs = q.guards(fn, line)
927
+ except NotImplementedError:
928
+ continue
929
+ pre = _trace_value(trace, st)
930
+ if not pre:
931
+ continue
932
+ for g in gs:
933
+ if g.kind in ("select", "select-default"):
934
+ continue # g1_select_checks handles select arms
935
+ m = _single_read_mapped(q, fn, g, owner)
936
+ if m is None:
937
+ continue
938
+ fld, var = m
939
+ holds = _guard_holds(g, var, pre, mod, q.language)
940
+ if holds is None or holds == g.polarity:
941
+ continue
942
+ if not _caller_only(q, fn):
943
+ continue
944
+ states = _var_states(mod, var)
945
+ if _refreshed(q, fn, states, g.line, line):
946
+ continue
947
+ out.append(Check("guard", "uncertain",
948
+ f"step {st.k} ({st.thread} {st.action}) runs at {here[0]}:{line}, which "
949
+ f"the code reaches only when `{g.text}` is {g.polarity}; in the state the step "
950
+ f"is taken from, {var} = {pre.get(var, '')}, so it is {holds} (no write, "
951
+ f"await, or unknown call refreshes {fld} between test and step)",
952
+ {"step": st.k, "variable": var, "guard": g.text}))
953
+ return out
954
+
955
+
956
+ # -- the g1 check for Python, judged on the trace's own window (uncertain) ------------------------------
957
+
958
+ def _window_refreshed(q, fn: str, states: list[str], test_line: int, step_line: int) -> bool:
959
+ """Anything in ``fn`` between the test and the step that could change the tested field (conservative): a write
960
+ to it in ``fn`` or a function it calls, or any call at all (a callee the facts do not see may write it)."""
961
+ for state in states:
962
+ for s in q.writes(fn, state):
963
+ if s.function == fn and test_line < s.line < step_line:
964
+ return True
965
+ if q.language == "python":
966
+ import ast
967
+ found = q._fn_node(fn)
968
+ if found is None:
969
+ return True
970
+ return any(isinstance(n, ast.Call) and test_line < n.lineno < step_line for n in ast.walk(found[0]))
971
+ row = q.r.fns.get(fn) if hasattr(q, "r") else None
972
+ if row is None:
973
+ return True
974
+ return any(test_line < c.get("line", 0) < step_line for c in row.get("calls", []))
975
+
976
+
977
+ def _window_mapped(q, fn: str, g, owner: dict) -> tuple[str, str] | None:
978
+ """(field, var) for a guard with exactly one read of a mapped field and no calls, else None. A dotted read
979
+ (``self.closed``, ``this.closed``) names a field. In Java a bare read names one when the method's own access rows
980
+ read that field on the test's line (an implicit ``this``); a Python bare name is a local."""
981
+ if g.calls:
982
+ return None
983
+ pruned = [r for r in g.reads if not any(o.startswith(r + ".") for o in g.reads)]
984
+ found = []
985
+ for r in pruned:
986
+ if "." not in r:
987
+ if getattr(q, "language", "") != "java":
988
+ continue
989
+ row = q.r.fns.get(fn, {}) if hasattr(q, "r") else {}
990
+ if not any(_field(a.get("state", "")) == r and a.get("line") == g.line and a.get("rw") in ("read", "rw")
991
+ for a in row.get("accesses", [])):
992
+ continue
993
+ if _field(r) in owner:
994
+ found.append(r)
995
+ if len(found) != 1:
996
+ return None
997
+ vs = owner.get(_field(found[0]), [])
998
+ return (_field(found[0]), vs[0]) if len(vs) == 1 else None
999
+
1000
+
1001
+ #: The window check was held off while it read a model's encoding of "absent" as non-null; with the strict
1002
+ #: null/truthiness decisions it re-calibrated clean (its demotions were all correct), so it is on.
1003
+ WINDOW_CHECK_ON = True
1004
+
1005
+
1006
+ def g1_window_checks(q, mod, steps, located, trace, *, pc_var: str = "pc") -> list:
1007
+ """An uncertain ``guard`` check for a located step inside a Python or Java ``if`` whose test, on one
1008
+ mapped field, fails throughout the window in which the test ran.
1009
+
1010
+ Node and Go's ``g1_checks`` asks that the function run only in the caller's context. Threads preempt, so that rule
1011
+ never fires on a thread race; this one reads the trace instead. The test runs after the thread's last step that
1012
+ sits before the test line (or Init) and before its first step past the test line. If the field holds the same value
1013
+ in every trace state of that window, the test saw that value. If it fails, the code does not reach the step. A
1014
+ value that changes inside the window (a check-then-act race) is never flagged. Nothing in the code between test
1015
+ and step may refresh the field (``_window_refreshed``). An unlocated step of the thread at the window's edge
1016
+ leaves the window unknown: nothing is flagged. Uncertain, not refuted: a writer the model does not cite could
1017
+ still change it. The window ends before the thread's first step past the test line (the test ran before it),
1018
+ and only ``if``/``else`` count: a ``while`` re-tests on every pass."""
1019
+ from .confirm import Check
1020
+ if not WINDOW_CHECK_ON:
1021
+ return []
1022
+ lang = getattr(q, "language", "")
1023
+ if lang not in ("python", "java") or not hasattr(q, "guards"):
1024
+ return []
1025
+ owner = _mapped_owner(mod, pc_var)
1026
+ out = []
1027
+ for i, st in enumerate(steps):
1028
+ here = located(st.step)
1029
+ if here is None or getattr(st, "state", None) is None:
1030
+ continue
1031
+ _, line, fn = here
1032
+ try:
1033
+ gs = q.guards(fn, line)
1034
+ except NotImplementedError:
1035
+ continue
1036
+ mine = [s for s in steps[:i] if s.thread == st.thread]
1037
+ for g in gs:
1038
+ if g.kind not in ("if", "else") or g.line == line:
1039
+ continue # branch_checks owns a step on the test line; a while re-tests each pass
1040
+ m = _window_mapped(q, fn, g, owner)
1041
+ if m is None:
1042
+ continue
1043
+ fld, var = m
1044
+ # the thread's first step past the test: walk back over its steps in fn after the test line
1045
+ first, j = st, len(mine) - 1
1046
+ while j >= 0 and (loc := located(mine[j].step)) is not None and loc[2] == fn and loc[1] > g.line:
1047
+ first, j = mine[j], j - 1
1048
+ prev = mine[j] if j >= 0 else None
1049
+ if prev is not None and located(prev.step) is None:
1050
+ continue # an unlocated step may be the test or past it: no window
1051
+ if getattr(first, "state", None) is None:
1052
+ continue
1053
+ lo = (prev.state - 1) if prev is not None else 0 # 0-based: the state after prev (or Init)
1054
+ hi = first.state - 2 # the state the first step past the test leaves
1055
+ if lo < 0 or hi < lo or hi >= len(trace):
1056
+ continue
1057
+ vals = {str(trace[k].values.get(var, "")).strip() for k in range(lo, hi + 1)}
1058
+ if len(vals) != 1 or vals == {""}:
1059
+ continue # it changes in the window: the trace may pass
1060
+ holds = _guard_holds(g, var, trace[hi].values, mod, lang, strict_null=True)
1061
+ if holds is None or holds == g.polarity:
1062
+ continue
1063
+ first_line = located(first.step)[1]
1064
+ if _window_refreshed(q, fn, _var_states(mod, var), g.line, first_line):
1065
+ continue
1066
+ out.append(Check("guard", "uncertain",
1067
+ f"step {st.k} ({st.thread} {st.action}) runs at {here[0]}:{line}, which the code reaches "
1068
+ f"only when `{g.text}` (line {g.line}) is {g.polarity}; {var} = {next(iter(vals))} "
1069
+ f"throughout the window in which that test ran, so it is {holds} (nothing in the code "
1070
+ f"between test and step refreshes {fld}; a writer the model does not cite could)",
1071
+ {"step": st.k, "variable": var, "guard": g.text}))
1072
+ return out
1073
+
1074
+
1075
+ def _var_states(mod, var: str) -> list[str]:
1076
+ """A mapped variable's @code state strings."""
1077
+ refs = mod.declaration_tags.get(var, (0, None))[1]
1078
+ return list(refs.code) if refs is not None else []
1079
+
1080
+
1081
+ def _refreshed(q, fn: str, states: list[str], test_line: int, step_line: int) -> bool:
1082
+ """Anything that could refresh the guarded value between test and step (conservative)."""
1083
+ fns = getattr(getattr(q, "r", None), "fns", None)
1084
+ fnrow = fns.get(fn) if isinstance(fns, dict) else None
1085
+ if fnrow is not None and any(test_line < a < step_line for a in fnrow.get("awaits", [])):
1086
+ return True # a loop gap: microtasks may run
1087
+ sset = set(states)
1088
+ for state in states:
1089
+ for s in q.write_sites(state):
1090
+ if s.function == fn and test_line < s.line < step_line:
1091
+ return True # a direct write between test and step
1092
+ if fnrow is None:
1093
+ return False
1094
+ for c in fnrow.get("calls", []):
1095
+ if not (test_line < c.get("line", 0) < step_line):
1096
+ continue
1097
+ try:
1098
+ tgts = q.r.call_targets(c)
1099
+ except (NotImplementedError, AttributeError, KeyError):
1100
+ return True
1101
+ if not tgts:
1102
+ return True # unknown callee: may write anything
1103
+ for t in tgts:
1104
+ g = fns.get(t, {})
1105
+ if g.get("awaits"):
1106
+ return True # async callee: resumption lands later
1107
+ if any(a["state"] in sset and a["rw"] in ("write", "rw") for a in g.get("accesses", [])):
1108
+ return True # a sync callee writes the field
1109
+ return False
1110
+
1111
+
1112
+ # -- Go default arms dead after close (uncertain) ------------------------------------------------------
1113
+
1114
+ def g1_select_checks(q, mod, steps, located, trace, *, pc_var: str = "pc") -> list:
1115
+ """A step in a select-default arm while a sibling recv-case's channel was
1116
+ closed by an earlier trace step located AT the close (trace-continued, so executed).
1117
+ A closed channel's recv-case is always ready and beats default (Go spec)."""
1118
+ from .confirm import Check
1119
+ if getattr(q, "language", "") not in ("node", "go") or not hasattr(q, "guards"):
1120
+ return []
1121
+ if not hasattr(q, "chanops"):
1122
+ return []
1123
+ out = []
1124
+ threads_after: dict[int, bool] = {}
1125
+ for i, st in enumerate(steps):
1126
+ threads_after[i] = any(s.thread == st.thread for s in steps[i + 1:])
1127
+ for i, st in enumerate(steps):
1128
+ here = located(st.step)
1129
+ if here is None:
1130
+ continue
1131
+ _, line, fn = here
1132
+ try:
1133
+ gs = q.guards(fn, line)
1134
+ except NotImplementedError:
1135
+ continue
1136
+ for g in [x for x in gs if x.kind == "select-default"]:
1137
+ if g.group is None or not hasattr(q, "select_arms"):
1138
+ continue
1139
+ try:
1140
+ siblings = q.select_arms(fn, g.group)
1141
+ except NotImplementedError:
1142
+ continue
1143
+ recvs = set()
1144
+ for h in siblings:
1145
+ if h.kind == "select" and h.comm == "recv":
1146
+ recvs.update(_field(r) for r in h.reads)
1147
+ if not recvs:
1148
+ continue
1149
+ for j in range(i):
1150
+ pj = located(steps[j].step)
1151
+ if pj is None or not threads_after[j]:
1152
+ continue
1153
+ _, pline, pfn = pj
1154
+ try:
1155
+ ops = q.chanops(pfn)
1156
+ except (NotImplementedError, AttributeError):
1157
+ continue
1158
+ hit = [o for o in ops if o.get("kind") == "close" and o.get("line") == pline
1159
+ and _field(str(o.get("value", ""))) in recvs]
1160
+ if not hit:
1161
+ continue
1162
+ ch = _field(str(hit[0].get("value", "")))
1163
+ out.append(Check("guard", "uncertain",
1164
+ f"step {st.k} ({st.thread} {st.action}) runs a select-default arm at "
1165
+ f"{here[0]}:{line}, but step {steps[j].k} closed channel {ch}, whose "
1166
+ f"recv-case is ready and beats default (Go select semantics)",
1167
+ {"step": st.k, "channel": ch, "closed_by": steps[j].k,
1168
+ "depends": "both closes act on one channel instance"}))
1169
+ return out
1170
+
1171
+
1172
+ # -- divergent call paths ruling out a shared step (uncertain, calibration-gated) -----------------------
1173
+
1174
+ def g1b_checks(q, mod, steps, located, trace, *, pc_var: str = "pc") -> list:
1175
+ """≥2 threads share one located step whose function has ≥2 call sites, the spec
1176
+ constrains the guarded field, and some call-site path establishes the guard's divert-value
1177
+ (right-hand-side matched). Call/write conditions are may-analyzed (uncertain absorbs it).
1178
+ It ships only while calibration stays quiet."""
1179
+ from .confirm import Check
1180
+ if getattr(q, "language", "") not in ("node", "go"):
1181
+ return []
1182
+ for meth in ("guards", "callers", "write_sites", "source_line"):
1183
+ if not hasattr(q, meth):
1184
+ return []
1185
+ owner = _mapped_owner(mod, pc_var)
1186
+ by_loc: dict[tuple, list] = {}
1187
+ for i, st in enumerate(steps):
1188
+ here = located(st.step)
1189
+ if here is None:
1190
+ continue
1191
+ by_loc.setdefault((here[2], here[1]), []).append((i, st))
1192
+ out = []
1193
+ seen = set()
1194
+ for (fn, line), occ in by_loc.items():
1195
+ if len({st.thread for _, st in occ}) < 2:
1196
+ continue
1197
+ try:
1198
+ sites = q.callers(fn)
1199
+ except NotImplementedError:
1200
+ continue
1201
+ if len({(s.function, s.line) for s in sites}) < 2:
1202
+ continue
1203
+ try:
1204
+ gs = q.guards(fn, line)
1205
+ except NotImplementedError:
1206
+ continue
1207
+ for i, st in occ:
1208
+ constrained = _spec_constrained_fields(mod, st.action, pc_var)
1209
+ if not constrained:
1210
+ continue
1211
+ for g in gs:
1212
+ if g.kind in ("select", "select-default"):
1213
+ continue
1214
+ reads = _mapped_reads(q, fn, g, set(owner))
1215
+ if g.calls or len(reads) != 1:
1216
+ continue
1217
+ fld = _field(reads[0])
1218
+ if fld not in constrained:
1219
+ continue
1220
+ vs = owner.get(fld, [])
1221
+ if len(vs) != 1:
1222
+ continue
1223
+ hit = _divergent_path(q, sites, vs[0], g, mod, q.language)
1224
+ if hit is None or (st.k, g.text) in seen:
1225
+ continue
1226
+ seen.add((st.k, g.text))
1227
+ caller, wit = hit
1228
+ out.append(Check("guard", "uncertain",
1229
+ f"step {st.k} ({st.thread} {st.action}) shares {fn}:{line} with "
1230
+ f"another thread while {fn} has divergent callers; the path via "
1231
+ f"{caller} {wit}, satisfying `{g.text}` to divert, so the step may "
1232
+ f"not run there as specified",
1233
+ {"step": st.k, "variable": vs[0], "guard": g.text,
1234
+ "caller": caller}))
1235
+ return out
1236
+
1237
+
1238
+ def _divergent_path(q, sites, var, g, mod, lang):
1239
+ """(caller, witness) for a call-site path establishing the guard's divert-value, else None.
1240
+
1241
+ May-analysis, uniform: direct writes textually before the call, or one-level transitive
1242
+ callee writes (any line), count when their right-hand side satisfies the divert. Call and
1243
+ write conditions are not checked (uncertain absorbs it)."""
1244
+ want_divert = not g.polarity
1245
+ fns = getattr(getattr(q, "r", None), "fns", None)
1246
+ if not isinstance(fns, dict) or not hasattr(q, "source_line"):
1247
+ return None
1248
+ parsed = _parse_guard_test(g, mod, var)
1249
+ if parsed is None:
1250
+ return None
1251
+ states = _var_states(mod, var)
1252
+ for s in sites:
1253
+ caller = fns.get(s.function)
1254
+ if caller is None:
1255
+ continue
1256
+ for state in states:
1257
+ for w in q.write_sites(state):
1258
+ if w.function != s.function or not (w.line < s.line):
1259
+ continue
1260
+ if _rhs_diverts(parsed, q.source_line(w.function, w.line), var, lang) is want_divert:
1261
+ return s.function, f"writes {var} at line {w.line}"
1262
+ for c in caller.get("calls", []):
1263
+ if not (c.get("line", 0) < s.line):
1264
+ continue
1265
+ try:
1266
+ tgts = q.r.call_targets(c)
1267
+ except (NotImplementedError, AttributeError, KeyError):
1268
+ continue
1269
+ for t in tgts:
1270
+ g2 = fns.get(t, {})
1271
+ for a in g2.get("accesses", []):
1272
+ if a["state"] not in states or a["rw"] not in ("write", "rw"):
1273
+ continue
1274
+ if _rhs_diverts(parsed, q.source_line(t, a["line"]), var, lang) is want_divert:
1275
+ return s.function, f"calls {t} writing {var} at line {a['line']}"
1276
+ return None
1277
+
1278
+
1279
+ def _rhs_diverts(parsed: tuple, line_text: str, var: str, lang: str) -> bool | None:
1280
+ """A write's right-hand side satisfies a parsed guard test (names match textually)."""
1281
+ short = var.rsplit(".", 1)[-1]
1282
+ rhs = _split_assign(line_text, short)
1283
+ if rhs is None:
1284
+ return None
1285
+ if parsed[0] == "lit":
1286
+ return _holds_rhs(parsed[1], rhs, lang)
1287
+ if not re.fullmatch(r"-?\d+", rhs.strip()):
1288
+ return None
1289
+ return _OPS[parsed[1][0]](int(rhs.strip()), parsed[1][1])
1290
+
1291
+
1292
+ def _split_assign(line_text: str, short: str) -> str | None:
1293
+ """Right-hand side of a plain `X = rhs` write to short-named X on one line, else None."""
1294
+ if not line_text or "=>" in line_text:
1295
+ return None
1296
+ idx = None
1297
+ for m in re.finditer(r"=", line_text):
1298
+ i = m.start()
1299
+ prev = line_text[i - 1] if i > 0 else ""
1300
+ nxt = line_text[i + 1] if i + 1 < len(line_text) else ""
1301
+ if prev in "=!<>+-*/%&|^" or nxt in "=>":
1302
+ continue
1303
+ idx = i
1304
+ break
1305
+ if idx is None:
1306
+ return None
1307
+ lhs, rhs = line_text[:idx], line_text[idx + 1:]
1308
+ if not re.search(r"(^|[\s.(#])" + re.escape(short) + r"\s*$", lhs):
1309
+ return None
1310
+ rhs = re.sub(r"/\*.*?\*/", "", rhs)
1311
+ out, in_str, quote, esc = [], False, "", False
1312
+ for ch in rhs:
1313
+ if esc:
1314
+ out.append(ch)
1315
+ esc = False
1316
+ elif ch == "\\" and in_str:
1317
+ out.append(ch)
1318
+ esc = True
1319
+ elif ch in ("\"", "'", "`") and (not in_str or ch == quote):
1320
+ in_str, quote = not in_str, ch if not in_str else ""
1321
+ out.append(ch)
1322
+ elif ch == "/" and not in_str and out and out[-1] == "/":
1323
+ out.pop()
1324
+ break
1325
+ else:
1326
+ out.append(ch)
1327
+ rhs = "".join(out).strip().rstrip(";").strip()
1328
+ if not re.fullmatch(r"[A-Za-z_$#][\w$#]*(?:\.[A-Za-z_$#][\w$#]*)*|-?\d+(?:\.\d+)?|"
1329
+ r"\"(?:[^\"\\]|\\.)*\"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`", rhs):
1330
+ return None
1331
+ return rhs
1332
+
1333
+
1334
+ def _value_satisfies(g, rhs: str, lang: str) -> bool | None:
1335
+ """A right-hand side satisfies a guard's test (names match textually)."""
1336
+ spellings = set()
1337
+ for r in g.reads:
1338
+ spellings |= {r, _field(r), f"this.{_field(r)}", f"self.{_field(r)}"}
1339
+ lt = _lit_test(g.text, spellings)
1340
+ if lt is not None:
1341
+ return _holds_rhs(lt, rhs, lang)
1342
+ cmp = _int_test(g.text, spellings)
1343
+ if cmp is not None and re.fullmatch(r"-?\d+", rhs.strip()):
1344
+ return _OPS[cmp[0]](int(rhs.strip()), cmp[1])
1345
+ return None
1346
+
1347
+
1348
+ def _holds_rhs(parsed: tuple[str, str | None], rhs: str, lang: str) -> bool | None:
1349
+ """A guard test evaluated with a right-hand side spelling (aliases undecided)."""
1350
+ op, lit = parsed
1351
+ r = rhs.strip()
1352
+ if op in ("truthy", "falsy"):
1353
+ if re.fullmatch(r"[A-Za-z_][\w$]*", r) and r.lower() not in (
1354
+ "true", "false", "null", "none", "nil", "undefined"):
1355
+ return None # a name's truthiness is unknown
1356
+ return _holds_lit(parsed, r, lang)
1357
+ assert lit is not None
1358
+ if _is_name(r) or _is_name(lit):
1359
+ if _is_name(r) and _is_name(lit) and _simple_match(r, lit):
1360
+ return op in ("==", "===")
1361
+ return None # aliases possible: undecided
1362
+ return _holds_lit((op, lit), r, lang)
1363
+
1364
+
1365
+ def _is_name(s: str) -> bool:
1366
+ return re.fullmatch(r"[A-Za-z_$#][\w$#]*(?:\.[A-Za-z_$#][\w$#]*)*", s) is not None
1367
+
1368
+
1369
+ def _simple_match(a: str, b: str) -> bool:
1370
+ """Same spelling, or one side bare matching the other's simple name (enum-style)."""
1371
+ if a == b:
1372
+ return True
1373
+ sa, sb = a.rsplit(".", 1)[-1], b.rsplit(".", 1)[-1]
1374
+ return sa == sb and ("." not in a or "." not in b)
1375
+
1376
+
1377
+ # -- single-write flags with contradictory requirements (uncertain) ----------------------------------------
1378
+
1379
+ _BRANCH_GOV_KINDS = {"if", "else", "match", "ternary", "exit"}
1380
+ _LOOP_GOV_KINDS = {"while", "for"}
1381
+
1382
+
1383
+ def g2_checks(q, mod, steps, located, trace, *, pc_var="pc", fns=None) -> list:
1384
+ """A step's write sits under a branch requiring F==V while an established
1385
+ counter-requirement (deferred-installation or direct callers) needs F==¬V, with F
1386
+ written exactly once (per-instance constant). Unlocated steps scan @code functions
1387
+ plus lexical descendants; located steps scan their segment."""
1388
+ from .confirm import Check
1389
+ if getattr(q, "language", "") not in ("node", "go"):
1390
+ return []
1391
+ for meth in ("guards", "write_sites", "callers", "source_line", "deferred_edges"):
1392
+ if not hasattr(q, meth):
1393
+ return []
1394
+ fns = fns if fns is not None else {}
1395
+ out = []
1396
+ for i, st in enumerate(steps):
1397
+ changed = [v for v in (getattr(st, "changed", None) or [])
1398
+ if v in _mapped_fields(mod, pc_var)]
1399
+ if not changed:
1400
+ continue
1401
+ sites = _g2_write_sites(q, mod, st, steps, i, located, fns, changed)
1402
+ for wfn, wline, var in sites:
1403
+ try:
1404
+ gs = q.guards(wfn, wline)
1405
+ except NotImplementedError:
1406
+ continue
1407
+ for g in gs:
1408
+ for fld, parsed, pol in _requirements(q, wfn, g, mod):
1409
+ const = _flag_constancy(q, mod, fld, wfn)
1410
+ if const is None:
1411
+ continue
1412
+ req = (parsed, pol)
1413
+ contra = _counter_requirement(q, mod, wfn, fld, req)
1414
+ if contra is None:
1415
+ continue
1416
+ out.append(Check("guard", "uncertain",
1417
+ f"step {st.k} ({st.thread} {st.action}) writes {var} at "
1418
+ f"{wfn}:{wline} under `{g.text}` requiring {fld} {_req_text(req)}, but "
1419
+ f"{contra} requires it otherwise, and {fld} is written once "
1420
+ f"({const}; aliasing or computed writes would void this)",
1421
+ {"step": st.k, "variable": var, "guard": g.text,
1422
+ "flag": fld}))
1423
+ return out
1424
+
1425
+
1426
+ def _g2_write_sites(q, mod, st, steps, i, located, fns, changed):
1427
+ """(fn, line, var) writes of the step's mapped vars in its scope (segment or @code+nested)."""
1428
+ here = located(st.step)
1429
+ states = {}
1430
+ for v in changed:
1431
+ for s in _var_states(mod, v):
1432
+ states.setdefault(s, v)
1433
+ if here is not None:
1434
+ _, line, fn = here
1435
+ nxt = next((s for s in steps[i + 1:] if s.thread == st.thread), None)
1436
+ there = located(nxt.step) if nxt is not None else None
1437
+ segs = [(fn, line, there[1] if there is not None and there[2] == fn and there[1] > line
1438
+ else None)]
1439
+ if there is not None and (there[2] != fn or there[1] <= line):
1440
+ try:
1441
+ end = q.span(fn)[1] + 1
1442
+ except (NotImplementedError, AttributeError, TypeError):
1443
+ end = None
1444
+ segs = [(fn, line, end)]
1445
+ try:
1446
+ fstart = q.span(there[2])[0]
1447
+ except (NotImplementedError, AttributeError, TypeError):
1448
+ fstart = None
1449
+ if fstart is not None:
1450
+ segs.append((there[2], fstart, there[1]))
1451
+ out = []
1452
+ for fn2, lo, hi in segs:
1453
+ for state, v in states.items():
1454
+ try:
1455
+ rows = q.write_sites(state)
1456
+ except NotImplementedError:
1457
+ continue
1458
+ out += [(fn2, s.line, v) for s in rows if s.function == fn2 and s.line >= lo
1459
+ and (hi is None or s.line < hi)]
1460
+ return out
1461
+ codefns = set(fns.get(st.action, []))
1462
+ r = getattr(q, "r", None)
1463
+ allfns = list(getattr(r, "fns", {}).keys()) if r is not None else []
1464
+ nested = {g for g in allfns for f in list(codefns)
1465
+ if g.startswith(f + ".") or g.startswith(f + "$")}
1466
+ scope = codefns | nested
1467
+ out = []
1468
+ for state, v in states.items():
1469
+ try:
1470
+ rows = q.write_sites(state)
1471
+ except NotImplementedError:
1472
+ continue
1473
+ out += [(s.function, s.line, v) for s in rows if s.function in scope]
1474
+ return out
1475
+
1476
+
1477
+ def _split_conjuncts(text: str) -> list[str] | None:
1478
+ """Top-level && conjuncts, or None when a top-level || appears (disjunction unpinned)."""
1479
+ if _has_toplevel_op(text, "||"):
1480
+ return None
1481
+ return [p.strip() for p in _split_toplevel(text, "&&") if p.strip()]
1482
+
1483
+
1484
+ def _has_toplevel_op(text: str, op: str) -> bool:
1485
+ depth, in_str, quote, esc, i = 0, False, "", False, 0
1486
+ while i < len(text):
1487
+ ch = text[i]
1488
+ if esc:
1489
+ esc = False
1490
+ elif ch == "\\" and in_str:
1491
+ esc = True
1492
+ elif ch in ("\"", "'", "`") and (not in_str or ch == quote):
1493
+ in_str, quote = (not in_str, ch if not in_str else "")
1494
+ elif not in_str and ch in "([":
1495
+ depth += 1
1496
+ elif not in_str and ch in ")]":
1497
+ depth = max(0, depth - 1)
1498
+ elif not in_str and depth == 0 and text.startswith(op, i):
1499
+ if op in ("&&", "||") or True:
1500
+ return True
1501
+ i += 1
1502
+ return False
1503
+
1504
+
1505
+ def _split_toplevel(text: str, op: str) -> list[str]:
1506
+ parts, depth, in_str, quote, esc, cur, i = [], 0, False, "", False, [], 0
1507
+ while i < len(text):
1508
+ ch = text[i]
1509
+ if esc:
1510
+ cur.append(ch)
1511
+ esc = False
1512
+ elif ch == "\\" and in_str:
1513
+ cur.append(ch)
1514
+ esc = True
1515
+ elif ch in ("\"", "'", "`") and (not in_str or ch == quote):
1516
+ in_str, quote = (not in_str, ch if not in_str else "")
1517
+ cur.append(ch)
1518
+ elif not in_str and ch in "([":
1519
+ depth += 1
1520
+ cur.append(ch)
1521
+ elif not in_str and ch in ")]":
1522
+ depth = max(0, depth - 1)
1523
+ cur.append(ch)
1524
+ elif not in_str and depth == 0 and text.startswith(op, i):
1525
+ parts.append("".join(cur))
1526
+ cur = []
1527
+ i += len(op)
1528
+ continue
1529
+ else:
1530
+ cur.append(ch)
1531
+ i += 1
1532
+ parts.append("".join(cur))
1533
+ return parts
1534
+
1535
+
1536
+ def _requirements(q, fn: str, g, mod) -> list:
1537
+ """(field, parsed-test) a guard establishes when taken (conjunction-aware)."""
1538
+ reqs = []
1539
+ if g.kind in ("select", "select-default"):
1540
+ return reqs
1541
+ conjuncts = _split_conjuncts(g.text)
1542
+ if conjuncts is None:
1543
+ if g.polarity:
1544
+ return reqs # disjunction may hold either way
1545
+ parts = _split_toplevel(g.text, "||") # De Morgan: else of || pins each false
1546
+ return [r for c in parts if (r := _conjunct_req(q, fn, g, c, False)) is not None]
1547
+ if len(conjuncts) <= 1:
1548
+ conjuncts = [g.text]
1549
+ for c in conjuncts:
1550
+ r = _conjunct_req(q, fn, g, c, g.polarity)
1551
+ if r is not None:
1552
+ reqs.append(r)
1553
+ return reqs
1554
+
1555
+
1556
+ def _conjunct_req(q, fn: str, g, text, polarity):
1557
+ """(field, parsed, required-holds) for one conjunct naming exactly one guard read."""
1558
+ reads = [r for r in _guard_reads(q, fn, g)
1559
+ if re.search(rf"(?<![\w$#]){re.escape(r)}(?![\w$#])", text)]
1560
+ if len(reads) != 1:
1561
+ return None
1562
+ fld = _field(reads[0])
1563
+ spellings = {reads[0], fld, f"this.{fld}", f"self.{fld}"}
1564
+ lt = _lit_test(text, spellings)
1565
+ if lt is not None:
1566
+ return (fld, ("lit", lt), polarity)
1567
+ cmp = _int_test(text, spellings)
1568
+ if cmp is not None:
1569
+ return (fld, ("int", cmp), polarity)
1570
+ return None
1571
+
1572
+
1573
+ def _flag_constancy(q, mod, fld: str, fn: str):
1574
+ """Why flag F is per-instance constant (single unconditional write), else None."""
1575
+ r = getattr(q, "r", None)
1576
+ fns = getattr(r, "fns", None)
1577
+ if not isinstance(fns, dict):
1578
+ return None
1579
+ sites = []
1580
+ for fq, g in fns.items():
1581
+ for a in g.get("accesses", []):
1582
+ if a["state"].rsplit(".", 1)[-1] != fld or a["rw"] not in ("write", "rw"):
1583
+ continue
1584
+ sites.append((fq, a["line"]))
1585
+ if len(sites) != 1:
1586
+ return None
1587
+ wfn, wline = sites[0]
1588
+ try:
1589
+ govs = q.guards(wfn, wline)
1590
+ except NotImplementedError:
1591
+ return None
1592
+ if any(g.kind in _BRANCH_GOV_KINDS for g in govs):
1593
+ return None
1594
+ if any(g.kind in _LOOP_GOV_KINDS for g in govs):
1595
+ if not hasattr(q, "source_line"):
1596
+ return None
1597
+ rhs = _split_assign(q.source_line(wfn, wline), fld)
1598
+ if rhs is None or not re.fullmatch(r"true|false|None|null|nil|undefined|-?\d+(?:\.\d+)?|"
1599
+ r"\"(?:[^\"\\]|\\.)*\"|'(?:[^'\\]|\\.)*'", rhs.strip()):
1600
+ return None # loop-varying dynamic value
1601
+ return f"one write at {wfn}:{wline} (loop-constant {rhs})"
1602
+ g = fns.get(wfn, {})
1603
+ if g.get("kind") != "constructor" and g.get("name") != "$init":
1604
+ calls = []
1605
+ if hasattr(q, "callers"):
1606
+ try:
1607
+ calls = q.callers(wfn)
1608
+ except NotImplementedError:
1609
+ calls = []
1610
+ if len(calls) != 1 or calls[0].function == wfn:
1611
+ return None # repeatedly-called initializer
1612
+ try:
1613
+ cgovs = q.guards(calls[0].function, calls[0].line)
1614
+ except NotImplementedError:
1615
+ cgovs = []
1616
+ if any(c.kind in _LOOP_GOV_KINDS for c in cgovs):
1617
+ return None # called from a loop
1618
+ setter = fld.lstrip("#").lower()
1619
+ for g in fns.values():
1620
+ for c in g.get("calls", []):
1621
+ if (c.get("method") or "").lower() in ("set" + setter, "set_" + setter):
1622
+ return None # a setter may rewrite it
1623
+ return f"one write at {wfn}:{wline}"
1624
+
1625
+
1626
+ def _counter_requirement(q, mod, st_fn: str, fld: str, req):
1627
+ """An established counter-requirement on F (installation/direct callers), else None."""
1628
+ cands: list[tuple] = []
1629
+ try:
1630
+ edges = q.deferred_edges() if hasattr(q, "deferred_edges") else []
1631
+ except NotImplementedError:
1632
+ edges = []
1633
+ for e in edges:
1634
+ cb = e.get("callback", "")
1635
+ if st_fn != cb and not st_fn.startswith(cb + ".") and not st_fn.startswith(cb + "$"):
1636
+ continue
1637
+ sched = e.get("scheduler", "")
1638
+ try:
1639
+ callers = q.callers(sched) if hasattr(q, "callers") else []
1640
+ except NotImplementedError:
1641
+ callers = []
1642
+ for s in callers:
1643
+ cands.append((s.function, s.line, f"installation via {sched} called at {s.function}:{s.line}"))
1644
+ try:
1645
+ direct = q.callers(st_fn) if hasattr(q, "callers") else []
1646
+ except NotImplementedError:
1647
+ direct = []
1648
+ for s in direct:
1649
+ cands.append((s.function, s.line, f"caller {s.function}:{s.line}"))
1650
+ for fn2, ln2, why in cands:
1651
+ try:
1652
+ gs = q.guards(fn2, ln2)
1653
+ except NotImplementedError:
1654
+ continue
1655
+ for g in gs:
1656
+ for f2, parsed2, pol2 in _requirements(q, fn2, g, mod):
1657
+ if f2 != fld:
1658
+ continue
1659
+ if _reqs_contradict(req[0], req[1], parsed2, pol2):
1660
+ return f"{why} (`{g.text}`)"
1661
+ return None
1662
+
1663
+
1664
+ def _req_text(req) -> str:
1665
+ """A (parsed, polarity) requirement as prose (``falsy``, ``== 3``)."""
1666
+ c = _constraint(req[0], req[1])
1667
+ if c is None:
1668
+ return "?"
1669
+ if c[0] == "lit":
1670
+ op, lit = c[1]
1671
+ return {"truthy": "truthy", "falsy": "falsy"}.get(op, f"{op} {lit}")
1672
+ return f"{c[1][0]} {c[1][1]}"
1673
+
1674
+
1675
+ def _reqs_contradict(a, pa, b, pb) -> bool:
1676
+ """Two (parsed, required-holds) requirements on one field are jointly unsatisfiable."""
1677
+ ca, cb = _constraint(a, pa), _constraint(b, pb)
1678
+ if ca is None or cb is None:
1679
+ return False
1680
+ return _disjoint(ca, cb)
1681
+
1682
+
1683
+ def _constraint(parsed, polarity: bool):
1684
+ """A requirement as (kind, payload), polarity applied; None when unknowable."""
1685
+ kind, p = parsed
1686
+ if kind == "lit":
1687
+ op, lit = p
1688
+ if not polarity:
1689
+ op = {"==": "!=", "!=": "==", "===": "!==", "!==": "===",
1690
+ "truthy": "falsy", "falsy": "truthy"}[op]
1691
+ return ("lit", (op, lit))
1692
+ op, c = p
1693
+ if not polarity:
1694
+ op = {"<": ">=", "<=": ">", ">": "<=", ">=": "<", "==": "!=", "!=": "=="}[op]
1695
+ return ("int", (op, c))
1696
+
1697
+
1698
+ def _disjoint(a, b) -> bool:
1699
+ ka, pa = a
1700
+ kb, pb = b
1701
+ if ka == "lit" and kb == "lit":
1702
+ return _lits_disjoint(pa, pb)
1703
+ if ka == "int" and kb == "int":
1704
+ return _intervals_disjoint(pa, pb)
1705
+ la, ia = (pa, pb) if ka == "lit" else (pb, pa)
1706
+ return _lit_int_disjoint(la, ia)
1707
+
1708
+
1709
+ def _lits_disjoint(a, b) -> bool:
1710
+ (oa, la), (ob, lb) = a, b
1711
+ ta = (oa == "truthy") if oa in ("truthy", "falsy") else None
1712
+ tb = (ob == "truthy") if ob in ("truthy", "falsy") else None
1713
+ if ta is not None and tb is not None:
1714
+ return ta != tb
1715
+ if ta is not None or tb is not None:
1716
+ want_true = ta if ta is not None else tb
1717
+ other = lb if ta is not None else la
1718
+ return _lit_truthy(other) is (not want_true)
1719
+ na = _is_name(la or "") and (la or "").lower() not in (
1720
+ "true", "false", "null", "none", "nil", "undefined")
1721
+ nb = _is_name(lb or "") and (lb or "").lower() not in (
1722
+ "true", "false", "null", "none", "nil", "undefined")
1723
+ if na or nb:
1724
+ if na and nb and _simple_match(la, lb):
1725
+ return (oa in ("==", "===")) != (ob in ("==", "==="))
1726
+ return False # aliases possible: undecided
1727
+ va, vb = _lit_value(la), _lit_value(lb)
1728
+ if va is None or vb is None:
1729
+ return False
1730
+ if oa in ("==", "===") and ob in ("==", "==="):
1731
+ return va != vb
1732
+ if oa in ("!=", "!==") and ob in ("!=", "!=="):
1733
+ return False # complements overlap
1734
+ eq, ne = (va, vb) if oa in ("==", "===") else (vb, va)
1735
+ return eq == ne
1736
+
1737
+
1738
+ def _lit_value(lit):
1739
+ """A literal's abstract value: number, string, bool, null, or None when unknowable."""
1740
+ if lit is None:
1741
+ return None
1742
+ s = lit.strip()
1743
+ if re.fullmatch(r"[A-Za-z_][\w$]*", s) and s.lower() not in (
1744
+ "true", "false", "null", "none", "nil", "undefined"):
1745
+ if "." in lit:
1746
+ return lit # dotted path: spelling identity only
1747
+ return None
1748
+ return _norm_lit(s)
1749
+
1750
+
1751
+ def _lit_truthy(v) -> bool | None:
1752
+ if v is None:
1753
+ return None
1754
+ if len(v) >= 2 and v[0] == v[-1] and v[0] in ("\"", "'"):
1755
+ v = v[1:-1]
1756
+ if v in ("true",):
1757
+ return True
1758
+ if v in ("false", "null", ""):
1759
+ return False
1760
+ if re.fullmatch(r"0[xX][0-9a-fA-F]+", v):
1761
+ try:
1762
+ return int(v, 16) != 0
1763
+ except ValueError:
1764
+ return None
1765
+ if re.fullmatch(r"-?\d+(?:\.\d+)?", v):
1766
+ try:
1767
+ return float(v) != 0.0
1768
+ except ValueError:
1769
+ return None
1770
+ if v.startswith(("[", "{", "(")):
1771
+ return None
1772
+ if re.fullmatch(r"[A-Za-z_][\w$]*", v):
1773
+ return None
1774
+ return True
1775
+
1776
+
1777
+ def _lit_int_disjoint(lit, iv) -> bool:
1778
+ op, c = iv
1779
+ if lit[0] in ("truthy", "falsy"):
1780
+ if lit[0] == "truthy":
1781
+ return False # some truthy number always fits
1782
+ return not _in_interval("0", iv)
1783
+ v = _lit_value(lit[1])
1784
+ if v is None or not re.fullmatch(r"-?\d+(?:\.\d+)?", v):
1785
+ return False
1786
+ if lit[0] in ("==", "==="):
1787
+ return not _in_interval(v, iv)
1788
+ return False # != ranges always overlap something
1789
+
1790
+
1791
+ def _in_interval(lit: str, iv) -> bool | None:
1792
+ op, c = iv
1793
+ if not re.fullmatch(r"-?\d+(?:\.\d+)?", lit):
1794
+ return None
1795
+ return _OPS[op](float(lit), c)
1796
+
1797
+
1798
+ def _intervals_disjoint(a, b) -> bool:
1799
+ (oa, ca), (ob, cb) = a, b
1800
+ if oa == "ne" or ob == "ne":
1801
+ return False # complements always overlap something
1802
+ lo_a, hi_a = _bounds(oa, ca)
1803
+ lo_b, hi_b = _bounds(ob, cb)
1804
+ if lo_a is None or lo_b is None:
1805
+ return False
1806
+ return lo_a[0] > hi_b[0] or (lo_a[0] == hi_b[0] and not (lo_a[1] and hi_b[1])) or \
1807
+ lo_b[0] > hi_a[0] or (lo_b[0] == hi_a[0] and not (lo_b[1] and hi_a[1]))
1808
+
1809
+
1810
+ def _bounds(op: str, c: int):
1811
+ inf = float("inf")
1812
+ if op == "==":
1813
+ return ((c, True), (c, True))
1814
+ if op == "<":
1815
+ return ((-inf, False), (c, False))
1816
+ if op == "<=":
1817
+ return ((-inf, False), (c, True))
1818
+ if op == ">":
1819
+ return ((c, False), (inf, False))
1820
+ if op == ">=":
1821
+ return ((c, True), (inf, False))
1822
+ return (None, None)
1823
+
1824
+
1825
+ # -- read-modify-write flow ----------------------------------------------------------------------------------
1826
+
1827
+ def _primes(mod, action: str) -> dict[str, str]:
1828
+ """variable -> the right-hand side of its prime, for each ``v' = rhs`` top-level conjunct of ``action``."""
1829
+ d = mod.definitions.get(action)
1830
+ out = {}
1831
+ if d is None:
1832
+ return out
1833
+ for part in top_level_conjuncts(d.body):
1834
+ m = re.match(r"\s*(\w+)'\s*=\s*(.+?)\s*$", part, re.S)
1835
+ if m and m.group(1) in mod.variables:
1836
+ out[m.group(1)] = m.group(2)
1837
+ return out
1838
+
1839
+
1840
+ def _names(text: str, v: str) -> bool:
1841
+ return re.search(rf"(?<![\w']){re.escape(v)}(?![\w'])", text) is not None
1842
+
1843
+
1844
+ def flow_checks(q, mod, steps, located, *, pc_var: str = "pc", notes: list | None = None) -> list:
1845
+ """For each read-then-write pair the spec declares, the code's ``flows`` between the two
1846
+ steps' locations. ``yes`` gives a passing ``flow`` check. ``no`` gives no check, only a note in ``notes``: a write
1847
+ that does not use the read can still lose updates (read-then-clear, ``self.buf = []``), so it must not move a
1848
+ verdict. ``unknown`` gives nothing."""
1849
+ from .confirm import Check
1850
+ from .queries import Site
1851
+ tags = mod.declaration_tags
1852
+ kinds = mod.variable_kinds()
1853
+
1854
+ def fields(v):
1855
+ refs = tags.get(v, (0, None))[1]
1856
+ return [r for r in (refs.code if refs is not None else [])]
1857
+ modelled = {v for v in mod.variables if v != pc_var and kinds.get(v) == ["python-state"] and fields(v)}
1858
+ local = {v for v in mod.variables if v != pc_var and v not in modelled}
1859
+ out = []
1860
+ for i, a in enumerate(steps):
1861
+ pa = _primes(mod, a.action)
1862
+ holds = {u: v for u, rhs in pa.items() if u in local for v in modelled if _names(rhs, v)}
1863
+ if not holds:
1864
+ continue
1865
+ for b in steps[i + 1:]:
1866
+ if b.thread != a.thread:
1867
+ continue
1868
+ pb = _primes(mod, b.action)
1869
+ pair = next(((u, v) for u, v in holds.items() if v in pb and _names(pb[v], u)), None)
1870
+ if pair is None:
1871
+ continue
1872
+ u, v = pair
1873
+ la, lb = located(a.step), located(b.step)
1874
+ if la is None or lb is None or not hasattr(q, "flows"): # two functions are asked too
1875
+ break
1876
+ try:
1877
+ fl = q.flows(Site(la[2], la[0], la[1]), Site(lb[2], lb[0], lb[1]))
1878
+ except NotImplementedError:
1879
+ break
1880
+ head = (f"step {b.k} ({b.thread} {b.action}) writes {v} from {u}, which step {a.k} ({a.action}) read from "
1881
+ f"{v}")
1882
+ detail = {"read": a.k, "write": b.k, "variable": v, "flow": fl.answer}
1883
+ if fl.answer == "yes":
1884
+ out.append(Check("flow", "pass", f"{head}: the code's write at {lb[0]}:{lb[1]} uses the value read at "
1885
+ f"{la[0]}:{la[1]}" + (f" (via {' -> '.join(fl.via)})" if fl.via
1886
+ else ""), detail))
1887
+ elif fl.answer == "no" and notes is not None:
1888
+ notes.append({"step": b.k, "action": b.action, "status": "flow-not-used", "variable": v,
1889
+ "read_step": a.k, "why": f"{head}, but the code's write at {lb[0]}:{lb[1]} does not use "
1890
+ f"the value read at {la[0]}:{la[1]} ({fl.why})"})
1891
+ # an undecided flow adds no check: a spec may anchor its read and write steps where the code's lines do
1892
+ # not show them (two steps on one line, a write located off the write's line), and only a
1893
+ # decided answer may move a verdict, as in branch_checks
1894
+ break
1895
+ return out