gdp-wired 0.48.0 → 0.50.0

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 (361) hide show
  1. package/README.md +6 -2
  2. package/dist/core/bmc.js +10 -7
  3. package/dist/core/candidate-seeds.d.ts +25 -0
  4. package/dist/core/candidate-seeds.js +90 -0
  5. package/dist/core/check.js +7 -2
  6. package/dist/core/cli.js +3 -0
  7. package/dist/core/count-attempt-work.d.ts +29 -0
  8. package/dist/core/count-attempt-work.js +96 -0
  9. package/dist/core/count-boolean-partition.d.ts +5 -0
  10. package/dist/core/count-boolean-partition.js +47 -0
  11. package/dist/core/count-bounded-quotient.d.ts +2 -0
  12. package/dist/core/count-bounded-quotient.js +13 -0
  13. package/dist/core/count-case-compose.d.ts +20 -0
  14. package/dist/core/count-case-compose.js +289 -0
  15. package/dist/core/count-cases.js +3 -2
  16. package/dist/core/count-cert-rename.d.ts +10 -0
  17. package/dist/core/count-cert-rename.js +69 -0
  18. package/dist/core/count-cert-transport.d.ts +10 -2
  19. package/dist/core/count-cert-transport.js +60 -9
  20. package/dist/core/count-certificate-minimize.d.ts +57 -0
  21. package/dist/core/count-certificate-minimize.js +263 -0
  22. package/dist/core/count-closed-family.d.ts +32 -0
  23. package/dist/core/count-closed-family.js +143 -0
  24. package/dist/core/count-closing-budget.d.ts +10 -0
  25. package/dist/core/count-closing-budget.js +49 -0
  26. package/dist/core/count-closing-needs.d.ts +5 -0
  27. package/dist/core/count-closing-needs.js +9 -0
  28. package/dist/core/count-component-budget.d.ts +5 -0
  29. package/dist/core/count-component-budget.js +9 -0
  30. package/dist/core/count-copy-shape.d.ts +11 -0
  31. package/dist/core/count-copy-shape.js +40 -0
  32. package/dist/core/count-disjoint-funding.d.ts +75 -0
  33. package/dist/core/count-disjoint-funding.js +284 -0
  34. package/dist/core/count-emitter-frame-pool.d.ts +23 -0
  35. package/dist/core/count-emitter-frame-pool.js +87 -0
  36. package/dist/core/count-final-step.d.ts +5 -0
  37. package/dist/core/count-final-step.js +20 -0
  38. package/dist/core/count-fixed-frame.d.ts +4 -0
  39. package/dist/core/count-fixed-frame.js +30 -0
  40. package/dist/core/count-frames.d.ts +25 -0
  41. package/dist/core/count-frames.js +118 -0
  42. package/dist/core/count-frozen-guard.d.ts +2 -0
  43. package/dist/core/count-frozen-guard.js +31 -0
  44. package/dist/core/count-generation-phase.d.ts +7 -0
  45. package/dist/core/count-generation-phase.js +33 -0
  46. package/dist/core/count-guard-composition.d.ts +12 -0
  47. package/dist/core/count-guard-composition.js +48 -0
  48. package/dist/core/count-guard-context.d.ts +11 -0
  49. package/dist/core/count-guard-context.js +50 -0
  50. package/dist/core/count-guard-facts.d.ts +50 -0
  51. package/dist/core/count-guard-facts.js +97 -0
  52. package/dist/core/count-guard-proposals.d.ts +7 -0
  53. package/dist/core/count-guard-proposals.js +106 -0
  54. package/dist/core/count-guard-shape.d.ts +18 -0
  55. package/dist/core/count-guard-shape.js +100 -0
  56. package/dist/core/count-guard-tree.d.ts +17 -0
  57. package/dist/core/count-guard-tree.js +125 -0
  58. package/dist/core/count-leader-facts.d.ts +10 -0
  59. package/dist/core/count-leader-facts.js +52 -0
  60. package/dist/core/count-leader.d.ts +10 -0
  61. package/dist/core/count-leader.js +331 -0
  62. package/dist/core/count-lemma-transport.d.ts +8 -0
  63. package/dist/core/count-lemma-transport.js +47 -0
  64. package/dist/core/count-lifted-budget.d.ts +54 -0
  65. package/dist/core/count-lifted-budget.js +97 -0
  66. package/dist/core/count-lifted-copy.d.ts +3 -0
  67. package/dist/core/count-lifted-copy.js +166 -0
  68. package/dist/core/count-lifted-increment.d.ts +3 -0
  69. package/dist/core/count-lifted-increment.js +146 -0
  70. package/dist/core/count-lifted-load.d.ts +5 -0
  71. package/dist/core/count-lifted-load.js +179 -0
  72. package/dist/core/count-lifted-prerequisite.d.ts +14 -0
  73. package/dist/core/count-lifted-prerequisite.js +53 -0
  74. package/dist/core/count-lifted-replacement.d.ts +3 -0
  75. package/dist/core/count-lifted-replacement.js +540 -0
  76. package/dist/core/count-lifted-shape.d.ts +63 -0
  77. package/dist/core/count-lifted-shape.js +115 -0
  78. package/dist/core/count-lifted-strategy.d.ts +7 -0
  79. package/dist/core/count-lifted-strategy.js +226 -0
  80. package/dist/core/count-lifted-transports.d.ts +32 -0
  81. package/dist/core/count-lifted-transports.js +293 -0
  82. package/dist/core/count-load-shape.d.ts +17 -0
  83. package/dist/core/count-load-shape.js +67 -0
  84. package/dist/core/count-minimal-view.d.ts +26 -0
  85. package/dist/core/count-minimal-view.js +46 -0
  86. package/dist/core/count-operation-observation.d.ts +9 -0
  87. package/dist/core/count-operation-observation.js +22 -0
  88. package/dist/core/count-operation-order.d.ts +5 -0
  89. package/dist/core/count-operation-order.js +4 -0
  90. package/dist/core/count-phase.d.ts +9 -0
  91. package/dist/core/count-phase.js +127 -0
  92. package/dist/core/count-premise-search.d.ts +9 -0
  93. package/dist/core/count-premise-search.js +41 -0
  94. package/dist/core/count-premise-view.d.ts +19 -0
  95. package/dist/core/count-premise-view.js +220 -0
  96. package/dist/core/count-prerequisite-components.d.ts +67 -0
  97. package/dist/core/count-prerequisite-components.js +239 -0
  98. package/dist/core/count-prerequisite-memory.d.ts +24 -0
  99. package/dist/core/count-prerequisite-memory.js +37 -0
  100. package/dist/core/count-prerequisite-plan.d.ts +12 -0
  101. package/dist/core/count-prerequisite-plan.js +88 -0
  102. package/dist/core/count-primitive-budget.d.ts +1 -0
  103. package/dist/core/count-primitive-budget.js +8 -0
  104. package/dist/core/count-project-free.d.ts +3 -0
  105. package/dist/core/count-project-free.js +24 -0
  106. package/dist/core/count-project-witness.d.ts +4 -0
  107. package/dist/core/count-project-witness.js +48 -0
  108. package/dist/core/count-proof-rescope.d.ts +14 -0
  109. package/dist/core/count-proof-rescope.js +71 -0
  110. package/dist/core/count-proof-scope.d.ts +68 -0
  111. package/dist/core/count-proof-scope.js +333 -0
  112. package/dist/core/count-prune-owned-root.d.ts +5 -0
  113. package/dist/core/count-prune-owned-root.js +27 -0
  114. package/dist/core/count-query-context.d.ts +3 -0
  115. package/dist/core/count-query-context.js +7 -0
  116. package/dist/core/count-query.d.ts +15 -0
  117. package/dist/core/count-query.js +59 -0
  118. package/dist/core/count-quorum-leaf.d.ts +9 -0
  119. package/dist/core/count-quorum-leaf.js +38 -0
  120. package/dist/core/count-reachability-budget.d.ts +1 -0
  121. package/dist/core/count-reachability-budget.js +7 -0
  122. package/dist/core/count-reachability-reconcile.d.ts +11 -0
  123. package/dist/core/count-reachability-reconcile.js +19 -0
  124. package/dist/core/count-reachability.d.ts +50 -0
  125. package/dist/core/count-reachability.js +351 -0
  126. package/dist/core/count-rebase-path.d.ts +9 -0
  127. package/dist/core/count-rebase-path.js +68 -0
  128. package/dist/core/count-recipe-context.d.ts +45 -0
  129. package/dist/core/count-recipe-context.js +71 -0
  130. package/dist/core/count-recipe-controller.d.ts +115 -0
  131. package/dist/core/count-recipe-controller.js +417 -0
  132. package/dist/core/count-recipe-graph.d.ts +36 -0
  133. package/dist/core/count-recipe-graph.js +211 -0
  134. package/dist/core/count-recovery/conditional-check-cache.js +3 -2
  135. package/dist/core/count-recovery/conditional-cuts.js +5 -4
  136. package/dist/core/count-recovery/conditional-proof.d.ts +37 -3
  137. package/dist/core/count-recovery/conditional-proof.js +72 -30
  138. package/dist/core/count-recovery/derivability-closure.js +2 -1
  139. package/dist/core/count-recovery/guard-cases.js +2 -1
  140. package/dist/core/count-recovery/reframe-tree.d.ts +2 -0
  141. package/dist/core/count-recovery/reframe-tree.js +24 -0
  142. package/dist/core/count-recovery/replay-linear-skeleton.d.ts +2 -0
  143. package/dist/core/count-recovery/replay-linear-skeleton.js +28 -0
  144. package/dist/core/count-recovery/row-cases.js +2 -1
  145. package/dist/core/count-rejection-budget.d.ts +8 -0
  146. package/dist/core/count-rejection-budget.js +15 -0
  147. package/dist/core/count-replacement.d.ts +5 -0
  148. package/dist/core/count-replacement.js +129 -0
  149. package/dist/core/count-replay-diagnostic.d.ts +21 -0
  150. package/dist/core/count-replay-diagnostic.js +49 -0
  151. package/dist/core/count-replay-skeleton.d.ts +4 -0
  152. package/dist/core/count-replay-skeleton.js +28 -0
  153. package/dist/core/count-rescope-funding.d.ts +3 -0
  154. package/dist/core/count-rescope-funding.js +17 -0
  155. package/dist/core/count-restrictions.d.ts +11 -0
  156. package/dist/core/count-restrictions.js +31 -0
  157. package/dist/core/count-retry-budget.d.ts +67 -0
  158. package/dist/core/count-retry-budget.js +114 -0
  159. package/dist/core/count-retry-round.d.ts +24 -0
  160. package/dist/core/count-retry-round.js +44 -0
  161. package/dist/core/count-row-agreement.d.ts +35 -0
  162. package/dist/core/count-row-agreement.js +270 -0
  163. package/dist/core/count-row-aliases.d.ts +3 -0
  164. package/dist/core/count-row-aliases.js +59 -0
  165. package/dist/core/count-row-composition.d.ts +6 -0
  166. package/dist/core/count-row-composition.js +55 -0
  167. package/dist/core/count-row-copy-linear.d.ts +4 -0
  168. package/dist/core/count-row-copy-linear.js +83 -0
  169. package/dist/core/count-row-copy.d.ts +4 -0
  170. package/dist/core/count-row-copy.js +94 -0
  171. package/dist/core/count-row-policy.d.ts +3 -0
  172. package/dist/core/count-row-policy.js +56 -0
  173. package/dist/core/count-row-reindex.d.ts +11 -0
  174. package/dist/core/count-row-reindex.js +126 -0
  175. package/dist/core/count-row-support.d.ts +9 -0
  176. package/dist/core/count-row-support.js +42 -0
  177. package/dist/core/count-row-symmetry.d.ts +7 -0
  178. package/dist/core/count-row-symmetry.js +100 -0
  179. package/dist/core/count-scope-hyps.d.ts +2 -0
  180. package/dist/core/count-scope-hyps.js +163 -0
  181. package/dist/core/count-scope-row-reuse.d.ts +3 -0
  182. package/dist/core/count-scope-row-reuse.js +92 -0
  183. package/dist/core/count-search-allowance.d.ts +1 -0
  184. package/dist/core/count-search-allowance.js +17 -0
  185. package/dist/core/count-stabilize-tree.d.ts +9 -0
  186. package/dist/core/count-stabilize-tree.js +35 -0
  187. package/dist/core/count-stage-trace.d.ts +8 -0
  188. package/dist/core/count-stage-trace.js +45 -0
  189. package/dist/core/count-strategies.d.ts +16 -0
  190. package/dist/core/count-strategies.js +155 -0
  191. package/dist/core/count-strategy-premises.d.ts +5 -0
  192. package/dist/core/count-strategy-premises.js +14 -0
  193. package/dist/core/count-strategy.d.ts +41 -0
  194. package/dist/core/count-strategy.js +76 -0
  195. package/dist/core/count-support.d.ts +1 -0
  196. package/dist/core/count-support.js +26 -4
  197. package/dist/core/count-tier-budget.d.ts +14 -0
  198. package/dist/core/count-tier-budget.js +64 -0
  199. package/dist/core/count-unwritten-prefix.d.ts +24 -0
  200. package/dist/core/count-unwritten-prefix.js +97 -0
  201. package/dist/core/count-write-shape.d.ts +15 -0
  202. package/dist/core/count-write-shape.js +73 -0
  203. package/dist/core/counted-candidate-seeds.d.ts +12 -0
  204. package/dist/core/counted-candidate-seeds.js +31 -0
  205. package/dist/core/counts.d.ts +37 -13
  206. package/dist/core/counts.js +999 -129
  207. package/dist/core/cycles.js +5 -4
  208. package/dist/core/cyclic.js +11 -10
  209. package/dist/core/data.js +16 -15
  210. package/dist/core/dsl-deadline.d.ts +3 -0
  211. package/dist/core/dsl-deadline.js +27 -0
  212. package/dist/core/dsl.d.ts +32 -2
  213. package/dist/core/dsl.js +202 -64
  214. package/dist/core/evaluation-admission.d.ts +1 -0
  215. package/dist/core/evaluation-admission.js +3 -0
  216. package/dist/core/exists.d.ts +6 -1
  217. package/dist/core/exists.js +53 -10
  218. package/dist/core/field-laws.d.ts +3 -1
  219. package/dist/core/field-laws.js +159 -3
  220. package/dist/core/finite-houdini.d.ts +6 -0
  221. package/dist/core/finite-houdini.js +63 -21
  222. package/dist/core/finite-tiny.js +95 -67
  223. package/dist/core/fixtures/count-completion/paxos-decision.json +1 -0
  224. package/dist/core/fresh.js +5 -1
  225. package/dist/core/infer.js +49 -33
  226. package/dist/core/kind.js +2 -1
  227. package/dist/core/lemma-cuts.js +11 -10
  228. package/dist/core/lift-cli.d.ts +11 -0
  229. package/dist/core/lift-cli.js +113 -0
  230. package/dist/core/linear-admission.d.ts +14 -0
  231. package/dist/core/linear-admission.js +151 -0
  232. package/dist/core/machine.d.ts +5 -2
  233. package/dist/core/machine.js +105 -31
  234. package/dist/core/meter.d.ts +22 -0
  235. package/dist/core/meter.js +34 -0
  236. package/dist/core/nonterm.js +4 -3
  237. package/dist/core/proof-output.d.ts +53 -0
  238. package/dist/core/proof-output.js +38 -0
  239. package/dist/core/prover-row-budget.d.ts +3 -0
  240. package/dist/core/prover-row-budget.js +106 -0
  241. package/dist/core/quorum-laws.d.ts +21 -1
  242. package/dist/core/quorum-laws.js +80 -17
  243. package/dist/core/rationals.js +3 -2
  244. package/dist/core/rejection-discovery.d.ts +34 -0
  245. package/dist/core/rejection-discovery.js +36 -0
  246. package/dist/core/rejection-stage.d.ts +39 -0
  247. package/dist/core/rejection-stage.js +205 -0
  248. package/dist/core/request-quotient.d.ts +8 -0
  249. package/dist/core/request-quotient.js +299 -0
  250. package/dist/core/row-agreement-shape.d.ts +15 -0
  251. package/dist/core/row-agreement-shape.js +68 -0
  252. package/dist/core/runtime-wall.d.ts +2 -0
  253. package/dist/core/search-policy.d.ts +15 -0
  254. package/dist/core/search-policy.js +68 -0
  255. package/dist/core/solver.d.ts +1 -1
  256. package/dist/core/solver.js +40 -6
  257. package/dist/core/step-work.d.ts +12 -0
  258. package/dist/core/step-work.js +14 -0
  259. package/dist/core/strategy-premises.d.ts +8 -0
  260. package/dist/core/strategy-premises.js +64 -0
  261. package/dist/core/system.js +4 -3
  262. package/dist/core/table-admission.d.ts +1 -0
  263. package/dist/core/table-admission.js +3 -0
  264. package/dist/core/trace-clock.d.ts +3 -0
  265. package/dist/core/trace-clock.js +16 -0
  266. package/dist/core/transfer.js +3 -2
  267. package/dist/core/translate.js +16 -3
  268. package/dist/core/wall.d.ts +6 -1
  269. package/dist/core/wall.js +23 -9
  270. package/dist/core/watch.d.ts +1 -1
  271. package/dist/core/watch.js +13 -4
  272. package/dist/core/work-admission.d.ts +164 -0
  273. package/dist/core/work-admission.js +418 -0
  274. package/dist/core/work-amount.d.ts +21 -0
  275. package/dist/core/work-amount.js +80 -0
  276. package/dist/core/work-collections.d.ts +11 -0
  277. package/dist/core/work-collections.js +198 -0
  278. package/dist/core/work-kinds.d.ts +11 -0
  279. package/dist/core/work-kinds.js +9 -0
  280. package/dist/core/work-meter.d.ts +8 -0
  281. package/dist/core/work-meter.js +83 -0
  282. package/dist/core/work-observe.d.ts +12 -0
  283. package/dist/core/work-observe.js +39 -0
  284. package/dist/core/work-profile.d.ts +10 -0
  285. package/dist/core/work-profile.js +21 -0
  286. package/dist/core/work-refusal.d.ts +1 -0
  287. package/dist/core/work-refusal.js +6 -0
  288. package/dist/interchange/format.js +2 -0
  289. package/dist/kernel/cdcl.js +93 -40
  290. package/dist/kernel/epr.js +23 -8
  291. package/dist/kernel/function-instances.d.ts +45 -0
  292. package/dist/kernel/function-instances.js +460 -0
  293. package/dist/kernel/kernel.d.ts +47 -1
  294. package/dist/kernel/kernel.js +417 -68
  295. package/dist/kernel/prove.d.ts +61 -6
  296. package/dist/kernel/prove.js +625 -205
  297. package/dist/kernel/prover-rows.d.ts +1 -0
  298. package/dist/kernel/prover-rows.js +12 -1
  299. package/dist/kernel/reader.d.ts +1 -1
  300. package/dist/kernel/reader.js +57 -12
  301. package/dist/kernel/simplex.js +9 -2
  302. package/dist/lean-kernel/axiom-audit.d.ts +11 -0
  303. package/dist/lean-kernel/axiom-audit.js +50 -0
  304. package/dist/lean-kernel/emit.d.ts +34 -3
  305. package/dist/lean-kernel/emit.js +215 -28
  306. package/dist/lean-kernel/legacy-family-library.d.ts +1 -0
  307. package/dist/lean-kernel/legacy-family-library.js +5 -0
  308. package/dist/lean-kernel/legacy-family-order.d.ts +1 -0
  309. package/dist/lean-kernel/legacy-family-order.js +26 -0
  310. package/dist/lean-kernel/library.js +25 -3
  311. package/dist/lean-kernel/lift/counted-source-data.d.ts +7 -0
  312. package/dist/lean-kernel/lift/counted-source-data.js +78 -0
  313. package/dist/lean-kernel/lift/index.d.ts +82 -0
  314. package/dist/lean-kernel/lift/index.js +116 -0
  315. package/dist/lean-kernel/lift/project.d.ts +4 -0
  316. package/dist/lean-kernel/lift/project.js +15 -0
  317. package/dist/lean-kernel/lift/proof-capture.d.ts +104 -0
  318. package/dist/lean-kernel/lift/proof-capture.js +216 -0
  319. package/dist/lean-kernel/lift/proof-codec.d.ts +28 -0
  320. package/dist/lean-kernel/lift/proof-codec.js +299 -0
  321. package/dist/lean-kernel/lift/proof-counted-source.d.ts +16 -0
  322. package/dist/lean-kernel/lift/proof-counted-source.js +68 -0
  323. package/dist/lean-kernel/lift/proof-frontier.d.ts +19 -0
  324. package/dist/lean-kernel/lift/proof-frontier.js +153 -0
  325. package/dist/lean-kernel/lift/proof-graph.d.ts +17 -0
  326. package/dist/lean-kernel/lift/proof-graph.js +130 -0
  327. package/dist/lean-kernel/lift/proof-parts.d.ts +29 -0
  328. package/dist/lean-kernel/lift/proof-parts.js +131 -0
  329. package/dist/lean-kernel/lift/proof-prelude.d.ts +2 -0
  330. package/dist/lean-kernel/lift/proof-prelude.js +38 -0
  331. package/dist/lean-kernel/lift/proof-witness.d.ts +30 -0
  332. package/dist/lean-kernel/lift/proof-witness.js +283 -0
  333. package/dist/lean-kernel/lift/shape.d.ts +5 -0
  334. package/dist/lean-kernel/lift/shape.js +57 -0
  335. package/dist/lean-kernel/lift/source-projection.d.ts +16 -0
  336. package/dist/lean-kernel/lift/source-projection.js +81 -0
  337. package/dist/lean-kernel/lift/source.d.ts +23 -0
  338. package/dist/lean-kernel/lift/source.js +111 -0
  339. package/dist/lean-kernel/lift/witness-alpha.d.ts +9 -0
  340. package/dist/lean-kernel/lift/witness-alpha.js +31 -0
  341. package/dist/lean-kernel/lift-legacy.d.ts +58 -0
  342. package/dist/lean-kernel/lift-legacy.js +84 -0
  343. package/dist/lean-kernel/lift-names.d.ts +22 -0
  344. package/dist/lean-kernel/lift-names.js +36 -0
  345. package/dist/lean-kernel/lift-simulation/index.d.ts +29 -0
  346. package/dist/lean-kernel/lift-simulation/index.js +352 -0
  347. package/dist/lean-kernel/lift-simulation/shape.d.ts +41 -0
  348. package/dist/lean-kernel/lift-simulation/shape.js +173 -0
  349. package/dist/lean-kernel/lift-special/index.d.ts +36 -0
  350. package/dist/lean-kernel/lift-special/index.js +241 -0
  351. package/dist/lean-kernel/lift-special/structural.d.ts +25 -0
  352. package/dist/lean-kernel/lift-special/structural.js +126 -0
  353. package/dist/lean-kernel/lift-typed/index.d.ts +35 -0
  354. package/dist/lean-kernel/lift-typed/index.js +256 -0
  355. package/dist/lean-kernel/lift-typed/roles.d.ts +17 -0
  356. package/dist/lean-kernel/lift-typed/roles.js +170 -0
  357. package/dist/lean-kernel/lift-typed/shape.d.ts +1 -0
  358. package/dist/lean-kernel/lift-typed/shape.js +12 -0
  359. package/dist/lean-kernel/lift.d.ts +30 -0
  360. package/dist/lean-kernel/lift.js +97 -0
  361. package/package.json +5 -1
@@ -18,8 +18,30 @@ export const leanLibrary = {
18
18
  "Data.lean": "import Cyclic\n\n/-!\nData: recursive datatypes as values, for cyclic proofs. Lean 4.34.0, core only, on top of `Cyclic.lean`.\n\ncore/data.ts proves laws about datatypes (lists, trees, any declared with constructors whose fields are naturals or\nvalues of the datatype) by cyclic proofs over an encoding: every natural is a value of each datatype, a value is read\nthrough maps (its constructor's tag, its fields, its size), a function of several arguments is a map read at their\npairing `pk a b = (a + b)² + b` (left-nested). Nothing here is trusted beyond `Cyclic.lean`: an export defines the\ndatatype as a Lean `inductive` and the functions by pattern matching, gives each map of the encoding its meaning (the\nmodel, through a bijection between the naturals and the datatype's values), proves every fact of the cyclic proof true\nof that model, and concludes the law about the Lean definitions from `cyclic_sound`. What this file gives the exports:\n\n- `pk`, the pairing, injective (`pk_inj`), and a left inverse `unpk` (`unpk_pk`, chosen classically, so no division or\n square root is computed);\n- `cun`, the naturals onto the pairs, in order of their sum (`cun 0 = (0, 0)`, then each pair after the last), with\n `cpair` its inverse (`cun_cpair`, `cpair_cun`): a bijection, the one a datatype's codes are built from, each part at\n most the whole (`cun_fst_le`, `cun_snd_le`) so a value's fields have smaller codes;\n- `tup q k i`, the i-th of k naturals packed in q by `tupk` (Kernel.lean's, with `cun` and `cpair`), at most q (`tup_le`);\n- `wf_fix_unique`: a definition by well-founded recursion has exactly one solution. core/data.ts takes a function whose\n recursion isn't structural once the kernel has proven that each of its calls lowers a measure (a lexicographic tuple\n of naturals, the order of the cyclic ranks, `lexLt`) under the path to the call; its body, read as a functional F of\n the function, then reads it only below the argument's measure, and such an F has one fixpoint. So the function's\n equation, a fact of its proofs, has a model (what they conclude isn't vacuous), and only one: the function as written.\n An export defines such a function with `termination_by` the same measure, `Lx` (a tuple, ordered by `lexLt`) where\n it has several components, and Lean checks the decrease again;\n- `wf_fix_unique_ring`: the same for a ring of functions calling each other (mutual recursion), each with its own\n measure (all of one length): one functional over the ring's tuple of functions, reading each only below the measure\n of the argument it is called at. An export defines the ring in one `mutual` block, each function with `termination_by`\n its measure;\n- `wf_fix_inv_unique_ring` (`wf_fix_inv_unique` its ring of one): nested recursion, a call of the ring in another's\n argument, so a body reads the ring at its own values. An invariant of each function (core/data.ts: how its value's\n size relates to an argument's) is proven with the decrease: each call lowers the measure and each body keeps the\n invariant, wherever the calls the body reads below the measure keep it. The fixpoint is unique and keeps it.\n research/termination/Nested.lean defines two such functions through it (Lean's `termination_by` can't read a call's\n value: core/data.ts's Lean export doesn't write these yet).\n-/\n\nnamespace Kern\n\n/-! ### The pairing the encoding reads several arguments at -/\n\n/-- `(a + b)² + b`: core/dsl.ts's argsKey of two arguments. -/\ndef pk (a b : Nat) : Nat := (a + b) * (a + b) + b\n\ntheorem sq_succ (s : Nat) : (s + 1) * (s + 1) = s * s + 2 * s + 1 := by\n rw [Nat.add_mul, Nat.mul_add, Nat.mul_one, Nat.one_mul]; omega\n\ntheorem pk_lt {a b c d : Nat} (h : a + b < c + d) : pk a b < pk c d := by\n unfold pk\n have h1 : (a + b + 1) * (a + b + 1) ≤ (c + d) * (c + d) := Nat.mul_self_le_mul_self h\n have h2 := sq_succ (a + b)\n omega\n\ntheorem pk_inj {a b c d : Nat} (h : pk a b = pk c d) : a = c ∧ b = d := by\n have hs : a + b = c + d := by\n rcases Nat.lt_trichotomy (a + b) (c + d) with hl | he | hg\n · exact absurd h (Nat.ne_of_lt (pk_lt hl))\n · exact he\n · exact absurd h (Nat.ne_of_gt (pk_lt hg))\n unfold pk at h\n rw [hs] at h\n omega\n\nopen Classical in\n/-- A left inverse of `pk`: the pair a natural is the pairing of, where it is one. -/\nnoncomputable def unpk (n : Nat) : Nat × Nat :=\n if h : ∃ p : Nat × Nat, pk p.1 p.2 = n then Classical.choose h else (0, 0)\n\ntheorem unpk_pk (a b : Nat) : unpk (pk a b) = (a, b) := by\n have h : ∃ p : Nat × Nat, pk p.1 p.2 = pk a b := ⟨(a, b), rfl⟩\n unfold unpk\n split\n · rename_i h'\n have ⟨h1, h2⟩ := pk_inj (Classical.choose_spec h')\n exact Prod.ext h1 h2\n · exact absurd h ‹_›\n\n@[simp] theorem unpk_fst (a b : Nat) : (unpk ((a + b) * (a + b) + b)).1 = a := by\n have := unpk_pk a b; unfold pk at this; rw [this]\n@[simp] theorem unpk_snd (a b : Nat) : (unpk ((a + b) * (a + b) + b)).2 = b := by\n have := unpk_pk a b; unfold pk at this; rw [this]\n\n-- The pairing with a 0 argument, as simp leaves it: (a + 0)² + 0 is a·a, (0 + b)² + b is b·b + b, and (0 + 0)² + 0 is 0.\n@[simp] theorem unpk_sq_fst (a : Nat) : (unpk (a * a)).1 = a := by\n have := unpk_pk a 0; simp only [pk, Nat.add_zero] at this; rw [this]\n@[simp] theorem unpk_sq_snd (a : Nat) : (unpk (a * a)).2 = 0 := by\n have := unpk_pk a 0; simp only [pk, Nat.add_zero] at this; rw [this]\n@[simp] theorem unpk_sqb_fst (b : Nat) : (unpk (b * b + b)).1 = 0 := by\n have := unpk_pk 0 b; simp only [pk, Nat.zero_add] at this; rw [this]\n@[simp] theorem unpk_sqb_snd (b : Nat) : (unpk (b * b + b)).2 = b := by\n have := unpk_pk 0 b; simp only [pk, Nat.zero_add] at this; rw [this]\n@[simp] theorem unpk_zero : unpk 0 = (0, 0) := unpk_pk 0 0\n\n/-! ### A bijection between the naturals and the pairs\n\n`cun`, `tri`, `cpair` and their inverse laws (`cun_cpair`, `cpair_cun`) are Kernel.lean's (a tuple key is a term there);\nwhat a datatype's codes need beyond them is here. -/\n\ntheorem cpair_ge (a b : Nat) : a + b ≤ cpair a b := by\n unfold cpair; have := le_tri (a + b); omega\n\ntheorem cun_fst_le (n : Nat) : (cun n).1 ≤ n := by\n have h := cpair_ge (cun n).1 (cun n).2; rw [cpair_cun] at h; omega\ntheorem cun_snd_le (n : Nat) : (cun n).2 ≤ n := by\n have h := cpair_ge (cun n).1 (cun n).2; rw [cpair_cun] at h; omega\n\n/-! ### Tuples of naturals -/\n\n/-- The i-th of k naturals packed in q (`tupk`): the first is `(cun q).1`, the rest packed in `(cun q).2`, the last q\nitself. -/\ndef tup (q : Nat) : Nat → Nat → Nat\n | 0, _ => q\n | 1, _ => q\n | _ + 2, 0 => (cun q).1\n | k + 2, i + 1 => tup (cun q).2 (k + 1) i\n\ntheorem tup_le : ∀ (k i q : Nat), tup q k i ≤ q\n | 0, _, _ => Nat.le_refl _\n | 1, _, _ => Nat.le_refl _\n | _ + 2, 0, q => cun_fst_le q\n | k + 2, i + 1, q => Nat.le_trans (tup_le (k + 1) i (cun q).2) (cun_snd_le q)\n\n@[simp] theorem tup_two_zero (k a q : Nat) : tup (cpair a q) (k + 2) 0 = a := by simp [tup]\n@[simp] theorem tup_two_succ (k i a q : Nat) : tup (cpair a q) (k + 2) (i + 1) = tup q (k + 1) i := by simp [tup]\n@[simp] theorem tup_one (q i : Nat) : tup q 1 i = q := rfl\n\n/-! ### Definitions by well-founded recursion -/\n\n/-- A functional that reads its function only at arguments of lower measure (lexicographic, as the cyclic ranks are\nordered) has exactly one fixpoint: a function satisfying `f x = F f x` at every argument, and every other one equal to\nit. `F g x = F h x` wherever g and h agree below x's measure: a body whose calls (under the path the argument takes)\nare each at a lower measure. -/\ntheorem wf_fix_unique {α β : Type} [Inhabited β] (μ : α → List Nat) (F : (α → β) → α → β)\n (hF : ∀ (g h : α → β) (x : α), (∀ y, lexLt (μ y) (μ x) → g y = h y) → F g x = F h x) :\n ∃ f : α → β, (∀ x, f x = F f x) ∧ ∀ f' : α → β, (∀ x, f' x = F f' x) → f' = f := by\n classical\n have wf : WellFounded (InvImage lexLt μ) := InvImage.wf μ lexLt_wf\n let G : (x : α) → ((y : α) → InvImage lexLt μ y x → β) → β :=\n fun x rec => F (fun y => if h : lexLt (μ y) (μ x) then rec y h else default) x\n have hfix : ∀ x, wf.fix G x = F (wf.fix G) x := by\n intro x\n rw [wf.fix_eq G x]\n apply hF\n intro y hy\n simp [hy]\n refine ⟨wf.fix G, hfix, fun f' hf' => funext fun x => ?_⟩\n exact wf.induction (C := fun x => f' x = wf.fix G x) x (fun x ih => by\n rw [hf' x, hfix x]\n exact hF f' (wf.fix G) x (fun y hy => ih y hy))\n\n/-- A ring of functions calling each other (one per index i, each `α i → β i`), read as one functional F over the ring's\ntuple, that reads each function of the ring only at arguments of lower measure than its own argument's (the measures\nof the ring's functions, one per function, all of one length, compared by `lexLt`), has exactly one fixpoint: a tuple\nsatisfying `f i x = F f i x` for every function and argument, and every other tuple equal to it. core/data.ts takes a\nring that isn't structural recursion once the kernel has proven that each call within the ring, under its path, lowers\nthe callee's measure at the call's arguments below the caller's at its parameters: that is `hF`, each function's body\nreading the ring's functions only at those calls. `wf_fix_unique` is the ring of one. -/\ntheorem wf_fix_unique_ring {ι : Type} {α β : ι → Type} [∀ i, Inhabited (β i)] (μ : (i : ι) → α i → List Nat)\n (F : ((i : ι) → α i → β i) → (i : ι) → α i → β i)\n (hF : ∀ (g h : (i : ι) → α i → β i) (i : ι) (x : α i),\n (∀ (j : ι) (y : α j), lexLt (μ j y) (μ i x) → g j y = h j y) → F g i x = F h i x) :\n ∃ f : (i : ι) → α i → β i, (∀ i x, f i x = F f i x) ∧\n ∀ f' : (i : ι) → α i → β i, (∀ i x, f' i x = F f' i x) → f' = f := by\n classical\n -- the ring's arguments as one type (a function's index and its argument), ordered by the measure there\n let m : (Σ i, α i) → List Nat := fun p => μ p.1 p.2\n have wf : WellFounded (InvImage lexLt m) := InvImage.wf m lexLt_wf\n let G : (p : Σ i, α i) → ((q : Σ i, α i) → InvImage lexLt m q p → β q.1) → β p.1 :=\n fun p rec => F (fun j y => if h : lexLt (μ j y) (μ p.1 p.2) then rec ⟨j, y⟩ h else default) p.1 p.2\n let f : (i : ι) → α i → β i := fun i x => wf.fix G ⟨i, x⟩\n have hfix : ∀ i x, f i x = F f i x := by\n intro i x\n show wf.fix G ⟨i, x⟩ = F f i x\n rw [wf.fix_eq G ⟨i, x⟩]\n apply hF\n intro j y hy\n simp [hy, f]\n refine ⟨f, hfix, fun f' hf' => ?_⟩\n have key : ∀ p : Σ i, α i, f' p.1 p.2 = f p.1 p.2 := fun p =>\n wf.induction (C := fun p => f' p.1 p.2 = f p.1 p.2) p (fun p ih => by\n rw [hf' p.1 p.2, hfix p.1 p.2]\n exact hF f' f p.1 p.2 (fun j y hy => ih ⟨j, y⟩ hy))\n funext i x\n exact key ⟨i, x⟩\n\n/-- Nested recursion: a ring whose calls may sit in the arguments (or conditions) of others, so a body reads the ring at\nvalues of the ring itself. A functional F such that, wherever g and h agree below x's measure and g keeps the invariant\nI there (`I j y (g j y)`), F g and F h agree at x and F g keeps I at x, has exactly one fixpoint, and it keeps I\neverywhere: the decrease and the invariant proven together, by well-founded induction on the measure. core/data.ts\ntakes such a ring once the kernel has proven, for each call within it (under its path, each call of the ring in its\nargument or condition read as a value r with `lexLt (μ j a) (μ i x) → I j a r`), that it lowers the callee's measure\nbelow the caller's, and that each body, its calls read the same way, keeps its function's invariant: that is `hF`.\n`wf_fix_unique_ring` is the case I = True. -/\ntheorem wf_fix_inv_unique_ring {ι : Type} {α β : ι → Type} [∀ i, Inhabited (β i)] (μ : (i : ι) → α i → List Nat)\n (I : (i : ι) → α i → β i → Prop) (F : ((i : ι) → α i → β i) → (i : ι) → α i → β i)\n (hF : ∀ (g h : (i : ι) → α i → β i) (i : ι) (x : α i),\n (∀ (j : ι) (y : α j), lexLt (μ j y) (μ i x) → g j y = h j y ∧ I j y (g j y)) →\n F g i x = F h i x ∧ I i x (F g i x)) :\n ∃ f : (i : ι) → α i → β i, (∀ i x, f i x = F f i x ∧ I i x (f i x)) ∧\n ∀ f' : (i : ι) → α i → β i, (∀ i x, f' i x = F f' i x) → f' = f := by\n classical\n let m : (Σ i, α i) → List Nat := fun p => μ p.1 p.2\n have wf : WellFounded (InvImage lexLt m) := InvImage.wf m lexLt_wf\n let G : (p : Σ i, α i) → ((q : Σ i, α i) → InvImage lexLt m q p → β q.1) → β p.1 :=\n fun p rec => F (fun j y => if h : lexLt (μ j y) (μ p.1 p.2) then rec ⟨j, y⟩ h else default) p.1 p.2\n let f : (i : ι) → α i → β i := fun i x => wf.fix G ⟨i, x⟩\n -- the equation and the invariant at once, by induction on the measure\n have hfix : ∀ p : Σ i, α i, f p.1 p.2 = F f p.1 p.2 ∧ I p.1 p.2 (f p.1 p.2) := fun p =>\n wf.induction (C := fun p => f p.1 p.2 = F f p.1 p.2 ∧ I p.1 p.2 (f p.1 p.2)) p (fun p ih => by\n have e : f p.1 p.2 = F (fun j y => if lexLt (μ j y) (μ p.1 p.2) then f j y else default) p.1 p.2 := by\n show wf.fix G p = _\n rw [wf.fix_eq G p]\n rfl\n have k := hF (fun j y => if lexLt (μ j y) (μ p.1 p.2) then f j y else default) f p.1 p.2\n (fun j y hy => by rw [if_pos hy]; exact ⟨rfl, (ih ⟨j, y⟩ hy).2⟩)\n rw [e]\n exact ⟨k.1, k.2⟩)\n refine ⟨f, fun i x => hfix ⟨i, x⟩, fun f' hf' => ?_⟩\n have key : ∀ p : Σ i, α i, f' p.1 p.2 = f p.1 p.2 := fun p =>\n wf.induction (C := fun p => f' p.1 p.2 = f p.1 p.2) p (fun p ih => by\n rw [hf' p.1 p.2, (hfix p).1]\n exact (hF f f' p.1 p.2 (fun j y hy => ⟨(ih ⟨j, y⟩ hy).symm, (hfix ⟨j, y⟩).2⟩)).1.symm)\n funext i x\n exact key ⟨i, x⟩\n\n/-- `wf_fix_inv_unique_ring`'s ring of one: a nested recursive function (McCarthy's `m(m(x + 11))`, a sort that sorts\nthe result of sorting) with its invariant. -/\ntheorem wf_fix_inv_unique {α β : Type} [Inhabited β] (μ : α → List Nat) (I : α → β → Prop) (F : (α → β) → α → β)\n (hF : ∀ (g h : α → β) (x : α), (∀ y, lexLt (μ y) (μ x) → g y = h y ∧ I y (g y)) → F g x = F h x ∧ I x (F g x)) :\n ∃ f : α → β, (∀ x, f x = F f x ∧ I x (f x)) ∧ ∀ f' : α → β, (∀ x, f' x = F f' x) → f' = f := by\n obtain ⟨f, hf, hu⟩ := wf_fix_inv_unique_ring (ι := Unit) (α := fun _ => α) (β := fun _ => β) (fun _ => μ) (fun _ => I)\n (fun g _ x => F (g ()) x) (fun g h _ x hy => hF (g ()) (h ()) x (fun y hy' => hy () y hy'))\n refine ⟨f (), fun x => hf () x, fun f' hf' => ?_⟩\n have := hu (fun _ => f') (fun _ x => hf' x)\n exact congrFun this ()\n\n/-- A measure of several components for `termination_by`: the tuple, ordered by `lexLt` (an export's measures all have\none length). -/\nstructure Lx where\n l : List Nat\n\ninstance : WellFoundedRelation Lx := ⟨fun a b => lexLt a.l b.l, InvImage.wf Lx.l lexLt_wf⟩\n\n/-! ### Facts at their keys -/\n\n/-- A condition's value as a natural is at most 1 (a function to `Bool` as the encoding reads it). -/\n@[simp] theorem ite_one_zero_le (p : Prop) [Decidable p] : (if p then 1 else 0) ≤ 1 := by\n split <;> omega\n\n/-- A fact read at its own keys reads the values given there. -/\ntheorem override_at (keys : List Nat) (i : Nat) (h : keys.contains i = true) (vals env : Nat → Nat) :\n override keys vals env i = vals i := by\n unfold override; rw [if_pos h]\n\nend Kern\n",
19
19
  "Rationals.lean": "import Kernel\n/-!\nRationals: linear arithmetic over ℚ, the twin of kernel/kernel.ts's rational section and core/check.ts's derivations\nwithout cuts, with its soundness proof. Lean 4.34.0, core only (core's `Rat`).\n\nThe rows are Cert's (integer coefficients and constant), read at a rational point, each with a strictness: `(r, false)`\nsays r ≤ 0, `(r, true)` says r < 0. A derivation is Cert's steps: an input row, or a positive combination of two\nearlier rows (strict when either is). A cut is refused: it is the one step whose soundness needs an integer point\n(`Cert.cut_sound`), so the naturals' and integers' checks are this one with the cut added. `checkQ` accepts when the\nlast row has only zero coefficients and a positive constant, or a constant ≥ 0 and is strict: Farkas' lemma with\nstrict rows (Motzkin's), the refutation complete for linear arithmetic over ℚ. `checkQ_sound`: no rational point\nsatisfies every input.\n\nTerms (`QE`) are rationals: variables, rational constants, +, − (not truncated), × by a rational constant, min, max,\nif; conditions (`QC`) ≤, <, =, and, or, not. A term's linear form is a Cert row over a positive denominator (`LF`:\nthe term's value is `evalQ row / den`), so every row a leaf reads has integer coefficients and none is rounded. A\nproof is a tree of splits on rows (yes: r ≤ 0, no: −r < 0) with a leaf certificate: the rows it claims (each one of\nthe leaf's rows, by coefficients) and a derivation over them. `sound`: if `checkGoal` accepts, no rational\nenvironment satisfies every hypothesis. `machine_sound`: the induction rule for a step machine whose state, params and\ninputs are rationals.\n-/\n\nnamespace Q\nopen Cert Kern\nset_option linter.unusedSimpArgs false\nset_option linter.unusedSectionVars false\n\n/-! Rows at a rational point. -/\n\ndef dotQ : List (Nat × Int) → (Nat → Rat) → Rat\n | [], _ => 0\n | p :: rest, x => (p.2 : Rat) * x p.1 + dotQ rest x\n\ndef evalQ (r : Row) (x : Nat → Rat) : Rat := dotQ r.coefs x + r.const\n\ntheorem dotQ_app (x : Nat → Rat) : ∀ (a b : List (Nat × Int)), dotQ (a ++ b) x = dotQ a x + dotQ b x\n | [], b => by simp [dotQ, Rat.zero_add]\n | p :: a, b => by simp only [List.cons_append, dotQ, dotQ_app x a b]; grind\n\ntheorem dotQ_addF (x : Nat → Rat) : ∀ (n : Nat) (a b : List (Nat × Int)), dotQ (addF n a b) x = dotQ a x + dotQ b x\n | 0, a, b => by simp only [addF, dotQ_app]\n | _ + 1, [], b => by simp [addF, dotQ, Rat.zero_add]\n | _ + 1, _ :: _, [] => by simp [addF, dotQ, Rat.add_zero]\n | n + 1, p :: as, q :: bs => by\n simp only [addF]\n split\n · simp only [dotQ, dotQ_addF x n as (q :: bs)]; grind\n · split\n · simp only [dotQ, dotQ_addF x n (p :: as) bs]; grind\n · have hpq : p.1 = q.1 := by omega\n split\n · rename_i hz\n simp only [dotQ, dotQ_addF x n as bs, hpq]\n have hz' : (p.2 : Rat) + (q.2 : Rat) = 0 := by rw [← Rat.intCast_add, hz]; rfl\n have : (p.2 : Rat) * x q.1 + (q.2 : Rat) * x q.1 = 0 := by rw [← Rat.add_mul, hz', Rat.zero_mul]\n grind\n · simp only [dotQ, dotQ_addF x n as bs, hpq, Rat.intCast_add, Rat.add_mul]; grind\n\ntheorem dotQ_addL (a b : List (Nat × Int)) (x : Nat → Rat) : dotQ (addL a b) x = dotQ a x + dotQ b x := dotQ_addF x _ a b\n\ntheorem dotQ_map (m : Int) (x : Nat → Rat) : ∀ (a : List (Nat × Int)), dotQ (a.map (fun p => (p.1, m * p.2))) x = m * dotQ a x\n | [] => by simp [dotQ]\n | p :: a => by simp only [List.map_cons, dotQ, dotQ_map m x a, Rat.intCast_mul, Rat.mul_add, Rat.mul_assoc]\n\ntheorem dotQ_scaleL (m : Int) (a : List (Nat × Int)) (x : Nat → Rat) : dotQ (scaleL m a) x = m * dotQ a x := by\n unfold scaleL\n split\n · rename_i h; subst h; simp [dotQ]\n · exact dotQ_map m x a\n\ntheorem dotQ_allZero : ∀ (a : List (Nat × Int)) (x : Nat → Rat), allZero a = true → dotQ a x = 0\n | [], _, _ => rfl\n | p :: a, x, h => by\n simp only [allZero, Bool.and_eq_true, beq_iff_eq] at h\n simp [dotQ, h.1, dotQ_allZero a x h.2, Rat.zero_add]\n\ntheorem evalQ_ladd (a b : Row) (x : Nat → Rat) : evalQ (ladd a b) x = evalQ a x + evalQ b x := by\n simp only [evalQ, ladd, dotQ_addL, Rat.intCast_add]; grind\ntheorem evalQ_lscale (m : Int) (a : Row) (x : Nat → Rat) : evalQ (lscale m a) x = m * evalQ a x := by\n simp only [evalQ, lscale, dotQ_scaleL, Rat.intCast_mul, Rat.mul_add]\ntheorem evalQ_lsub (a b : Row) (x : Nat → Rat) : evalQ (lsub a b) x = evalQ a x - evalQ b x := by\n simp only [lsub, evalQ_ladd, evalQ_lscale]; grind\ntheorem evalQ_lunit (j : Nat) (x : Nat → Rat) : evalQ (lunit j) x = x j := by\n simp [evalQ, lunit, dotQ, Rat.add_zero]\ntheorem evalQ_lconst (n : Int) (x : Nat → Rat) : evalQ (lconst n) x = n := by\n simp [evalQ, lconst, dotQ, Rat.zero_add]\ntheorem same_evalQ {a b : Row} (h : same a b = true) (x : Nat → Rat) : evalQ a x = evalQ b x := by\n simp only [same, Bool.and_eq_true, beq_iff_eq] at h\n have h1 : evalQ (lsub a b) x = 0 := by simp only [evalQ, dotQ_allZero _ x h.1, h.2]; grind\n rw [evalQ_lsub] at h1; grind\n\n/-! Derivations without cuts, over strict and non-strict rows. -/\n\n-- `(r, s)` holds at x: r < 0 if s, else r ≤ 0.\ndef Holds (x : Nat → Rat) (p : Row × Bool) : Prop := if p.2 then evalQ p.1 x < 0 else evalQ p.1 x ≤ 0\n\ntheorem Holds.le {x : Nat → Rat} {p : Row × Bool} (h : Holds x p) : evalQ p.1 x ≤ 0 := by\n unfold Holds at h; split at h\n · exact Rat.le_of_lt h\n · exact h\n\ndef replayQ (inputs : List (Row × Bool)) : List Step → Nat → List (Row × Bool) → Option (List (Row × Bool))\n | [], _, rows => some rows\n | .input i :: ss, n, rows =>\n match inputs[i]? with\n | some r => replayQ inputs ss (n + 1) (r :: rows)\n | none => none\n | .combine a b ma mb :: ss, n, rows =>\n match rows[n - 1 - a]?, rows[n - 1 - b]? with\n | some A, some B => if a < n ∧ b < n ∧ 0 < ma ∧ 0 < mb then replayQ inputs ss (n + 1) ((combineRow ma mb A.1 B.1, A.2 || B.2) :: rows) else none\n | _, _ => none\n | .cut _ _ _ _ :: _, _, _ => none\n\ndef checkQ (inputs : List (Row × Bool)) (steps : List Step) : Bool :=\n match replayQ inputs steps 0 [] with\n | some rows =>\n match rows.head? with\n | some r => allZero r.1.coefs && (decide (0 < r.1.const) || (r.2 && decide (0 ≤ r.1.const)))\n | none => false\n | none => false\n\ntheorem combine_holds {x : Nat → Rat} {ma mb : Int} (hma : 0 < ma) (hmb : 0 < mb) {A B : Row × Bool}\n (hA : Holds x A) (hB : Holds x B) : Holds x (combineRow ma mb A.1 B.1, A.2 || B.2) := by\n have eq : evalQ (combineRow ma mb A.1 B.1) x = (ma : Rat) * evalQ A.1 x + (mb : Rat) * evalQ B.1 x := by\n simp only [evalQ, combineRow, dotQ_addL, dotQ_scaleL, Rat.intCast_add, Rat.intCast_mul]; grind\n have pa : (0 : Rat) < ma := Rat.intCast_pos.mpr hma\n have pb : (0 : Rat) < mb := Rat.intCast_pos.mpr hmb\n have la : (ma : Rat) * evalQ A.1 x ≤ 0 := by\n have := Rat.mul_le_mul_of_nonneg_left hA.le (Rat.le_of_lt pa); simpa using this\n have lb : (mb : Rat) * evalQ B.1 x ≤ 0 := by\n have := Rat.mul_le_mul_of_nonneg_left hB.le (Rat.le_of_lt pb); simpa using this\n unfold Holds\n simp only [eq]\n split\n · rename_i hs\n simp only [Bool.or_eq_true] at hs\n rcases hs with hs | hs\n · have hA' : evalQ A.1 x < 0 := by unfold Holds at hA; simp [hs] at hA; exact hA\n have : (ma : Rat) * evalQ A.1 x < 0 := by\n have := Rat.mul_lt_mul_of_pos_left hA' pa; simpa using this\n grind\n · have hB' : evalQ B.1 x < 0 := by unfold Holds at hB; simp [hs] at hB; exact hB\n have : (mb : Rat) * evalQ B.1 x < 0 := by\n have := Rat.mul_lt_mul_of_pos_left hB' pb; simpa using this\n grind\n · grind\n\n-- Every row a replay produces holds wherever the inputs and the rows so far hold.\ntheorem replayQ_holds (inputs : List (Row × Bool)) (x : Nat → Rat) (hx : ∀ r ∈ inputs, Holds x r) :\n ∀ (ss : List Step) (n : Nat) (rows out : List (Row × Bool)), (∀ r ∈ rows, Holds x r) →\n replayQ inputs ss n rows = some out → ∀ r ∈ out, Holds x r := by\n intro ss\n induction ss with\n | nil =>\n intro n rows out hrows h\n simp only [replayQ, Option.some.injEq] at h\n exact h ▸ hrows\n | cons s ss ih =>\n intro n rows out hrows h\n cases s with\n | input i =>\n simp only [replayQ] at h\n split at h\n · rename_i r hr\n refine ih _ _ out ?_ h\n intro r' hr'\n rcases List.mem_cons.mp hr' with hr' | hr'\n · exact hr' ▸ hx r (List.mem_of_getElem? hr)\n · exact hrows r' hr'\n · exact absurd h (by simp)\n | combine a b ma mb =>\n simp only [replayQ] at h\n split at h\n · rename_i A B hA hB\n split at h\n · rename_i hm\n refine ih _ _ out ?_ h\n intro r' hr'\n rcases List.mem_cons.mp hr' with hr' | hr'\n · subst hr'\n exact combine_holds hm.2.2.1 hm.2.2.2 (hrows A (List.mem_of_getElem? hA)) (hrows B (List.mem_of_getElem? hB))\n · exact hrows r' hr'\n · exact absurd h (by simp)\n · exact absurd h (by simp)\n | cut o g q c => simp [replayQ] at h\n\n/-- A certificate `checkQ` accepts refutes its inputs: no rational point satisfies them all. -/\ntheorem checkQ_sound (inputs : List (Row × Bool)) (steps : List Step) (h : checkQ inputs steps = true) (x : Nat → Rat)\n (hx : ∀ r ∈ inputs, Holds x r) : False := by\n simp only [checkQ] at h\n split at h\n · rename_i rows hrows\n split at h\n · rename_i r hr\n simp only [Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at h\n have hall := replayQ_holds inputs x hx steps 0 [] rows (by simp) hrows\n have hm : r ∈ rows := by\n cases rows with\n | nil => simp at hr\n | cons a as => simp only [List.head?, Option.some.injEq] at hr; subst hr; exact List.mem_cons_self\n have hh := hall r hm\n have hv : evalQ r.1 x = r.1.const := by simp only [evalQ, dotQ_allZero r.1.coefs x h.1]; grind\n unfold Holds at hh\n rcases h.2 with hc | ⟨hs, hc⟩\n · have hc' : (0 : Rat) < r.1.const := Rat.intCast_pos.mpr hc\n split at hh <;> grind\n · have hc' : (0 : Rat) ≤ r.1.const := Rat.intCast_nonneg.mpr hc\n simp only [hs, ite_true] at hh\n grind\n · exact absurd h (by simp)\n · exact absurd h (by simp)\n\n/-! Terms and conditions over the rationals. -/\n\nmutual\ninductive QE where\n | var (i : Nat)\n | const (q : Rat)\n | add (a b : QE)\n | sub (a b : QE)\n | mul (k : Rat) (a : QE)\n | min (a b : QE)\n | max (a b : QE)\n | ite (c : QC) (t f : QE)\ninductive QC where\n | le (a b : QE)\n | lt (a b : QE)\n | eq (a b : QE)\n | and (a b : QC)\n | or (a b : QC)\n | not (a : QC)\nend\n\nmutual\ndef evalE (ρ : Nat → Rat) : QE → Rat\n | .var i => ρ i\n | .const q => q\n | .add a b => evalE ρ a + evalE ρ b\n | .sub a b => evalE ρ a - evalE ρ b\n | .mul k a => k * evalE ρ a\n | .min a b => if evalE ρ a ≤ evalE ρ b then evalE ρ a else evalE ρ b\n | .max a b => if evalE ρ a ≤ evalE ρ b then evalE ρ b else evalE ρ a\n | .ite c t f => if evalC ρ c then evalE ρ t else evalE ρ f\ndef evalC (ρ : Nat → Rat) : QC → Bool\n | .le a b => decide (evalE ρ a ≤ evalE ρ b)\n | .lt a b => decide (evalE ρ a < evalE ρ b)\n | .eq a b => decide (evalE ρ a = evalE ρ b)\n | .and a b => evalC ρ a && evalC ρ b\n | .or a b => evalC ρ a || evalC ρ b\n | .not a => !evalC ρ a\nend\n\n/-! Linear forms: a row over a positive denominator, the term's value being `evalQ row / den`. -/\n\nstructure LF where\n row : Row\n den : Nat\n\n-- The row of a − b (its value a positive multiple of a's value minus b's).\ndef dif (a b : LF) : Row := lsub (lscale b.den a.row) (lscale a.den b.row)\n\n-- The path: rows decided so far. `(l, true)` says l ≤ 0, `(l, false)` says l > 0.\ndef PathHolds (path : Path) (x : Nat → Rat) : Prop := ∀ a ∈ path, decide (evalQ a.1 x ≤ 0) = a.2\n\n-- Whether the path decides l ≤ 0: a constant row decides itself, else the path's own decision on the same row.\ndef dec (path : Path) (l : Row) : Option Bool :=\n if allZero l.coefs then some (decide (l.const ≤ 0)) else (lookup (fun a => same a.1 l) path).map (·.2)\n\nmutual\ndef linear (path : Path) : QE → Option LF\n | .var i => some ⟨lunit i, 1⟩\n | .const q => some ⟨lconst q.num, q.den⟩\n | .add a b => match linear path a, linear path b with\n | some la, some lb => some ⟨ladd (lscale lb.den la.row) (lscale la.den lb.row), la.den * lb.den⟩\n | _, _ => none\n | .sub a b => match linear path a, linear path b with\n | some la, some lb => some ⟨dif la lb, la.den * lb.den⟩\n | _, _ => none\n | .mul k a => match linear path a with\n | some la => some ⟨lscale k.num la.row, k.den * la.den⟩\n | none => none\n | .min a b => match linear path a, linear path b with\n | some la, some lb => match dec path (dif la lb) with\n | some true => some la\n | some false => some lb\n | none => none\n | _, _ => none\n | .max a b => match linear path a, linear path b with\n | some la, some lb => match dec path (dif la lb) with\n | some true => some lb\n | some false => some la\n | none => none\n | _, _ => none\n | .ite c t f => match truth path c with\n | some true => linear path t\n | some false => linear path f\n | none => none\ndef truth (path : Path) : QC → Option Bool\n | .le a b => match linear path a, linear path b with\n | some la, some lb => dec path (dif la lb)\n | _, _ => none\n | .lt a b => match linear path a, linear path b with\n | some la, some lb => (dec path (dif lb la)).map (!·)\n | _, _ => none\n | .eq a b => match linear path a, linear path b with\n | some la, some lb => match dec path (dif la lb), dec path (dif lb la) with\n | some false, _ => some false\n | _, some false => some false\n | some true, some true => some true\n | _, _ => none\n | _, _ => none\n | .and a b => match truth path a, truth path b with\n | some false, _ => some false\n | _, some false => some false\n | some true, some true => some true\n | _, _ => none\n | .or a b => match truth path a, truth path b with\n | some true, _ => some true\n | _, some true => some true\n | some false, some false => some false\n | _, _ => none\n | .not a => (truth path a).map (!·)\nend\n\n/-! Facts: the rows a hypothesis gives under the path when it has the truth value `pos` (strict ones flagged). -/\n\ndef facts (path : Path) : Bool → QC → List (Row × Bool)\n | pos, .not a => facts path (!pos) a\n | pos, .and a b =>\n if pos then facts path pos a ++ facts path pos b\n else if truth path a = some true then facts path false b\n else if truth path b = some true then facts path false a\n else []\n | pos, .or a b =>\n if !pos then facts path false a ++ facts path false b\n else if truth path a = some false then facts path true b\n else if truth path b = some false then facts path true a\n else []\n | pos, .le a b => match linear path a, linear path b with\n | some la, some lb => if pos then [(dif la lb, false)] else [(dif lb la, true)]\n | _, _ => []\n | pos, .lt a b => match linear path a, linear path b with\n | some la, some lb => if pos then [(dif la lb, true)] else [(dif lb la, false)]\n | _, _ => []\n | pos, .eq a b => match linear path a, linear path b with\n | some la, some lb =>\n if pos then [(dif la lb, false), (dif lb la, false)]\n else if dec path (dif la lb) = some true then [(dif la lb, true)]\n else if dec path (dif lb la) = some true then [(dif lb la, true)]\n else []\n | _, _ => []\n\n/-! Leaves and trees. -/\n\n-- A decided atom as a row: l ≤ 0, or −l < 0.\ndef atomRow (a : Row × Bool) : Row × Bool := if a.2 then (a.1, false) else (lscale (-1) a.1, true)\ndef leafRows (path : Path) (hyps : List QC) : List (Row × Bool) := path.map atomRow ++ hyps.flatMap (facts path true)\n\n-- A claimed row is a leaf row with the same coefficients, as strict as claimed (a strict row may be claimed as ≤).\ndef claimOk (rows : List (Row × Bool)) (r : Row × Bool) : Bool := rows.any fun q => same q.1 r.1 && (q.2 || !r.2)\n\ninductive QTree where\n | split (l : Row) (yes no : QTree)\n | leaf (rows : List (Row × Bool)) (steps : List Step)\n\n-- A split on a row the path already decides is refused (its two sides would read one decision two ways).\ndef checkT (hyps : List QC) : Path → QTree → Bool\n | path, .leaf rows steps => rows.all (claimOk (leafRows path hyps)) && checkQ rows steps\n | path, .split l yes no => (dec path l).isNone && checkT hyps ((l, true) :: path) yes && checkT hyps ((l, false) :: path) no\n\ndef checkGoal (hyps : List QC) (t : QTree) : Bool := checkT hyps [] t\n\n/-! Soundness. -/\n\ntheorem num_eq (q : Rat) : (q.num : Rat) = (q.den : Rat) * q := by\n have h1 := Rat.num_divInt_den q\n rw [Rat.divInt_eq_div] at h1\n have hd : (q.den : Rat) ≠ 0 := by simp [q.den_nz]\n have e : ((q.den : Int) : Rat) = (q.den : Rat) := rfl\n rw [e] at h1\n calc (q.num : Rat) = (q.num : Rat) / q.den * q.den := (Rat.div_mul_cancel hd).symm\n _ = q * q.den := by rw [h1]\n _ = q.den * q := Rat.mul_comm _ _\n\ntheorem mul_nonpos_iff {k t : Rat} (hk : 0 < k) : k * t ≤ 0 ↔ t ≤ 0 := by\n constructor\n · intro h; exact Rat.le_of_mul_le_mul_left (by simpa using h) hk\n · intro h; have := Rat.mul_le_mul_of_nonneg_left h (Rat.le_of_lt hk); simpa using this\ntheorem mul_neg_iff {k t : Rat} (hk : 0 < k) : k * t < 0 ↔ t < 0 := by\n have := Rat.mul_lt_mul_left (a := t) (b := 0) hk; simpa using this\n\n-- l represents the value v at x.\ndef Rep (x : Nat → Rat) (l : LF) (v : Rat) : Prop := 0 < l.den ∧ evalQ l.row x = (l.den : Rat) * v\n\ntheorem dif_eval {x : Nat → Rat} {la lb : LF} {va vb : Rat} (ha : Rep x la va) (hb : Rep x lb vb) :\n evalQ (dif la lb) x = ((la.den : Rat) * lb.den) * (va - vb) := by\n simp only [dif, evalQ_lsub, evalQ_lscale, ha.2, hb.2, Rat.intCast_natCast]; grind\n\ntheorem den_pos {la lb : LF} {va vb : Rat} {x : Nat → Rat} (ha : Rep x la va) (hb : Rep x lb vb) :\n (0 : Rat) < (la.den : Rat) * lb.den :=\n Rat.mul_pos (Rat.natCast_pos.mpr ha.1) (Rat.natCast_pos.mpr hb.1)\n\ntheorem dif_le {x : Nat → Rat} {la lb : LF} {va vb : Rat} (ha : Rep x la va) (hb : Rep x lb vb) :\n evalQ (dif la lb) x ≤ 0 ↔ va ≤ vb := by\n rw [dif_eval ha hb, mul_nonpos_iff (den_pos ha hb)]; grind\ntheorem dif_lt {x : Nat → Rat} {la lb : LF} {va vb : Rat} (ha : Rep x la va) (hb : Rep x lb vb) :\n evalQ (dif la lb) x < 0 ↔ va < vb := by\n rw [dif_eval ha hb, mul_neg_iff (den_pos ha hb)]; grind\n\ntheorem dec_sound {path : Path} {x : Nat → Rat} (hP : PathHolds path x) {l : Row} {b : Bool}\n (h : dec path l = some b) : decide (evalQ l x ≤ 0) = b := by\n simp only [dec] at h\n split at h\n · rename_i hz\n simp only [Option.some.injEq] at h\n subst h\n have hv : evalQ l x = l.const := by simp only [evalQ, dotQ_allZero _ x hz]; grind\n rw [hv]; simp only [decide_eq_decide]\n exact ⟨fun h => Rat.intCast_nonpos.mp h, fun h => Rat.intCast_nonpos.mpr h⟩\n · simp only [Option.map_eq_some_iff] at h\n obtain ⟨a, ha, rfl⟩ := h\n have ⟨hm, hs⟩ := lookup_some ha\n rw [← hP a hm, same_evalQ hs]\n\ntheorem dec_le {path : Path} {x : Nat → Rat} (hP : PathHolds path x) {la lb : LF} {va vb : Rat}\n (ha : Rep x la va) (hb : Rep x lb vb) {b : Bool} (h : dec path (dif la lb) = some b) : decide (va ≤ vb) = b := by\n rw [← dec_sound hP h]; simp only [decide_eq_decide]; exact (dif_le ha hb).symm\n\nsection\nvariable {x : Nat → Rat} {path : Path}\n\nmutual\ntheorem linear_sound (hP : PathHolds path x) : (e : QE) → (l : LF) → linear path e = some l → Rep x l (evalE x e)\n | .var i, l, h => by\n simp only [linear, Option.some.injEq] at h; subst h\n refine ⟨Nat.one_pos, ?_⟩\n simp only [evalQ_lunit, evalE]; grind\n | .const q, l, h => by\n simp only [linear, Option.some.injEq] at h; subst h\n exact ⟨q.den_pos, by simp only [evalQ_lconst, evalE]; exact num_eq q⟩\n | .add a b, l, h => by\n simp only [linear] at h\n split at h\n · rename_i la lb ha hb\n simp only [Option.some.injEq] at h; subst h\n have ea := linear_sound hP a la ha\n have eb := linear_sound hP b lb hb\n refine ⟨Nat.mul_pos ea.1 eb.1, ?_⟩\n simp only [evalQ_ladd, evalQ_lscale, ea.2, eb.2, evalE, Rat.intCast_natCast, Rat.natCast_mul]; grind\n · simp at h\n | .sub a b, l, h => by\n simp only [linear] at h\n split at h\n · rename_i la lb ha hb\n simp only [Option.some.injEq] at h; subst h\n have ea := linear_sound hP a la ha\n have eb := linear_sound hP b lb hb\n refine ⟨Nat.mul_pos ea.1 eb.1, ?_⟩\n simp only [dif_eval ea eb, evalE, Rat.natCast_mul]\n · simp at h\n | .mul k a, l, h => by\n simp only [linear] at h\n split at h\n · rename_i la ha\n simp only [Option.some.injEq] at h; subst h\n have ea := linear_sound hP a la ha\n refine ⟨Nat.mul_pos k.den_pos ea.1, ?_⟩\n simp only [evalQ_lscale, ea.2, evalE, Rat.natCast_mul, num_eq k]; grind\n · simp at h\n | .min a b, l, h => by\n simp only [linear] at h\n split at h\n · rename_i la lb ha hb\n have ea := linear_sound hP a la ha\n have eb := linear_sound hP b lb hb\n split at h\n · rename_i hd\n simp only [Option.some.injEq] at h; subst h\n have := dec_le hP ea eb hd\n simp only [decide_eq_true_eq] at this\n simp only [evalE, this, ite_true]; exact ea\n · rename_i hd\n simp only [Option.some.injEq] at h; subst h\n have := dec_le hP ea eb hd\n simp only [decide_eq_false_iff_not] at this\n simp only [evalE, this, ite_false]; exact eb\n · simp at h\n · simp at h\n | .max a b, l, h => by\n simp only [linear] at h\n split at h\n · rename_i la lb ha hb\n have ea := linear_sound hP a la ha\n have eb := linear_sound hP b lb hb\n split at h\n · rename_i hd\n simp only [Option.some.injEq] at h; subst h\n have := dec_le hP ea eb hd\n simp only [decide_eq_true_eq] at this\n simp only [evalE, this, ite_true]; exact eb\n · rename_i hd\n simp only [Option.some.injEq] at h; subst h\n have := dec_le hP ea eb hd\n simp only [decide_eq_false_iff_not] at this\n simp only [evalE, this, ite_false]; exact ea\n · simp at h\n · simp at h\n | .ite c t f, l, h => by\n simp only [linear] at h\n split at h\n · rename_i hc\n simp only [evalE, truth_sound hP c true hc, ite_true]; exact linear_sound hP t l h\n · rename_i hc\n simp only [evalE, truth_sound hP c false hc]; exact linear_sound hP f l h\n · simp at h\ntheorem truth_sound (hP : PathHolds path x) : (c : QC) → (b : Bool) → truth path c = some b → evalC x c = b\n | .le a b', r, h => by\n simp only [truth] at h\n split at h\n · rename_i la lb ha hb\n simp only [evalC]; exact dec_le hP (linear_sound hP a la ha) (linear_sound hP b' lb hb) h\n · simp at h\n | .lt a b', r, h => by\n simp only [truth] at h\n split at h\n · rename_i la lb ha hb\n simp only [Option.map_eq_some_iff] at h\n obtain ⟨r', hr, rfl⟩ := h\n have := dec_le hP (linear_sound hP b' lb hb) (linear_sound hP a la ha) hr\n simp only [evalC]; rw [← this]\n cases h' : decide (evalE x b' ≤ evalE x a) <;> simp at h' <;> simp [h'] <;> grind\n · simp at h\n | .eq a b', r, h => by\n simp only [truth] at h\n split at h\n · rename_i la lb ha hb\n have ea := linear_sound hP a la ha\n have eb := linear_sound hP b' lb hb\n simp only [evalC]\n revert h\n rcases h1 : dec path (dif la lb) with _ | _ | _ <;> rcases h2 : dec path (dif lb la) with _ | _ | _ <;>\n intro h <;> simp only [Option.some.injEq, reduceCtorEq] at h <;> subst h <;>\n first\n | (have t1 := dec_le hP ea eb h1; have t2 := dec_le hP eb ea h2\n simp only [decide_eq_true_eq, decide_eq_false_iff_not, decide_eq_decide] at t1 t2 ⊢; grind)\n | (have t1 := dec_le hP ea eb h1\n simp only [decide_eq_true_eq, decide_eq_false_iff_not, decide_eq_decide] at t1 ⊢; grind)\n | (have t2 := dec_le hP eb ea h2\n simp only [decide_eq_true_eq, decide_eq_false_iff_not, decide_eq_decide] at t2 ⊢; grind)\n · simp at h\n | .and a b', r, h => by\n simp only [truth] at h\n simp only [evalC]\n split at h\n · rename_i h1; simp only [Option.some.injEq] at h; subst h; simp [truth_sound hP a false h1]\n · rename_i h2 _; simp only [Option.some.injEq] at h; subst h; simp [truth_sound hP b' false h2]\n · rename_i h1 h2; simp only [Option.some.injEq] at h; subst h; simp [truth_sound hP a true h1, truth_sound hP b' true h2]\n · simp at h\n | .or a b', r, h => by\n simp only [truth] at h\n simp only [evalC]\n split at h\n · rename_i h1; simp only [Option.some.injEq] at h; subst h; simp [truth_sound hP a true h1]\n · rename_i h2 _; simp only [Option.some.injEq] at h; subst h; simp [truth_sound hP b' true h2]\n · rename_i h1 h2; simp only [Option.some.injEq] at h; subst h; simp [truth_sound hP a false h1, truth_sound hP b' false h2]\n · simp at h\n | .not a, r, h => by\n simp only [truth, Option.map_eq_some_iff] at h\n obtain ⟨r', h1, rfl⟩ := h\n simp [evalC, truth_sound hP a r' h1]\nend\n\ntheorem facts_sound (hP : PathHolds path x) : (pos : Bool) → (c : QC) → evalC x c = pos → ∀ r ∈ facts path pos c, Holds x r\n | pos, .not a, h, r, hr => by\n simp only [facts] at hr\n exact facts_sound hP (!pos) a (by simp only [evalC] at h; cases pos <;> simp_all) r hr\n | pos, .and a b, h, r, hr => by\n simp only [facts] at hr\n simp only [evalC] at h\n split at hr\n · rename_i hp; subst hp\n simp only [Bool.and_eq_true] at h\n rcases List.mem_append.mp hr with hr | hr\n · exact facts_sound hP true a h.1 r hr\n · exact facts_sound hP true b h.2 r hr\n · rename_i hp\n simp only [Bool.not_eq_true] at hp; subst hp\n split at hr\n · rename_i ht; have := truth_sound hP a true ht\n exact facts_sound hP false b (by simp_all) r hr\n · split at hr\n · rename_i _ ht; have := truth_sound hP b true ht\n exact facts_sound hP false a (by simp_all) r hr\n · simp at hr\n | pos, .or a b, h, r, hr => by\n simp only [facts] at hr\n simp only [evalC] at h\n split at hr\n · rename_i hp\n simp only [Bool.not_eq_true'] at hp; subst hp\n simp only [Bool.or_eq_false_iff] at h\n rcases List.mem_append.mp hr with hr | hr\n · exact facts_sound hP false a h.1 r hr\n · exact facts_sound hP false b h.2 r hr\n · rename_i hp\n simp only [Bool.not_eq_true', Bool.not_eq_false] at hp; subst hp\n split at hr\n · rename_i ht; have := truth_sound hP a false ht\n exact facts_sound hP true b (by simp_all) r hr\n · split at hr\n · rename_i _ ht; have := truth_sound hP b false ht\n exact facts_sound hP true a (by simp_all) r hr\n · simp at hr\n | pos, .le a b, h, r, hr => by\n simp only [facts] at hr\n split at hr\n · rename_i la lb ha hb\n have ea := linear_sound hP a la ha\n have eb := linear_sound hP b lb hb\n simp only [evalC] at h\n cases pos\n · simp only [Bool.false_eq_true, ite_false, List.mem_singleton] at hr; subst hr\n simp only [decide_eq_false_iff_not] at h\n unfold Holds; simp only [ite_true]; exact (dif_lt eb ea).mpr (by grind)\n · simp only [ite_true, List.mem_singleton] at hr; subst hr\n simp only [decide_eq_true_eq] at h\n unfold Holds; simp only [Bool.false_eq_true, ite_false]; exact (dif_le ea eb).mpr h\n · simp at hr\n | pos, .lt a b, h, r, hr => by\n simp only [facts] at hr\n split at hr\n · rename_i la lb ha hb\n have ea := linear_sound hP a la ha\n have eb := linear_sound hP b lb hb\n simp only [evalC] at h\n cases pos\n · simp only [Bool.false_eq_true, ite_false, List.mem_singleton] at hr; subst hr\n simp only [decide_eq_false_iff_not] at h\n unfold Holds; simp only [Bool.false_eq_true, ite_false]; exact (dif_le eb ea).mpr (by grind)\n · simp only [ite_true, List.mem_singleton] at hr; subst hr\n simp only [decide_eq_true_eq] at h\n unfold Holds; simp only [ite_true]; exact (dif_lt ea eb).mpr h\n · simp at hr\n | pos, .eq a b, h, r, hr => by\n simp only [facts] at hr\n split at hr\n · rename_i la lb ha hb\n have ea := linear_sound hP a la ha\n have eb := linear_sound hP b lb hb\n simp only [evalC] at h\n cases pos\n · simp only [decide_eq_false_iff_not] at h\n simp only [Bool.false_eq_true, ite_false] at hr\n split at hr\n · rename_i hd\n simp only [List.mem_singleton] at hr; subst hr\n have := dec_le hP ea eb hd; simp only [decide_eq_true_eq] at this\n unfold Holds; simp only [ite_true]; exact (dif_lt ea eb).mpr (by grind)\n · split at hr\n · rename_i _ hd\n simp only [List.mem_singleton] at hr; subst hr\n have := dec_le hP eb ea hd; simp only [decide_eq_true_eq] at this\n unfold Holds; simp only [ite_true]; exact (dif_lt eb ea).mpr (by grind)\n · simp at hr\n · simp only [decide_eq_true_eq] at h\n simp only [ite_true, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hr\n unfold Holds\n rcases hr with rfl | rfl\n · simp only [Bool.false_eq_true, ite_false]; exact (dif_le ea eb).mpr (by grind)\n · simp only [Bool.false_eq_true, ite_false]; exact (dif_le eb ea).mpr (by grind)\n · simp at hr\n\ntheorem atomRow_holds (hP : PathHolds path x) : ∀ a ∈ path, Holds x (atomRow a) := by\n intro a ha\n have := hP a ha\n unfold atomRow Holds\n cases hb : a.2\n · simp only [hb, decide_eq_false_iff_not] at this\n simp only [Bool.false_eq_true, ite_false, ite_true, evalQ_lscale]; grind\n · simp only [hb, decide_eq_true_eq] at this\n simp only [ite_true, Bool.false_eq_true, ite_false]; exact this\n\ntheorem leafRows_sound (hP : PathHolds path x) {hyps : List QC} (hH : ∀ c ∈ hyps, evalC x c = true) :\n ∀ r ∈ leafRows path hyps, Holds x r := by\n intro r hr\n simp only [leafRows, List.mem_append, List.mem_map, List.mem_flatMap] at hr\n rcases hr with ⟨a, ha, rfl⟩ | ⟨c, hc, hr⟩\n · exact atomRow_holds hP a ha\n · exact facts_sound hP true c (hH c hc) r hr\n\ntheorem claim_holds {rows : List (Row × Bool)} (hrows : ∀ q ∈ rows, Holds x q) {r : Row × Bool}\n (h : claimOk rows r = true) : Holds x r := by\n simp only [claimOk, List.any_eq_true, Bool.and_eq_true, Bool.or_eq_true, Bool.not_eq_true'] at h\n obtain ⟨q, hq, hs, hst⟩ := h\n have hq' := hrows q hq\n have e := same_evalQ hs x\n unfold Holds at hq' ⊢\n rw [← e]\n rcases hst with h1 | h1\n · simp only [h1, ite_true] at hq'\n split\n · exact hq'\n · exact Rat.le_of_lt hq'\n · simp only [h1, Bool.false_eq_true, ite_false]\n split at hq'\n · exact Rat.le_of_lt hq'\n · exact hq'\nend\n\ntheorem checkT_sound {x : Nat → Rat} {hyps : List QC} (hH : ∀ c ∈ hyps, evalC x c = true) :\n ∀ (t : QTree) (path : Path), PathHolds path x → checkT hyps path t = true → False\n | .leaf rows steps, path, hP, h => by\n simp only [checkT, Bool.and_eq_true, List.all_eq_true] at h\n exact checkQ_sound rows steps h.2 x (fun r hr => claim_holds (leafRows_sound hP hH) (h.1 r hr))\n | .split l yes no, path, hP, h => by\n simp only [checkT, Bool.and_eq_true] at h\n by_cases hl : evalQ l x ≤ 0\n · refine checkT_sound hH yes ((l, true) :: path) ?_ h.1.2\n intro a ha\n rcases List.mem_cons.mp ha with rfl | ha\n · simp [hl]\n · exact hP a ha\n · refine checkT_sound hH no ((l, false) :: path) ?_ h.2\n intro a ha\n rcases List.mem_cons.mp ha with rfl | ha\n · simp [hl]\n · exact hP a ha\n\n/-- The tree check is sound: an accepted goal's hypotheses hold together at no rational point. -/\ntheorem sound (hyps : List QC) (t : QTree) (h : checkGoal hyps t = true) (x : Nat → Rat) :\n ¬ (∀ c ∈ hyps, evalC x c = true) :=\n fun hH => checkT_sound hH t [] (by simp [PathHolds]) h\n\n/-! Step machines over the rationals: the induction rule over these goals, built here in Lean from the machine (as\nKernel.lean's `checkMachine`), so the TypeScript obligations are not trusted. A law holds at the start (`startGoal` is\nrefuted) and one step keeps every law (`stepGoal` is refuted, assuming them all and the request's assumption), so every\nlaw holds in every reachable state. Laws may not read the request's inputs. -/\n\ndef assoc (σ : List (Nat × QE)) (i : Nat) : Option QE := (lookup (fun p => p.1 == i) σ).map (·.2)\n\nmutual\ndef substE (σ : List (Nat × QE)) : QE → QE\n | .var i => match assoc σ i with\n | some e => e\n | none => .var i\n | .const q => .const q\n | .add a b => .add (substE σ a) (substE σ b)\n | .sub a b => .sub (substE σ a) (substE σ b)\n | .mul k a => .mul k (substE σ a)\n | .min a b => .min (substE σ a) (substE σ b)\n | .max a b => .max (substE σ a) (substE σ b)\n | .ite c t f => .ite (substC σ c) (substE σ t) (substE σ f)\ndef substC (σ : List (Nat × QE)) : QC → QC\n | .le a b => .le (substE σ a) (substE σ b)\n | .lt a b => .lt (substE σ a) (substE σ b)\n | .eq a b => .eq (substE σ a) (substE σ b)\n | .and a b => .and (substC σ a) (substC σ b)\n | .or a b => .or (substC σ a) (substC σ b)\n | .not a => .not (substC σ a)\nend\n\n-- The environment after σ: each assigned variable takes its term's value, the rest keep theirs.\ndef applyS (σ : List (Nat × QE)) (ρ : Nat → Rat) : Nat → Rat :=\n fun i => match assoc σ i with\n | some e => evalE ρ e\n | none => ρ i\n\nmutual\ntheorem subst_evalE (σ : List (Nat × QE)) (ρ : Nat → Rat) : (e : QE) → evalE ρ (substE σ e) = evalE (applyS σ ρ) e\n | .var i => by\n simp only [substE]\n cases h : assoc σ i <;> simp [evalE, applyS, h]\n | .const q => by simp [substE, evalE]\n | .add a b => by simp [substE, evalE, subst_evalE σ ρ a, subst_evalE σ ρ b]\n | .sub a b => by simp [substE, evalE, subst_evalE σ ρ a, subst_evalE σ ρ b]\n | .mul k a => by simp [substE, evalE, subst_evalE σ ρ a]\n | .min a b => by simp [substE, evalE, subst_evalE σ ρ a, subst_evalE σ ρ b]\n | .max a b => by simp [substE, evalE, subst_evalE σ ρ a, subst_evalE σ ρ b]\n | .ite c t f => by simp [substE, evalE, subst_evalC σ ρ c, subst_evalE σ ρ t, subst_evalE σ ρ f]\ntheorem subst_evalC (σ : List (Nat × QE)) (ρ : Nat → Rat) : (c : QC) → evalC ρ (substC σ c) = evalC (applyS σ ρ) c\n | .le a b => by simp [substC, evalC, subst_evalE σ ρ a, subst_evalE σ ρ b]\n | .lt a b => by simp [substC, evalC, subst_evalE σ ρ a, subst_evalE σ ρ b]\n | .eq a b => by simp [substC, evalC, subst_evalE σ ρ a, subst_evalE σ ρ b]\n | .and a b => by simp [substC, evalC, subst_evalC σ ρ a, subst_evalC σ ρ b]\n | .or a b => by simp [substC, evalC, subst_evalC σ ρ a, subst_evalC σ ρ b]\n | .not a => by simp [substC, evalC, subst_evalC σ ρ a]\nend\n\nmutual\ndef occE (i : Nat) : QE → Bool\n | .var j => j == i\n | .const _ => false\n | .add a b => occE i a || occE i b\n | .sub a b => occE i a || occE i b\n | .mul _ a => occE i a\n | .min a b => occE i a || occE i b\n | .max a b => occE i a || occE i b\n | .ite c t f => occC i c || occE i t || occE i f\ndef occC (i : Nat) : QC → Bool\n | .le a b => occE i a || occE i b\n | .lt a b => occE i a || occE i b\n | .eq a b => occE i a || occE i b\n | .and a b => occC i a || occC i b\n | .or a b => occC i a || occC i b\n | .not a => occC i a\nend\n\nmutual\ntheorem congrE (ρ ρ' : Nat → Rat) : (e : QE) → (∀ i, occE i e = true → ρ i = ρ' i) → evalE ρ e = evalE ρ' e\n | .var j, h => by simp only [evalE]; exact h j (by simp [occE])\n | .const _, _ => rfl\n | .add a b, h => by\n simp only [evalE, congrE ρ ρ' a (fun i hi => h i (by simp [occE, hi])), congrE ρ ρ' b (fun i hi => h i (by simp [occE, hi]))]\n | .sub a b, h => by\n simp only [evalE, congrE ρ ρ' a (fun i hi => h i (by simp [occE, hi])), congrE ρ ρ' b (fun i hi => h i (by simp [occE, hi]))]\n | .mul k a, h => by simp only [evalE, congrE ρ ρ' a (fun i hi => h i (by simp [occE, hi]))]\n | .min a b, h => by\n simp only [evalE, congrE ρ ρ' a (fun i hi => h i (by simp [occE, hi])), congrE ρ ρ' b (fun i hi => h i (by simp [occE, hi]))]\n | .max a b, h => by\n simp only [evalE, congrE ρ ρ' a (fun i hi => h i (by simp [occE, hi])), congrE ρ ρ' b (fun i hi => h i (by simp [occE, hi]))]\n | .ite c t f, h => by\n simp only [evalE, congrC ρ ρ' c (fun i hi => h i (by simp [occE, hi])), congrE ρ ρ' t (fun i hi => h i (by simp [occE, hi])),\n congrE ρ ρ' f (fun i hi => h i (by simp [occE, hi]))]\ntheorem congrC (ρ ρ' : Nat → Rat) : (c : QC) → (∀ i, occC i c = true → ρ i = ρ' i) → evalC ρ c = evalC ρ' c\n | .le a b, h => by\n simp only [evalC, congrE ρ ρ' a (fun i hi => h i (by simp [occC, hi])), congrE ρ ρ' b (fun i hi => h i (by simp [occC, hi]))]\n | .lt a b, h => by\n simp only [evalC, congrE ρ ρ' a (fun i hi => h i (by simp [occC, hi])), congrE ρ ρ' b (fun i hi => h i (by simp [occC, hi]))]\n | .eq a b, h => by\n simp only [evalC, congrE ρ ρ' a (fun i hi => h i (by simp [occC, hi])), congrE ρ ρ' b (fun i hi => h i (by simp [occC, hi]))]\n | .and a b, h => by\n simp only [evalC, congrC ρ ρ' a (fun i hi => h i (by simp [occC, hi])), congrC ρ ρ' b (fun i hi => h i (by simp [occC, hi]))]\n | .or a b, h => by\n simp only [evalC, congrC ρ ρ' a (fun i hi => h i (by simp [occC, hi])), congrC ρ ρ' b (fun i hi => h i (by simp [occC, hi]))]\n | .not a, h => by simp only [evalC, congrC ρ ρ' a (fun i hi => h i (by simp [occC, hi]))]\nend\n\nstructure Machine where\n inputs : List Nat\n init : List (Nat × QE) -- each state variable's start, over the params\n step : List (Nat × QE) -- each state variable after a request, over params, inputs and state\n pre : QC -- about the params alone: a precondition, so it holds at the start and at every step\n assume : QC -- about each request (and the params); holds at a step, not at the start\n\n-- A request: its inputs replace those variables; nothing else changes until the step.\ndef withInputs (inputs : List Nat) (ρ ι : Nat → Rat) : Nat → Rat := fun i => if inputs.contains i then ι i else ρ i\n\ninductive Reach (m : Machine) : (Nat → Rat) → Prop\n | start (ρ : Nat → Rat) : evalC ρ m.pre = true → Reach m (applyS m.init ρ)\n | step (ρ ι : Nat → Rat) : Reach m ρ → evalC (withInputs m.inputs ρ ι) m.assume = true →\n Reach m (applyS m.step (withInputs m.inputs ρ ι))\n\ndef startGoal (m : Machine) (law : QC) : List QC := [m.pre, .not (substC m.init law)]\ndef stepGoal (m : Machine) (laws : List QC) (law : QC) : List QC := [m.pre, m.assume] ++ laws ++ [.not (substC m.step law)]\n\n-- Per law: the law, then the trees of its start goal and of its step goal.\nabbrev MachineProof := List (QC × QTree × QTree)\n\ndef avoids (vs : List Nat) (c : QC) : Bool := vs.all fun i => !occC i c\n-- The precondition reads only params: no input, no variable the start or a step assigns.\ndef preOk (m : Machine) : Bool := avoids (m.inputs ++ m.init.map (·.1) ++ m.step.map (·.1)) m.pre\n\ndef checkMachine (m : Machine) (ps : MachineProof) : Bool :=\n preOk m && ps.all fun p => avoids m.inputs p.1\n && checkGoal (startGoal m p.1) p.2.1\n && checkGoal (stepGoal m (ps.map (·.1)) p.1) p.2.2\n\ntheorem avoids_occ {vs : List Nat} {c : QC} (h : avoids vs c = true) {i : Nat} (hi : occC i c = true) : i ∉ vs := by\n intro hm\n simp only [avoids, List.all_eq_true] at h\n have := h i hm; simp [hi] at this\n\ntheorem assoc_mem {σ : List (Nat × QE)} {i : Nat} {e : QE} (h : assoc σ i = some e) : i ∈ σ.map (·.1) := by\n simp only [assoc, Option.map_eq_some_iff] at h\n obtain ⟨a, ha, _⟩ := h\n have ⟨hm, hp⟩ := lookup_some ha\n simp only [beq_iff_eq] at hp\n exact List.mem_map.mpr ⟨a, hm, hp⟩\n\ntheorem applyS_other {σ : List (Nat × QE)} {i : Nat} (h : i ∉ σ.map (·.1)) (ρ : Nat → Rat) : applyS σ ρ i = ρ i := by\n simp only [applyS]\n cases ha : assoc σ i with\n | none => rfl\n | some e => exact absurd (assoc_mem ha) h\n\ntheorem withInputs_other {inputs : List Nat} {i : Nat} (h : i ∉ inputs) (ρ ι : Nat → Rat) : withInputs inputs ρ ι i = ρ i := by\n simp only [withInputs]; split\n · rename_i hc; exact absurd (List.contains_iff_mem.mp hc) h\n · rfl\n\ntheorem evalC_avoids {vs : List Nat} {c : QC} (h : avoids vs c = true) {ρ ρ' : Nat → Rat}\n (hρ : ∀ i, i ∉ vs → ρ i = ρ' i) : evalC ρ c = evalC ρ' c :=\n congrC ρ ρ' c (fun i hi => hρ i (avoids_occ h hi))\n\ntheorem pre_reach {m : Machine} (hp : preOk m = true) : ∀ {ρ}, Reach m ρ → evalC ρ m.pre = true := by\n intro ρ hr\n induction hr with\n | start ρ h0 =>\n rw [evalC_avoids hp (ρ' := ρ) (fun i hi => applyS_other (fun h => hi (by simp [h])) ρ)]; exact h0\n | step ρ ι _ _ ih =>\n rw [evalC_avoids hp (ρ' := ρ) (fun i hi => by\n rw [applyS_other (fun h => hi (by simp [h])), withInputs_other (fun h => hi (by simp [h]))])]; exact ih\n\n/-- The induction rule over the rationals: for params that meet the precondition, every law of an accepted machine\nproof holds in every reachable state. -/\ntheorem machine_sound (m : Machine) (ps : MachineProof) (h : checkMachine m ps = true) :\n ∀ ρ, Reach m ρ → ∀ l ∈ ps.map (·.1), evalC ρ l = true := by\n simp only [checkMachine, List.all_eq_true, Bool.and_eq_true] at h\n obtain ⟨hpre, h⟩ := h\n intro ρ hr\n induction hr with\n | start ρ h0 =>\n intro l hl\n obtain ⟨p, hp, rfl⟩ := List.mem_map.mp hl\n have hs := sound _ _ (h p hp).1.2 ρ\n apply Decidable.byContradiction\n intro hf\n apply hs\n intro c hc\n simp only [startGoal, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hc\n rcases hc with rfl | rfl\n · exact h0\n · simp only [evalC, subst_evalC]; simpa using hf\n | step ρ ι hr ha ih =>\n intro l hl\n obtain ⟨p, hp, rfl⟩ := List.mem_map.mp hl\n have hs := sound _ _ (h p hp).2 (withInputs m.inputs ρ ι)\n apply Decidable.byContradiction\n intro hf\n apply hs\n intro c hc\n simp only [stepGoal, List.mem_append, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hc\n rcases hc with ((rfl | rfl) | hc) | rfl\n · rw [evalC_avoids hpre (ρ' := ρ) (fun i hi => withInputs_other (fun h => hi (by simp [h])) ρ ι)]\n exact pre_reach hpre hr\n · exact ha\n · obtain ⟨q, hq, rfl⟩ := List.mem_map.mp hc\n rw [evalC_avoids (h q hq).1.1 (ρ' := ρ) (fun i hi => withInputs_other hi ρ ι)]\n exact ih q.1 (List.mem_map.mpr ⟨q, hq, rfl⟩)\n · simp only [evalC, subst_evalC]; simpa using hf\n\n#print axioms checkQ_sound\n#print axioms sound\n#print axioms machine_sound\n\nend Q\n",
20
20
  "KInd.lean": "import Live\n\n/-!\nKInd: k-induction for machines with sets, proven sound. Lean 4.34.0, core only, on top of `Sets.lean` and `Live.lean`.\n\nA law L (about the state, params and maps, no key) is k-inductive when\n- the base: L holds at the start (`kStartGoal`), and after every run of j steps from the start, 1 ≤ j < k; and\n- the step: after any k steps in a row from a reachable state, each starting where L holds, L holds.\n\nEvery goal but the start's is Sets.lean's k-step goal (`SKStep`, checked by `checkSKStep`, its claim `skstep_sound`):\nLean builds each `when` and the `then` itself from L (`KInd.with`), and only the trees, the instances and the names a\ngoal reads later requests by come from the certificate. The base of depth j reads the first state as the start\n(`startC`: each state variable its start term; a reachable state where they hold is the start's as far as the scalars\ngo, so the claim, made of every reachable state, covers the start) with L there too, and L before each later step; the\nstep reads L before each of its k steps. `then` is L with its state variables and maps renamed to their primed names\n(Live.lean's `primeC`). So `kind_sound`: if the laws' proof checks and the certificate does, L holds in every reachable\nstate, by strong induction on the length of the run that reaches it: a run shorter than k is a base, a longer one is the\nstep from the state k requests back, where L held at each state after by the induction.\n-/\n\nnamespace Kern\nset_option linter.unusedSimpArgs false\nset_option linter.unusedSectionVars false\n\n/-! The certificate -/\n\n-- A conjunction: the condition itself for one, true for none (as kernel.ts's `and` prints).\ndef andC : List C → C\n | [] => trueC\n | [c] => c\n | c :: cs => .and c (andC cs)\n\n-- The start, as a condition: each state variable its start term.\ndef startC (s : SMachine) : C := andC (s.f.m.init.map fun p => .eq (.var p.1) p.2)\n\nstructure KInd where\n law : C\n k : Nat\n prime : List (Nat × Nat) -- a state variable, and the name `then` reads its value after the last step by\n primeMaps : List (Nat × Nat) -- a map, and the name `then` reads it after the last step by\n finsts : List (Nat × E) -- the start goal's fact instances\n pfinsts : List (Nat × E × List E) -- and its instances of the facts about several keys\n start : Cert -- L at the start\n base : List SKStep -- depth j = 1, …, k − 1: its instances, names and tree (Lean sets whens and then)\n step : SKStep -- depth k: k states where L held, then L\n\ndef KInd.then_ (kc : KInd) : C := primeC kc.prime kc.primeMaps kc.law\ndef KInd.with (kc : KInd) (ws : List C) (sl : SKStep) : SKStep :=\n { sl with k := { sl.k with whens := ws, then_ := kc.then_, prime := kc.prime, primeMaps := kc.primeMaps } }\n\n-- The base of depth j: the start with L, then L before each later step.\ndef baseWhens (s : SMachine) (L : C) (j : Nat) : List C := .and (startC s) L :: List.replicate (j - 1) L\ndef kStartGoal (s : SMachine) (kc : KInd) : List C :=\n [s.f.m.pre] ++ factHyps s kc.finsts kc.pfinsts ++ [.not (substRC s.f.m.init (rdStart s.f.m) kc.law)]\n\n-- What L may not read: a primed name, a request's variables, a flag, and a state variable a step writes that has no\n-- primed name; a primed map, a carried map, and a map a step writes that has none.\ndef kindVars (s : SMachine) (kc : KInd) : List Nat :=\n kc.prime.map (·.2) ++ s.extVars ++ (flagVars s.f.flags ++ s.f.m.step.map (·.1)).filter (fun i => !(kc.prime.map (·.1)).contains i)\ndef kindMaps (s : SMachine) (kc : KInd) : List Nat :=\n kc.primeMaps.map (·.2) ++ s.carried ++ (s.f.m.writes.map (·.1) ++ s.every.map (·.1)).filter (fun mp => !(kc.primeMaps.map (·.1)).contains mp)\n-- Nor a name a k-step goal reads a later request by.\ndef kAvoids (kc : KInd) (sl : SKStep) : Bool := avoids (tgts sl.k.ren) kc.law && avoidsMaps (tgts sl.mren) kc.law\n\n-- The start terms read no request variable, no state variable the start sets and no carried map; each variable once.\ndef startOk (s : SMachine) : Bool :=\n distinct (s.f.m.init.map (·.1))\n && s.f.m.init.all (fun p => !s.extVars.contains p.1 && avoidsE (s.extVars ++ s.f.m.init.map (·.1)) p.2 && avoidsMapsE s.carried p.2)\n\ndef checkBase (s : SMachine) (ps : List SEntry) (kc : KInd) : Nat → List SKStep → Bool\n | _, [] => true\n | j, sl :: rest => kAvoids kc sl && checkSKStep s ps (kc.with (baseWhens s kc.law j) sl) && checkBase s ps kc (j + 1) rest\n\ndef checkKInd (s : SMachine) (ps : List SEntry) (kc : KInd) : Bool :=\n 1 ≤ kc.k && kc.base.length + 1 == kc.k\n && distinct (kc.prime.map (·.2)) && distinct (kc.primeMaps.map (·.2))\n && avoids (kindVars s kc) kc.law && avoidsMaps (kindMaps s kc) kc.law\n && startOk s\n && checkIn (kStartGoal s kc) kc.start\n && checkBase s ps kc 1 kc.base\n && kAvoids kc kc.step && checkSKStep s ps (kc.with (List.replicate kc.k kc.law) kc.step)\n\n/-! Runs as lists of requests -/\n\n-- Each request allowed in turn.\ndef SPath (s : SMachine) : (Nat → Nat) → (Nat → Nat → Nat) → List SRequest → Prop\n | _, _, [] => True\n | ρ, M, q :: qs => evalC (sView s ρ M q.1 q.2).1 (sView s ρ M q.1 q.2).2 s.f.m.assume = true\n ∧ SPath s (sNext s ρ M q.1 q.2).1 (sNext s ρ M q.1 q.2).2 qs\n\ntheorem sEnd_append (s : SMachine) : ∀ (a b : List SRequest) (ρ : Nat → Nat) (M : Nat → Nat → Nat),\n sEnd s ρ M (a ++ b) = sEnd s (sEnd s ρ M a).1 (sEnd s ρ M a).2 b\n | [], _, _, _ => rfl\n | q :: a, b, ρ, M => by simp only [List.cons_append, sEnd]; exact sEnd_append s a b _ _\n\ntheorem spath_append (s : SMachine) : ∀ (a b : List SRequest) (ρ : Nat → Nat) (M : Nat → Nat → Nat),\n SPath s ρ M (a ++ b) ↔ SPath s ρ M a ∧ SPath s (sEnd s ρ M a).1 (sEnd s ρ M a).2 b\n | [], _, _, _ => by simp [SPath, sEnd]\n | q :: a, b, ρ, M => by\n simp only [List.cons_append, SPath, sEnd]\n rw [spath_append s a b _ _]; exact and_assoc.symm\n\ntheorem spath_take {s : SMachine} {ρ : Nat → Nat} {M : Nat → Nat → Nat} {qs : List SRequest} (h : SPath s ρ M qs) (j : Nat) :\n SPath s ρ M (qs.take j) := by\n rw [← List.take_append_drop j qs, spath_append] at h; exact h.1\n\ntheorem sreach_path (s : SMachine) : ∀ (qs : List SRequest) {ρ : Nat → Nat} {M : Nat → Nat → Nat},\n SReach s ρ M → SPath s ρ M qs → SReach s (sEnd s ρ M qs).1 (sEnd s ρ M qs).2\n | [], _, _, hr, _ => hr\n | q :: qs, _, _, hr, hp => sreach_path s qs (SReach.step _ _ _ _ hr hp.1) hp.2\n\n-- A reachable state is the end of a run from a start.\ntheorem sreach_from (s : SMachine) {ρ : Nat → Nat} {M : Nat → Nat → Nat} (h : SReach s ρ M) :\n ∃ ρ0 M0, StartMaps s.f.m M0 ∧ evalC ρ0 M0 s.f.m.pre = true ∧ (∀ l ∈ s.facts, l.Holds ρ0 M0) ∧ s.PFacts ρ0 M0\n ∧ ∃ qs, SPath s (applyS s.f.m.init ρ0 M0) M0 qs ∧ sEnd s (applyS s.f.m.init ρ0 M0) M0 qs = (ρ, M) := by\n induction h with\n | start ρ M hM h0 hf hpf => exact ⟨ρ, M, hM, h0, hf, hpf, [], trivial, rfl⟩\n | step ρ M ι κ _ ha ih =>\n obtain ⟨ρ0, M0, hM, h0, hf, hpf, qs, hp, he⟩ := ih\n refine ⟨ρ0, M0, hM, h0, hf, hpf, qs ++ [(ι, κ)], ?_, ?_⟩\n · rw [spath_append, he]; exact ⟨hp, ha, trivial⟩\n · rw [sEnd_append, he]; rfl\n\n/-! What a run leaves alone -/\n\ntheorem sNext_other (s : SMachine) {i : Nat} (hx : i ∉ s.extVars) (hf : i ∉ flagVars s.f.flags) (hs : i ∉ s.f.m.step.map (·.1))\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat) : (sNext s ρ M ι κ).1 i = ρ i := by\n simp only [SMachine.extVars, SMachine.qVars, List.mem_append, not_or] at hx\n simp only [sNext, sView]\n rw [applyS_other hs, decide_other hf, decideQ_other (by simpa [SMachine.qVars] using hx.1.2), withInputs_other hx.1.1]\n\ntheorem sEnd_other (s : SMachine) {i : Nat} (hx : i ∉ s.extVars) (hf : i ∉ flagVars s.f.flags) (hs : i ∉ s.f.m.step.map (·.1)) :\n ∀ (qs : List SRequest) (ρ : Nat → Nat) (M : Nat → Nat → Nat), (sEnd s ρ M qs).1 i = ρ i\n | [], _, _ => rfl\n | q :: qs, ρ, M => by simp only [sEnd]; rw [sEnd_other s hx hf hs qs _ _, sNext_other s hx hf hs]\n\ntheorem sNext_maps_other (s : SMachine) {mp : Nat} (hc : mp ∉ s.carried) (hw : mp ∉ s.f.m.writes.map (·.1)) (he : mp ∉ s.every.map (·.1))\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat) : (sNext s ρ M ι κ).2 mp = M mp := by\n funext k\n simp only [sNext, everyMaps]\n rw [lookup_none (fun w hw' => by simp only [beq_eq_false_iff_ne]; intro h; exact he (by rw [← h]; exact List.mem_map_of_mem hw'))]\n simp only [writeMaps]\n rw [lookup_none (fun w hw' => by simp only [beq_eq_false_iff_ne]; intro h; exact hw (by rw [← h]; exact List.mem_map_of_mem hw'))]\n simp only [sView, withCarried]\n rw [if_neg (by simpa [List.contains_iff_mem] using hc)]\n\ntheorem sEnd_maps_other (s : SMachine) {mp : Nat} (hc : mp ∉ s.carried) (hw : mp ∉ s.f.m.writes.map (·.1)) (he : mp ∉ s.every.map (·.1)) :\n ∀ (qs : List SRequest) (ρ : Nat → Nat) (M : Nat → Nat → Nat), (sEnd s ρ M qs).2 mp = M mp\n | [], _, _ => rfl\n | q :: qs, ρ, M => by simp only [sEnd]; rw [sEnd_maps_other s hc hw he qs _ _, sNext_maps_other s hc hw he]\n\n-- A condition that reads no request variable and no carried map reads the same in a step's view.\ntheorem view_eval {s : SMachine} {c : C} (hx : avoids s.extVars c = true) (hm : avoidsMaps s.carried c = true)\n (ρ X : Nat → Nat) (M κ : Nat → Nat → Nat) : evalC (withExt s ρ X) (withCarried s M κ) c = evalC ρ M c := by\n rw [congrMC _ _ M c (fun mp hmp => by\n simp only [withCarried]; rw [if_neg (by simpa [List.contains_iff_mem] using avoidsMaps_occ hm hmp)])]\n exact congrC _ _ _ c (fun i hi => by\n simp only [withExt]; rw [if_neg (by simpa [List.contains_iff_mem] using avoids_occ hx hi)])\n\ntheorem andC_true {ρ : Nat → Nat} {M : Nat → Nat → Nat} : ∀ {cs : List C}, (∀ c ∈ cs, evalC ρ M c = true) → evalC ρ M (andC cs) = true\n | [], _ => by simp [andC, trueC, evalC, evalE]\n | [c], h => by simpa [andC] using h c List.mem_cons_self\n | c :: d :: cs, h => by\n simp only [andC, evalC, Bool.and_eq_true]\n exact ⟨h c List.mem_cons_self, andC_true (fun x hx => h x (List.mem_cons_of_mem _ hx))⟩\n\n/-! The parts of the check -/\n\nsection parts\nvariable {s : SMachine} {ps : List SEntry} {kc : KInd}\n\ntheorem kind_parts (h : checkKInd s ps kc = true) :\n 1 ≤ kc.k ∧ kc.base.length + 1 = kc.k ∧ distinct (kc.prime.map (·.2)) = true ∧ distinct (kc.primeMaps.map (·.2)) = true\n ∧ avoids (kindVars s kc) kc.law = true ∧ avoidsMaps (kindMaps s kc) kc.law = true ∧ startOk s = true\n ∧ checkIn (kStartGoal s kc) kc.start = true ∧ checkBase s ps kc 1 kc.base = true\n ∧ kAvoids kc kc.step = true ∧ checkSKStep s ps (kc.with (List.replicate kc.k kc.law) kc.step) = true := by\n simp only [checkKInd, Bool.and_eq_true, decide_eq_true_eq, beq_iff_eq] at h\n obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩, h9⟩, h10⟩, h11⟩ := h\n exact ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11⟩\n\ntheorem checkBase_get : ∀ (l : List SKStep) (j : Nat), checkBase s ps kc j l = true → ∀ i (hi : i < l.length),\n kAvoids kc l[i] = true ∧ checkSKStep s ps (kc.with (baseWhens s kc.law (j + i)) l[i]) = true\n | [], _, _, i, hi => absurd hi (Nat.not_lt_zero _)\n | sl :: rest, j, h, i, hi => by\n simp only [checkBase, Bool.and_eq_true] at h\n cases i with\n | zero => exact ⟨h.1.1, by simpa using h.1.2⟩\n | succ i =>\n have := checkBase_get rest (j + 1) h.2 i (by simpa using hi)\n simpa [Nat.add_assoc, Nat.add_comm 1 i] using this\n\n-- L reads none of the request variables and carried maps; outside its primed names, what it reads no step moves.\ntheorem law_reads (h5 : avoids (kindVars s kc) kc.law = true) (h6 : avoidsMaps (kindMaps s kc) kc.law = true) :\n avoids s.extVars kc.law = true ∧ avoidsMaps s.carried kc.law = true\n ∧ (∀ i, occC i kc.law = true → i ∉ kc.prime.map (·.2) ∧ i ∉ s.extVars\n ∧ (i ∈ kc.prime.map (·.1) ∨ (i ∉ flagVars s.f.flags ∧ i ∉ s.f.m.step.map (·.1))))\n ∧ (∀ mp, occMC mp kc.law = true → mp ∉ kc.primeMaps.map (·.2) ∧ mp ∉ s.carried\n ∧ (mp ∈ kc.primeMaps.map (·.1) ∨ (mp ∉ s.f.m.writes.map (·.1) ∧ mp ∉ s.every.map (·.1)))) := by\n have hv : ∀ i, occC i kc.law = true → i ∉ kindVars s kc := fun i hi => avoids_occ h5 hi\n have hm : ∀ mp, occMC mp kc.law = true → mp ∉ kindMaps s kc := fun mp hmp => avoidsMaps_occ h6 hmp\n refine ⟨?_, ?_, fun i hi => ?_, fun mp hmp => ?_⟩\n · simp only [avoids, List.all_eq_true, Bool.not_eq_true']\n intro i hx\n cases hc : occC i kc.law\n · rfl\n · exact absurd (List.mem_append_left _ (List.mem_append_right _ hx)) (hv i hc)\n · simp only [avoidsMaps, List.all_eq_true, Bool.not_eq_true']\n intro mp hx\n cases hc : occMC mp kc.law\n · rfl\n · exact absurd (List.mem_append_left _ (List.mem_append_right _ hx)) (hm mp hc)\n · have h := hv i hi\n simp only [kindVars, List.mem_append, List.mem_filter, not_or, not_and, Bool.not_eq_true', List.contains_iff_mem] at h\n refine ⟨h.1.1, h.1.2, ?_⟩\n by_cases hp : i ∈ kc.prime.map (·.1)\n · exact Or.inl hp\n · right\n have hpf : (kc.prime.map (·.1)).contains i = false := by simpa [List.contains_iff_mem] using hp\n exact ⟨fun hf => by have := h.2 (Or.inl hf); simp_all, fun hs => by have := h.2 (Or.inr hs); simp_all⟩\n · have h := hm mp hmp\n simp only [kindMaps, List.mem_append, List.mem_filter, not_or, not_and, Bool.not_eq_true', List.contains_iff_mem] at h\n refine ⟨h.1.1, h.1.2, ?_⟩\n by_cases hp : mp ∈ kc.primeMaps.map (·.1)\n · exact Or.inl hp\n · right\n have hpf : (kc.primeMaps.map (·.1)).contains mp = false := by simpa [List.contains_iff_mem] using hp\n exact ⟨fun hf => by have := h.2 (Or.inl hf); simp_all, fun hs => by have := h.2 (Or.inr hs); simp_all⟩\n\nend parts\n\n/-! Each part's meaning -/\n\n-- The start goal: L at the start.\ntheorem kind_start (s : SMachine) (ps : List SEntry) (kc : KInd) (hl : checkSMachine s ps = true)\n (hst : checkIn (kStartGoal s kc) kc.start = true) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (hM : StartMaps s.f.m M) (h0 : evalC ρ M s.f.m.pre = true) (hfa : ∀ l ∈ s.facts, l.Holds ρ M) (hpf : s.PFacts ρ M) :\n evalC (applyS s.f.m.init ρ M) M kc.law = true := by\n have hfok := sfacts_ok hl\n apply Decidable.byContradiction; intro hn\n apply sound_in _ _ hst ρ M\n intro c hc\n simp only [kStartGoal, List.mem_append, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hc\n rcases hc with (rfl | hc) | rfl\n · exact h0\n · exact facthyps_true s kc.finsts kc.pfinsts ρ M (fun f hf => (pfactsOk_parts hfok f hf).2.2) hfa hpf c hc\n · have hrd : ∀ mp k, evalE ρ M (rdStart s.f.m mp k) = M mp (evalE ρ M k) := by\n intro mp k\n simp only [rdStart]\n split\n · rename_i p hp\n have ⟨hm, hq⟩ := lookup_some hp\n simp only [beq_iff_eq] at hq\n simp only [evalE]; rw [← hq, hM p hm]\n · rfl\n simp only [evalC, substR_evalC _ _ _ M M hrd]\n simpa using hn\n\n-- The start meets `startC`, read in a step's view.\ntheorem start_meets (s : SMachine) (hs : startOk s = true) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (X : Nat → Nat) (κ : Nat → Nat → Nat) :\n evalC (withExt s (applyS s.f.m.init ρ M) X) (withCarried s M κ) (startC s) = true := by\n simp only [startOk, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true'] at hs\n obtain ⟨hd, hp⟩ := hs\n apply andC_true\n intro c hc\n obtain ⟨p, hpm, rfl⟩ := List.mem_map.mp hc\n obtain ⟨⟨hx, hav⟩, havm⟩ := hp p hpm\n have hx' : p.1 ∉ s.extVars := by simpa [List.contains_iff_mem] using hx\n simp only [evalC]\n apply decide_eq_true\n simp only [evalE]\n have hl : withExt s (applyS s.f.m.init ρ M) X p.1 = evalE ρ M p.2 := by\n simp only [withExt]; rw [if_neg (by simpa [List.contains_iff_mem] using hx')]\n simp only [applyS, assoc, lookup_unique hd hpm, Option.map_some]\n rw [hl]\n symm\n rw [congrME _ _ M p.2 (fun mp hmp => by\n simp only [withCarried]\n rw [if_neg (by\n simp only [avoidsMapsE, List.all_eq_true, Bool.not_eq_true'] at havm\n intro hc'; have := havm mp (List.contains_iff_mem.mp hc'); simp [hmp] at this)])]\n exact congrE _ _ M p.2 (fun i hi => by\n simp only [avoidsE, List.all_eq_true, Bool.not_eq_true'] at hav\n have hi1 : i ∉ s.extVars := fun h' => by have := hav i (List.mem_append_left _ h'); simp [hi] at this\n have hi2 : i ∉ s.f.m.init.map (·.1) := fun h' => by have := hav i (List.mem_append_right _ h'); simp [hi] at this\n simp only [withExt]; rw [if_neg (by simpa [List.contains_iff_mem] using hi1)]\n exact applyS_other hi2 ρ M)\n\n-- Requests allowed in turn, L before each: the k-step goal's `when`s for L, k times.\ntheorem sallowed_rep (s : SMachine) (L : C) (hx : avoids s.extVars L = true) (hm : avoidsMaps s.carried L = true) :\n ∀ (qs : List SRequest) (ρ : Nat → Nat) (M : Nat → Nat → Nat), SPath s ρ M qs →\n (∀ j < qs.length, evalC (sEnd s ρ M (qs.take j)).1 (sEnd s ρ M (qs.take j)).2 L = true) →\n SAllowed s (List.replicate qs.length L) ρ M qs\n | [], _, _, _, _ => by simp [SAllowed]\n | q :: qs, ρ, M, hp, hL => by\n simp only [List.length_cons, List.replicate_succ, SAllowed]\n refine ⟨hp.1, ?_, sallowed_rep s L hx hm qs _ _ hp.2 (fun j hj => ?_)⟩\n · rw [view_eval hx hm]; exact hL 0 (by simp)\n · have := hL (j + 1) (by simp; omega)\n simpa [List.take_succ_cons, sEnd] using this\n\n-- A k-step goal Lean built from L: L after its steps.\ntheorem kind_then (s : SMachine) (kc : KInd) (ws : List C) (sl : SKStep) (h : SKStepHolds s (kc.with ws sl))\n (h3 : distinct (kc.prime.map (·.2)) = true) (h4 : distinct (kc.primeMaps.map (·.2)) = true)\n (h5 : avoids (kindVars s kc) kc.law = true) (h6 : avoidsMaps (kindMaps s kc) kc.law = true) (hav : kAvoids kc sl = true)\n {ρ : Nat → Nat} {M : Nat → Nat → Nat} (hr : SReach s ρ M) (q₁ : SRequest) (qs : List SRequest)\n (hlen : qs.length + 1 = ws.length) (hA : SAllowed s ws ρ M (q₁ :: qs)) :\n evalC (sEnd s ρ M (q₁ :: qs)).1 (sEnd s ρ M (q₁ :: qs)).2 kc.law = true := by\n have hh := h ρ M hr q₁ qs hlen hA\n simp only [KInd.with, KInd.then_] at hh\n obtain ⟨_, _, hv, hmv⟩ := law_reads h5 h6\n simp only [kAvoids, Bool.and_eq_true] at hav\n rw [primeC_eval kc.prime kc.primeMaps h3 h4 _ _ _ _ kc.law (fun i hi => ?_) (fun mp hmp => ?_)] at hh\n · exact hh\n · obtain ⟨hpt, hx, hor⟩ := hv i hi\n refine ⟨hpt, hor.imp id (fun hn => ?_)⟩\n rw [sEnd_other s hx hn.1 hn.2, renEnv_other _ _ _ i (avoids_occ hav.1 hi)]\n simp only [withExt]; rw [if_neg (by simpa [List.contains_iff_mem] using hx)]\n · obtain ⟨hpt, hc, hor⟩ := hmv mp hmp\n refine ⟨hpt, hor.imp id (fun hn => ?_)⟩\n rw [sEnd_maps_other s hc hn.1 hn.2, renMaps_other _ _ _ mp (avoidsMaps_occ hav.2 hmp)]\n simp only [withCarried]; rw [if_neg (by simpa [List.contains_iff_mem] using hc)]\n\n/-! k-induction -/\n\n/-- k-induction: if the laws' proof checks and a k-induction certificate for L does (its start goal, the k-step goals\nof its base from the start for each depth 1 ≤ j < k, and its step over k steps, every `when` and `then` built by Lean\nfrom L), then L holds in every reachable state. -/\ntheorem kind_sound (s : SMachine) (ps : List SEntry) (kc : KInd) (hl : checkSMachine s ps = true) (hk : checkKInd s ps kc = true) :\n ∀ ρ M, SReach s ρ M → evalC ρ M kc.law = true := by\n obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11⟩ := kind_parts hk\n obtain ⟨hx, hm, _, _⟩ := law_reads h5 h6\n intro ρ M hr\n obtain ⟨ρ0, M0, hM0, hp0, hf0, hpf0, qs, hpath, hend⟩ := sreach_from s hr\n have hrs : SReach s (applyS s.f.m.init ρ0 M0) M0 := SReach.start ρ0 M0 hM0 hp0 hf0 hpf0\n suffices hall : ∀ n, ∀ qs : List SRequest, qs.length = n → SPath s (applyS s.f.m.init ρ0 M0) M0 qs →\n evalC (sEnd s (applyS s.f.m.init ρ0 M0) M0 qs).1 (sEnd s (applyS s.f.m.init ρ0 M0) M0 qs).2 kc.law = true by\n have := hall qs.length qs rfl hpath\n rw [hend] at this; exact this\n intro n\n induction n using Nat.strongRecOn with\n | ind n ih =>\n intro qs hn hp\n -- L at every shorter run's end, and so at each state along this one.\n have ihp : ∀ j < n, evalC (sEnd s (applyS s.f.m.init ρ0 M0) M0 (qs.take j)).1 (sEnd s (applyS s.f.m.init ρ0 M0) M0 (qs.take j)).2 kc.law = true :=\n fun j hj => ih j hj _ (by rw [List.length_take]; omega) (spath_take hp j)\n by_cases h0 : n = 0\n · -- The start.\n subst h0\n rw [List.length_eq_zero_iff.mp hn]\n exact kind_start s ps kc hl h8 ρ0 M0 hM0 hp0 hf0 hpf0\n by_cases hlt : n < kc.k\n · -- A base: the run from the start, of depth n.\n obtain ⟨q₁, rest, rfl⟩ : ∃ q₁ rest, qs = q₁ :: rest := by\n cases qs with\n | nil => simp at hn; omega\n | cons q rest => exact ⟨q, rest, rfl⟩\n have hi : n - 1 < kc.base.length := by omega\n obtain ⟨hav, hc⟩ := checkBase_get kc.base 1 h9 (n - 1) hi\n rw [show 1 + (n - 1) = n by omega] at hc\n have hs := skstep_sound s ps _ hl hc\n simp only [List.length_cons] at hn\n refine kind_then s kc _ _ hs h3 h4 h5 h6 hav hrs q₁ rest (by simp [baseWhens]; omega) ?_\n simp only [baseWhens, SAllowed]\n refine ⟨hp.1, ?_, ?_⟩\n · simp only [evalC, Bool.and_eq_true]\n refine ⟨start_meets s h7 ρ0 M0 _ _, ?_⟩\n rw [view_eval hx hm]; exact ihp 0 (by omega)\n · rw [show n - 1 = rest.length by omega]\n exact sallowed_rep s kc.law hx hm rest _ _ hp.2 (fun j hj => by\n have := ihp (j + 1) (by omega)\n simpa [List.take_succ_cons, sEnd] using this)\n · -- The step: the state k requests back, and L at each state after it.\n have hkn : kc.k ≤ n := by omega\n let pre := qs.take (n - kc.k)\n let post := qs.drop (n - kc.k)\n have hsplit : pre ++ post = qs := List.take_append_drop _ _\n have hpost : post.length = kc.k := by simp only [post, List.length_drop]; omega\n have hp' := hp\n rw [← hsplit, spath_append] at hp'\n have hr' := sreach_path s pre hrs hp'.1\n obtain ⟨q₁, rest, hqr⟩ : ∃ q₁ rest, post = q₁ :: rest := by\n cases h : post with\n | nil => rw [h] at hpost; simp at hpost; omega\n | cons q rest => exact ⟨q, rest, rfl⟩\n have hs := skstep_sound s ps _ hl h11\n have hA : SAllowed s (List.replicate kc.k kc.law) (sEnd s (applyS s.f.m.init ρ0 M0) M0 pre).1 (sEnd s (applyS s.f.m.init ρ0 M0) M0 pre).2 post := by\n rw [← hpost]\n refine sallowed_rep s kc.law hx hm post _ _ hp'.2 (fun j hj => ?_)\n rw [← sEnd_append]\n have hpre : pre.length = n - kc.k := by simp only [pre, List.length_take]; omega\n have := ih (n - kc.k + j) (by omega) (pre ++ post.take j) (by simp [hpre, List.length_take]; omega)\n ((spath_append s _ _ _ _).mpr ⟨hp'.1, spath_take hp'.2 j⟩)\n exact this\n rw [hqr] at hA\n have := kind_then s kc _ _ hs h3 h4 h5 h6 h10 hr' q₁ rest (by rw [List.length_replicate, ← hpost, hqr]; simp) hA\n rw [← hqr, ← sEnd_append, hsplit] at this\n exact this\n\nend Kern\n\n#print axioms Kern.kind_sound\n",
21
- "Count.lean": "import Kernel\n\n/-!\nCount: quorum facts as a certificate kind, proven sound. Lean 4.34.0, core only; on top of `Kernel.lean` alone.\n\n**The lemma.** Finite sums over the keys below a bound (`sumBelow f n` = f 0 + … + f (n − 1)) are monotone and linear,\nso a pointwise inequality sums: if g sums below f over the keys below n, some key below n has g below f there\n(`exists_lt_of_sumBelow_lt`). Its corollaries are the quorum facts, for sets of keys below n (`card`):\n- `pigeonhole`: A, B ⊆ S and |A| + |B| > |S| give a key in A ∩ B;\n- `majorities_meet`: two majorities of S (2|A| > |S|, 2|B| > |S|) meet;\n- `quorums_meet_outside`: A, B ⊆ S and |A| + |B| > |S| + |F| give a key in A ∩ B outside F (thresholds: two sets of\n f + 1 out of 2f + 1, or two sets of n − t when n > 3t, meet in a process outside the t faulty ones).\n\n**The certificate kind** (kernel.ts's `checkCounted`, its twin). A counted goal is a goal (hypotheses over naturals and\nmaps, as `Kernel.lean`'s) and counts: each a variable `v` that names Σ_{k < below} body(k), the body read with its key\nvariable `key` at k (a 0/1 body is a set's size). A certificate is a list of instances and a tree. An instance names a\nfresh witness variable `wit`, a bound `below` every count it reads shares, integer coefficients on counts (`terms`) and\non the constant 1 (`unit`). With P the positive parts and N the negative parts (posP z = max z 0, negP z = max (−z) 0):\n\n countHyp = ( P·counts + P(unit)·below ≤ N·counts + N(unit)·below )\n ∨ ( wit < below ∧ N·bodies(wit) + N(unit) < P·bodies(wit) + P(unit) )\n\nwhich is the lemma read at one key: either the combination's sum is not positive, or `wit` is a key below the bound\nwhere its pointwise value is. Lean builds the instances' hypotheses itself (`countHyps`), checks each witness is fresh\n(`countedOk`) and checks the tree against the goal's hypotheses followed by them (`checkGoal`). `counted_sound`: an\naccepted counted goal's hypotheses hold at no naturals and maps where every count is its sum.\n\nWhy this shape is the smallest that covers the class: the whole of a Venn-region (BAPA) certificate is a linear\ncombination of set sizes whose pointwise value is never positive, so one instance (its Farkas coefficients on the\ncounts) plus a refutation at the witness key replaces the region variables: the case split on which sets hold the\nwitness is the tree's, over the cells it reads, as the kernel already splits. Majorities (+1, +1 on two counts, −1 on\nthe set's), f + 1 of 2f + 1 (the same) and more than 2/3 with faulty processes (+1, +1, −1 on S, −1 on F) are each one\ninstance; a count of a compound body (A ∩ B, say) gives the numeric forms (|A ∩ B| ≥ |A| + |B| − |S|).\n-/\n\nnamespace Kern\n\n/-! Finite sums below a bound -/\n\ndef sumBelow (f : Nat → Nat) : Nat → Nat\n | 0 => 0\n | n + 1 => sumBelow f n + f n\n\ntheorem sumBelow_mono {f g : Nat → Nat} (n : Nat) (h : ∀ k, k < n → f k ≤ g k) : sumBelow f n ≤ sumBelow g n := by\n induction n with\n | zero => simp [sumBelow]\n | succ n ih =>\n simp only [sumBelow]\n have h1 := ih (fun k hk => h k (by omega))\n have h2 := h n (by omega)\n omega\n\ntheorem sumBelow_add (f g : Nat → Nat) (n : Nat) : sumBelow (fun k => f k + g k) n = sumBelow f n + sumBelow g n := by\n induction n with\n | zero => simp [sumBelow]\n | succ n ih => simp only [sumBelow, ih]; omega\n\ntheorem sumBelow_mul (c : Nat) (f : Nat → Nat) (n : Nat) : sumBelow (fun k => c * f k) n = c * sumBelow f n := by\n induction n with\n | zero => simp [sumBelow]\n | succ n ih => simp only [sumBelow, ih, Nat.mul_add]\n\ntheorem sumBelow_const (d n : Nat) : sumBelow (fun _ => d) n = d * n := by\n induction n with\n | zero => simp [sumBelow]\n | succ n ih => simp only [sumBelow, ih, Nat.mul_add, Nat.mul_one]\n\ntheorem sumBelow_congr {f g : Nat → Nat} (n : Nat) (h : ∀ k, k < n → f k = g k) : sumBelow f n = sumBelow g n := by\n induction n with\n | zero => rfl\n | succ n ih => simp only [sumBelow, ih (fun k hk => h k (by omega)), h n (by omega)]\n\n/-- A pointwise inequality, summed: if g sums below f over the keys below n, some key below n has g below f. -/\ntheorem exists_lt_of_sumBelow_lt {f g : Nat → Nat} {n : Nat} (h : sumBelow g n < sumBelow f n) : ∃ k, k < n ∧ g k < f k := by\n apply Classical.byContradiction\n intro hno\n have hle : ∀ k, k < n → f k ≤ g k := fun k hk => Nat.le_of_not_lt (fun hlt => hno ⟨k, hk, hlt⟩)\n have := sumBelow_mono n hle\n omega\n\n/-! Sets of keys below a bound, and the quorum facts -/\n\n-- The number of keys below n where p holds.\ndef card (p : Nat → Bool) (n : Nat) : Nat := sumBelow (fun k => if p k then 1 else 0) n\n\n/-- The pigeonhole: two subsets of S whose sizes add up to more than S's meet. -/\ntheorem pigeonhole {a b s : Nat → Bool} {n : Nat} (ha : ∀ k, k < n → a k = true → s k = true)\n (hb : ∀ k, k < n → b k = true → s k = true) (h : card s n < card a n + card b n) :\n ∃ k, k < n ∧ a k = true ∧ b k = true := by\n unfold card at h\n rw [← sumBelow_add] at h\n obtain ⟨k, hk, hlt⟩ := exists_lt_of_sumBelow_lt h\n have h1 := ha k hk\n have h2 := hb k hk\n refine ⟨k, hk, ?_⟩\n cases hak : a k <;> cases hbk : b k <;> cases hsk : s k <;> simp_all\n\n/-- Two majorities of S meet. -/\ntheorem majorities_meet {a b s : Nat → Bool} {n : Nat} (ha : ∀ k, k < n → a k = true → s k = true)\n (hb : ∀ k, k < n → b k = true → s k = true) (h1 : card s n < 2 * card a n) (h2 : card s n < 2 * card b n) :\n ∃ k, k < n ∧ a k = true ∧ b k = true :=\n pigeonhole ha hb (by omega)\n\n/-- Thresholds: two subsets of S whose sizes add up to more than |S| + |F| meet outside F (f + 1 of 2f + 1 with F\nempty; n − t of n with n > 3t and at most t faulty). -/\ntheorem quorums_meet_outside {a b s f : Nat → Bool} {n : Nat} (ha : ∀ k, k < n → a k = true → s k = true)\n (hb : ∀ k, k < n → b k = true → s k = true) (h : card s n + card f n < card a n + card b n) :\n ∃ k, k < n ∧ a k = true ∧ b k = true ∧ f k = false := by\n unfold card at h\n rw [← sumBelow_add, ← sumBelow_add] at h\n obtain ⟨k, hk, hlt⟩ := exists_lt_of_sumBelow_lt h\n have h1 := ha k hk\n have h2 := hb k hk\n refine ⟨k, hk, ?_⟩\n cases hak : a k <;> cases hbk : b k <;> cases hsk : s k <;> cases hfk : f k <;> simp_all\n\n/-! The certificate kind: counts in a goal -/\n\n-- A count: the variable v names the sum of `body` over the keys below `below`, `body` read with `key` at each key.\nstructure Count where\n v : Nat\n key : Nat\n below : E\n body : E\n\n-- What a count means at an environment.\ndef Count.Holds (c : Count) (ρ : Nat → Nat) (M : Nat → Nat → Nat) : Prop :=\n ρ c.v = sumBelow (fun k => evalE (upd ρ c.key k) M c.body) (evalE ρ M c.below)\n\n-- An instance of the lemma: a fresh witness, the bound its counts share, a coefficient per count (named by its\n-- variable) and one on the constant 1.\nstructure CInst where\n wit : Nat\n below : E\n terms : List (Int × Nat)\n unit : Int\n\n-- A counted goal: its hypotheses, and the counts they read.\nstructure CGoal where\n hyps : List C\n counts : List Count\n\ndef findCount (cs : List Count) (v : Nat) : Option Count := lookup (fun c => c.v == v) cs\n\n-- Each term's count (the first with its variable), when every term names one whose bound is the instance's.\ndef resolve (cs : List Count) (B : E) : List (Int × Nat) → Option (List (Int × Count))\n | [] => some []\n | t :: ts => match findCount cs t.2 with\n | none => none\n | some c => if beqE c.below B then (resolve cs B ts).map (fun rs => (t.1, c) :: rs) else none\n\n-- A sum of terms, right-nested from 0.\ndef sumE : List E → E\n | [] => .const 0\n | e :: es => .add e (sumE es)\n\ndef posP (z : Int) : Nat := z.toNat\ndef negP (z : Int) : Nat := (-z).toNat\n\n-- One side of an instance: each count read by `rd` times its coefficient's part, then the unit's part times `one`.\ndef side (part : Int → Nat) (rd : Count → E) (one : E) (u : Int) (rs : List (Int × Count)) : E :=\n .add (sumE (rs.map fun r => .mul (part r.1) (rd r.2))) (.mul (part u) one)\n\n-- A count read as its variable, and its body read at the witness.\ndef atCount (c : Count) : E := .var c.v\ndef atWit (w : Nat) (c : Count) : E := substE [(c.key, .var w)] c.body\n\n-- The instance's hypothesis: the combination's sum is not positive, or the witness is a key below the bound where the\n-- combination's value is.\ndef countHyp (cs : List Count) (i : CInst) : Option C :=\n (resolve cs i.below i.terms).map fun rs =>\n .or (.le (side posP atCount i.below i.unit rs) (side negP atCount i.below i.unit rs))\n (.and (.lt (.var i.wit) i.below)\n (.lt (side negP (atWit i.wit) (.const 1) i.unit rs) (side posP (atWit i.wit) (.const 1) i.unit rs)))\n\ndef countHyps (cs : List Count) : List CInst → Option (List C)\n | [] => some []\n | i :: is => match countHyp cs i with\n | none => none\n | some h => (countHyps cs is).map (h :: ·)\n\ndef cDistinct : List Nat → Bool\n | [] => true\n | a :: as => !as.contains a && cDistinct as\n\n-- A witness is fresh: no hypothesis reads it, no count names it or reads it (in its bound or its body), and no\n-- instance's bound reads it.\ndef witFresh (hyps : List C) (cs : List Count) (is : List CInst) (w : Nat) : Bool :=\n hyps.all (fun h => !occC w h) && cs.all (fun c => c.v != w && !occE w c.below && !occE w c.body) && is.all (fun j => !occE w j.below)\n\ndef countedOk (hyps : List C) (cs : List Count) (is : List CInst) : Bool :=\n cDistinct (is.map (·.wit)) && is.all (fun i => witFresh hyps cs is i.wit)\n\n/-! Conditional lemma cuts. A lemma shares the containing goal's table and may select only its hypotheses.\nIts proof is an old-language tree, checked without any lemma assumptions. This rules out circular citations. -/\n\nsection LemmaCuts\nset_option autoImplicit false\n\nstructure CutLemma where\n when : List Cert.Row\n cut : Cert.Row\n tree : Tree\n slice : Option (List Nat) := none\n\ndef lemmaSlice (hyps : List C) : List Nat → Option (List C)\n | [] => some []\n | i :: is => match hyps[i]?, lemmaSlice hyps is with\n | some h, some hs => some (h :: hs)\n | _, _ => none\n\ndef lemmaHyps (hyps : List C) (l : CutLemma) : Option (List C) :=\n match l.slice with\n | none => some hyps\n | some is => lemmaSlice hyps is\n\ndef checkLemma (tab : List VDef) (hyps : List C) (l : CutLemma) : Bool :=\n match lemmaHyps hyps l with\n | some hs => checkT tab hs ((l.cut, false) :: l.when.map (fun w => (w, true))) l.tree\n | none => false\n\n-- Eligibility reads only the original split path, never the cuts being made available.\ndef lemmaActive (path : Path) (l : CutLemma) : Bool :=\n l.when.all (fun w => dec path w == some true)\n\ndef lemmaPath (lemmas : List CutLemma) (path : Path) : Path :=\n (lemmas.filter (lemmaActive path)).map (fun l => (l.cut, true)) ++ path\n\ndef checkTLemmas (tab : List VDef) (hyps : List C) (lemmas : List CutLemma) : Path → Tree → Bool\n | path, .split l y n => checkTLemmas tab hyps lemmas ((l, true) :: path) y && checkTLemmas tab hyps lemmas ((l, false) :: path) n\n | path, t => checkT tab hyps (lemmaPath lemmas path) t\n\ndef checkGoalLemmas (g : Goal) (t : Tree) (lemmas : List CutLemma) : Bool :=\n wfTab 0 g.tab && lemmas.all (checkLemma g.tab g.hyps) && checkTLemmas g.tab g.hyps lemmas [] t\n\n@[simp] theorem lemmaPath_nil (path : Path) : lemmaPath [] path = path := rfl\n\n@[simp] theorem checkTLemmas_nil (tab : List VDef) (hyps : List C) (t : Tree) (path : Path) :\n checkTLemmas tab hyps [] path t = checkT tab hyps path t := by\n induction t generalizing path with\n | split l y n ihy ihn => simp only [checkTLemmas, checkT, ihy, ihn]\n | leaf rows steps eqs prods => rfl\n | leafAt rows steps eqs prods => rfl\n | leafSq rows sqs steps eqs prods => rfl\n\n@[simp] theorem checkGoalLemmas_nil (g : Goal) (t : Tree) : checkGoalLemmas g t [] = checkGoal g t := by\n simp [checkGoalLemmas, checkGoal]\n\ntheorem lemmaSlice_sub {hyps : List C} : ∀ {is : List Nat} {hs : List C},\n lemmaSlice hyps is = some hs → ∀ h ∈ hs, h ∈ hyps\n | [], hs, he => by simp only [lemmaSlice, Option.some.injEq] at he; subst he; simp\n | i :: is, hs, he => by\n cases hi : hyps[i]? with\n | none => simp [lemmaSlice, hi] at he\n | some c =>\n cases ht : lemmaSlice hyps is with\n | none => simp [lemmaSlice, hi, ht] at he\n | some cs =>\n simp only [lemmaSlice, hi, ht, Option.some.injEq] at he\n subst he\n intro h hh\n rcases List.mem_cons.mp hh with rfl | hh\n · exact List.mem_of_getElem? hi\n · exact lemmaSlice_sub ht h hh\n\ntheorem lemmaHyps_sub {hyps hs : List C} {l : CutLemma} (he : lemmaHyps hyps l = some hs) :\n ∀ h ∈ hs, h ∈ hyps := by\n cases sl : l.slice with\n | none => simp only [lemmaHyps, sl, Option.some.injEq] at he; subst he; exact fun _ hh => hh\n | some is => exact lemmaSlice_sub (by simpa only [lemmaHyps, sl] using he)\n\ndef CutHolds (l : CutLemma) (x : List Int) : Prop :=\n (∀ w ∈ l.when, Cert.eval w x ≤ 0) → Cert.eval l.cut x ≤ 0\n\n/-- A checked lemma proves its cut under exactly its declared linear conditions. -/\ntheorem lemma_sound {tab : List VDef} {hyps : List C} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int}\n (hM : Model tab env maps x) (hH : ∀ c ∈ hyps, evalC env maps c = true)\n {l : CutLemma} (hck : checkLemma tab hyps l = true) : CutHolds l x := by\n intro hw\n apply Int.not_lt.mp\n intro hc\n cases hs : lemmaHyps hyps l with\n | none => simp [checkLemma, hs] at hck\n | some cs =>\n simp only [checkLemma, hs] at hck\n have hp : PathHolds ((l.cut, false) :: l.when.map (fun w => (w, true))) x := by\n intro a ha\n rcases List.mem_cons.mp ha with rfl | ha\n · have hn : ¬ Cert.eval l.cut x ≤ 0 := by omega\n simpa using hn\n · obtain ⟨w, hwm, rfl⟩ := List.mem_map.mp ha\n simpa using hw w hwm\n exact checkT_sound hM (fun c hc => hH c (lemmaHyps_sub hs c hc)) l.tree _ hp hck\n\ntheorem lemmaPath_holds {lemmas : List CutLemma} {path : Path} {x : List Int}\n (hP : PathHolds path x) (hL : ∀ l ∈ lemmas, CutHolds l x) : PathHolds (lemmaPath lemmas path) x := by\n intro a ha\n rcases List.mem_append.mp ha with ha | ha\n · obtain ⟨l, hl, rfl⟩ := List.mem_map.mp ha\n obtain ⟨hlm, hactive⟩ := List.mem_filter.mp hl\n have hc : Cert.eval l.cut x ≤ 0 := hL l hlm (fun w hw => by\n have hd : dec path w = some true := by\n simpa only [lemmaActive, List.all_eq_true, beq_iff_eq] using (List.all_eq_true.mp hactive w hw)\n have := dec_sound hP hd\n simpa using this)\n simpa using hc\n · exact hP a ha\n\ntheorem checkTLemmas_sound {tab : List VDef} {hyps : List C} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int}\n (hM : Model tab env maps x) (hH : ∀ c ∈ hyps, evalC env maps c = true)\n {lemmas : List CutLemma} (hL : ∀ l ∈ lemmas, CutHolds l x) :\n ∀ (t : Tree) (path : Path), PathHolds path x → checkTLemmas tab hyps lemmas path t = true → False\n | .split l y n, path, hP, h => by\n simp only [checkTLemmas, Bool.and_eq_true] at h\n by_cases hl : Cert.eval l x ≤ 0\n · refine checkTLemmas_sound hM hH hL y _ ?_ h.1\n intro a ha\n rcases List.mem_cons.mp ha with rfl | ha\n · simpa using hl\n · exact hP a ha\n · refine checkTLemmas_sound hM hH hL n _ ?_ h.2\n intro a ha\n rcases List.mem_cons.mp ha with rfl | ha\n · simpa using hl\n · exact hP a ha\n | .leaf rows steps eqs prods, path, hP, h =>\n checkT_sound hM hH _ _ (lemmaPath_holds hP hL) h\n | .leafAt rows steps eqs prods, path, hP, h =>\n checkT_sound hM hH _ _ (lemmaPath_holds hP hL) h\n | .leafSq rows sqs steps eqs prods, path, hP, h =>\n checkT_sound hM hH _ _ (lemmaPath_holds hP hL) h\n\n/-- The extended goal checker has the original unsatisfiability conclusion. -/\ntheorem goalLemmas_sound (g : Goal) (t : Tree) (lemmas : List CutLemma)\n (h : checkGoalLemmas g t lemmas = true) (env : Nat → Nat) (maps : Nat → Nat → Nat) :\n ¬ ∀ c ∈ g.hyps, evalC env maps c = true := by\n intro hH\n simp only [checkGoalLemmas, Bool.and_eq_true, List.all_eq_true] at h\n obtain ⟨⟨hw, hl⟩, ht⟩ := h\n have hv := build_valid env maps g.tab [] [] ⟨rfl, by simp, by simp⟩ (by simpa using hw)\n simp only [List.nil_append] at hv\n have hM := model_of_valid hv\n exact checkTLemmas_sound hM hH (fun l hm => lemma_sound hM hH (hl l hm)) t [] (by simp [PathHolds]) ht\n\nend LemmaCuts\n\n-- The check: fresh witnesses, every instance built, then the same goal extended by checked conditional cuts.\ndef checkCounted (g : CGoal) (is : List CInst) (tab : List VDef) (t : Tree) (lemmas : List CutLemma := []) : Bool :=\n countedOk g.hyps g.counts is && match countHyps g.counts is with\n | some hs => checkGoalLemmas ⟨tab, g.hyps ++ hs⟩ t lemmas\n | none => false\n\n/-- With no lemma entries the old counted check is unchanged. -/\ntheorem checkCounted_nil (g : CGoal) (is : List CInst) (tab : List VDef) (t : Tree) :\n checkCounted g is tab t [] = (countedOk g.hyps g.counts is && match countHyps g.counts is with\n | some hs => checkGoal ⟨tab, g.hyps ++ hs⟩ t\n | none => false) := by\n simp only [checkCounted, checkGoalLemmas_nil]\n\n/-! Soundness -/\n\ntheorem cDistinct_cons {a : Nat} {as : List Nat} (h : cDistinct (a :: as) = true) : a ∉ as ∧ cDistinct as = true := by\n simp only [cDistinct, Bool.and_eq_true] at h\n refine ⟨fun hm => ?_, h.2⟩\n have h1 := h.1\n simp at h1\n exact h1 hm\n\ntheorem applyS_one (k : Nat) (t : E) (ρ : Nat → Nat) (M : Nat → Nat → Nat) : applyS [(k, t)] ρ M = upd ρ k (evalE ρ M t) := by\n funext i\n simp only [applyS, assoc, lookup, upd]\n by_cases h : i = k\n · subst h; simp\n · have hb : (k == i) = false := by simp; omega\n simp [hb, h]\n\ntheorem resolve_mem {cs : List Count} {B : E} : ∀ {ts : List (Int × Nat)} {rs : List (Int × Count)},\n resolve cs B ts = some rs → ∀ r ∈ rs, r.2 ∈ cs ∧ r.2.below = B\n | [], rs, h => by simp only [resolve, Option.some.injEq] at h; subst h; simp\n | t :: ts, rs, h => by\n cases hc : findCount cs t.2 with\n | none => simp [resolve, hc] at h\n | some c =>\n by_cases hb : beqE c.below B = true\n · cases hr : resolve cs B ts with\n | none => simp [resolve, hc, hb, hr] at h\n | some rs' =>\n simp [resolve, hc, hb, hr] at h\n subst h\n intro r hr'\n rcases List.mem_cons.mp hr' with rfl | hr'\n · exact ⟨(lookup_some hc).1, beqE_eq hb⟩\n · exact resolve_mem hr r hr'\n · simp [resolve, hc, hb] at h\n\ntheorem countHyps_mem {cs : List Count} : ∀ {is : List CInst} {hs : List C}, countHyps cs is = some hs → ∀ h ∈ hs, ∃ i ∈ is, countHyp cs i = some h\n | [], hs, hh => by simp only [countHyps, Option.some.injEq] at hh; subst hh; simp\n | i :: is, hs, hh => by\n cases e1 : countHyp cs i with\n | none => simp [countHyps, e1] at hh\n | some h1 =>\n cases e2 : countHyps cs is with\n | none => simp [countHyps, e1, e2] at hh\n | some hs' =>\n simp [countHyps, e1, e2] at hh\n subst hh\n intro h hm\n rcases List.mem_cons.mp hm with rfl | hm\n · exact ⟨i, List.mem_cons_self, e1⟩\n · obtain ⟨j, hj, hj'⟩ := countHyps_mem e2 h hm\n exact ⟨j, List.mem_cons_of_mem _ hj, hj'⟩\n\n-- The two sides, evaluated: the counts' combination, and the bodies' at a key.\ndef sumSide (part : Int → Nat) (ρ : Nat → Nat) : List (Int × Count) → Nat\n | [] => 0\n | r :: rs => part r.1 * ρ r.2.v + sumSide part ρ rs\ndef ptSide (part : Int → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat) : List (Int × Count) → Nat → Nat\n | [], _ => 0\n | r :: rs, k => part r.1 * evalE (upd ρ r.2.key k) M r.2.body + ptSide part ρ M rs k\n\ntheorem eval_sumE_count (part : Int → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat) : ∀ rs : List (Int × Count),\n evalE ρ M (sumE (rs.map fun r => .mul (part r.1) (atCount r.2))) = sumSide part ρ rs\n | [] => by simp [sumE, evalE, sumSide]\n | r :: rs => by\n simp only [List.map_cons, sumE, evalE, eval_sumE_count part ρ M rs]\n simp [atCount, evalE, sumSide]\n\ntheorem eval_sumE_wit (part : Int → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (w : Nat) : ∀ rs : List (Int × Count),\n evalE ρ M (sumE (rs.map fun r => .mul (part r.1) (atWit w r.2))) = ptSide part ρ M rs (ρ w)\n | [] => by simp [sumE, evalE, ptSide]\n | r :: rs => by\n simp only [List.map_cons, sumE, evalE, eval_sumE_wit part ρ M w rs]\n simp only [ptSide, atWit, subst_evalE, applyS_one, evalE]\n\n-- With every count its sum below one bound, the counts' combination sums the bodies' over the keys below it.\ntheorem sumSide_eq (part : Int → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (n : Nat) : ∀ rs : List (Int × Count),\n (∀ r ∈ rs, ρ r.2.v = sumBelow (fun k => evalE (upd ρ r.2.key k) M r.2.body) n) →\n sumSide part ρ rs = sumBelow (ptSide part ρ M rs) n\n | [], _ => by\n have : ptSide part ρ M [] = fun _ => 0 := funext fun k => by simp [ptSide]\n simp [sumSide, this, sumBelow_const]\n | r :: rs, h => by\n simp only [sumSide]\n have hp : ptSide part ρ M (r :: rs) = fun k => part r.1 * evalE (upd ρ r.2.key k) M r.2.body + ptSide part ρ M rs k := rfl\n rw [hp, sumBelow_add, sumBelow_mul, ← h r List.mem_cons_self, sumSide_eq part ρ M n rs (fun r' hr' => h r' (List.mem_cons_of_mem _ hr'))]\n\n-- The witness values a state gives the instances' witnesses.\ndef setWits (ρ : Nat → Nat) (ws : List (Nat × Nat)) : Nat → Nat := fun j =>\n match lookup (fun p => p.1 == j) ws with\n | some p => p.2\n | none => ρ j\n\ntheorem setWits_other {ρ : Nat → Nat} {ws : List (Nat × Nat)} {j : Nat} (h : j ∉ ws.map (·.1)) : setWits ρ ws j = ρ j := by\n have hl : lookup (fun p => p.1 == j) ws = none :=\n lookup_none (fun p hp => by simp only [beq_eq_false_iff_ne]; intro he; exact h (by rw [← he]; exact List.mem_map_of_mem hp))\n simp [setWits, hl]\n\ntheorem setWits_at {ρ : Nat → Nat} : ∀ {ws : List (Nat × Nat)}, cDistinct (ws.map (·.1)) = true → ∀ {p : Nat × Nat}, p ∈ ws → setWits ρ ws p.1 = p.2\n | [], _, _, hp => by simp at hp\n | a :: as, hd, p, hp => by\n simp only [List.map_cons] at hd\n obtain ⟨hna, hd'⟩ := cDistinct_cons hd\n rcases List.mem_cons.mp hp with rfl | hp'\n · simp [setWits, lookup]\n · have hne : (a.1 == p.1) = false := by\n simp only [beq_eq_false_iff_ne]; intro he; exact hna (by rw [he]; exact List.mem_map_of_mem hp')\n have ih := setWits_at (ρ := ρ) hd' hp'\n simp only [setWits, lookup, hne, Bool.false_eq_true, ite_false] at ih ⊢\n exact ih\n\ntheorem witFresh_parts {hyps : List C} {cs : List Count} {is : List CInst} {w : Nat} (h : witFresh hyps cs is w = true) :\n (∀ h' ∈ hyps, occC w h' = false) ∧ (∀ c ∈ cs, c.v ≠ w ∧ occE w c.below = false ∧ occE w c.body = false) ∧ (∀ j ∈ is, occE w j.below = false) := by\n simp only [witFresh, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at h\n exact ⟨h.1.1, fun c hc => ⟨(h.1.2 c hc).1.1, (h.1.2 c hc).1.2, (h.1.2 c hc).2⟩, h.2⟩\n\n/-- The kind is sound: an accepted counted goal's hypotheses hold at no naturals and maps where every count is its\nsum. -/\ntheorem counted_sound (g : CGoal) (is : List CInst) (tab : List VDef) (t : Tree) {lemmas : List CutLemma}\n (hck : checkCounted g is tab t lemmas = true)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hc : ∀ c ∈ g.counts, c.Holds ρ M) : ¬ ∀ h ∈ g.hyps, evalC ρ M h = true := by\n intro hH\n simp only [checkCounted, Bool.and_eq_true] at hck\n obtain ⟨hok, hgoal⟩ := hck\n simp only [countedOk, Bool.and_eq_true, List.all_eq_true] at hok\n obtain ⟨hdist, hfresh⟩ := hok\n cases hhs : countHyps g.counts is with\n | none => simp [hhs] at hgoal\n | some hs =>\n simp only [hhs] at hgoal\n -- Each instance's witness value, chosen at ρ: a key below the bound where the combination is positive, when its sum is.\n have hx : ∀ i : CInst, ∃ x : Nat, ∀ rs, resolve g.counts i.below i.terms = some rs →\n sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below) ≤ sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below)\n ∨ (x < evalE ρ M i.below ∧ ptSide negP ρ M rs x + negP i.unit < ptSide posP ρ M rs x + posP i.unit) := by\n intro i\n cases hr : resolve g.counts i.below i.terms with\n | none => exact ⟨0, fun rs h => by simp at h⟩\n | some rs =>\n by_cases hlt : sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below) < sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below)\n · obtain ⟨k, hk, hk'⟩ := exists_lt_of_sumBelow_lt hlt\n exact ⟨k, fun rs' h => by simp only [Option.some.injEq] at h; subst h; exact Or.inr ⟨hk, hk'⟩⟩\n · exact ⟨0, fun rs' h => by simp only [Option.some.injEq] at h; subst h; exact Or.inl (Nat.le_of_not_lt hlt)⟩\n obtain ⟨xs, hxs⟩ : ∃ xs : CInst → Nat, ∀ i rs, resolve g.counts i.below i.terms = some rs →\n sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below) ≤ sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below)\n ∨ (xs i < evalE ρ M i.below ∧ ptSide negP ρ M rs (xs i) + negP i.unit < ptSide posP ρ M rs (xs i) + posP i.unit) :=\n ⟨fun i => Classical.choose (hx i), fun i => Classical.choose_spec (hx i)⟩\n -- ρs: ρ with each witness set to its value.\n obtain ⟨ρs, hother, hat⟩ : ∃ ρs : Nat → Nat, (∀ j, (∀ i ∈ is, i.wit ≠ j) → ρs j = ρ j) ∧ (∀ i ∈ is, ρs i.wit = xs i) := by\n have hws : (is.map fun i => (i.wit, xs i)).map (·.1) = is.map (·.wit) := by induction is <;> simp_all\n refine ⟨setWits ρ (is.map fun i => (i.wit, xs i)), fun j hj => setWits_other ?_, fun i hi => ?_⟩\n · rw [hws]; intro hm; obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hm; exact hj i hi rfl\n · exact setWits_at (ρ := ρ) (ws := is.map fun i => (i.wit, xs i)) (by rw [hws]; exact hdist) (p := (i.wit, xs i)) (List.mem_map.mpr ⟨i, hi, rfl⟩)\n -- What the witnesses' freshness gives: counts and bounds read alike at ρs and ρ.\n have hvar : ∀ c ∈ g.counts, ρs c.v = ρ c.v := fun c hc =>\n hother c.v (fun i hi he => ((witFresh_parts (hfresh i hi)).2.1 c hc).1 he.symm)\n have hbound : ∀ e : E, (∀ i ∈ is, occE i.wit e = false) → evalE ρs M e = evalE ρ M e := fun e he =>\n congrE ρs ρ M e (fun j hj => hother j (fun i hi hij => by have := he i hi; rw [hij] at this; simp [this] at hj))\n have hbody : ∀ c ∈ g.counts, ∀ k, evalE (upd ρs c.key k) M c.body = evalE (upd ρ c.key k) M c.body := fun c hc k =>\n congrE _ _ M c.body (fun j hj => by\n simp only [upd]; split\n · rfl\n · exact hother j (fun i hi hij => by\n have := ((witFresh_parts (hfresh i hi)).2.1 c hc).2.2; rw [hij] at this; simp [this] at hj))\n have hpt : ∀ (part : Int → Nat) (rs : List (Int × Count)), (∀ r ∈ rs, r.2 ∈ g.counts) → ∀ k, ptSide part ρs M rs k = ptSide part ρ M rs k := by\n intro part rs hrs k\n induction rs with\n | nil => rfl\n | cons r rs ih =>\n simp only [ptSide, hbody r.2 (hrs r List.mem_cons_self) k, ih (fun r' hr' => hrs r' (List.mem_cons_of_mem _ hr'))]\n -- Every instance's hypothesis holds at ρs.\n have hinst : ∀ i ∈ is, ∀ h, countHyp g.counts i = some h → evalC ρs M h = true := by\n intro i hi h hh\n simp only [countHyp, Option.map_eq_some_iff] at hh\n obtain ⟨rs, hr, rfl⟩ := hh\n have hrm := resolve_mem hr\n have hB : evalE ρs M i.below = evalE ρ M i.below := hbound i.below (fun j hj => (witFresh_parts (hfresh j hj)).2.2 i hi)\n have hcnt : ∀ r ∈ rs, ρs r.2.v = sumBelow (fun k => evalE (upd ρs r.2.key k) M r.2.body) (evalE ρ M i.below) := by\n intro r hr'\n obtain ⟨hcm, hcb⟩ := hrm r hr'\n have h1 : ρ r.2.v = sumBelow (fun k => evalE (upd ρ r.2.key k) M r.2.body) (evalE ρ M r.2.below) := hc r.2 hcm\n rw [hvar r.2 hcm, h1, hcb]\n exact sumBelow_congr _ (fun k _ => (hbody r.2 hcm k).symm)\n have hS : ∀ part, evalE ρs M (side part atCount i.below i.unit rs)\n = sumBelow (fun k => ptSide part ρ M rs k + part i.unit) (evalE ρ M i.below) := by\n intro part\n have e1 : evalE ρs M (side part atCount i.below i.unit rs) = sumSide part ρs rs + part i.unit * evalE ρ M i.below := by\n simp only [side, evalE, eval_sumE_count, hB]\n have e2 : sumBelow (fun k => ptSide part ρ M rs k + part i.unit) (evalE ρ M i.below)\n = sumBelow (ptSide part ρ M rs) (evalE ρ M i.below) + part i.unit * evalE ρ M i.below := by\n rw [sumBelow_add (ptSide part ρ M rs) (fun _ => part i.unit), sumBelow_const]\n have e3 : sumSide part ρs rs = sumBelow (ptSide part ρ M rs) (evalE ρ M i.below) := by\n rw [sumSide_eq part ρs M _ rs hcnt]\n exact sumBelow_congr _ (fun k _ => hpt part rs (fun r hr' => (hrm r hr').1) k)\n rw [e1, e2, e3]\n have hW : ∀ part, evalE ρs M (side part (atWit i.wit) (.const 1) i.unit rs) = ptSide part ρ M rs (xs i) + part i.unit := by\n intro part\n simp only [side, evalE, eval_sumE_wit, hat i hi, hpt part rs (fun r hr' => (hrm r hr').1), Nat.mul_one]\n have hv := hxs i rs hr\n simp only [evalC, hS, hW, evalE, hat i hi, hB, Bool.or_eq_true, Bool.and_eq_true, decide_eq_true_eq]\n exact hv\n -- The goal's hypotheses hold at ρs too: no witness is read there.\n have hhyp : ∀ h ∈ g.hyps, evalC ρs M h = true := fun h hm => by\n rw [congrC ρs ρ M h (fun j hj => hother j (fun i hi hij => by\n have := (witFresh_parts (hfresh i hi)).1 h hm; rw [hij] at this; simp [this] at hj))]\n exact hH h hm\n exact goalLemmas_sound ⟨tab, g.hyps ++ hs⟩ t lemmas hgoal ρs M (fun h hm => by\n rcases List.mem_append.mp hm with hm | hm\n · exact hhyp h hm\n · obtain ⟨i, hi, hh⟩ := countHyps_mem hhs h hm\n exact hinst i hi h hh)\n\nend Kern\n\n#print axioms Kern.exists_lt_of_sumBelow_lt\n#print axioms Kern.pigeonhole\n#print axioms Kern.majorities_meet\n#print axioms Kern.quorums_meet_outside\n#print axioms Kern.lemma_sound\n#print axioms Kern.goalLemmas_sound\n#print axioms Kern.counted_sound\n",
22
- "CountMachine.lean": "import Sets\nimport Count\n\n/-!\nCountMachine: counts in a machine's laws and steps, proven sound. Lean 4.34.0, core only; on top of `Sets.lean` (the\nmachines with sets) and `Count.lean` (the counted goal and `counted_sound`), neither changed.\n\n**What a machine may count.** A count declaration (`CDecl`) names a map `mp` whose cell at x is the number Σ_{k < below}\nbody(k), with the declaration's parameters at x and its key variable `key` at k (a 0/1 body is a set's size: the\nvotes for x, the members of a request's set). One parameter: `j` at x. Two (`atJ`): `j` at x / base and `lo` at\nx % base, so a count over a pair (a, b), the nodes that voted b at round a, is read at a relation's composed key base·a\n+ b; a certificate's read of it at a key term written base·a + b gives Count.lean the count with j at a and lo at b,\nunder the hypothesis `base ≤ b ∨ the cell` (`countKeyParts`, `readHyp`), so a key past the base reads nothing. The map is one the request carries (`mp ∈ s.carried`), so the machine\nitself is an `SMachine` as it was: its runs (`CReach`) are `SReach`'s with each request's count maps at their counts,\nread at the request's view (its inputs set, over the state's maps and the maps it carries; a count reads no flag,\nquantified flag or witness, so the view's flags don't change it). A guard (the assumption)\nreads a count there: `2·|Q| > size` for a request's set Q. A law reads a count of the state: a declaration whose bound\nand body read no request (`stateOnly`: no input, quantified flag, witness, flag variable or carried map), whose value\nat a state is `withCnt` (each count map at its count there): `2·|{n < size: vote[n] = x + 1}| > size` for a decided x.\n\n**The goals** are `Sets.lean`'s, with the counts read twice in a step. Before the step a law and the guard read each\ncount map as the request carries it (its count at the view, which for a state-only count is its count at the state).\nAfter the step, the law is read with each count map renamed to its `post` name (`frameRd`), and the goal declares the\npost name a count too, its bound and body read across the step (`afterDecl`: substituted by the step, as the law is,\nwith `j` and `key` kept). The start goal reads the law at the start the same way. A goal is a `CGoalM`: hypotheses\nand the count maps it declares (`GHolds`: each map at its count, at every key).\n\n**The certificate** (`CCert`, checked by `checkMC`) names the goal's hypotheses it uses (each one Lean builds), the\ncells it reads (`reads`: a fresh variable for a count map's cell at a key term), and Count.lean's instances and tree.\n`checkMC` turns it into Count.lean's counted goal: the named hypotheses, each read variable equal to its cell, and a\ncount per read (its declaration with `j` at the key term), and checks it as Count.lean does, but with each instance's\nwitness fresh for the counts and the instances' bounds only (`checkCountedW`): a goal's hypotheses may read a witness\nin their instances of the laws, facts and quantified flags (the voters of Q at the key two majorities share), which\nhold at every value of a variable the machine never reads (`witsOk`). `mc_sound`: an accepted goal's hypotheses do not\nhold at every value of the witnesses, at naturals and maps where each declared map is its count.\n\n**Soundness.** `cmachine_sound`: every entry of an accepted proof holds in every reachable state, its laws reading\neach count map as the state's count (`withCnt`). The proof is `Sets.lean`'s `smachine_sound` with the counted goals in\nplace of `checkIn`: the goals are refuted where the count maps before the step are what the request carried (`CReach`),\nand the post names are the counts of the state after it.\n-/\n\nnamespace Kern\nopen Classical\n\n/-! Counts of a map, and the counted goals over them -/\n\n-- A count map: `mp` at x is Σ_{k < below} body(k), read with its parameters at x and key at k; `post` the name a step's\n-- goal reads it by after the step. Its parameters: j at x / base and lo at x % base, so a count over two parameters\n-- (a, b) is read at the key base·a + b with b < base (a relation's composed key); one parameter is lo = j and base = 0\n-- (j at x).\nstructure CDecl where\n mp : Nat\n post : Nat\n j : Nat\n key : Nat\n below : E\n body : E\n lo : Nat\n base : Nat\n\n-- The environment with the parameters at x.\ndef atJ (d : CDecl) (ρ : Nat → Nat) (x : Nat) : Nat → Nat := upd (upd ρ d.j (x / d.base)) d.lo (x % d.base)\n\n-- The count at x.\ndef cntOf (d : CDecl) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (x : Nat) : Nat :=\n sumBelow (fun k => evalE (upd (atJ d ρ x) d.key k) M d.body) (evalE (atJ d ρ x) M d.below)\n\n-- Each declared map is its count, at every key.\ndef GHolds (ds : List CDecl) (ρ : Nat → Nat) (M : Nat → Nat → Nat) : Prop := ∀ d ∈ ds, ∀ x, M d.mp x = cntOf d ρ M x\n\n-- A certificate for a counted goal: the goal's hypotheses it names, the cells it reads (a variable, a count map, a key\n-- term), Count.lean's instances, the table and the tree.\nstructure CCert where\n hyps : List C\n reads : List (Nat × Nat × E)\n insts : List CInst\n tab : List VDef\n tree : Tree\n picks : List (Nat × List E)\n lemmas : List CutLemma := []\n\n/-! A count at least its body at distinct keys: a read's count picked at key terms (`picks`) gives the hypothesis that,\nwhere the terms are distinct and below the bound, the count is at least the sum of its body at them (`pickHyp`). It\nholds wherever the count is its sum (`pickHyp_true`), so a certificate may name any terms. -/\n\ndef allNe (k : E) : List E → C\n | [] => .le (.const 0) (.const 0)\n | k' :: ks => .and (.not (.eq k k')) (allNe k ks)\n\ndef distinctBelow (b : E) : List E → C\n | [] => .le (.const 0) (.const 0)\n | k :: ks => .and (.lt k b) (.and (allNe k ks) (distinctBelow b ks))\n\ndef pickHyp (c : Count) (ks : List E) : C :=\n .or (.not (distinctBelow c.below ks)) (.le (sumE (ks.map fun k => substE [(c.key, k)] c.body)) (.var c.v))\n\ntheorem evalE_sumEs (X : Nat → Nat) (M : Nat → Nat → Nat) : ∀ es : List E, evalE X M (sumE es) = (es.map (evalE X M)).sum\n | [] => by simp [sumE, evalE]\n | e :: es => by simp [sumE, evalE, evalE_sumEs X M es]\n\ntheorem allNe_ok (X : Nat → Nat) (M : Nat → Nat → Nat) (k : E) : ∀ ks : List E, evalC X M (allNe k ks) = true →\n ∀ k' ∈ ks, evalE X M k ≠ evalE X M k'\n | [], _ => by simp\n | k' :: ks, h => by\n simp only [allNe, evalC, Bool.and_eq_true, Bool.not_eq_true', decide_eq_false_iff_not] at h\n intro k'' hk\n rcases List.mem_cons.mp hk with rfl | hk\n · exact h.1\n · exact allNe_ok X M k ks h.2 k'' hk\n\ntheorem distinctBelow_ok (X : Nat → Nat) (M : Nat → Nat → Nat) (b : E) : ∀ ks : List E, evalC X M (distinctBelow b ks) = true →\n (ks.map (evalE X M)).Pairwise (· ≠ ·) ∧ ∀ k ∈ ks, evalE X M k < evalE X M b\n | [], _ => by simp\n | k :: ks, h => by\n simp only [distinctBelow, evalC, Bool.and_eq_true, decide_eq_true_eq] at h\n obtain ⟨hlt, hne, hrest⟩ := h\n obtain ⟨hp, hb⟩ := distinctBelow_ok X M b ks hrest\n refine ⟨?_, ?_⟩\n · simp only [List.map_cons, List.pairwise_cons, List.mem_map]\n exact ⟨fun a ⟨k', hk', he⟩ => he ▸ allNe_ok X M k ks hne k' hk', hp⟩\n · intro k' hk'\n rcases List.mem_cons.mp hk' with rfl | hk'\n · exact hlt\n · exact hb k' hk'\n\ntheorem sum_split (f : Nat → Nat) (n : Nat) : ∀ ks : List Nat, ks.Pairwise (· ≠ ·) → n ∈ ks →\n (ks.map f).sum = f n + ((ks.filter (· != n)).map f).sum\n | [], _, h => by simp at h\n | a :: t, hp, h => by\n rw [List.pairwise_cons] at hp\n by_cases ha : a = n\n · subst ha\n have ht : t.filter (· != a) = t := List.filter_eq_self.mpr (fun x hx => by simpa using (hp.1 x hx).symm)\n rw [List.filter_cons_of_neg (by simp), ht]\n simp\n · have hn : n ∈ t := by rcases List.mem_cons.mp h with h | h; exact absurd h.symm ha; exact h\n have ih := sum_split f n t hp.2 hn\n simp only [List.map_cons, List.sum_cons, List.filter_cons, bne_iff_ne, ne_eq, ha, not_false_eq_true, ite_true]\n rw [ih]; omega\n\n-- A sum below n is at least its terms at distinct keys below n.\ntheorem sum_le_sumBelow (f : Nat → Nat) : ∀ (n : Nat) (ks : List Nat), ks.Pairwise (· ≠ ·) → (∀ k ∈ ks, k < n) →\n (ks.map f).sum ≤ sumBelow f n\n | 0, ks, _, hb => by\n cases ks with\n | nil => simp [sumBelow]\n | cons k _ => exact absurd (hb k List.mem_cons_self) (Nat.not_lt_zero k)\n | n + 1, ks, hp, hb => by\n simp only [sumBelow]\n by_cases hn : n ∈ ks\n · rw [sum_split f n ks hp hn]\n have := sum_le_sumBelow f n (ks.filter (· != n)) (hp.filter _) (fun k hk => by\n obtain ⟨hk, hne⟩ := List.mem_filter.mp hk\n have := hb k hk; simp only [bne_iff_ne, ne_eq, decide_eq_true_eq] at hne; omega)\n omega\n · have := sum_le_sumBelow f n ks hp (fun k hk => by have := hb k hk; have : k ≠ n := fun h => hn (h ▸ hk); omega)\n omega\n\ntheorem pickHyp_true (c : Count) (ks : List E) (X : Nat → Nat) (M : Nat → Nat → Nat) (h : c.Holds X M) :\n evalC X M (pickHyp c ks) = true := by\n simp only [pickHyp, evalC, Bool.or_eq_true, Bool.not_eq_true', decide_eq_true_eq]\n by_cases hg : evalC X M (distinctBelow c.below ks) = true\n · right\n obtain ⟨hp, hb⟩ := distinctBelow_ok X M c.below ks hg\n rw [evalE_sumEs]\n simp only [evalE]\n rw [h, List.map_map]\n have he : (ks.map ((evalE X M) ∘ fun k => substE [(c.key, k)] c.body)) = ((ks.map (evalE X M)).map fun k => evalE (upd X c.key k) M c.body) := by\n rw [List.map_map]; congr 1; funext k; simp only [Function.comp, subst_evalE, applyS_one]\n rw [he]\n exact sum_le_sumBelow _ _ _ hp (fun k hk => by obtain ⟨k', hk', rfl⟩ := List.mem_map.mp hk; exact hb k' hk')\n · left; simpa using hg\n\n-- A key term's parts, the terms the parameters take: one parameter, the term (j a constant 0); two, the term written\n-- base·a + b (j at a, lo at b), which is the count at (a, b) where b < base.\ndef countKeyParts (d : CDecl) (e : E) : Option (E × E) :=\n if d.base == 0 then some (.const 0, e) else match e with\n | .add (.mul b a) c => if b == d.base then some (a, c) else none\n | _ => none\n\n-- A read cell as Count.lean's count: its variable, the declaration with its parameters at the key term's parts.\ndef toCount (ds : List CDecl) (r : Nat × Nat × E) : Option Count :=\n match lookup (fun d => d.mp == r.2.1) ds with\n | some d => (countKeyParts d r.2.2).map fun p => ⟨r.1, d.key, substE [(d.lo, p.2), (d.j, p.1)] d.below, substE [(d.lo, p.2), (d.j, p.1)] d.body⟩\n | none => none\n\ndef toCounts (ds : List CDecl) : List (Nat × Nat × E) → Option (List Count)\n | [] => some []\n | r :: rs => match toCount ds r with\n | none => none\n | some c => (toCounts ds rs).map (c :: ·)\n\n-- A read's hypothesis: its variable is the cell; for two parameters, where the second part is below the base.\ndef readHyp (ds : List CDecl) (r : Nat × Nat × E) : C :=\n match lookup (fun d => d.mp == r.2.1) ds with\n | some d => if d.base == 0 then .eq (.var r.1) (.get r.2.1 r.2.2) else match countKeyParts d r.2.2 with\n | some p => .or (.le (.const d.base) p.2) (.eq (.var r.1) (.get r.2.1 r.2.2))\n | none => .eq (.var r.1) (.get r.2.1 r.2.2)\n | none => .eq (.var r.1) (.get r.2.1 r.2.2)\n\n-- The picks' hypotheses: each pick of a read, at its count.\ndef pickHyps (ds : List CDecl) (rs : List (Nat × Nat × E)) (ps : List (Nat × List E)) : List C :=\n ps.filterMap fun p => match lookup (fun r => r.1 == p.1) rs with\n | some r => (toCount ds r).map fun c => pickHyp c p.2\n | none => none\n\n-- A read's variable is fresh: no named hypothesis, declaration or key term reads it, and it is no declaration's j, lo or\n-- key.\ndef readFresh (hyps : List C) (ds : List CDecl) (rs : List (Nat × Nat × E)) (v : Nat) : Bool :=\n hyps.all (fun h => !occC v h) && ds.all (fun d => !occE v d.below && !occE v d.body && d.j != v && d.lo != v && d.key != v)\n && rs.all (fun r => !occE v r.2.2)\n\n-- The reads: distinct fresh variables, each key term reading no declaration's key.\ndef readsOk (hyps : List C) (ds : List CDecl) (rs : List (Nat × Nat × E)) : Bool :=\n cDistinct (rs.map (·.1)) && rs.all (fun r => readFresh hyps ds rs r.1 && ds.all (fun d => !occE d.key r.2.2))\n\n-- Count.lean's check with the witnesses fresh for the counts and the instances' bounds only: a machine's goal may read\n-- a witness in its instances of laws and flags, which hold at every value of a variable the machine never reads, so the\n-- goal's hypotheses are asked to hold at every value of the witnesses (`countedW_sound`).\ndef witFreshW (cs : List Count) (is : List CInst) (w : Nat) : Bool :=\n cs.all (fun c => c.v != w && !occE w c.below && !occE w c.body) && is.all (fun j => !occE w j.below)\n\ndef countedOkW (cs : List Count) (is : List CInst) : Bool :=\n cDistinct (is.map (·.wit)) && is.all (fun i => witFreshW cs is i.wit)\n\ndef checkCountedW (hyps : List C) (cs : List Count) (is : List CInst) (tab : List VDef) (t : Tree) (lemmas : List CutLemma := []) : Bool :=\n countedOkW cs is && match countHyps cs is with\n | some hs => checkGoalLemmas ⟨tab, hyps ++ hs⟩ t lemmas\n | none => false\n\n/-- The witness-generalized wrapper conserves the original checker on empty lemma lists. -/\ntheorem checkCountedW_nil (hyps : List C) (cs : List Count) (is : List CInst) (tab : List VDef) (t : Tree) :\n checkCountedW hyps cs is tab t [] = (countedOkW cs is && match countHyps cs is with\n | some hs => checkGoal ⟨tab, hyps ++ hs⟩ t\n | none => false) := by\n simp only [checkCountedW, checkGoalLemmas_nil]\n\ntheorem countedW_sound (hyps : List C) (cs : List Count) (is : List CInst) (tab : List VDef) (t : Tree) {lemmas : List CutLemma}\n (hck : checkCountedW hyps cs is tab t lemmas = true)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hc : ∀ c ∈ cs, c.Holds ρ M)\n (hH : ∀ ρw : Nat → Nat, (∀ j, (∀ i ∈ is, i.wit ≠ j) → ρw j = ρ j) → ∀ h ∈ hyps, evalC ρw M h = true) : False := by\n simp only [checkCountedW, Bool.and_eq_true] at hck\n obtain ⟨hok, hgoal⟩ := hck\n simp only [countedOkW, Bool.and_eq_true, List.all_eq_true] at hok\n obtain ⟨hdist, hfresh⟩ := hok\n have hfr : ∀ i ∈ is, (∀ c ∈ cs, c.v ≠ i.wit ∧ occE i.wit c.below = false ∧ occE i.wit c.body = false) ∧ (∀ j ∈ is, occE i.wit j.below = false) := by\n intro i hi\n have := hfresh i hi\n simp only [witFreshW, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at this\n exact ⟨fun c hc => ⟨(this.1 c hc).1.1, (this.1 c hc).1.2, (this.1 c hc).2⟩, this.2⟩\n cases hhs : countHyps cs is with\n | none => simp [hhs] at hgoal\n | some hs =>\n simp only [hhs] at hgoal\n have hx : ∀ i : CInst, ∃ x : Nat, ∀ rs, resolve cs i.below i.terms = some rs →\n sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below) ≤ sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below)\n ∨ (x < evalE ρ M i.below ∧ ptSide negP ρ M rs x + negP i.unit < ptSide posP ρ M rs x + posP i.unit) := by\n intro i\n cases hr : resolve cs i.below i.terms with\n | none => exact ⟨0, fun rs h => by simp at h⟩\n | some rs =>\n by_cases hlt : sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below) < sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below)\n · obtain ⟨k, hk, hk'⟩ := exists_lt_of_sumBelow_lt hlt\n exact ⟨k, fun rs' h => by simp only [Option.some.injEq] at h; subst h; exact Or.inr ⟨hk, hk'⟩⟩\n · exact ⟨0, fun rs' h => by simp only [Option.some.injEq] at h; subst h; exact Or.inl (Nat.le_of_not_lt hlt)⟩\n obtain ⟨xs, hxs⟩ : ∃ xs : CInst → Nat, ∀ i rs, resolve cs i.below i.terms = some rs →\n sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below) ≤ sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below)\n ∨ (xs i < evalE ρ M i.below ∧ ptSide negP ρ M rs (xs i) + negP i.unit < ptSide posP ρ M rs (xs i) + posP i.unit) :=\n ⟨fun i => Classical.choose (hx i), fun i => Classical.choose_spec (hx i)⟩\n obtain ⟨ρs, hother, hat⟩ : ∃ ρs : Nat → Nat, (∀ j, (∀ i ∈ is, i.wit ≠ j) → ρs j = ρ j) ∧ (∀ i ∈ is, ρs i.wit = xs i) := by\n have hws : (is.map fun i => (i.wit, xs i)).map (·.1) = is.map (·.wit) := by induction is <;> simp_all\n refine ⟨setWits ρ (is.map fun i => (i.wit, xs i)), fun j hj => setWits_other ?_, fun i hi => ?_⟩\n · rw [hws]; intro hm; obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hm; exact hj i hi rfl\n · exact setWits_at (ρ := ρ) (ws := is.map fun i => (i.wit, xs i)) (by rw [hws]; exact hdist) (p := (i.wit, xs i)) (List.mem_map.mpr ⟨i, hi, rfl⟩)\n have hvar : ∀ c ∈ cs, ρs c.v = ρ c.v := fun c hc => hother c.v (fun i hi he => ((hfr i hi).1 c hc).1 he.symm)\n have hbound : ∀ e : E, (∀ i ∈ is, occE i.wit e = false) → evalE ρs M e = evalE ρ M e := fun e he =>\n congrE ρs ρ M e (fun j hj => hother j (fun i hi hij => by have := he i hi; rw [hij] at this; simp [this] at hj))\n have hbody : ∀ c ∈ cs, ∀ k, evalE (upd ρs c.key k) M c.body = evalE (upd ρ c.key k) M c.body := fun c hc k =>\n congrE _ _ M c.body (fun j hj => by\n simp only [upd]; split\n · rfl\n · exact hother j (fun i hi hij => by\n have := ((hfr i hi).1 c hc).2.2; rw [hij] at this; simp [this] at hj))\n have hpt : ∀ (part : Int → Nat) (rs : List (Int × Count)), (∀ r ∈ rs, r.2 ∈ cs) → ∀ k, ptSide part ρs M rs k = ptSide part ρ M rs k := by\n intro part rs hrs k\n induction rs with\n | nil => rfl\n | cons r rs ih =>\n simp only [ptSide, hbody r.2 (hrs r List.mem_cons_self) k, ih (fun r' hr' => hrs r' (List.mem_cons_of_mem _ hr'))]\n have hinst : ∀ i ∈ is, ∀ h, countHyp cs i = some h → evalC ρs M h = true := by\n intro i hi h hh\n simp only [countHyp, Option.map_eq_some_iff] at hh\n obtain ⟨rs, hr, rfl⟩ := hh\n have hrm := resolve_mem hr\n have hB : evalE ρs M i.below = evalE ρ M i.below := hbound i.below (fun j hj => (hfr j hj).2 i hi)\n have hcnt : ∀ r ∈ rs, ρs r.2.v = sumBelow (fun k => evalE (upd ρs r.2.key k) M r.2.body) (evalE ρ M i.below) := by\n intro r hr'\n obtain ⟨hcm, hcb⟩ := hrm r hr'\n have h1 : ρ r.2.v = sumBelow (fun k => evalE (upd ρ r.2.key k) M r.2.body) (evalE ρ M r.2.below) := hc r.2 hcm\n rw [hvar r.2 hcm, h1, hcb]\n exact sumBelow_congr _ (fun k _ => (hbody r.2 hcm k).symm)\n have hS : ∀ part, evalE ρs M (side part atCount i.below i.unit rs)\n = sumBelow (fun k => ptSide part ρ M rs k + part i.unit) (evalE ρ M i.below) := by\n intro part\n have e1 : evalE ρs M (side part atCount i.below i.unit rs) = sumSide part ρs rs + part i.unit * evalE ρ M i.below := by\n simp only [side, evalE, eval_sumE_count, hB]\n have e2 : sumBelow (fun k => ptSide part ρ M rs k + part i.unit) (evalE ρ M i.below)\n = sumBelow (ptSide part ρ M rs) (evalE ρ M i.below) + part i.unit * evalE ρ M i.below := by\n rw [sumBelow_add (ptSide part ρ M rs) (fun _ => part i.unit), sumBelow_const]\n have e3 : sumSide part ρs rs = sumBelow (ptSide part ρ M rs) (evalE ρ M i.below) := by\n rw [sumSide_eq part ρs M _ rs hcnt]\n exact sumBelow_congr _ (fun k _ => hpt part rs (fun r hr' => (hrm r hr').1) k)\n rw [e1, e2, e3]\n have hW : ∀ part, evalE ρs M (side part (atWit i.wit) (.const 1) i.unit rs) = ptSide part ρ M rs (xs i) + part i.unit := by\n intro part\n simp only [side, evalE, eval_sumE_wit, hat i hi, hpt part rs (fun r hr' => (hrm r hr').1), Nat.mul_one]\n have hv := hxs i rs hr\n simp only [evalC, hS, hW, evalE, hat i hi, hB, Bool.or_eq_true, Bool.and_eq_true, decide_eq_true_eq]\n exact hv\n exact goalLemmas_sound ⟨tab, hyps ++ hs⟩ t lemmas hgoal ρs M (fun h hm => by\n rcases List.mem_append.mp hm with hm | hm\n · exact hH ρs hother h hm\n · obtain ⟨i, hi, hh⟩ := countHyps_mem hhs h hm\n exact hinst i hi h hh)\n\n-- The check: the named hypotheses are the goal's, each declaration's j and lo differ from its key, the reads are fresh\n-- and their key terms read no witness, and Count.lean's check (witnesses fresh for the counts) accepts the counted goal\n-- they make.\ndef checkMC (hyps : List C) (ds : List CDecl) (k : CCert) : Bool :=\n namedIn hyps k.hyps hyps && ds.all (fun d => d.j != d.key && d.lo != d.key) && readsOk k.hyps ds k.reads\n && k.reads.all (fun r => k.insts.all (fun i => i.wit != r.1 && !occE i.wit r.2.2))\n && match toCounts ds k.reads with\n | some cs => checkCountedW (k.hyps ++ k.reads.map (readHyp ds) ++ pickHyps ds k.reads k.picks) cs k.insts k.tab k.tree k.lemmas\n | none => false\n\n/-! The counted goal's soundness -/\n\ntheorem toCounts_mem {ds : List CDecl} : ∀ {rs : List (Nat × Nat × E)} {cs : List Count}, toCounts ds rs = some cs →\n ∀ c ∈ cs, ∃ r ∈ rs, toCount ds r = some c\n | [], cs, h => by simp only [toCounts, Option.some.injEq] at h; subst h; simp\n | r :: rs, cs, h => by\n cases e1 : toCount ds r with\n | none => simp [toCounts, e1] at h\n | some c1 =>\n cases e2 : toCounts ds rs with\n | none => simp [toCounts, e1, e2] at h\n | some cs' =>\n simp [toCounts, e1, e2] at h\n subst h\n intro c hc\n rcases List.mem_cons.mp hc with rfl | hc\n · exact ⟨r, List.mem_cons_self, e1⟩\n · obtain ⟨r', hr', h'⟩ := toCounts_mem e2 c hc\n exact ⟨r', List.mem_cons_of_mem _ hr', h'⟩\n\n-- The environment with two parameters set at once by a substitution.\ntheorem applyS_two (lo j : Nat) (a b : E) (ρ : Nat → Nat) (M : Nat → Nat → Nat) :\n applyS [(lo, b), (j, a)] ρ M = upd (upd ρ j (evalE ρ M a)) lo (evalE ρ M b) := by\n funext i\n simp only [applyS, assoc, lookup, upd]\n by_cases h1 : i = lo\n · subst h1; simp\n · by_cases h2 : i = j\n · subst h2; simp [h1, Ne.symm h1]\n · simp [h1, h2, Ne.symm h1, Ne.symm h2]\n\ntheorem atJ_congr (d : CDecl) (x : Nat) {ρ ρ' : Nat → Nat} (i : Nat) (h : i ≠ d.j → i ≠ d.lo → ρ i = ρ' i) :\n atJ d ρ x i = atJ d ρ' x i := by\n simp only [atJ, upd]\n by_cases h2 : i = d.lo\n · simp [h2]\n · by_cases h1 : i = d.j\n · simp [h1, h2]\n · simp only [if_neg h1, if_neg h2]; exact h h1 h2\n\n-- A key term's parts read the key term's variables only, and are the parameters where the second is below the base.\ntheorem keyParts_occ {d : CDecl} {e : E} {p : E × E} (h : countKeyParts d e = some p) (i : Nat) :\n (occE i p.1 = true → occE i e = true) ∧ (occE i p.2 = true → occE i e = true) := by\n unfold countKeyParts at h\n by_cases hb : d.base = 0\n · simp only [hb, beq_self_eq_true, ite_true, Option.some.injEq] at h; subst h; simp [occE]\n · rw [if_neg (by simp [hb])] at h\n split at h\n · split at h\n · simp only [Option.some.injEq] at h; subst h; simp only [occE, Bool.or_eq_true]\n exact ⟨fun h => Or.inl h, fun h => Or.inr h⟩\n · cases h\n · cases h\n\ntheorem keyParts_eval {d : CDecl} {e : E} {p : E × E} (h : countKeyParts d e = some p) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (hg : d.base = 0 ∨ evalE ρ M p.2 < d.base) : evalE ρ M p.1 = evalE ρ M e / d.base ∧ evalE ρ M p.2 = evalE ρ M e % d.base := by\n unfold countKeyParts at h\n by_cases hb : d.base = 0\n · simp only [hb, beq_self_eq_true, ite_true, Option.some.injEq] at h; subst h; simp [evalE, hb]\n · have hpos : 0 < d.base := Nat.pos_of_ne_zero hb\n have hg' : evalE ρ M p.2 < d.base := hg.resolve_left hb\n rw [if_neg (by simp [hb])] at h\n split at h\n · split at h\n · rename_i hbe\n simp only [Option.some.injEq] at h; subst h\n simp only [beq_iff_eq] at hbe\n simp only [evalE, hbe] at hg' ⊢\n constructor\n · rw [Nat.add_comm, Nat.add_mul_div_left _ _ hpos, Nat.div_eq_of_lt hg', Nat.zero_add]\n · rw [Nat.add_comm, Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hg']\n · cases h\n · cases h\n\n-- A term read across the parameters' substitution, at two environments that agree where it matters.\ntheorem subst2_congr {lo j : Nat} {a b : E} {X X' : Nat → Nat} {M : Nat → Nat → Nat} (t : E)\n (ht : ∀ i, occE i t = true → i ≠ lo → i ≠ j → X i = X' i) (ha : evalE X M a = evalE X' M a) (hb : evalE X M b = evalE X' M b) :\n evalE X M (substE [(lo, b), (j, a)] t) = evalE X' M (substE [(lo, b), (j, a)] t) := by\n rw [subst_evalE, subst_evalE, applyS_two, applyS_two, ha, hb]\n exact congrE _ _ M t (fun i hi => by\n simp only [upd]\n by_cases h1 : i = lo\n · simp [h1]\n · by_cases h2 : i = j\n · simp [h1, h2]\n · simp only [if_neg h1, if_neg h2]; exact ht i hi h1 h2)\n\n-- A read's count, its parameters at the key term's parts, is the declaration's count at the key term's value, where the\n-- second part is below the base.\ntheorem cnt_read {d : CDecl} {e : E} {p : E × E} (hp : countKeyParts d e = some p) (hjk : d.j ≠ d.key) (hlk : d.lo ≠ d.key)\n (hke : occE d.key e = false) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hg : d.base = 0 ∨ evalE ρ M p.2 < d.base) :\n sumBelow (fun k => evalE (upd ρ d.key k) M (substE [(d.lo, p.2), (d.j, p.1)] d.body)) (evalE ρ M (substE [(d.lo, p.2), (d.j, p.1)] d.below))\n = cntOf d ρ M (evalE ρ M e) := by\n obtain ⟨h1, h2⟩ := keyParts_eval hp ρ M hg\n simp only [cntOf]\n have hB : evalE ρ M (substE [(d.lo, p.2), (d.j, p.1)] d.below) = evalE (atJ d ρ (evalE ρ M e)) M d.below := by\n rw [subst_evalE, applyS_two, h1, h2]; rfl\n rw [hB]\n refine sumBelow_congr _ (fun k _ => ?_)\n have hk : ∀ t : E, (occE d.key t = true → occE d.key e = true) → evalE (upd ρ d.key k) M t = evalE ρ M t := fun t ht =>\n congrE _ _ M t (fun i hi => by\n simp only [upd]\n by_cases hi' : i = d.key\n · subst hi'; rw [ht hi] at hke; cases hke\n · simp [hi'])\n rw [subst_evalE, applyS_two, hk p.1 (keyParts_occ hp d.key).1, hk p.2 (keyParts_occ hp d.key).2, h1, h2]\n refine congrArg (fun f => evalE f M d.body) (funext fun i => ?_)\n simp only [atJ, upd]\n by_cases h3 : i = d.lo\n · subst h3; simp [hlk]\n · by_cases h4 : i = d.j\n · subst h4; simp [h3, hjk]\n · simp [h3, h4]\n\ntheorem toCounts_some {ds : List CDecl} : ∀ {rs : List (Nat × Nat × E)} {cs : List Count}, toCounts ds rs = some cs →\n ∀ r ∈ rs, ∃ c, toCount ds r = some c\n | [], _, _ => by simp\n | r :: rs, cs, h => by\n cases e1 : toCount ds r with\n | none => simp [toCounts, e1] at h\n | some c1 =>\n cases e2 : toCounts ds rs with\n | none => simp [toCounts, e1, e2] at h\n | some cs' =>\n intro r' hr'\n rcases List.mem_cons.mp hr' with rfl | hr'\n · exact ⟨c1, e1⟩\n · exact toCounts_some e2 r' hr'\n\ntheorem toCounts_in {ds : List CDecl} : ∀ {rs : List (Nat × Nat × E)} {cs : List Count}, toCounts ds rs = some cs →\n ∀ {r c}, r ∈ rs → toCount ds r = some c → c ∈ cs\n | [], _, _, _, _, h, _ => by simp at h\n | r0 :: rs, cs, h, r, c, hr, hc => by\n cases e1 : toCount ds r0 with\n | none => simp [toCounts, e1] at h\n | some c1 =>\n cases e2 : toCounts ds rs with\n | none => simp [toCounts, e1, e2] at h\n | some cs' =>\n simp only [toCounts, e1, e2, Option.map_some, Option.some.injEq] at h\n subst h\n rcases List.mem_cons.mp hr with rfl | hr\n · rw [e1] at hc; cases hc; exact List.mem_cons_self\n · exact List.mem_cons_of_mem _ (toCounts_in e2 hr hc)\n\n-- A read's value: its count at ρ.\ndef rval (ds : List CDecl) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (r : Nat × Nat × E) : Nat :=\n match toCount ds r with\n | some c => sumBelow (fun k => evalE (upd ρ c.key k) M c.body) (evalE ρ M c.below)\n | none => 0\n\n-- Each read's variable set to its count, the rest of the environment kept.\ndef setReads (ds : List CDecl) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (rs : List (Nat × Nat × E)) : Nat → Nat :=\n setWits ρ (rs.map fun r => (r.1, rval ds ρ M r))\n\ntheorem mc_sound (hyps : List C) (ds : List CDecl) (k : CCert) (hck : checkMC hyps ds k = true)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hd : GHolds ds ρ M)\n (hH : ∀ ρw : Nat → Nat, (∀ j, (∀ i ∈ k.insts, i.wit ≠ j) → ρw j = ρ j) → ∀ h ∈ hyps, evalC ρw M h = true) : False := by\n simp only [checkMC, Bool.and_eq_true] at hck\n obtain ⟨⟨⟨⟨hnamed, hjk⟩, hrok⟩, hrw⟩, hcc⟩ := hck\n have hjk' : ∀ d ∈ ds, d.j ≠ d.key ∧ d.lo ≠ d.key := fun d hdm => by\n have := List.all_eq_true.mp hjk d hdm; simpa using this\n have hrw' : ∀ r ∈ k.reads, ∀ i ∈ k.insts, i.wit ≠ r.1 ∧ occE i.wit r.2.2 = false := by\n intro r hr i hi\n have := List.all_eq_true.mp (List.all_eq_true.mp hrw r hr) i hi\n simp only [Bool.and_eq_true, bne_iff_ne, ne_eq, Bool.not_eq_true'] at this\n exact this\n cases hcs : toCounts ds k.reads with\n | none => simp [hcs] at hcc\n | some cs =>\n simp only [hcs] at hcc\n simp only [readsOk, Bool.and_eq_true, List.all_eq_true] at hrok\n obtain ⟨hdist, hrs⟩ := hrok\n have hmap : (k.reads.map fun r => (r.1, rval ds ρ M r)).map (·.1) = k.reads.map (·.1) := by\n induction k.reads <;> simp_all\n -- ρ' : ρ with each read's variable at its count.\n let ρ' := setReads ds ρ M k.reads\n have hother : ∀ i, (∀ r ∈ k.reads, r.1 ≠ i) → ρ' i = ρ i := fun i hi => setWits_other (by\n rw [hmap]; intro hm; obtain ⟨r, hr, he⟩ := List.mem_map.mp hm; exact hi r hr he)\n have hat : ∀ r ∈ k.reads, ρ' r.1 = rval ds ρ M r := by\n intro r hr\n have h := setWits_at (ρ := ρ) (ws := k.reads.map fun r => (r.1, rval ds ρ M r)) (by rw [hmap]; exact hdist)\n (p := (r.1, rval ds ρ M r)) (List.mem_map.mpr ⟨r, hr, rfl⟩)\n exact h\n have hfr : ∀ r ∈ k.reads, readFresh k.hyps ds k.reads r.1 = true := fun r hr => (hrs r hr).1\n have hfr' : ∀ r ∈ k.reads, (∀ h ∈ k.hyps, occC r.1 h = false)\n ∧ (∀ d ∈ ds, occE r.1 d.below = false ∧ occE r.1 d.body = false ∧ d.j ≠ r.1 ∧ d.lo ≠ r.1 ∧ d.key ≠ r.1)\n ∧ (∀ r' ∈ k.reads, occE r.1 r'.2.2 = false) := by\n intro r hr\n have := hfr r hr\n simp only [readFresh, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at this\n exact ⟨this.1.1, fun d hd => ⟨(this.1.2 d hd).1.1.1.1, (this.1.2 d hd).1.1.1.2, (this.1.2 d hd).1.1.2, (this.1.2 d hd).1.2,\n (this.1.2 d hd).2⟩, this.2⟩\n -- A term no read's variable occurs in reads alike at ρ' and ρ.\n have hcong : ∀ e : E, (∀ r ∈ k.reads, occE r.1 e = false) → evalE ρ' M e = evalE ρ M e := fun e he =>\n congrE ρ' ρ M e (fun i hi => hother i (fun r hr hri => by have := he r hr; rw [hri] at this; simp [this] at hi))\n -- A read's parts: its declaration and the key term's parts.\n have hparts : ∀ r ∈ k.reads, ∀ c, toCount ds r = some c → ∃ d ∈ ds, ∃ p, lookup (fun d => d.mp == r.2.1) ds = some d\n ∧ d.mp = r.2.1 ∧ countKeyParts d r.2.2 = some p\n ∧ c = ⟨r.1, d.key, substE [(d.lo, p.2), (d.j, p.1)] d.below, substE [(d.lo, p.2), (d.j, p.1)] d.body⟩ := by\n intro r _ c hc\n simp only [toCount] at hc\n split at hc\n · rename_i d hl\n obtain ⟨hdm, hdq⟩ := lookup_some hl\n simp only [beq_iff_eq] at hdq\n cases hk : countKeyParts d r.2.2 with\n | none => simp [hk] at hc\n | some p =>\n rw [hk] at hc\n exact ⟨d, hdm, p, hl, hdq, hk, (Option.some.inj hc).symm⟩\n · cases hc\n -- The key term's parts read no read's variable, and a read's count reads none.\n have hpr : ∀ r ∈ k.reads, ∀ d p, countKeyParts d r.2.2 = some p → ∀ r' ∈ k.reads, occE r'.1 p.1 = false ∧ occE r'.1 p.2 = false := by\n intro r hr d p hp r' hr'\n have h0 := (hfr' r' hr').2.2 r hr\n refine ⟨?_, ?_⟩\n · cases h1 : occE r'.1 p.1\n · rfl\n · rw [(keyParts_occ hp r'.1).1 h1] at h0; cases h0\n · cases h1 : occE r'.1 p.2\n · rfl\n · rw [(keyParts_occ hp r'.1).2 h1] at h0; cases h0\n -- every count is its sum at ρ'\n have hholds : ∀ c ∈ cs, c.Holds ρ' M := by\n intro c hc\n obtain ⟨r, hr, hrc⟩ := toCounts_mem hcs c hc\n obtain ⟨d, hdm, p, _, _, hp, rfl⟩ := hparts r hr c hrc\n have hvr : ∀ t : E, (t = d.below ∨ t = d.body) → ∀ i, occE i t = true → (∀ r' ∈ k.reads, r'.1 ≠ i) := by\n intro t ht i hi r' hr' he\n have := (hfr' r' hr').2.1 d hdm\n rcases ht with rfl | rfl\n · rw [he, hi] at this; exact absurd this.1 (by simp)\n · rw [he, hi] at this; exact absurd this.2.1 (by simp)\n simp only [Count.Holds]\n rw [hat r hr]\n simp only [rval, hrc]\n have hp1 : evalE ρ M p.1 = evalE ρ' M p.1 := (hcong p.1 (fun r' hr' => (hpr r hr d p hp r' hr').1)).symm\n have hp2 : evalE ρ M p.2 = evalE ρ' M p.2 := (hcong p.2 (fun r' hr' => (hpr r hr d p hp r' hr').2)).symm\n rw [subst2_congr d.below (fun i hi _ _ => (hother i (hvr d.below (Or.inl rfl) i hi)).symm) hp1 hp2]\n refine sumBelow_congr _ (fun kk _ => ?_)\n refine subst2_congr d.body (fun i hi _ _ => ?_) ?_ ?_\n · simp only [upd]; split\n · rfl\n · exact (hother i (hvr d.body (Or.inr rfl) i hi)).symm\n · exact congrE _ _ M p.1 (fun i hi => by\n simp only [upd]; split\n · rfl\n · exact (hother i (fun r' hr' he => by have := (hpr r hr d p hp r' hr').1; rw [he, hi] at this; cases this)).symm)\n · exact congrE _ _ M p.2 (fun i hi => by\n simp only [upd]; split\n · rfl\n · exact (hother i (fun r' hr' he => by have := (hpr r hr d p hp r' hr').2; rw [he, hi] at this; cases this)).symm)\n have hwf : ∀ c ∈ cs, ∀ i ∈ k.insts, c.v ≠ i.wit ∧ occE i.wit c.below = false ∧ occE i.wit c.body = false := by\n have h1 := hcc\n simp only [checkCountedW, countedOkW, Bool.and_eq_true, List.all_eq_true] at h1\n intro c hc i hi\n have := h1.1.2 i hi\n simp only [witFreshW, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at this\n exact ⟨fun he => (this.1 c hc).1.1 he, (this.1 c hc).1.2, (this.1 c hc).2⟩\n refine countedW_sound _ _ _ _ _ hcc ρ' M hholds ?_\n intro ρw hρw h hm\n rcases List.mem_append.mp hm with hm | hm\n · rcases List.mem_append.mp hm with hm | hm\n · -- a named hypothesis: it reads no read variable, and holds where the witnesses are anything\n let ρw2 : Nat → Nat := fun j => if (k.reads.map (·.1)).contains j then ρ j else ρw j\n have h2 := hH ρw2 (fun j hj => by\n simp only [ρw2]\n split\n · rfl\n · rename_i hn\n rw [hρw j hj]\n exact hother j (fun r hr hrj => hn (List.contains_iff_mem.mpr (List.mem_map.mpr ⟨r, hr, hrj⟩))))\n h (namedIn_sound hyps k.hyps hyps (fun _ hx => hx) hnamed h hm)\n rw [congrC ρw ρw2 M h (fun i hi => by\n simp only [ρw2]\n split\n · rename_i hc\n obtain ⟨r, hr, hri⟩ := List.mem_map.mp (List.contains_iff_mem.mp hc)\n have := (hfr' r hr).1 h hm; rw [hri] at this; simp [this] at hi\n · rfl)]\n exact h2\n · obtain ⟨r, hr, rfl⟩ := List.mem_map.mp hm\n have hw1 : ρw r.1 = ρ' r.1 := hρw r.1 (fun i hi he => (hrw' r hr i hi).1 he)\n -- a term inside the key term reads alike at ρw and ρ\n have hwk : ∀ t : E, (∀ i, occE i t = true → occE i r.2.2 = true) → evalE ρw M t = evalE ρ M t := fun t ht => by\n rw [← hcong t (fun r' hr' => by\n cases h1 : occE r'.1 t\n · rfl\n · have := (hfr' r' hr').2.2 r hr; rw [ht _ h1] at this; cases this)]\n exact congrE _ _ M t (fun j hj => hρw j (fun i hi he => by\n have := (hrw' r hr i hi).2; rw [he, ht j hj] at this; cases this))\n obtain ⟨c, hc⟩ := toCounts_some hcs r hr\n obtain ⟨d, hdm, p, hl, hdq, hp, rfl⟩ := hparts r hr c hc\n have hkey : occE d.key r.2.2 = false := by have := (hrs r hr).2 d hdm; simpa using this\n have hval : ∀ hg : d.base = 0 ∨ evalE ρ M p.2 < d.base, ρw r.1 = M r.2.1 (evalE ρw M r.2.2) := fun hg => by\n rw [hw1, hat r hr, hwk r.2.2 (fun _ h => h)]\n simp only [rval, hc]\n rw [cnt_read hp (hjk' d hdm).1 (hjk' d hdm).2 hkey ρ M hg, ← hd d hdm, hdq]\n simp only [readHyp, hl]\n by_cases hb : d.base = 0\n · simp only [hb, beq_self_eq_true, ite_true, evalC, evalE]\n exact decide_eq_true (hval (Or.inl hb))\n · rw [if_neg (by simp [hb])]\n simp only [hp, evalC, evalE, Bool.or_eq_true]\n by_cases hlt : evalE ρ M p.2 < d.base\n · exact Or.inr (decide_eq_true (hval (Or.inr hlt)))\n · exact Or.inl (decide_eq_true (by rw [hwk p.2 (fun i => (keyParts_occ hp i).2)]; omega))\n · -- a pick: its count at ρw is its sum, as at ρ' (it reads no witness)\n obtain ⟨p, _, hph⟩ := List.mem_filterMap.mp hm\n split at hph\n · rename_i r hl\n obtain ⟨c, hc, rfl⟩ := Option.map_eq_some_iff.mp hph\n have hcm : c ∈ cs := toCounts_in hcs (lookup_some hl).1 hc\n have hc' := hholds c hcm\n have hag : ∀ j, (∀ i ∈ k.insts, i.wit ≠ j) → ρw j = ρ' j := hρw\n refine pickHyp_true c p.2 ρw M ?_\n simp only [Count.Holds] at hc' ⊢\n rw [hag c.v (fun i hi he => (hwf c hcm i hi).1 he.symm), hc']\n have hB : evalE ρ' M c.below = evalE ρw M c.below := congrE _ _ M c.below (fun j hj => (hag j (fun i hi he => by\n have := (hwf c hcm i hi).2.1; rw [he, hj] at this; cases this)).symm)\n rw [hB]\n exact sumBelow_congr _ (fun kk _ => congrE _ _ M c.body (fun j hj => by\n simp only [upd]; split\n · rfl\n · exact (hag j (fun i hi he => by have := (hwf c hcm i hi).2.2; rw [he, hj] at this; cases this)).symm))\n · cases hph\n\n/-! Counts in a machine -/\n\n-- The maps with each count map at its count at ρ, M.\ndef withCnt (ds : List CDecl) (ρ : Nat → Nat) (M : Nat → Nat → Nat) : Nat → Nat → Nat := fun mp =>\n match lookup (fun d => d.mp == mp) ds with\n | some d => cntOf d ρ M\n | none => M mp\n\n-- The runs: `SReach`'s, each request carrying each count map at its count at the request's view.\ninductive CReach (s : SMachine) (ds : List CDecl) : (Nat → Nat) → (Nat → Nat → Nat) → Prop\n | start (ρ : Nat → Nat) (M : Nat → Nat → Nat) : StartMaps s.f.m M → evalC ρ M s.f.m.pre = true → (∀ l ∈ s.facts, l.Holds ρ M) →\n s.PFacts ρ M → CReach s ds (applyS s.f.m.init ρ M) M\n | step (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat) : CReach s ds ρ M →\n GHolds ds (withInputs s.f.m.inputs ρ ι) (withCarried s M κ) →\n evalC (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 s.f.m.assume = true → CReach s ds (sNext s ρ M ι κ).1 (sNext s ρ M ι κ).2\n\ntheorem creach_sreach {s : SMachine} {ds : List CDecl} : ∀ {ρ M}, CReach s ds ρ M → SReach s ρ M := by\n intro ρ M h\n induction h with\n | start ρ M hM h0 hf hp => exact .start ρ M hM h0 hf hp\n | step ρ M ι κ _ _ ha ih => exact .step ρ M ι κ ih ha\n\n-- A count of the state alone: its bound and body read no request (input, quantified flag, witness), no flag and no\n-- carried map. A law reads only these.\ndef stateOnly (s : SMachine) (d : CDecl) : Bool :=\n avoidsE (s.extVars ++ flagVars s.f.flags) d.below && avoidsE (s.extVars ++ flagVars s.f.flags) d.body\n && avoidsMapsE s.carried d.below && avoidsMapsE s.carried d.body\n\ndef cMaps (ds : List CDecl) : List Nat := ds.map (·.mp)\ndef cPosts (ds : List CDecl) : List Nat := ds.map (·.post)\ndef cren (ds : List CDecl) : List (Nat × Nat) := ds.map fun d => (d.mp, d.post)\ndef stateMaps (s : SMachine) (ds : List CDecl) : List Nat := (ds.filter (stateOnly s)).map (·.mp)\n\n-- A law with each count map read by its post name.\ndef renLaw (ds : List CDecl) (l : MLaw) : MLaw := ⟨substRC [] (frameRd (cren ds) getRd) l.holds, l.key⟩\n\n-- σ with the parameters and key kept.\ndef keepJ (d : CDecl) (σ : List (Nat × E)) : List (Nat × E) := (d.j, .var d.j) :: (d.lo, .var d.lo) :: (d.key, .var d.key) :: σ\n\n-- A count declared after σ, rd: its bound and body read across them, its parameters and key kept.\ndef afterDecl (σ : List (Nat × E)) (rd : Nat → E → E) (d : CDecl) : CDecl :=\n ⟨d.post, d.post, d.j, d.key, substRE (keepJ d σ) rd d.below, substRE (keepJ d σ) rd d.body, d.lo, d.base⟩\n\ntheorem cntOf_after (σ : List (Nat × E)) (rd : Nat → E → E) (d : CDecl) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (x : Nat) :\n cntOf (afterDecl σ rd d) ρ M x = sumBelow (fun k => evalE (upd (atJ d ρ x) d.key k) M (substRE (keepJ d σ) rd d.body))\n (evalE (atJ d ρ x) M (substRE (keepJ d σ) rd d.below)) := rfl\n\n-- The goals: Sets.lean's, the law proven read with its count maps renamed; the counts the goals declare: at the start,\n-- each state count after the start; at a step, each count as the request carries it, and each state count after it.\ndef cStartGoal (s : SMachine) (ds : List CDecl) (e : SEntry) : List C := sStartGoal s { e with law := renLaw ds e.law }\ndef cStartDecls (s : SMachine) (ds : List CDecl) : List CDecl := (ds.filter (stateOnly s)).map (afterDecl s.f.m.init (rdStart s.f.m))\ndef cStepGoal (s : SMachine) (ds : List CDecl) (ps : List SEntry) (e : SEntry) : List C := sStepGoal s ps { e with law := renLaw ds e.law }\ndef cStepDecls (s : SMachine) (ds : List CDecl) : List CDecl :=\n ds ++ (ds.filter (stateOnly s)).map (afterDecl (stepSub s.f (frameSub [] []) (frameRd [] getRd)) (stepRdS s (frameSub [] []) (frameRd [] getRd)))\n\n-- A variable no part of the machine reads or binds (as a skolem is).\ndef mFresh (s : SMachine) (x : Nat) : Bool :=\n skFresh s x && s.f.m.init.all (fun p => !occE x p.2) && !(s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains x\n\n-- What the machine's own parts may not read: the post names (nothing reads them but the goals), which are none of its\n-- maps.\ndef cApart (s : SMachine) (ds : List CDecl) : Bool :=\n s.f.flags.all (fun p => avoidsMaps (cPosts ds) p.2) && s.qflags.all (fun q => avoidsMaps (cPosts ds) q.2.2)\n && s.f.m.step.all (fun p => avoidsMapsE (cPosts ds) p.2)\n && s.f.m.writes.all (fun w => avoidsMapsE (cPosts ds) w.2.1 && avoidsMapsE (cPosts ds) w.2.2)\n && s.every.all (fun w => avoidsMapsE (cPosts ds) w.2.2)\n && s.f.m.init.all (fun p => avoidsMapsE (cPosts ds) p.2) && avoidsMaps (cPosts ds) s.f.m.assume\n && s.facts.all (fun l => avoidsMaps (cPosts ds) l.holds) && s.pfacts.all (fun f => avoidsMaps (cPosts ds) f.1.holds)\n && (cPosts ds).all (fun mp => !s.carried.contains mp && !(s.f.m.maps0.map (·.1)).contains mp\n && !(s.every.map (·.1)).contains mp && !(s.f.m.writes.map (·.1)).contains mp)\n\n-- A declaration's parameters as the runtime reads them: one, lo = j and base 0; two, lo ≠ j (and base > 0).\ndef canonOk (d : CDecl) : Bool := if d.base == 0 then d.lo == d.j else d.lo != d.j\n\n-- Each declaration: its map carried, its j, lo and key fresh, j and lo not its key, one parameter lo = j and base 0 and\n-- two lo ≠ j (what the runtime computes), its bound and body reading no flag,\n-- quantified flag, witness, count map or post name, and no entry's skolem, key or further key (nor having them as j or\n-- key): a law reads a count at the state, its own keys set after (withCnt).\ndef cDeclOk (s : SMachine) (ds : List CDecl) (ps : List SEntry) (d : CDecl) : Bool :=\n s.carried.contains d.mp && d.j != d.key && mFresh s d.j && mFresh s d.key && !occE d.key d.below\n && avoidsE (s.qVars ++ s.wVars ++ flagVars s.f.flags) d.below && avoidsE (s.qVars ++ s.wVars ++ flagVars s.f.flags) d.body\n && avoidsMapsE (cMaps ds ++ cPosts ds) d.below && avoidsMapsE (cMaps ds ++ cPosts ds) d.body\n && ps.all (fun e => (e.sk :: (e.keys2 ++ e.law.key.toList)).all (fun g => !occE g d.below && !occE g d.body && g != d.j && g != d.key))\n && d.lo != d.key && mFresh s d.lo && canonOk d\n\n-- The entries' own conditions (Sets.lean's checkSMachine's), a law reading count maps of the state only, and no post name.\ndef cEntryOk (s : SMachine) (ds : List CDecl) (ps : List SEntry) (e : SEntry) : Bool :=\n avoids (s.extVars ++ flagVars s.f.flags) e.law.holds && avoidsMaps (s.carried.filter (fun mp => !(stateMaps s ds).contains mp) ++ cPosts ds) e.law.holds\n && !(s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains e.sk\n && ps.all (fun e' => !occC e.sk e'.law.holds) && !occC e.sk s.f.m.pre && s.f.m.init.all (fun p => !occE e.sk p.2)\n && skFresh s e.sk && key2Ok s ps e\n\n-- A certificate's witnesses: variables no part of the machine or law reads (a goal reads them only in its instances,\n-- which hold at every value), none an entry's skolem or further key.\ndef witsOk (s : SMachine) (ps : List SEntry) (k : CCert) : Bool :=\n k.insts.all fun i => mFresh s i.wit && !occC i.wit s.f.m.pre\n && ps.all (fun e => !occC i.wit e.law.holds && e.sk != i.wit && !e.keys2.contains i.wit)\n\nstructure CEntry where\n e : SEntry -- the law, its skolem and further keys, and where its goals assume the laws and facts (its certs unused)\n start : CCert\n step : CCert\n\ndef checkCMachine (s : SMachine) (ds : List CDecl) (ps : List CEntry) : Bool :=\n sOk s && avoids (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)) s.f.m.pre && !readsC s.f.m.pre\n && sTermsOk s (flagVars s.f.flags) && factsOk s\n && cDistinct (cMaps ds ++ cPosts ds) && cApart s ds && ds.all (cDeclOk s ds (ps.map (·.e)))\n && ps.all (fun ce => cEntryOk s ds (ps.map (·.e)) ce.e && witsOk s (ps.map (·.e)) ce.start && witsOk s (ps.map (·.e)) ce.step\n && checkMC (cStartGoal s ds ce.e) (cStartDecls s ds) ce.start\n && checkMC (cStepGoal s ds (ps.map (·.e)) ce.e) (cStepDecls s ds) ce.step)\n\n/-! Reading a law with its count maps renamed -/\n\n-- The maps a renamed term reads: a renamed map's cells are its new name's.\ndef renM (mr : List (Nat × Nat)) (N : Nat → Nat → Nat) : Nat → Nat → Nat := fun mp =>\n match lookup (fun p => p.1 == mp) mr with\n | some p => N p.2\n | none => N mp\n\ntheorem ren_evalC (mr : List (Nat × Nat)) (X : Nat → Nat) (N : Nat → Nat → Nat) (c : C) :\n evalC X N (substRC [] (frameRd mr getRd) c) = evalC X (renM mr N) c := by\n rw [substR_evalC [] (frameRd mr getRd) X N (renM mr N) (fun m k => by\n simp only [frameRd, renM]; cases h : lookup (fun p => p.1 == m) mr <;> simp [getRd, evalE]), applyS_nil']\n\nmutual\ntheorem occ_renE (mr : List (Nat × Nat)) (i : Nat) : (e : E) → occE i (substRE [] (frameRd mr getRd) e) = occE i e\n | .var j => by simp [substRE, assoc, lookup, occE]\n | .const _ => by simp [substRE, occE]\n | .add a b => by simp [substRE, occE, occ_renE mr i a, occ_renE mr i b]\n | .sub a b => by simp [substRE, occE, occ_renE mr i a, occ_renE mr i b]\n | .mul _ a => by simp [substRE, occE, occ_renE mr i a]\n | .min a b => by simp [substRE, occE, occ_renE mr i a, occ_renE mr i b]\n | .max a b => by simp [substRE, occE, occ_renE mr i a, occ_renE mr i b]\n | .prod a b => by simp [substRE, occE, occ_renE mr i a, occ_renE mr i b]\n | .ite c t f => by simp [substRE, occE, occ_renC mr i c, occ_renE mr i t, occ_renE mr i f]\n | .get m key => by\n simp only [substRE, frameRd]\n split <;> simp [getRd, occE, occ_renE mr i key]\n | .tup a b => by simp [substRE, occE, occ_renE mr i a, occ_renE mr i b]\n | .proj _ a => by simp [substRE, occE, occ_renE mr i a]\ntheorem occ_renC (mr : List (Nat × Nat)) (i : Nat) : (c : C) → occC i (substRC [] (frameRd mr getRd) c) = occC i c\n | .le a b => by simp [substRC, occC, occ_renE mr i a, occ_renE mr i b]\n | .lt a b => by simp [substRC, occC, occ_renE mr i a, occ_renE mr i b]\n | .eq a b => by simp [substRC, occC, occ_renE mr i a, occ_renE mr i b]\n | .and a b => by simp [substRC, occC, occ_renC mr i a, occ_renC mr i b]\n | .or a b => by simp [substRC, occC, occ_renC mr i a, occ_renC mr i b]\n | .not a => by simp [substRC, occC, occ_renC mr i a]\nend\n\n-- A renamed law holds where the law holds with its maps renamed.\ntheorem renLaw_holds (ds : List CDecl) (l : MLaw) (X : Nat → Nat) (N : Nat → Nat → Nat) :\n (renLaw ds l).Holds X N ↔ l.Holds X (renM (cren ds) N) := by\n unfold MLaw.Holds\n simp only [renLaw]\n split <;> simp [ren_evalC]\n\n/-! Counts read where a fresh variable is set -/\n\ntheorem cntOf_upd {d : CDecl} {g : Nat} (hb : occE g d.below = false) (hd : occE g d.body = false) (X : Nat → Nat) (N : Nat → Nat → Nat) (w x : Nat) :\n cntOf d (upd X g w) N x = cntOf d X N x := by\n simp only [cntOf]\n have hB : evalE (atJ d (upd X g w) x) N d.below = evalE (atJ d X x) N d.below :=\n congrE _ _ N d.below (fun i hi => atJ_congr d x i (fun _ _ => by\n have hig : i ≠ g := fun h => by rw [h, hb] at hi; cases hi\n simp [upd, hig]))\n rw [hB]\n exact sumBelow_congr _ (fun k _ => congrE _ _ N d.body (fun i hi => by\n have hig : i ≠ g := fun h => by rw [h, hd] at hi; cases hi\n simp only [upd]; split\n · rfl\n · exact atJ_congr d x i (fun _ _ => by simp [upd, hig])))\n\ntheorem withCnt_upd {ds : List CDecl} {g : Nat} (h : ∀ d ∈ ds, occE g d.below = false ∧ occE g d.body = false) (X : Nat → Nat) (N : Nat → Nat → Nat) (w : Nat) :\n withCnt ds (upd X g w) N = withCnt ds X N := by\n funext mp\n simp only [withCnt]\n split\n · rename_i d hd\n have := h d (lookup_some hd).1\n funext x; exact cntOf_upd this.1 this.2 X N w x\n · rfl\n\ntheorem withCnt_at {ds : List CDecl} (hd : cDistinct (cMaps ds) = true) {d : CDecl} (hm : d ∈ ds) (X : Nat → Nat) (N : Nat → Nat → Nat) :\n withCnt ds X N d.mp = cntOf d X N := by\n simp only [withCnt]\n have : lookup (fun d' => d'.mp == d.mp) ds = some d := by\n induction ds with\n | nil => simp at hm\n | cons a as ih =>\n simp only [cMaps, List.map_cons] at hd\n obtain ⟨hna, hd'⟩ := cDistinct_cons hd\n rcases List.mem_cons.mp hm with rfl | hm'\n · simp [lookup]\n · have hne : (a.mp == d.mp) = false := by\n simp only [beq_eq_false_iff_ne]; intro he; exact hna (by rw [he]; exact List.mem_map_of_mem hm')\n simp only [lookup, hne, Bool.false_eq_true, ite_false]\n exact ih hd' hm'\n rw [this]\n\ntheorem withCnt_other {ds : List CDecl} {mp : Nat} (h : mp ∉ cMaps ds) (X : Nat → Nat) (N : Nat → Nat → Nat) : withCnt ds X N mp = N mp := by\n simp only [withCnt]\n rw [lookup_none (fun d hd => by simp only [beq_eq_false_iff_ne]; intro he; exact h (by rw [← he]; exact List.mem_map_of_mem hd))]\n\n/-! A request's view, read where a fresh variable is set -/\n\ntheorem witnessKeys_congr {X X' : Nat → Nat} {N N' : Nat → Nat → Nat} {q : Nat × List Nat × C}\n (h : ∀ k, holdsC (atKeys X q.2.1 k) N q.2.2 ↔ holdsC (atKeys X' q.2.1 k) N' q.2.2) : witnessKeys X N q = witnessKeys X' N' q := by\n have hp : (fun k => ¬holdsC (atKeys X q.2.1 k) N q.2.2) = (fun k => ¬holdsC (atKeys X' q.2.1 k) N' q.2.2) := funext fun k => by rw [h k]\n unfold witnessKeys\n split\n · rename_i h1\n have h2 : ∃ k, ¬holdsC (atKeys X' q.2.1 k) N' q.2.2 := by obtain ⟨k, hk⟩ := h1; exact ⟨k, by rwa [← h k]⟩\n rw [dif_pos h2]\n have : ∀ (p p' : (Nat → Nat) → Prop) (e : p = p') (h1 : ∃ k, p k) (h2 : ∃ k, p' k), Classical.choose h1 = Classical.choose h2 := by\n intro p p' e h1 h2; subst e; rfl\n exact this _ _ hp h1 h2\n · rename_i h1\n have h2 : ¬∃ k, ¬holdsC (atKeys X' q.2.1 k) N' q.2.2 := fun ⟨k, hk⟩ => h1 ⟨k, by rwa [h k]⟩\n rw [dif_neg h2]\n\ntheorem sReq_upd {s : SMachine} {g : Nat} (hi : g ∉ s.f.m.inputs) (hq : g ∉ s.qVars) (hb : ∀ q ∈ s.qflags, occC g q.2.2 = false)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat) (w : Nat) :\n sReq s (upd ρ g w) M ι κ = sReq s ρ M ι κ := by\n funext v\n simp only [sReq]\n split\n · rfl\n · split\n · rename_i q hql\n have hvq : v ≠ g := fun h => hq (by\n have := lookup_some hql; simp only [beq_iff_eq] at this; rw [← h, ← this.2]; exact List.mem_map_of_mem this.1)\n rw [withInputs_upd hi, decideQ_upd hq hb]\n simp only [upd, hvq, ite_false]\n · split\n · split\n · rename_i q hq'\n split\n · apply congrFun\n apply witnessKeys_congr\n intro k\n rw [withInputs_upd hi]\n simp only [← evalC_iff]\n rw [congrC _ (atKeys (withInputs s.f.m.inputs ρ ι) q.2.1 k) _ q.2.2 (fun i hi' => by\n have hig : i ≠ g := fun h => by rw [h, hb q (lookup_some hq').1] at hi'; cases hi'\n simp only [atKeys]; split\n · rfl\n · simp [upd, hig])]\n · rfl\n · rfl\n · rfl\n\n/-! The check, taken apart -/\n\ntheorem cDistinct_append {a b : List Nat} (h : cDistinct (a ++ b) = true) : cDistinct a = true ∧ cDistinct b = true ∧ ∀ x ∈ a, x ∉ b := by\n induction a with\n | nil => exact ⟨rfl, h, by simp⟩\n | cons x xs ih =>\n obtain ⟨hx, hr⟩ := cDistinct_cons h\n obtain ⟨h1, h2, h3⟩ := ih hr\n refine ⟨?_, h2, fun y hy => ?_⟩\n · simp only [cDistinct, Bool.and_eq_true, Bool.not_eq_true']\n exact ⟨by simpa [List.contains_iff_mem] using fun hm => hx (List.mem_append_left _ hm), h1⟩\n · rcases List.mem_cons.mp hy with rfl | hy\n · exact fun hm => hx (List.mem_append_right _ hm)\n · exact h3 y hy\n\nstructure CParts (s : SMachine) (ds : List CDecl) (ps : List CEntry) : Prop where\n sok : sOk s = true\n pre : avoids (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)) s.f.m.pre = true\n preR : readsC s.f.m.pre = false\n terms : sTermsOk s (flagVars s.f.flags) = true\n facts : factsOk s = true\n dist : cDistinct (cMaps ds ++ cPosts ds) = true\n apart : cApart s ds = true\n decls : ∀ d ∈ ds, cDeclOk s ds (ps.map (·.e)) d = true\n entries : ∀ ce ∈ ps, cEntryOk s ds (ps.map (·.e)) ce.e = true ∧ checkMC (cStartGoal s ds ce.e) (cStartDecls s ds) ce.start = true\n ∧ checkMC (cStepGoal s ds (ps.map (·.e)) ce.e) (cStepDecls s ds) ce.step = true\n wits : ∀ ce ∈ ps, witsOk s (ps.map (·.e)) ce.start = true ∧ witsOk s (ps.map (·.e)) ce.step = true\n\ntheorem cparts {s : SMachine} {ds : List CDecl} {ps : List CEntry} (h : checkCMachine s ds ps = true) : CParts s ds ps := by\n simp only [checkCMachine, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true'] at h\n obtain ⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩, h9⟩ := h\n exact ⟨h1, h2, h3, h4, h5, h6, h7, h8, fun ce hce => ⟨(h9 ce hce).1.1.1.1, (h9 ce hce).1.2, (h9 ce hce).2⟩,\n fun ce hce => ⟨(h9 ce hce).1.1.1.2, (h9 ce hce).1.1.2⟩⟩\n\nstructure ApartParts (s : SMachine) (ds : List CDecl) : Prop where\n flags : ∀ p ∈ s.f.flags, avoidsMaps (cPosts ds) p.2 = true\n qflags : ∀ q ∈ s.qflags, avoidsMaps (cPosts ds) q.2.2 = true\n step : ∀ p ∈ s.f.m.step, avoidsMapsE (cPosts ds) p.2 = true\n writes : ∀ w ∈ s.f.m.writes, avoidsMapsE (cPosts ds) w.2.1 = true ∧ avoidsMapsE (cPosts ds) w.2.2 = true\n every : ∀ w ∈ s.every, avoidsMapsE (cPosts ds) w.2.2 = true\n init : ∀ p ∈ s.f.m.init, avoidsMapsE (cPosts ds) p.2 = true\n assume : avoidsMaps (cPosts ds) s.f.m.assume = true\n facts : ∀ l ∈ s.facts, avoidsMaps (cPosts ds) l.holds = true\n pfacts : ∀ f ∈ s.pfacts, avoidsMaps (cPosts ds) f.1.holds = true\n posts : ∀ mp ∈ cPosts ds, mp ∉ s.carried ∧ mp ∉ s.f.m.maps0.map (·.1) ∧ mp ∉ s.every.map (·.1) ∧ mp ∉ s.f.m.writes.map (·.1)\n\ntheorem apart_parts {s : SMachine} {ds : List CDecl} (h : cApart s ds = true) : ApartParts s ds := by\n simp only [cApart, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true'] at h\n obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩, h9⟩, h10⟩ := h\n exact ⟨h1, h2, h3, fun w hw => ⟨(h4 w hw).1, (h4 w hw).2⟩, h5, h6, h7, h8, h9, fun mp hm =>\n ⟨by simpa [List.contains_iff_mem] using (h10 mp hm).1.1.1, by simpa [List.contains_iff_mem] using (h10 mp hm).1.1.2,\n by simpa [List.contains_iff_mem] using (h10 mp hm).1.2, by simpa [List.contains_iff_mem] using (h10 mp hm).2⟩⟩\n\nstructure FreshParts (s : SMachine) (x : Nat) : Prop where\n sk : skFresh s x = true\n init : ∀ p ∈ s.f.m.init, occE x p.2 = false\n out : (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains x = false\n\ntheorem mfresh_parts {s : SMachine} {x : Nat} (h : mFresh s x = true) : FreshParts s x := by\n simp only [mFresh, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true'] at h\n exact ⟨h.1.1, h.1.2, h.2⟩\n\ntheorem fresh_out {s : SMachine} {x : Nat} (h : (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains x = false) :\n x ∉ s.extVars ∧ x ∉ flagVars s.f.flags ∧ x ∉ s.f.m.init.map (·.1) ∧ x ∉ s.f.m.step.map (·.1) ∧ x ∉ s.f.m.inputs ∧ x ∉ s.qVars ∧ x ∉ s.wVars := by\n have hn : x ∉ s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1) := fun hm => by\n rw [List.contains_iff_mem.mpr hm] at h; cases h\n simp only [List.mem_append, not_or] at hn\n obtain ⟨⟨⟨hE, hF⟩, hI⟩, hS⟩ := hn\n simp only [SMachine.extVars, List.mem_append, not_or] at hE\n exact ⟨by simp only [SMachine.extVars, List.mem_append, not_or]; exact hE, hF, hI, hS, hE.1.1, hE.1.2, hE.2⟩\n\nstructure DeclParts (s : SMachine) (ds : List CDecl) (ps : List SEntry) (d : CDecl) : Prop where\n carried : d.mp ∈ s.carried\n jk : d.j ≠ d.key\n jf : FreshParts s d.j\n kf : FreshParts s d.key\n kB : occE d.key d.below = false\n qwB : avoidsE (s.qVars ++ s.wVars ++ flagVars s.f.flags) d.below = true\n qwD : avoidsE (s.qVars ++ s.wVars ++ flagVars s.f.flags) d.body = true\n mB : avoidsMapsE (cMaps ds ++ cPosts ds) d.below = true\n mD : avoidsMapsE (cMaps ds ++ cPosts ds) d.body = true\n ent : ∀ e ∈ ps, ∀ g ∈ e.sk :: (e.keys2 ++ e.law.key.toList), occE g d.below = false ∧ occE g d.body = false ∧ g ≠ d.j ∧ g ≠ d.key\n lk : d.lo ≠ d.key\n lf : FreshParts s d.lo\n canon : canonOk d = true\n\ntheorem decl_parts {s : SMachine} {ds : List CDecl} {ps : List SEntry} {d : CDecl} (h : cDeclOk s ds ps d = true) : DeclParts s ds ps d := by\n simp only [cDeclOk, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at h\n obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h0⟩, h5⟩, h6⟩, h7⟩, h8⟩, h9⟩, h10⟩, h11⟩, h12⟩ := h\n exact ⟨by simpa [List.contains_iff_mem] using h1, h2, mfresh_parts h3, mfresh_parts h4, h0, h5, h6, h7, h8,\n fun e he g hg => ⟨(h9 e he g hg).1.1.1, (h9 e he g hg).1.1.2, (h9 e he g hg).1.2, (h9 e he g hg).2⟩, h10, mfresh_parts h11, h12⟩\n\nstructure EntryParts (s : SMachine) (ds : List CDecl) (ps : List SEntry) (e : SEntry) : Prop where\n lx : avoids (s.extVars ++ flagVars s.f.flags) e.law.holds = true\n lm : avoidsMaps (s.carried.filter (fun mp => !(stateMaps s ds).contains mp) ++ cPosts ds) e.law.holds = true\n fresh : (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains e.sk = false\n slaw : ∀ e' ∈ ps, occC e.sk e'.law.holds = false\n spre : occC e.sk s.f.m.pre = false\n sinit : ∀ p ∈ s.f.m.init, occE e.sk p.2 = false\n skf : skFresh s e.sk = true\n k2 : key2Ok s ps e = true\n\ntheorem entry_parts {s : SMachine} {ds : List CDecl} {ps : List SEntry} {e : SEntry} (h : cEntryOk s ds ps e = true) : EntryParts s ds ps e := by\n simp only [cEntryOk, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true'] at h\n obtain ⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩ := h\n exact ⟨h1, h2, h3, h4, h5, h6, h7, h8⟩\n\n-- The entries, as checkSMachine's lemmas read them.\ntheorem key2_parts {s : SMachine} {ds : List CDecl} {ps : List SEntry} (hk : ∀ e ∈ ps, cEntryOk s ds ps e = true) {e : SEntry} (he : e ∈ ps) {g : Nat} (hg : g ∈ e.keys2) :\n skFresh s g = true ∧ (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains g = false\n ∧ occC g s.f.m.pre = false ∧ (∀ p ∈ s.f.m.init, occE g p.2 = false) ∧ (∀ e' ∈ ps, occC g e'.law.holds = false ∨ g ∈ e'.keys2)\n ∧ e.law.key ≠ some g := by\n have hk' := (entry_parts (hk e he)).k2\n simp only [key2Ok, List.all_eq_true, Bool.and_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq, Bool.or_eq_true, List.contains_iff_mem] at hk'\n obtain ⟨⟨⟨⟨⟨hkey, hf⟩, hc⟩, hp⟩, hi⟩, hall⟩ := hk' g hg\n exact ⟨hf, by simpa [List.contains_iff_mem] using hc, hp, hi, fun e' he' => (by have := (hall e' he').1; simpa using this), hkey⟩\n\n/-! Variables set at once: a certificate's witnesses -/\n\ndef setAll (X : Nat → Nat) : List Nat → (Nat → Nat) → Nat → Nat\n | [], _ => X\n | v :: vs, f => upd (setAll X vs f) v (f v)\n\ntheorem setAll_at (X : Nat → Nat) (f : Nat → Nat) : ∀ (vs : List Nat) (i : Nat), setAll X vs f i = if i ∈ vs then f i else X i\n | [], i => by simp [setAll]\n | v :: vs, i => by\n simp only [setAll, upd, List.mem_cons]\n by_cases h : i = v\n · subst h; simp\n · rw [setAll_at X f vs i]; simp [h]\n\n-- A state that agrees with X off vs is X with vs set at its values.\ntheorem setAll_self {X Y : Nat → Nat} {vs : List Nat} (h : ∀ i, i ∉ vs → Y i = X i) : setAll X vs Y = Y := by\n funext i; rw [setAll_at]; split\n · rfl\n · rename_i hi; exact (h i hi).symm\n\nstructure WitParts (s : SMachine) (ps : List SEntry) (w : Nat) : Prop where\n fr : FreshParts s w\n pre : occC w s.f.m.pre = false\n laws : ∀ e ∈ ps, occC w e.law.holds = false ∧ e.sk ≠ w ∧ w ∉ e.keys2\n\ntheorem wits_parts {s : SMachine} {ps : List SEntry} {k : CCert} (h : witsOk s ps k = true) : ∀ i ∈ k.insts, WitParts s ps i.wit := by\n intro i hi\n have := List.all_eq_true.mp h i hi\n simp only [Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at this\n exact ⟨mfresh_parts this.1.1, this.1.2, fun e he => ⟨(this.2 e he).1.1, (this.2 e he).1.2, by simpa [List.contains_iff_mem] using (this.2 e he).2⟩⟩\n\ntheorem sNext_setAll {s : SMachine} {vs : List Nat} (hv : ∀ v ∈ vs, FreshParts s v) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat)\n (κ : Nat → Nat → Nat) (f : Nat → Nat) :\n sNext s (setAll ρ vs f) M ι κ = (setAll (sNext s ρ M ι κ).1 vs f, (sNext s ρ M ι κ).2)\n ∧ sView s (setAll ρ vs f) M ι κ = (setAll (sView s ρ M ι κ).1 vs f, (sView s ρ M ι κ).2) := by\n induction vs with\n | nil => simp [setAll]\n | cons v vs ih =>\n obtain ⟨h1, h2⟩ := ih (fun v' hv' => hv v' (List.mem_cons_of_mem _ hv'))\n have F := hv v List.mem_cons_self\n obtain ⟨hN, hV, _⟩ := fresh_parts F.sk F.out (setAll ρ vs f) M ι κ (f v)\n simp only [setAll]\n rw [hN, hV, h1, h2]\n exact ⟨rfl, rfl⟩\n\ntheorem sReq_setAll {s : SMachine} {vs : List Nat} (hv : ∀ v ∈ vs, FreshParts s v) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat)\n (κ : Nat → Nat → Nat) (f : Nat → Nat) : sReq s (setAll ρ vs f) M ι κ = sReq s ρ M ι κ := by\n induction vs with\n | nil => rfl\n | cons v vs ih =>\n have F := hv v List.mem_cons_self\n have o := fresh_out F.out\n simp only [setAll]\n rw [sReq_upd o.2.2.2.2.1 o.2.2.2.2.2.1 (skFresh_parts F.sk).2.1, ih (fun v' hv' => hv v' (List.mem_cons_of_mem _ hv'))]\n\ntheorem withExt_upd {s : SMachine} {g : Nat} (hg : g ∉ s.extVars) (ρ R : Nat → Nat) (w : Nat) : withExt s (upd ρ g w) R = upd (withExt s ρ R) g w := by\n funext i\n simp only [withExt, upd]\n by_cases h : i = g\n · subst h; simp [List.contains_iff_mem, hg]\n · simp [h]\n\ntheorem withExt_setAll {s : SMachine} {vs : List Nat} (hv : ∀ v ∈ vs, v ∉ s.extVars) (ρ R : Nat → Nat) (f : Nat → Nat) :\n withExt s (setAll ρ vs f) R = setAll (withExt s ρ R) vs f := by\n induction vs with\n | nil => rfl\n | cons v vs ih =>\n simp only [setAll]\n rw [withExt_upd (hv v List.mem_cons_self), ih (fun v' hv' => hv v' (List.mem_cons_of_mem _ hv'))]\n\ntheorem applyS_setAll {σ : List (Nat × E)} {vs : List Nat} (hv : ∀ v ∈ vs, v ∉ σ.map (·.1) ∧ ∀ p ∈ σ, occE v p.2 = false)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (f : Nat → Nat) : applyS σ (setAll ρ vs f) M = setAll (applyS σ ρ M) vs f := by\n induction vs with\n | nil => rfl\n | cons v vs ih =>\n simp only [setAll]\n rw [applyS_upd (hv v List.mem_cons_self).1 (by simpa [List.all_eq_true] using (hv v List.mem_cons_self).2),\n ih (fun v' hv' => hv v' (List.mem_cons_of_mem _ hv'))]\n\ntheorem sentry_setAll {e : SEntry} {vs : List Nat} (hv : ∀ v ∈ vs, occC v e.law.holds = false) {ρ : Nat → Nat} {M : Nat → Nat → Nat} (f : Nat → Nat) :\n e.Holds ρ M → e.Holds (setAll ρ vs f) M := by\n induction vs with\n | nil => exact id\n | cons v vs ih =>\n intro h\n simp only [setAll]\n exact sentry_upd (Or.inl (hv v List.mem_cons_self)) (f v) (ih (fun v' hv' => hv v' (List.mem_cons_of_mem _ hv')) h)\n\n/-! Maps read off a list's names -/\n\n-- A map with the names a declaration list posts at its post counts.\ndef atPosts (ds : List CDecl) (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) : Nat → Nat → Nat := fun mp =>\n match lookup (fun d => d.post == mp) ds with\n | some d => F d\n | none => N mp\n\ntheorem atPosts_other {ds : List CDecl} {mp : Nat} (h : mp ∉ cPosts ds) (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) : atPosts ds F N mp = N mp := by\n simp only [atPosts]\n rw [lookup_none (fun d hd => by simp only [beq_eq_false_iff_ne]; intro he; exact h (by rw [← he]; exact List.mem_map_of_mem hd))]\n\ntheorem atPosts_at {ds : List CDecl} (hd : cDistinct (cPosts ds) = true) {d : CDecl} (hm : d ∈ ds) (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) :\n atPosts ds F N d.post = F d := by\n simp only [atPosts]\n have : lookup (fun d' => d'.post == d.post) ds = some d := by\n induction ds with\n | nil => simp at hm\n | cons a as ih =>\n simp only [cPosts, List.map_cons] at hd\n obtain ⟨hna, hd'⟩ := cDistinct_cons hd\n rcases List.mem_cons.mp hm with rfl | hm'\n · simp [lookup]\n · have hne : (a.post == d.post) = false := by\n simp only [beq_eq_false_iff_ne]; intro he; exact hna (by rw [he]; exact List.mem_map_of_mem hm')\n simp only [lookup, hne, Bool.false_eq_true, ite_false]\n exact ih hd' hm'\n rw [this]\n\n-- Renamed, the post counts read as the counts: a count map read by its post name.\ntheorem renM_atPosts {ds : List CDecl} (hd : cDistinct (cMaps ds ++ cPosts ds) = true) (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) :\n ∀ mp, mp ∉ cPosts ds → renM (cren ds) (atPosts ds F N) mp = match lookup (fun d => d.mp == mp) ds with\n | some d => F d\n | none => N mp := by\n obtain ⟨hdm, hdp, hap⟩ := cDistinct_append hd\n intro mp hmp\n simp only [renM]\n have hl : ∀ (ds' : List CDecl), (∀ d ∈ ds', d ∈ ds) → (lookup (fun p => p.1 == mp) (cren ds')).map (·.2) = (lookup (fun d => d.mp == mp) ds').map (·.post) := by\n intro ds' _\n induction ds' with\n | nil => rfl\n | cons a as ih =>\n simp only [cren, List.map_cons, lookup] at ih ⊢\n by_cases ha : a.mp = mp\n · simp [ha]\n · simp only [ha, beq_self_eq_true, beq_iff_eq, ite_false]; exact ih (fun d hd => by simp_all)\n have := hl ds (fun d hd => hd)\n cases h1 : lookup (fun d => d.mp == mp) ds with\n | none =>\n rw [h1] at this\n cases h2 : lookup (fun p => p.1 == mp) (cren ds) with\n | none => simp only []; exact atPosts_other hmp F N\n | some p => rw [h2] at this; simp at this\n | some d =>\n rw [h1] at this\n cases h2 : lookup (fun p => p.1 == mp) (cren ds) with\n | none => rw [h2] at this; simp at this\n | some p =>\n rw [h2] at this\n simp only [Option.map_some, Option.some.injEq] at this\n simp only []\n rw [this]\n exact atPosts_at hdp (lookup_some h1).1 F N\n\n/-! Terms read across a substitution that keeps j and key -/\n\ntheorem assoc_term {σ : List (Nat × E)} {i : Nat} {t : E} (h : assoc σ i = some t) : (i, t) ∈ σ := by\n simp only [assoc, Option.map_eq_some_iff] at h\n obtain ⟨a, ha, rfl⟩ := h\n have ⟨hm, hp⟩ := lookup_some ha\n simp only [beq_iff_eq] at hp\n rw [← hp]; exact hm\n\ntheorem applyS_congrM {σ : List (Nat × E)} {X : List Nat} (h : ∀ p ∈ σ, avoidsMapsE X p.2 = true) (ρ : Nat → Nat) {M M' : Nat → Nat → Nat}\n (hm : ∀ mp, mp ∉ X → M mp = M' mp) : applyS σ ρ M = applyS σ ρ M' := by\n funext i\n simp only [applyS]\n cases ha : assoc σ i with\n | none => rfl\n | some t => exact congrME ρ M M' t (fun mp hmp => hm mp (avoidsMapsE_occ (h _ (assoc_term ha)) hmp))\n\ntheorem applyS_keep (d : CDecl) (σ : List (Nat × E)) (Y : Nat → Nat) (N : Nat → Nat → Nat) (i : Nat) :\n applyS (keepJ d σ) Y N i = if i = d.j ∨ i = d.lo ∨ i = d.key then Y i else applyS σ Y N i := by\n simp only [keepJ, applyS, assoc, lookup, beq_iff_eq]\n by_cases h1 : d.j = i\n · subst h1; simp [evalE]\n · by_cases h2 : d.lo = i\n · subst h2; simp [h1, Ne.symm h1, evalE]\n · by_cases h3 : d.key = i\n · subst h3; simp [h1, h2, Ne.symm h1, Ne.symm h2, evalE]\n · simp [h1, h2, h3, Ne.symm h1, Ne.symm h2, Ne.symm h3]\n\ntheorem avoidsMaps_right {A B : List Nat} {c : C} (h : avoidsMaps (A ++ B) c = true) : avoidsMaps B c = true := by\n simp only [avoidsMaps, List.all_append, Bool.and_eq_true] at h; exact h.2\ntheorem avoidsMapsE_right {A B : List Nat} {e : E} (h : avoidsMapsE (A ++ B) e = true) : avoidsMapsE B e = true := by\n simp only [avoidsMapsE, List.all_append, Bool.and_eq_true] at h; exact h.2\n\n/-! The start -/\n\ntheorem cstart_case (s : SMachine) (ds : List CDecl) (ps : List CEntry) (h : checkCMachine s ds ps = true) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (hM : StartMaps s.f.m M) (h0 : evalC ρ M s.f.m.pre = true) (hfa : ∀ l ∈ s.facts, l.Holds ρ M) (hpf : s.PFacts ρ M) :\n ∀ ce ∈ ps, ce.e.law.Holds (applyS s.f.m.init ρ M) (withCnt ds (applyS s.f.m.init ρ M) M) := by\n have P := cparts h\n have A := apart_parts P.apart\n obtain ⟨_, hdp, _⟩ := cDistinct_append P.dist\n intro ce hce\n obtain ⟨hent, hst, _⟩ := P.entries ce hce\n have E' := entry_parts hent\n have hskI : ce.e.sk ∉ s.f.m.init.map (·.1) := (fresh_out E'.fresh).2.2.1\n let X0 := applyS s.f.m.init ρ M\n let M2 := atPosts ds (fun d => cntOf d X0 M) M\n have hM2 : ∀ mp, mp ∉ cPosts ds → M2 mp = M mp := fun mp h => atPosts_other h _ M\n have hlp : avoidsMaps (cPosts ds) ce.e.law.holds = true := avoidsMaps_right E'.lm\n -- The law at the start reads as the renamed law with the post names at the counts.\n refine holds_transfer (V := []) (MS := cPosts ds) ce.e.law (by simp [avoids]) hlp (fun _ _ => rfl)\n (fun mp hmp => (renM_atPosts P.dist (fun d => cntOf d X0 M) M mp hmp).symm) ?_\n rw [← renLaw_holds]\n refine goalOf_holds (renLaw ds ce.e.law) (by simp only [renLaw, occ_renC]; exact E'.slaw ce.e (List.mem_map_of_mem hce)) X0 M2 (fun v => ?_)\n apply Decidable.byContradiction; intro hn\n -- The start's reads: a declared map's constant, any other map as M2 holds it.\n have hrdS : ∀ (Y : Nat → Nat) mp k, mp ∉ cPosts ds → evalE Y M2 (rdStart s.f.m mp k) = M mp (evalE Y M2 k) := by\n intro Y mp k hmp\n simp only [rdStart]\n split\n · rename_i p hp\n have ⟨hm, hq⟩ := lookup_some hp\n simp only [beq_iff_eq] at hq\n simp only [evalE]; rw [← hq, hM p hm]\n · simp only [evalE]; rw [hM2 mp hmp]\n have hrd2 : ∀ (Y : Nat → Nat) mp k, evalE Y M2 (rdStart s.f.m mp k) = M2 mp (evalE Y M2 k) := by\n intro Y mp k\n simp only [rdStart]\n split\n · rename_i p hp\n have ⟨hm, hq⟩ := lookup_some hp\n simp only [beq_iff_eq] at hq\n have hp1 : p.1 ∉ cPosts ds := fun hc => (A.posts p.1 hc).2.1 (List.mem_map_of_mem hm)\n simp only [evalE]; rw [← hq, hM2 _ hp1, hM p hm]\n · rfl\n have hX0 : applyS s.f.m.init ρ M2 = X0 := applyS_congrM A.init ρ (fun mp hmp => hM2 mp hmp)\n apply mc_sound _ _ _ hst (upd ρ ce.e.sk v) M2\n · -- Each post count: its bound and body, read across the start, are the declaration's at the start state.\n intro d' hd' x\n obtain ⟨d, hdf, rfl⟩ := List.mem_map.mp hd'\n have hd := (List.mem_filter.mp hdf).1\n have D := decl_parts (P.decls d hd)\n obtain ⟨hskB, hskD, hskj, hskk⟩ := D.ent ce.e (List.mem_map_of_mem hce) ce.e.sk List.mem_cons_self\n have hpB : avoidsMapsE (cPosts ds) d.below = true := avoidsMapsE_right D.mB\n have hpD : avoidsMapsE (cPosts ds) d.body = true := avoidsMapsE_right D.mD\n have hkI := (fresh_out D.kf.out).2.2.1\n show M2 d.post x = cntOf (afterDecl s.f.m.init (rdStart s.f.m) d) (upd ρ ce.e.sk v) M2 x\n rw [cntOf_after, show M2 d.post = cntOf d X0 M from atPosts_at hdp hd _ M]\n simp only [cntOf]\n -- reading across the start at Y (the goal's state with the parameters, and key, set): the start state with them set\n have hacross : ∀ (Y T : Nat → Nat) (e : E), avoidsMapsE (cPosts ds) e = true → occE ce.e.sk e = false →\n (∀ i, i ≠ d.j → i ≠ d.lo → i ≠ d.key → Y i = upd ρ ce.e.sk v i) → T d.j = Y d.j → T d.lo = Y d.lo → T d.key = Y d.key →\n (∀ i, i ≠ d.j → i ≠ d.lo → i ≠ d.key → T i = X0 i) →\n evalE Y M2 (substRE (keepJ d s.f.m.init) (rdStart s.f.m) e) = evalE T M e := by\n intro Y T e hpe hske hY hTj hTl hTk hT\n rw [substR_evalE_on _ _ Y M2 M (cPosts ds) (fun mp k hmp => hrdS Y mp k hmp) e hpe]\n refine congrE _ _ M e (fun i hi => ?_)\n rw [applyS_keep]\n by_cases h1 : i = d.j\n · subst h1; simp [hTj]\n · by_cases h1' : i = d.lo\n · subst h1'; simp [hTl]\n · by_cases h2 : i = d.key\n · subst h2; simp [hTk]\n · rw [if_neg (by simp [h1, h1', h2])]\n have hik : i ≠ ce.e.sk := fun h' => by rw [h', hske] at hi; cases hi\n rw [hT i h1 h1' h2, ← hX0]\n simp only [applyS]\n cases ha : assoc s.f.m.init i with\n | none => simp [hY i h1 h1' h2, upd, hik]\n | some t =>\n have hmem := assoc_term ha\n refine congrE _ _ M2 t (fun i' hi' => ?_)\n have hi'j : i' ≠ d.j := fun h' => by rw [h', D.jf.init _ hmem] at hi'; cases hi'\n have hi'l : i' ≠ d.lo := fun h' => by rw [h', D.lf.init _ hmem] at hi'; cases hi'\n have hi'k : i' ≠ d.key := fun h' => by rw [h', D.kf.init _ hmem] at hi'; cases hi'\n have hi's : i' ≠ ce.e.sk := fun h' => by rw [h', E'.sinit _ hmem] at hi'; cases hi'\n rw [hY i' hi'j hi'l hi'k]; simp [upd, hi's]\n have hkey : X0 d.key = upd ρ ce.e.sk v d.key := by\n show applyS s.f.m.init ρ M d.key = upd ρ ce.e.sk v d.key\n simp only [upd, if_neg (Ne.symm hskk)]; exact applyS_other hkI ρ M\n have hB := hacross (atJ d (upd ρ ce.e.sk v) x) (atJ d X0 x) d.below hpB hskB\n (fun i h1 h2 _ => by simp [atJ, upd, h1, h2])\n (atJ_congr d x d.j (fun h _ => absurd rfl h)) (atJ_congr d x d.lo (fun _ h => absurd rfl h))\n (atJ_congr d x d.key (fun _ _ => hkey))\n (fun i h1 h2 _ => by simp [atJ, upd, h1, h2])\n rw [hB]\n refine sumBelow_congr _ (fun k _ => ?_)\n exact (hacross (upd (atJ d (upd ρ ce.e.sk v) x) d.key k) (upd (atJ d X0 x) d.key k) d.body hpD hskD\n (fun i h1 h2 h3 => by simp [atJ, upd, h1, h2, h3])\n (by simp only [upd, if_neg D.jk]; exact atJ_congr d x d.j (fun h _ => absurd rfl h))\n (by simp only [upd, if_neg D.lk]; exact atJ_congr d x d.lo (fun _ h => absurd rfl h))\n (by simp [upd]) (fun i h1 h2 h3 => by simp [atJ, upd, h1, h2, h3])).symm\n · -- The goal's hypotheses, wherever the witnesses are.\n have Wt := wits_parts (P.wits ce hce).1\n intro ρw hρw c hc\n have hw : ∀ i, (∀ i' ∈ ce.start.insts, i'.wit ≠ i) → i ≠ ce.e.sk → ρw i = ρ i := fun i hi hik => by\n rw [hρw i hi]; simp [upd, hik]\n have hwsk : ρw ce.e.sk = v := by\n rw [hρw ce.e.sk (fun i hi he => (Wt i hi).laws ce.e (List.mem_map_of_mem hce) |>.2.1 he.symm)]; simp [upd]\n simp only [cStartGoal, sStartGoal, List.mem_append, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hc\n rcases hc with (rfl | hc) | rfl\n · rw [noReadsC _ M2 M s.f.m.pre P.preR, congrC _ ρ M s.f.m.pre (fun i hi => hw i\n (fun i' hi' he => by rw [← he, (Wt i' hi').pre] at hi; cases hi)\n (fun h' => by rw [h', E'.spre] at hi; cases hi))]\n exact h0\n · exact facthyps_true s ce.e.finsts ce.e.pfinsts _ M2 (fun f hf => (pfactsOk_parts P.facts f hf).2.2)\n (facts_frame s P.facts (ce.e.sk :: ce.start.insts.map (·.wit)) (cPosts ds)\n (fun l hl => by\n simp only [avoids, List.all_cons, List.all_map, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true']\n exact ⟨(skFresh_parts E'.skf).2.2.2.2.2.2 l hl, fun i hi => by simp [(skFresh_parts (Wt i hi).fr.sk).2.2.2.2.2.2 l hl]⟩) A.facts\n (fun i _ hik => hw i (fun i' hi' he => hik (List.mem_cons_of_mem _ (List.mem_map.mpr ⟨i', hi', he⟩))) (fun h' => hik (h' ▸ List.mem_cons_self)))\n (fun mp _ hmp => hM2 mp hmp) hfa)\n (pfacts_frame s P.facts (ce.e.sk :: ce.start.insts.map (·.wit)) (cPosts ds)\n (fun f hf => by\n simp only [avoids, List.all_cons, List.all_map, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true']\n exact ⟨skFresh_pfacts E'.skf f hf, fun i hi => by simp [skFresh_pfacts (Wt i hi).fr.sk f hf]⟩) A.pfacts\n (fun i _ hik => hw i (fun i' hi' he => hik (List.mem_cons_of_mem _ (List.mem_map.mpr ⟨i', hi', he⟩))) (fun h' => hik (h' ▸ List.mem_cons_self)))\n (fun mp _ hmp => hM2 mp hmp) hpf) c hc\n · simp only [evalC, substR_evalC _ _ _ M2 M2 (hrd2 ρw)]\n have hρw' : ρw = setAll (upd ρ ce.e.sk v) (ce.start.insts.map (·.wit)) ρw := (setAll_self (fun i hi => by\n rw [hρw i (fun i' hi' he => hi (List.mem_map.mpr ⟨i', hi', he⟩))])).symm\n rw [hρw', applyS_setAll (fun w hw' => by\n obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hw'\n exact ⟨(fresh_out (Wt i hi).fr.out).2.2.1, (Wt i hi).fr.init⟩),\n applyS_upd hskI (by simpa [List.all_eq_true] using E'.sinit), hX0]\n rw [goalOf_agree (renLaw ds ce.e.law) ce.e.sk M2 (X' := upd X0 ce.e.sk v)\n (by rw [setAll_at]; split\n · rename_i hm; obtain ⟨i, hi, he⟩ := List.mem_map.mp hm\n exact absurd he.symm ((Wt i hi).laws ce.e (List.mem_map_of_mem hce)).2.1\n · rfl)\n (fun i hi => by\n rw [setAll_at]; split\n · rename_i hm; obtain ⟨i', hi', he⟩ := List.mem_map.mp hm\n have := ((Wt i' hi').laws ce.e (List.mem_map_of_mem hce)).1\n simp only [renLaw, occ_renC] at hi; rw [← he, this] at hi; cases hi\n · rfl)]\n simpa using hn\n\n/-! A state with the post names set: the machine reads them nowhere -/\n\ntheorem withCarried_posts {s : SMachine} {ds : List CDecl} (hpc : ∀ mp ∈ cPosts ds, mp ∉ s.carried) (F : CDecl → Nat → Nat)\n (M κ : Nat → Nat → Nat) : withCarried s (atPosts ds F M) κ = atPosts ds F (withCarried s M κ) := by\n funext mp\n by_cases hmp : mp ∈ cPosts ds\n · have hc : mp ∉ s.carried := hpc mp hmp\n have e1 : withCarried s (atPosts ds F M) κ mp = atPosts ds F M mp := by simp [withCarried, List.contains_iff_mem, hc]\n have e2 : withCarried s M κ mp = M mp := by simp [withCarried, List.contains_iff_mem, hc]\n rw [e1]\n cases hl : lookup (fun d => d.post == mp) ds with\n | none => simp only [atPosts, hl]; exact e2.symm\n | some d => simp only [atPosts, hl]\n · rw [atPosts_other hmp]; simp only [withCarried]; split\n · rfl\n · exact atPosts_other hmp F M\n\ntheorem posts_evalC {ds : List CDecl} {c : C} (h : avoidsMaps (cPosts ds) c = true) (X : Nat → Nat) (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) :\n evalC X (atPosts ds F N) c = evalC X N c :=\n congrMC X _ N c (fun mp hm => atPosts_other (avoidsMaps_occ h hm) F N)\ntheorem posts_evalE {ds : List CDecl} {e : E} (h : avoidsMapsE (cPosts ds) e = true) (X : Nat → Nat) (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) :\n evalE X (atPosts ds F N) e = evalE X N e :=\n congrME X _ N e (fun mp hm => atPosts_other (avoidsMapsE_occ h hm) F N)\n\ntheorem decideQ_posts {s : SMachine} {ds : List CDecl} (hq : ∀ q ∈ s.qflags, avoidsMaps (cPosts ds) q.2.2 = true) (X : Nat → Nat)\n (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) : decideQ s X (atPosts ds F N) = decideQ s X N := by\n funext v\n simp only [decideQ]\n split\n · rename_i q hl\n have hb := hq q (lookup_some hl).1\n have : (∀ k, holdsC (atKeys X q.2.1 k) (atPosts ds F N) q.2.2) ↔ (∀ k, holdsC (atKeys X q.2.1 k) N q.2.2) := by\n simp only [← evalC_iff, posts_evalC hb]\n simp only [this]\n · rfl\n\ntheorem decideFlags_posts {fl : List (Nat × C)} {ds : List CDecl} (hf : ∀ p ∈ fl, avoidsMaps (cPosts ds) p.2 = true) (X : Nat → Nat)\n (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) : decideFlags fl X (atPosts ds F N) = decideFlags fl X N :=\n applyS_congrM (X := cPosts ds) (fun p hp => by\n obtain ⟨q, hq, rfl⟩ := List.mem_map.mp hp\n have := hf q hq\n simp only [avoidsMapsE, avoidsMaps, List.all_eq_true, Bool.not_eq_true'] at this ⊢\n intro mp hm; simp [occME, this mp hm]) X (fun mp hmp => atPosts_other hmp F N)\n\ntheorem sView_posts {s : SMachine} {ds : List CDecl} (A : ApartParts s ds) (F : CDecl → Nat → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) : sView s ρ (atPosts ds F M) ι κ = ((sView s ρ M ι κ).1, atPosts ds F (sView s ρ M ι κ).2) := by\n simp only [sView, withCarried_posts (fun mp hm => (A.posts mp hm).1), decideQ_posts A.qflags, decideFlags_posts A.flags]\n\ntheorem sNext_posts {s : SMachine} {ds : List CDecl} (A : ApartParts s ds) (F : CDecl → Nat → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) : sNext s ρ (atPosts ds F M) ι κ = ((sNext s ρ M ι κ).1, atPosts ds F (sNext s ρ M ι κ).2) := by\n simp only [sNext, sView_posts A]\n congr 1\n · exact applyS_congrM A.step _ (fun mp hmp => atPosts_other hmp F _)\n · funext mp key\n by_cases hmp : mp ∈ cPosts ds\n · have he : lookup (fun w => w.1 == mp) s.every = none := lookup_none (fun w hw => by\n simp only [beq_eq_false_iff_ne]; intro h'; exact (A.posts mp hmp).2.2.1 (by rw [← h']; exact List.mem_map_of_mem hw))\n have hw : lookup (fun w : Nat × E × E => w.1 == mp) s.f.m.writes = none := lookup_none (fun w hw => by\n simp only [beq_eq_false_iff_ne]; intro h'; exact (A.posts mp hmp).2.2.2 (by rw [← h']; exact List.mem_map_of_mem hw))\n have hE : everyMaps s (sView s ρ M ι κ).1 (atPosts ds F (sView s ρ M ι κ).2) mp key = atPosts ds F (sView s ρ M ι κ).2 mp key := by\n simp only [everyMaps, he, writeMaps, hw]\n have hE' : everyMaps s (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 mp key = (sView s ρ M ι κ).2 mp key := by\n simp only [everyMaps, he, writeMaps, hw]\n rw [hE]\n cases hl : lookup (fun d => d.post == mp) ds with\n | none => simp only [atPosts, hl]; exact hE'.symm\n | some d => simp only [atPosts, hl]\n · rw [atPosts_other hmp]\n simp only [everyMaps]\n split\n · rename_i w hw\n exact posts_evalE (A.every w (lookup_some hw).1) _ F _\n · simp only [writeMaps]\n split\n · rename_i w hw\n have ⟨h1, h2⟩ := A.writes w (lookup_some hw).1\n rw [posts_evalE h1, posts_evalE h2, atPosts_other hmp]\n · rw [atPosts_other hmp]\n\ntheorem sReq_posts {s : SMachine} {ds : List CDecl} (A : ApartParts s ds) (F : CDecl → Nat → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) : sReq s ρ (atPosts ds F M) ι κ = sReq s ρ M ι κ := by\n funext v\n simp only [sReq, withCarried_posts (fun mp hm => (A.posts mp hm).1), decideQ_posts A.qflags]\n split\n · rfl\n · split\n · rfl\n · split\n · split\n · rename_i q hq'\n split\n · apply congrFun\n apply witnessKeys_congr\n intro k\n simp only [← evalC_iff, posts_evalC (A.qflags q (lookup_some hq').1)]\n · rfl\n · rfl\n · rfl\n\n/-! One step's frame, at any state (Sets.lean's sstep_case builds the same) -/\n\ntheorem cframe {s : SMachine} (hs : sOk s = true) (hterms : sTermsOk s (flagVars s.f.flags) = true) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) :\n (∀ Z, SHead s Z [] (withExt s ρ (sReq s ρ M ι κ)) (withCarried s M κ) [] getRd ρ M [] [] ι κ)\n ∧ SDenotes s (flagVars s.f.flags) [] (withExt s ρ (sReq s ρ M ι κ)) (withCarried s M κ)\n (stepSub s.f (frameSub [] []) (frameRd [] getRd)) (stepRdS s (frameSub [] []) (frameRd [] getRd)) (sNext s ρ M ι κ).1 (sNext s ρ M ι κ).2 := by\n obtain ⟨hfav, hstp, hwr, hev⟩ := sTermsOk_parts hterms\n let W := withExt s ρ (sReq s ρ M ι κ)\n let M0 := withCarried s M κ\n have hH : ∀ Z, SHead s Z [] W M0 [] getRd ρ M [] [] ι κ := fun Z => by\n refine ⟨fun i _ => ?_, fun mp k _ => ?_⟩\n · show applyS (frameSub [] []) W M0 i = W i\n simp only [frameSub, List.map_nil, List.append_nil, applyS_nil']\n · simp [frameRd, getRd, lookup, evalE, M0]\n have hD : SDenotes s (flagVars s.f.flags) [] W M0 [] getRd ρ M := by\n refine ⟨fun i hie _ => ?_, fun mp k hmp _ => ?_⟩\n · rw [applyS_nil']; simp only [W, withExt]; rw [if_neg (by simpa [List.contains_iff_mem] using hie)]\n · simp only [getRd, evalE, M0, withCarried]; rw [if_neg (by simpa [List.contains_iff_mem] using hmp)]\n exact ⟨hH, sstep_denotes s (flagVars s.f.flags) [] W M0 hs (fun v hv => hv) hfav [] [] ι κ hD (hH _) (fun p hp => by simp at hp)\n hstp (fun w hw => (hwr w hw).1) hev (fun _ _ => by simp [avoidsMapsE]) (fun _ _ => by simp [avoidsMapsE]) (fun _ _ => by simp [avoidsMapsE])⟩\n\n/-! Terms across a step that keeps the parameters and key -/\n\n-- A term of the state read across the step, the parameters and key kept: its value at the state after the step, where\n-- the frame reads them as the state after it does.\ntheorem across_step {s : SMachine} (hs : sOk s = true) (hterms : sTermsOk s (flagVars s.f.flags) = true) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) (d : CDecl) (e : E) (he : avoidsE (s.extVars ++ flagVars s.f.flags) e = true)\n (hem : avoidsMapsE s.carried e = true)\n (hj : (sNext s ρ M ι κ).1 d.j = withExt s ρ (sReq s ρ M ι κ) d.j) (hl : (sNext s ρ M ι κ).1 d.lo = withExt s ρ (sReq s ρ M ι κ) d.lo)\n (hk : (sNext s ρ M ι κ).1 d.key = withExt s ρ (sReq s ρ M ι κ) d.key) :\n evalE (withExt s ρ (sReq s ρ M ι κ)) (withCarried s M κ)\n (substRE (keepJ d (stepSub s.f (frameSub [] []) (frameRd [] getRd))) (stepRdS s (frameSub [] []) (frameRd [] getRd)) e)\n = evalE (sNext s ρ M ι κ).1 (sNext s ρ M ι κ).2 e := by\n obtain ⟨_, hD⟩ := cframe hs hterms ρ M ι κ\n rw [substR_evalE_on _ _ _ _ (sNext s ρ M ι κ).2 s.carried (fun mp k hmp => hD.2 mp k hmp (by simp)) e hem]\n refine congrE _ _ _ e (fun i hi => ?_)\n rw [applyS_keep]\n by_cases h1 : i = d.j\n · subst h1; simp [hj]\n · by_cases h1' : i = d.lo\n · subst h1'; simp [hl]\n · by_cases h2 : i = d.key\n · subst h2; simp [hk]\n · rw [if_neg (by simp [h1, h1', h2])]\n have hx := avoidsE_occ he hi\n exact hD.1 i (fun h => hx (List.mem_append_left _ h)) (fun h => hx (List.mem_append_right _ h))\n\n-- Two reads of a count agree where its bound and body read alike.\ntheorem cntOf_congr (d : CDecl) (hkB : occE d.key d.below = false) {X X' : Nat → Nat} {N N' : Nat → Nat → Nat}\n (hv : ∀ i, i ≠ d.j → i ≠ d.lo → i ≠ d.key → occE i d.below = true ∨ occE i d.body = true → X i = X' i)\n (hm : ∀ mp, occME mp d.below = true ∨ occME mp d.body = true → N mp = N' mp) (x : Nat) : cntOf d X N x = cntOf d X' N' x := by\n simp only [cntOf]\n have hB : evalE (atJ d X x) N d.below = evalE (atJ d X' x) N' d.below := by\n rw [congrME _ N N' d.below (fun mp h => hm mp (Or.inl h))]\n exact congrE _ _ _ d.below (fun i hi => atJ_congr d x i (fun h1 h1' => by\n have h2 : i ≠ d.key := fun h => by rw [h, hkB] at hi; cases hi\n exact hv i h1 h1' h2 (Or.inl hi)))\n rw [hB]\n exact sumBelow_congr _ (fun k _ => by\n rw [congrME _ N N' d.body (fun mp h => hm mp (Or.inr h))]\n exact congrE _ _ _ d.body (fun i hi => by\n simp only [upd]\n by_cases h2 : i = d.key\n · simp [h2]\n · simp only [if_neg h2]; exact atJ_congr d x i (fun h1 h1' => hv i h1 h1' h2 (Or.inr hi))))\n\n/-! One step -/\n\n-- A variable no step sets, decides or reads from the request: the state after a step keeps it.\ntheorem sNext_other {s : SMachine} {x : Nat} (h : (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains x = false)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat) : (sNext s ρ M ι κ).1 x = ρ x := by\n obtain ⟨_, hF, _, hS, hI, hQ, _⟩ := fresh_out h\n simp only [sNext, sView]\n rw [applyS_other hS, decide_other hF]\n simp only [decideQ]\n rw [lookup_none (fun q hq => by\n simp only [beq_eq_false_iff_ne]; intro he\n exact hQ (by simp only [SMachine.qVars, List.mem_map]; exact ⟨q, hq, he⟩))]\n exact withInputs_other hI ρ ι\n\ntheorem avoids_left {A B : List Nat} {c : C} (h : avoids (A ++ B) c = true) : avoids A c = true := by\n simp only [avoids, List.all_append, Bool.and_eq_true] at h; exact h.1\ntheorem cstep_case (s : SMachine) (ds : List CDecl) (ps : List CEntry) (h : checkCMachine s ds ps = true) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) (hp0 : evalC ρ M s.f.m.pre = true) (hfa : ∀ l ∈ s.facts, l.Holds ρ M) (hpf : s.PFacts ρ M)\n (ih : ∀ ce ∈ ps, ce.e.Holds ρ (withCnt ds ρ M)) (hG : GHolds ds (withInputs s.f.m.inputs ρ ι) (withCarried s M κ))\n (ha : evalC (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 s.f.m.assume = true) :\n ∀ ce ∈ ps, ce.e.law.Holds (sNext s ρ M ι κ).1 (withCnt ds (sNext s ρ M ι κ).1 (sNext s ρ M ι κ).2) := by\n have P := cparts h\n have A := apart_parts P.apart\n have hs := P.sok\n obtain ⟨hdm, hdp, hap⟩ := cDistinct_append P.dist\n have hentry : ∀ e ∈ ps.map (·.e), cEntryOk s ds (ps.map (·.e)) e = true := fun e he => by\n obtain ⟨ce, hce, rfl⟩ := List.mem_map.mp he; exact (P.entries ce hce).1\n have hkk : ∀ e ∈ ps.map (·.e), ∀ k, e.law.key = some k → k ∉ e.keys2 := fun e he k hk hg => (key2_parts hentry he hg).2.2.2.2.2 hk\n intro ce hce\n obtain ⟨hent, _, hstep⟩ := P.entries ce hce\n have E' := entry_parts hent\n have hsk := fresh_out E'.fresh\n let Nx := sNext s ρ M ι κ\n let F : CDecl → Nat → Nat := fun d => cntOf d Nx.1 Nx.2\n let M' := atPosts ds F M\n have hNx' : sNext s ρ M' ι κ = (Nx.1, atPosts ds F Nx.2) := sNext_posts A F ρ M ι κ\n have hpc : ∀ mp ∈ cPosts ds, mp ∉ s.carried := fun mp hm => (A.posts mp hm).1\n let Mq := withCarried s (atPosts ds F Nx.2) κ\n have hMq : Mq = atPosts ds F (withCarried s Nx.2 κ) := withCarried_posts hpc F Nx.2 κ\n -- The maps a law reads count maps of the state in: those the request carries but those, and the post names.\n let MS := s.carried.filter (fun mp => !(stateMaps s ds).contains mp) ++ cPosts ds\n have hMS : ∀ mp, mp ∉ MS → mp ∈ s.carried → ∃ d ∈ ds, d.mp = mp ∧ stateOnly s d = true := by\n intro mp hmp hc\n have : (stateMaps s ds).contains mp = true := by\n apply Classical.byContradiction; intro hn\n exact hmp (List.mem_append_left _ (List.mem_filter.mpr ⟨hc, by simpa using hn⟩))\n obtain ⟨d, hd, hdmp⟩ := List.mem_map.mp (List.contains_iff_mem.mp this)\n exact ⟨d, (List.mem_filter.mp hd).1, hdmp, (List.mem_filter.mp hd).2⟩\n have hnotP : ∀ mp, mp ∉ MS → mp ∉ cPosts ds := fun mp hmp h' => hmp (List.mem_append_right _ h')\n -- A state count read at the view is the count at the state.\n have hview : ∀ d ∈ ds, stateOnly s d = true → ∀ x, κ d.mp x = cntOf d ρ M x := by\n intro d hd hso x\n have hc : d.mp ∈ s.carried := (decl_parts (P.decls d hd)).carried\n have := hG d hd x\n simp only [withCarried, List.contains_iff_mem.mpr hc, ite_true] at this\n rw [this]\n simp only [stateOnly, Bool.and_eq_true] at hso\n obtain ⟨⟨⟨hvB, hvD⟩, hmB⟩, hmD⟩ := hso\n refine cntOf_congr d (decl_parts (P.decls d hd)).kB (fun i _ _ _ hi => ?_) (fun mp hm => ?_) x\n · have hx : i ∉ s.extVars := fun h' => by\n rcases hi with hi | hi\n · exact avoidsE_occ hvB hi (List.mem_append_left _ h')\n · exact avoidsE_occ hvD hi (List.mem_append_left _ h')\n exact withInputs_other (fun h' => hx (by simp only [SMachine.extVars, List.mem_append]; exact Or.inl (Or.inl h'))) ρ ι\n · have hx : mp ∉ s.carried := by\n rcases hm with hm | hm\n · exact avoidsMapsE_occ hmB hm\n · exact avoidsMapsE_occ hmD hm\n simp [withCarried, List.contains_iff_mem, hx]\n -- The law after the step: the renamed law, with the post names at the counts after it.\n refine holds_transfer (V := []) (MS := MS) (M' := renM (cren ds) Mq) ce.e.law (by simp [avoids]) E'.lm (fun _ _ => rfl) (fun mp hmp => ?_) ?_\n · rw [hMq, renM_atPosts P.dist F _ mp (hnotP mp hmp)]\n simp only [withCnt]\n cases hl : lookup (fun d => d.mp == mp) ds with\n | some d => rfl\n | none =>\n have hnc : mp ∉ s.carried := fun hc => by\n obtain ⟨d, hd, hdmp, _⟩ := hMS mp hmp hc\n have := lookup_none_all hl d hd\n simp [hdmp] at this\n show (sNext s ρ M ι κ).2 mp = withCarried s (sNext s ρ M ι κ).2 κ mp\n simp [withCarried, List.contains_iff_mem, hnc]\n rw [← renLaw_holds]\n refine goalOf_holds (renLaw ds ce.e.law) (by simp only [renLaw, occ_renC]; exact E'.slaw ce.e (List.mem_map_of_mem hce)) Nx.1 Mq (fun v => ?_)\n apply Decidable.byContradiction; intro hn\n obtain ⟨hNext, hView, _⟩ := fresh_parts E'.skf E'.fresh ρ M' ι κ v\n let ρ' := upd ρ ce.e.sk v\n let W := withExt s ρ' (sReq s ρ' M' ι κ)\n let M0 := withCarried s M' κ\n obtain ⟨hH, hD'⟩ := cframe hs P.terms ρ' M' ι κ\n have hM0 : ∀ mp, mp ∉ cPosts ds → M0 mp = withCarried s M κ mp := fun mp hmp => by\n show withCarried s M' κ mp = _\n rw [withCarried_posts hpc F M κ, atPosts_other hmp]\n apply mc_sound _ _ _ hstep W M0\n · -- The counts the goal declares.\n intro d' hd' x\n rcases List.mem_append.mp hd' with hd | hd'\n · -- before the step: the request's count at its view\n have D := decl_parts (P.decls d' hd)\n obtain ⟨hskB, hskD, _, _⟩ := D.ent ce.e (List.mem_map_of_mem hce) ce.e.sk List.mem_cons_self\n rw [hM0 d'.mp (fun h' => hap d'.mp (List.mem_map_of_mem hd) h'), hG d' hd x]\n refine cntOf_congr d' D.kB (fun i _ _ _ hi => ?_) (fun mp hm => ?_) x\n · show withInputs s.f.m.inputs ρ ι i = withExt s ρ' (sReq s ρ' M' ι κ) i\n have hq : i ∉ s.qVars ++ s.wVars := by\n rcases hi with hi | hi\n · exact fun h' => avoidsE_occ D.qwB hi (List.mem_append_left _ h')\n · exact fun h' => avoidsE_occ D.qwD hi (List.mem_append_left _ h')\n have hik : i ≠ ce.e.sk := fun h' => by rcases hi with hi | hi <;> (rw [h'] at hi; simp_all)\n simp only [withExt]\n by_cases hie : s.extVars.contains i = true\n · simp only [hie, ite_true, sReq]\n have hin : s.f.m.inputs.contains i = true := by\n simp only [SMachine.extVars, List.contains_iff_mem, List.mem_append] at hie\n rcases hie with (h1 | h1) | h1\n · exact List.contains_iff_mem.mpr h1\n · exact absurd (List.mem_append_left _ h1) hq\n · exact absurd (List.mem_append_right _ h1) hq\n simp only [hin, ite_true, withInputs]\n · simp only [hie, Bool.false_eq_true, ite_false]\n have hin : i ∉ s.f.m.inputs := by\n simp only [SMachine.extVars, List.contains_iff_mem, List.mem_append, not_or] at hie\n exact hie.1.1\n rw [withInputs_other hin]\n simp [ρ', upd, hik]\n · have hx : mp ∉ cPosts ds := by\n rcases hm with hm | hm\n · exact fun h' => avoidsMapsE_occ D.mB hm (List.mem_append_right _ h')\n · exact fun h' => avoidsMapsE_occ D.mD hm (List.mem_append_right _ h')\n exact (hM0 mp hx).symm\n · -- after the step: a state count read across it\n obtain ⟨d, hdf, rfl⟩ := List.mem_map.mp hd'\n have hd := (List.mem_filter.mp hdf).1\n have hso := (List.mem_filter.mp hdf).2\n have D := decl_parts (P.decls d hd)\n obtain ⟨hskB, hskD, _, hskk⟩ := D.ent ce.e (List.mem_map_of_mem hce) ce.e.sk List.mem_cons_self\n simp only [stateOnly, Bool.and_eq_true] at hso\n obtain ⟨⟨⟨hvB, hvD⟩, hmB⟩, hmD⟩ := hso\n have hjo := fresh_out D.jf.out\n have hlo := fresh_out D.lf.out\n have hko := fresh_out D.kf.out\n have hpB : avoidsMapsE (cPosts ds) d.below = true := avoidsMapsE_right D.mB\n have hpD : avoidsMapsE (cPosts ds) d.body = true := avoidsMapsE_right D.mD\n show M0 d.post x = cntOf (afterDecl _ _ d) W M0 x\n rw [cntOf_after, show M0 d.post = F d from by\n show withCarried s M' κ d.post = F d\n rw [withCarried_posts hpc F M κ]; exact atPosts_at hdp hd F _]\n -- reading a term of the state across the step at a state with fresh variables set: its value after the step there\n have hacross : ∀ (ρx : Nat → Nat) (Y : Nat → Nat) (e : E), avoidsE (s.extVars ++ flagVars s.f.flags) e = true → avoidsMapsE s.carried e = true →\n avoidsMapsE (cPosts ds) e = true →\n withExt s ρx (sReq s ρx M' ι κ) = Y →\n (sNext s ρx M' ι κ).1 d.j = Y d.j → (sNext s ρx M' ι κ).1 d.lo = Y d.lo → (sNext s ρx M' ι κ).1 d.key = Y d.key →\n (sNext s ρx M' ι κ).2 = atPosts ds F Nx.2 →\n evalE Y M0 (substRE (keepJ d (stepSub s.f (frameSub [] []) (frameRd [] getRd)))\n (stepRdS s (frameSub [] []) (frameRd [] getRd)) e) = evalE (sNext s ρx M' ι κ).1 Nx.2 e := by\n intro ρx Y e he hem hpe hY hj hl hk hM\n have := across_step hs P.terms ρx M' ι κ d e he hem (by rw [hj, hY]) (by rw [hl, hY]) (by rw [hk, hY])\n rw [hY, hM] at this\n rw [this, posts_evalE hpe]\n -- the state with the parameters at x (the bound), and with key at k too (the body)\n have hsj : sReq s (atJ d ρ' x) M' ι κ = sReq s ρ' M' ι κ := by\n simp only [atJ]\n rw [sReq_upd hlo.2.2.2.2.1 hlo.2.2.2.2.2.1 (skFresh_parts D.lf.sk).2.1, sReq_upd hjo.2.2.2.2.1 hjo.2.2.2.2.2.1 (skFresh_parts D.jf.sk).2.1]\n have hsk : ∀ k, sReq s (upd (atJ d ρ' x) d.key k) M' ι κ = sReq s ρ' M' ι κ := fun k => by\n rw [sReq_upd hko.2.2.2.2.1 hko.2.2.2.2.2.1 (skFresh_parts D.kf.sk).2.1, hsj]\n have hWj : withExt s (atJ d ρ' x) (sReq s ρ' M' ι κ) = atJ d W x := by\n simp only [atJ]; rw [withExt_upd hlo.1, withExt_upd hjo.1]\n have hNj : sNext s (atJ d ρ' x) M' ι κ = (atJ d (upd Nx.1 ce.e.sk v) x, atPosts ds F Nx.2) := by\n simp only [atJ]\n rw [(fresh_parts D.lf.sk D.lf.out _ M' ι κ _).1, (fresh_parts D.jf.sk D.jf.out _ M' ι κ _).1, hNext, hNx']\n have hNk : ∀ k, sNext s (upd (atJ d ρ' x) d.key k) M' ι κ = (upd (atJ d (upd Nx.1 ce.e.sk v) x) d.key k, atPosts ds F Nx.2) := fun k => by\n rw [(fresh_parts D.kf.sk D.kf.out _ M' ι κ k).1, hNj]\n have hkey : upd (sNext s ρ M ι κ).1 ce.e.sk v d.key = withExt s ρ' (sReq s ρ' M' ι κ) d.key := by\n simp only [upd, if_neg (Ne.symm hskk)]\n rw [sNext_other D.kf.out]; simp only [withExt]\n rw [if_neg (by simpa [List.contains_iff_mem] using hko.1)]; simp [ρ', upd, Ne.symm hskk]\n have hB := hacross (atJ d ρ' x) (atJ d W x) d.below hvB hmB hpB\n (by rw [hsj, hWj])\n (by rw [hNj]; exact atJ_congr d x d.j (fun h _ => absurd rfl h))\n (by rw [hNj]; exact atJ_congr d x d.lo (fun _ h => absurd rfl h))\n (by rw [hNj]; exact atJ_congr d x d.key (fun _ _ => hkey))\n (by rw [hNj])\n rw [hB, hNj]\n have hB' : evalE (atJ d (upd Nx.1 ce.e.sk v) x) Nx.2 d.below = evalE (atJ d Nx.1 x) Nx.2 d.below :=\n congrE _ _ _ _ (fun i hi => atJ_congr d x i (fun _ _ => by\n have hik : i ≠ ce.e.sk := fun h' => by rw [h', hskB] at hi; cases hi\n simp [upd, hik]))\n simp only [] at hB' ⊢\n rw [hB']\n refine sumBelow_congr _ (fun k _ => ?_)\n have hD := hacross (upd (atJ d ρ' x) d.key k) (upd (atJ d W x) d.key k) d.body hvD hmD hpD\n (by rw [hsk k, withExt_upd hko.1, hWj])\n (by rw [hNk k]; simp only [upd, if_neg D.jk]; exact atJ_congr d x d.j (fun h _ => absurd rfl h))\n (by rw [hNk k]; simp only [upd, if_neg D.lk]; exact atJ_congr d x d.lo (fun _ h => absurd rfl h))\n (by rw [hNk k]; simp [upd]) (by rw [hNk k])\n rw [hD, hNk k]\n dsimp only\n exact congrE _ _ _ _ (fun i hi => by\n have hik : i ≠ ce.e.sk := fun h' => by rw [h', hskD] at hi; cases hi\n simp only [upd]\n by_cases h2 : i = d.key\n · simp [h2]\n · simp only [if_neg h2]; exact atJ_congr d x i (fun _ _ => by simp [upd, hik]))\n · -- The goal's hypotheses hold where the frame is read, wherever the witnesses are: the state with them set.\n obtain ⟨hfav, hstp, hwr, hev⟩ := sTermsOk_parts P.terms\n have Wt := wits_parts (P.wits ce hce).2\n let ws := ce.step.insts.map (·.wit)\n have hwsF : ∀ w ∈ ws, FreshParts s w := fun w hw => by obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hw; exact (Wt i hi).fr\n have hwsL : ∀ w ∈ ws, ∀ e ∈ ps.map (·.e), occC w e.law.holds = false ∧ e.sk ≠ w := fun w hw e he => by\n obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hw; exact ⟨((Wt i hi).laws e he).1, ((Wt i hi).laws e he).2.1⟩\n have hwsP : ∀ w ∈ ws, occC w s.f.m.pre = false := fun w hw => by obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hw; exact (Wt i hi).pre\n have hskw : ce.e.sk ∉ ws := fun h' => (hwsL _ h' ce.e (List.mem_map_of_mem hce)).2 rfl\n intro ρw hρw c hc\n have hρw' : ∀ i, i ∉ ws → ρw i = W i := fun i hi => hρw i (fun i' hi' he => hi (List.mem_map.mpr ⟨i', hi', he⟩))\n let ρ'' := setAll ρ' ws ρw\n have hext : ∀ w ∈ ws, w ∉ s.extVars := fun w hw => (fresh_out (hwsF w hw).out).1\n have hWw : withExt s ρ'' (sReq s ρ'' M' ι κ) = ρw := by\n rw [sReq_setAll hwsF, withExt_setAll hext]; exact setAll_self hρw'\n obtain ⟨hNw, hVw⟩ := sNext_setAll hwsF ρ' M' ι κ ρw\n obtain ⟨hH2, hD2⟩ := cframe hs P.terms ρ'' M' ι κ\n rw [hWw] at hH2 hD2\n have hρ'' : ∀ i, i ∉ ws → i ≠ ce.e.sk → ρ'' i = ρ i := fun i hi hik => by\n simp only [ρ'']; rw [setAll_at, if_neg hi]; simp [ρ', upd, hik]\n -- (ρw off the request's variables is ρ'')\n have hwx : ∀ i, i ∉ s.extVars → ρw i = ρ'' i := fun i hi => by\n rw [← hWw]; simp only [withExt]; rw [if_neg (by simpa [List.contains_iff_mem] using hi)]\n simp only [cStepGoal, sStepGoal, List.mem_append, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false, List.mem_map] at hc\n rcases hc with ((rfl | hc) | ⟨c', hc', rfl⟩) | rfl\n · rw [noReadsC ρw M0 M s.f.m.pre P.preR, congrC ρw ρ M s.f.m.pre (fun i hi => ?_)]\n · exact hp0\n · have hi1 := avoids_occ P.pre hi\n have hik : i ≠ ce.e.sk := fun h' => by rw [h'] at hi; simp [E'.spre] at hi\n have hiw : i ∉ ws := fun h' => by rw [hwsP i h'] at hi; cases hi\n rw [hwx i (fun h' => hi1 (List.mem_append_left _ (List.mem_append_left _ (List.mem_append_left _ h')))), hρ'' i hiw hik]\n · have hX : ∀ i, i ∉ s.extVars → i ∉ ce.e.sk :: ws → ρw i = ρ i := fun i hie hik => by\n rw [hwx i hie, hρ'' i (fun h' => hik (List.mem_cons_of_mem _ h')) (fun h' => hik (h' ▸ List.mem_cons_self))]\n exact facthyps_true s ce.e.finsts ce.e.pfinsts ρw M0 (fun f hf => (pfactsOk_parts P.facts f hf).2.2)\n (facts_frame s P.facts (ce.e.sk :: ws) (cPosts ds)\n (fun l hl => by\n simp only [avoids, List.all_cons, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true']\n exact ⟨(skFresh_parts E'.skf).2.2.2.2.2.2 l hl, fun w hw => (skFresh_parts (hwsF w hw).sk).2.2.2.2.2.2 l hl⟩) A.facts\n hX (fun mp hmc hmp => by rw [hM0 mp hmp]; simp only [withCarried]; rw [if_neg (by simpa [List.contains_iff_mem] using hmc)]) hfa)\n (pfacts_frame s P.facts (ce.e.sk :: ws) (cPosts ds)\n (fun f hf => by\n simp only [avoids, List.all_cons, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true']\n exact ⟨skFresh_pfacts E'.skf f hf, fun w hw => skFresh_pfacts (hwsF w hw).sk f hf⟩) A.pfacts\n hX (fun mp hmc hmp => by rw [hM0 mp hmp]; simp only [withCarried]; rw [if_neg (by simpa [List.contains_iff_mem] using hmc)]) hpf) c hc\n · have hA : evalC (sView s ρ'' M' ι κ).1 (sView s ρ'' M' ι κ).2 s.f.m.assume = true := by\n rw [hVw, hView]; dsimp only\n rw [sView_posts A F ρ M ι κ]; dsimp only\n rw [posts_evalC A.assume]\n rw [congrC _ (sView s ρ M ι κ).1 _ _ (fun i hi => by\n have hik : i ≠ ce.e.sk := fun h' => by rw [h', (skFresh_parts E'.skf).2.2.1] at hi; cases hi\n have hiw : i ∉ ws := fun h' => by rw [(skFresh_parts (hwsF i h').sk).2.2.1] at hi; cases hi\n rw [setAll_at, if_neg hiw]; simp only [upd, if_neg hik])]\n exact ha\n have hallY : ∀ e' ∈ ps.map (·.e), e'.Holds ρw M0 := fun e' he' => by\n obtain ⟨ce', hce', rfl⟩ := List.mem_map.mp he'\n have E2 := entry_parts (P.entries ce' hce').1\n refine sentry_transfer (V := s.extVars) (MS := MS) (ρ' := ρ'') (avoids_left E2.lx) E2.lm (fun i hi => hwx i hi) (fun mp hmp => ?_)\n (sentry_setAll (fun w hw => (hwsL w hw ce'.e (List.mem_map_of_mem hce')).1) ρw\n (sentry_upd (Or.inl (E'.slaw ce'.e (List.mem_map_of_mem hce'))) v (ih ce' hce')))\n rw [hM0 mp (hnotP mp hmp)]\n by_cases hc : mp ∈ s.carried\n · obtain ⟨d, hd, hdmp, hso⟩ := hMS mp hmp hc\n subst hdmp\n rw [withCnt_at hdm hd]\n funext x\n simp only [withCarried, List.contains_iff_mem.mpr hc, ite_true]\n exact hview d hd hso x\n · rw [withCnt_other (fun h' => by\n obtain ⟨d, hd, hdmp⟩ := List.mem_map.mp h'\n exact hc (by rw [← hdmp]; exact (decl_parts (P.decls d hd)).carried))]\n simp [withCarried, List.contains_iff_mem, hc]\n have hfr := sframe_hyps s [] [] ρw M0 hs (sLaws (ps.map (·.e)) ce.e.pinsts) (sInsts (ps.map (·.e)) ce.e.insts ce.e.pinsts) ce.e.qinsts\n (ρ := ρ'') (M := M') (ι := ι) (κ := κ) (σ := []) (rd := getRd) (r := []) (mr := []) (w := trueC)\n (fun l hl => by\n rw [hWw]\n rcases List.mem_append.mp hl with hl | hl\n · obtain ⟨e', he', rfl⟩ := List.mem_map.mp hl; exact SEntry.holds_law (hallY e' he')\n · exact pairLaws_hold _ ce.e.pinsts hkk hallY l hl)\n (hH2 []) (fun _ _ => by simp [avoids]) (fun _ _ => by simp [avoids]) (fun _ _ => by simp [avoidsMaps]) hA rfl\n exact hfr c' hc'\n · have hrd' : ∀ mp k, evalE ρw M0 (stepRdS s (frameSub [] []) (frameRd [] getRd) mp k) = Mq mp (evalE ρw M0 k) := by\n intro mp k\n by_cases hmp : mp ∈ s.carried\n · have hne : lookup (fun w => w.1 == mp) s.every = none := lookup_none (fun w hw => by\n simp only [beq_eq_false_iff_ne]; intro h'; exact (hev w hw).2.2.2.2.1 (by rw [h']; exact hmp))\n have hnw : lookup (fun w : Nat × E × E => w.1 == mp) s.f.m.writes = none := lookup_none (fun w hw => by\n simp only [beq_eq_false_iff_ne]; intro h'; exact (hwr w hw).2 (by rw [h']; exact hmp))\n simp only [stepRdS, hne, stepRd, hnw]\n simp [frameRd, getRd, lookup, evalE, M0, Mq, withCarried, hmp]\n · rw [hD2.2 mp k hmp (by simp), hNw, hNext]; dsimp only; rw [hNx']\n simp only [Mq, withCarried]; rw [if_neg (by simpa [List.contains_iff_mem] using hmp)]\n simp only [evalC]\n have hpost : ∀ i, i ∉ ws → i ∉ s.extVars → i ∉ flagVars s.f.flags →\n applyS (stepSub s.f (frameSub [] []) (frameRd [] getRd)) ρw M0 i = upd Nx.1 ce.e.sk v i := fun i hiw hie hif => by\n rw [hD2.1 i hie hif, hNw, hNext]; dsimp only; rw [hNx', setAll_at, if_neg hiw]\n rw [substR_evalC _ _ ρw M0 _ hrd', goalOf_agree (renLaw ds ce.e.law) ce.e.sk _ (X' := upd Nx.1 ce.e.sk v)\n (hpost ce.e.sk hskw hsk.1 hsk.2.1) (fun i hi => ?_)]\n · simpa using hn\n · have hi' : occC i ce.e.law.holds = true := by simpa [renLaw, occ_renC] using hi\n have hi1 := avoids_occ E'.lx hi'\n exact hpost i (fun h' => by rw [(hwsL i h' ce.e (List.mem_map_of_mem hce)).1] at hi'; cases hi')\n (fun h' => hi1 (List.mem_append_left _ h')) (fun h' => hi1 (List.mem_append_right _ h'))\n\n/-! Soundness -/\n\n/-- The induction rule with counts: for params that meet the precondition, maps that start as declared and functions\nthat meet the facts, every entry of an accepted proof holds in every reachable state (each request carrying its count\nmaps at their counts), each count map read as the state's count, a law about several keys at every value of its\nfurther keys. -/\ntheorem cmachine_sound (s : SMachine) (ds : List CDecl) (ps : List CEntry) (h : checkCMachine s ds ps = true) :\n ∀ ρ M, CReach s ds ρ M → ∀ ce ∈ ps, ce.e.Holds ρ (withCnt ds ρ M) := by\n have P := cparts h\n have hfok := P.facts\n have hentry : ∀ e ∈ ps.map (·.e), cEntryOk s ds (ps.map (·.e)) e = true := fun e he => by\n obtain ⟨ce, hce, rfl⟩ := List.mem_map.mp he; exact (P.entries ce hce).1\n have hfacts : ∀ {ρ : Nat → Nat} {M : Nat → Nat → Nat} {g : Nat}, skFresh s g = true → (∀ l ∈ s.facts, l.Holds ρ M) → ∀ w, ∀ l ∈ s.facts, l.Holds (upd ρ g w) M := by\n intro ρ M g hf hfa w\n exact facts_frame s hfok [g] [] (fun l hl => by simp [avoids, (skFresh_parts hf).2.2.2.2.2.2 l hl]) (fun _ _ => by simp [avoidsMaps])\n (fun i _ hig' => by simp only [upd]; rw [if_neg (by simpa using hig')]) (fun _ _ _ => rfl) hfa\n have hpfacts : ∀ {ρ : Nat → Nat} {M : Nat → Nat → Nat} {g : Nat}, skFresh s g = true → s.PFacts ρ M → ∀ w, s.PFacts (upd ρ g w) M := by\n intro ρ M g hf hpf w\n exact pfacts_frame s hfok [g] [] (fun f hfm => by simp [avoids, skFresh_pfacts hf f hfm]) (fun _ _ => by simp [avoidsMaps])\n (fun i _ hig' => by simp only [upd]; rw [if_neg (by simpa using hig')]) (fun _ _ _ => rfl) hpf\n have hpreu : ∀ {ρ : Nat → Nat} {M : Nat → Nat → Nat} {g : Nat}, occC g s.f.m.pre = false → evalC ρ M s.f.m.pre = true → ∀ w, evalC (upd ρ g w) M s.f.m.pre = true := by\n intro ρ M g hpg h0 w\n rw [congrC _ ρ M s.f.m.pre (fun i hi => by have hig' : i ≠ g := (fun h' => by rw [h', hpg] at hi; cases hi); simp only [upd, if_neg hig'])]; exact h0\n -- The counts read no further key.\n have hcg : ∀ ce ∈ ps, ∀ g ∈ ce.e.keys2, ∀ d ∈ ds, occE g d.below = false ∧ occE g d.body = false := fun ce hce g hg d hd =>\n ⟨((decl_parts (P.decls d hd)).ent ce.e (List.mem_map_of_mem hce) g (List.mem_cons_of_mem _ (List.mem_append_left _ hg))).1,\n ((decl_parts (P.decls d hd)).ent ce.e (List.mem_map_of_mem hce) g (List.mem_cons_of_mem _ (List.mem_append_left _ hg))).2.1⟩\n intro ρ M hr\n induction hr with\n | start ρ M hM h0 hfa hpf =>\n intro ce hce\n suffices hs : ∀ gs : List Nat, (∀ g ∈ gs, g ∈ ce.e.keys2) → ∀ ρ', evalC ρ' M s.f.m.pre = true → (∀ l ∈ s.facts, l.Holds ρ' M) →\n s.PFacts ρ' M → holdsOver ce.e.law (withCnt ds (applyS s.f.m.init ρ' M) M) gs (applyS s.f.m.init ρ' M) from\n hs ce.e.keys2 (fun g hg => hg) ρ h0 hfa hpf\n intro gs\n induction gs with\n | nil => intro _ ρ' hp hf hq; exact cstart_case s ds ps h ρ' M hM hp hf hq ce hce\n | cons g gs ih =>\n intro hsub ρ' hp hf hq w\n obtain ⟨hfr, hc, hpg, hig, _, _⟩ := key2_parts hentry (List.mem_map_of_mem hce) (hsub g List.mem_cons_self)\n have hI := (fresh_parts hfr hc ρ' M (fun _ => 0) (fun _ _ => 0) 0).2.2\n have := ih (fun g' hg' => hsub g' (List.mem_cons_of_mem _ hg')) (upd ρ' g w) (hpreu hpg hp w) (hfacts hfr hf w) (hpfacts hfr hq w)\n rw [applyS_upd hI (by simpa [List.all_eq_true] using hig), withCnt_upd (hcg ce hce g (hsub g List.mem_cons_self))] at this\n exact this\n | step ρ M ι κ hr hG ha ih =>\n intro ce hce\n suffices hs : ∀ gs : List Nat, (∀ g ∈ gs, g ∈ ce.e.keys2) → ∀ ρ', evalC ρ' M s.f.m.pre = true → (∀ l ∈ s.facts, l.Holds ρ' M) →\n s.PFacts ρ' M → (∀ ce' ∈ ps, ce'.e.Holds ρ' (withCnt ds ρ' M)) → GHolds ds (withInputs s.f.m.inputs ρ' ι) (withCarried s M κ) →\n evalC (sView s ρ' M ι κ).1 (sView s ρ' M ι κ).2 s.f.m.assume = true →\n holdsOver ce.e.law (withCnt ds (sNext s ρ' M ι κ).1 (sNext s ρ' M ι κ).2) gs (sNext s ρ' M ι κ).1 from\n hs ce.e.keys2 (fun g hg => hg) ρ (pre_sreach s P.pre P.preR (creach_sreach hr)) (facts_sreach s hfok (creach_sreach hr))\n (pfacts_sreach s hfok (creach_sreach hr)) ih hG ha\n intro gs\n induction gs with\n | nil => intro _ ρ' hp hf hq hi hg ha'; exact cstep_case s ds ps h ρ' M ι κ hp hf hq hi hg ha' ce hce\n | cons g gs ihg =>\n intro hsub ρ' hp hf hq hi hg ha' w\n have hgk := hsub g List.mem_cons_self\n obtain ⟨hfr, hc, hpg, _, hall, _⟩ := key2_parts hentry (List.mem_map_of_mem hce) hgk\n obtain ⟨hNext, hView, _⟩ := fresh_parts hfr hc ρ' M ι κ w\n have hgi := (fresh_out hc).2.2.2.2.1\n have := ihg (fun g' hg' => hsub g' (List.mem_cons_of_mem _ hg')) (upd ρ' g w) (hpreu hpg hp w) (hfacts hfr hf w) (hpfacts hfr hq w)\n (fun ce' hce' => by\n rw [withCnt_upd (hcg ce hce g hgk)]\n exact sentry_upd (hall ce'.e (List.mem_map_of_mem hce')) w (hi ce' hce'))\n (fun d hd x => by\n rw [hg d hd x, withInputs_upd hgi, cntOf_upd (hcg ce hce g hgk d hd).1 (hcg ce hce g hgk d hd).2])\n (by\n rw [hView]; dsimp only\n rw [congrC _ (sView s ρ' M ι κ).1 _ _ (fun i hi => by\n have hig' : i ≠ g := fun h' => by rw [h', (skFresh_parts hfr).2.2.1] at hi; cases hi\n simp only [upd, if_neg hig'])]\n exact ha')\n rw [hNext] at this; dsimp only at this\n rw [withCnt_upd (hcg ce hce g hgk)] at this\n exact this\n\n/-- `CReach` is the rule's own runs: at any state and request, the maps the request carries can be set at the count\nmaps to their counts (what the runtimes compute) and kept as they are elsewhere. -/\ntheorem counts_exist (s : SMachine) (ds : List CDecl) (hd : cDistinct (cMaps ds) = true) (hc : ∀ d ∈ ds, d.mp ∈ s.carried)\n (hav : ∀ d ∈ ds, avoidsMapsE (cMaps ds) d.below = true ∧ avoidsMapsE (cMaps ds) d.body = true)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat) :\n ∃ κ' : Nat → Nat → Nat, (∀ mp, mp ∉ cMaps ds → withCarried s M κ' mp = withCarried s M κ mp)\n ∧ GHolds ds (withInputs s.f.m.inputs ρ ι) (withCarried s M κ') := by\n let X := withInputs s.f.m.inputs ρ ι\n let κ' := withCnt ds X (withCarried s M κ)\n have hoff : ∀ mp, mp ∉ cMaps ds → withCarried s M κ' mp = withCarried s M κ mp := by\n intro mp hmp\n simp only [withCarried]; split\n · rename_i hcm\n show withCnt ds X (withCarried s M κ) mp = κ mp\n rw [withCnt_other hmp]; simp only [withCarried, hcm, ite_true]\n · rfl\n refine ⟨κ', hoff, fun d hdm x => ?_⟩\n have hcd : s.carried.contains d.mp = true := List.contains_iff_mem.mpr (hc d hdm)\n show (if s.carried.contains d.mp then κ' d.mp else M d.mp) x = _\n rw [if_pos hcd]\n show withCnt ds X (withCarried s M κ) d.mp x = _\n rw [withCnt_at hd hdm]\n unfold cntOf\n have hB : evalE (atJ d X x) (withCarried s M κ) d.below = evalE (atJ d X x) (withCarried s M κ') d.below :=\n congrME _ _ _ d.below (fun mp hm => (hoff mp (avoidsMapsE_occ (hav d hdm).1 hm)).symm)\n rw [hB]\n exact sumBelow_congr _ (fun k _ => congrME _ _ _ d.body (fun mp hm => (hoff mp (avoidsMapsE_occ (hav d hdm).2 hm)).symm))\n\nend Kern\n\n#print axioms Kern.mc_sound\n#print axioms Kern.cmachine_sound\n#print axioms Kern.counts_exist\n#print axioms Kern.pickHyp_true\n",
21
+ "Count.lean": "import Kernel\n\n/-!\nCount: quorum facts as a certificate kind, proven sound. Lean 4.34.0, core only; on top of `Kernel.lean` alone.\n\n**The lemma.** Finite sums over the keys below a bound (`sumBelow f n` = f 0 + … + f (n − 1)) are monotone and linear,\nso a pointwise inequality sums: if g sums below f over the keys below n, some key below n has g below f there\n(`exists_lt_of_sumBelow_lt`). Its corollaries are the quorum facts, for sets of keys below n (`card`):\n- `pigeonhole`: A, B ⊆ S and |A| + |B| > |S| give a key in A ∩ B;\n- `majorities_meet`: two majorities of S (2|A| > |S|, 2|B| > |S|) meet;\n- `quorums_meet_outside`: A, B ⊆ S and |A| + |B| > |S| + |F| give a key in A ∩ B outside F (thresholds: two sets of\n f + 1 out of 2f + 1, or two sets of n − t when n > 3t, meet in a process outside the t faulty ones).\n\n**The certificate kind** (kernel.ts's `checkCounted`, its twin). A counted goal is a goal (hypotheses over naturals and\nmaps, as `Kernel.lean`'s) and counts: each a variable `v` that names Σ_{k < below} body(k), the body read with its key\nvariable `key` at k (a 0/1 body is a set's size). A certificate is a list of instances and a tree. An instance names a\nfresh witness variable `wit`, a bound `below` every count it reads shares, integer coefficients on counts (`terms`) and\non the constant 1 (`unit`). With P the positive parts and N the negative parts (posP z = max z 0, negP z = max (−z) 0):\n\n countHyp = ( P·counts + P(unit)·below ≤ N·counts + N(unit)·below )\n ∨ ( wit < below ∧ N·bodies(wit) + N(unit) < P·bodies(wit) + P(unit) )\n\nwhich is the lemma read at one key: either the combination's sum is not positive, or `wit` is a key below the bound\nwhere its pointwise value is. Lean builds the instances' hypotheses itself (`countHyps`), checks each witness is fresh\n(`countedOk`) and checks the tree against the goal's hypotheses followed by them (`checkGoal`). `counted_sound`: an\naccepted counted goal's hypotheses hold at no naturals and maps where every count is its sum.\n\nWhy this shape is the smallest that covers the class: the whole of a Venn-region (BAPA) certificate is a linear\ncombination of set sizes whose pointwise value is never positive, so one instance (its Farkas coefficients on the\ncounts) plus a refutation at the witness key replaces the region variables: the case split on which sets hold the\nwitness is the tree's, over the cells it reads, as the kernel already splits. Majorities (+1, +1 on two counts, −1 on\nthe set's), f + 1 of 2f + 1 (the same) and more than 2/3 with faulty processes (+1, +1, −1 on S, −1 on F) are each one\ninstance; a count of a compound body (A ∩ B, say) gives the numeric forms (|A ∩ B| ≥ |A| + |B| − |S|).\n-/\n\nnamespace Kern\n\n/-! Finite sums below a bound -/\n\ndef sumBelow (f : Nat → Nat) : Nat → Nat\n | 0 => 0\n | n + 1 => sumBelow f n + f n\n\ntheorem sumBelow_mono {f g : Nat → Nat} (n : Nat) (h : ∀ k, k < n → f k ≤ g k) : sumBelow f n ≤ sumBelow g n := by\n induction n with\n | zero => simp [sumBelow]\n | succ n ih =>\n simp only [sumBelow]\n have h1 := ih (fun k hk => h k (by omega))\n have h2 := h n (by omega)\n omega\n\ntheorem sumBelow_add (f g : Nat → Nat) (n : Nat) : sumBelow (fun k => f k + g k) n = sumBelow f n + sumBelow g n := by\n induction n with\n | zero => simp [sumBelow]\n | succ n ih => simp only [sumBelow, ih]; omega\n\ntheorem sumBelow_mul (c : Nat) (f : Nat → Nat) (n : Nat) : sumBelow (fun k => c * f k) n = c * sumBelow f n := by\n induction n with\n | zero => simp [sumBelow]\n | succ n ih => simp only [sumBelow, ih, Nat.mul_add]\n\ntheorem sumBelow_const (d n : Nat) : sumBelow (fun _ => d) n = d * n := by\n induction n with\n | zero => simp [sumBelow]\n | succ n ih => simp only [sumBelow, ih, Nat.mul_add, Nat.mul_one]\n\ntheorem sumBelow_congr {f g : Nat → Nat} (n : Nat) (h : ∀ k, k < n → f k = g k) : sumBelow f n = sumBelow g n := by\n induction n with\n | zero => rfl\n | succ n ih => simp only [sumBelow, ih (fun k hk => h k (by omega)), h n (by omega)]\n\ntheorem sumBelow_zero_fn (n : Nat) : sumBelow (fun _ => 0) n = 0 := by\n induction n with\n | zero => rfl\n | succ n ih => simp [sumBelow, ih]\n\n/-- A pointwise inequality, summed: if g sums below f over the keys below n, some key below n has g below f. -/\ntheorem exists_lt_of_sumBelow_lt {f g : Nat → Nat} {n : Nat} (h : sumBelow g n < sumBelow f n) : ∃ k, k < n ∧ g k < f k := by\n apply Classical.byContradiction\n intro hno\n have hle : ∀ k, k < n → f k ≤ g k := fun k hk => Nat.le_of_not_lt (fun hlt => hno ⟨k, hk, hlt⟩)\n have := sumBelow_mono n hle\n omega\n\n/-! Sets of keys below a bound, and the quorum facts -/\n\n-- The number of keys below n where p holds.\ndef card (p : Nat → Bool) (n : Nat) : Nat := sumBelow (fun k => if p k then 1 else 0) n\n\n/-- The pigeonhole: two subsets of S whose sizes add up to more than S's meet. -/\ntheorem pigeonhole {a b s : Nat → Bool} {n : Nat} (ha : ∀ k, k < n → a k = true → s k = true)\n (hb : ∀ k, k < n → b k = true → s k = true) (h : card s n < card a n + card b n) :\n ∃ k, k < n ∧ a k = true ∧ b k = true := by\n unfold card at h\n rw [← sumBelow_add] at h\n obtain ⟨k, hk, hlt⟩ := exists_lt_of_sumBelow_lt h\n have h1 := ha k hk\n have h2 := hb k hk\n refine ⟨k, hk, ?_⟩\n cases hak : a k <;> cases hbk : b k <;> cases hsk : s k <;> simp_all\n\n/-- Two majorities of S meet. -/\ntheorem majorities_meet {a b s : Nat → Bool} {n : Nat} (ha : ∀ k, k < n → a k = true → s k = true)\n (hb : ∀ k, k < n → b k = true → s k = true) (h1 : card s n < 2 * card a n) (h2 : card s n < 2 * card b n) :\n ∃ k, k < n ∧ a k = true ∧ b k = true :=\n pigeonhole ha hb (by omega)\n\n/-- Thresholds: two subsets of S whose sizes add up to more than |S| + |F| meet outside F (f + 1 of 2f + 1 with F\nempty; n − t of n with n > 3t and at most t faulty). -/\ntheorem quorums_meet_outside {a b s f : Nat → Bool} {n : Nat} (ha : ∀ k, k < n → a k = true → s k = true)\n (hb : ∀ k, k < n → b k = true → s k = true) (h : card s n + card f n < card a n + card b n) :\n ∃ k, k < n ∧ a k = true ∧ b k = true ∧ f k = false := by\n unfold card at h\n rw [← sumBelow_add, ← sumBelow_add] at h\n obtain ⟨k, hk, hlt⟩ := exists_lt_of_sumBelow_lt h\n have h1 := ha k hk\n have h2 := hb k hk\n refine ⟨k, hk, ?_⟩\n cases hak : a k <;> cases hbk : b k <;> cases hsk : s k <;> cases hfk : f k <;> simp_all\n\n/-! The certificate kind: counts in a goal -/\n\n-- A count: the variable v names the sum of `body` over the keys below `below`, `body` read with `key` at each key.\nstructure Count where\n v : Nat\n key : Nat\n below : E\n body : E\n\n-- What a count means at an environment.\ndef Count.Holds (c : Count) (ρ : Nat → Nat) (M : Nat → Nat → Nat) : Prop :=\n ρ c.v = sumBelow (fun k => evalE (upd ρ c.key k) M c.body) (evalE ρ M c.below)\n\n-- An instance of the lemma: a fresh witness, the bound its counts share, a coefficient per count (named by its\n-- variable) and one on the constant 1.\nstructure CInst where\n wit : Nat\n below : E\n terms : List (Int × Nat)\n unit : Int\n\n-- A counted goal: its hypotheses, and the counts they read.\nstructure CGoal where\n hyps : List C\n counts : List Count\n\ndef findCount (cs : List Count) (v : Nat) : Option Count := lookup (fun c => c.v == v) cs\n\n-- Each term's count (the first with its variable), when every term names one whose bound is the instance's.\ndef resolve (cs : List Count) (B : E) : List (Int × Nat) → Option (List (Int × Count))\n | [] => some []\n | t :: ts => match findCount cs t.2 with\n | none => none\n | some c => if beqE c.below B then (resolve cs B ts).map (fun rs => (t.1, c) :: rs) else none\n\n-- A sum of terms, right-nested from 0.\ndef sumE : List E → E\n | [] => .const 0\n | e :: es => .add e (sumE es)\n\ndef posP (z : Int) : Nat := z.toNat\ndef negP (z : Int) : Nat := (-z).toNat\n\n-- One side of an instance: each count read by `rd` times its coefficient's part, then the unit's part times `one`.\ndef side (part : Int → Nat) (rd : Count → E) (one : E) (u : Int) (rs : List (Int × Count)) : E :=\n .add (sumE (rs.map fun r => .mul (part r.1) (rd r.2))) (.mul (part u) one)\n\n-- A count read as its variable, and its body read at the witness.\ndef atCount (c : Count) : E := .var c.v\ndef atWit (w : Nat) (c : Count) : E := substE [(c.key, .var w)] c.body\n\n-- The instance's hypothesis: the combination's sum is not positive, or the witness is a key below the bound where the\n-- combination's value is.\ndef countHyp (cs : List Count) (i : CInst) : Option C :=\n (resolve cs i.below i.terms).map fun rs =>\n .or (.le (side posP atCount i.below i.unit rs) (side negP atCount i.below i.unit rs))\n (.and (.lt (.var i.wit) i.below)\n (.lt (side negP (atWit i.wit) (.const 1) i.unit rs) (side posP (atWit i.wit) (.const 1) i.unit rs)))\n\ndef countHyps (cs : List Count) : List CInst → Option (List C)\n | [] => some []\n | i :: is => match countHyp cs i with\n | none => none\n | some h => (countHyps cs is).map (h :: ·)\n\ndef cDistinct : List Nat → Bool\n | [] => true\n | a :: as => !as.contains a && cDistinct as\n\n-- A witness is fresh: no hypothesis reads it, no count names it or reads it (in its bound or its body), and no\n-- instance's bound reads it.\ndef witFresh (hyps : List C) (cs : List Count) (is : List CInst) (w : Nat) : Bool :=\n hyps.all (fun h => !occC w h) && cs.all (fun c => c.v != w && !occE w c.below && !occE w c.body) && is.all (fun j => !occE w j.below)\n\ndef countedOk (hyps : List C) (cs : List Count) (is : List CInst) : Bool :=\n cDistinct (is.map (·.wit)) && is.all (fun i => witFresh hyps cs is i.wit)\n\n/-! Conditional lemma cuts. A lemma shares the containing goal's table and may select only its hypotheses.\nIts proof is an old-language tree, checked without any lemma assumptions. This rules out circular citations. -/\n\nsection LemmaCuts\nset_option autoImplicit false\n\nstructure CutLemma where\n when : List Cert.Row\n cut : Cert.Row\n tree : Tree\n slice : Option (List Nat) := none\n\ndef lemmaSlice (hyps : List C) : List Nat → Option (List C)\n | [] => some []\n | i :: is => match hyps[i]?, lemmaSlice hyps is with\n | some h, some hs => some (h :: hs)\n | _, _ => none\n\ndef lemmaHyps (hyps : List C) (l : CutLemma) : Option (List C) :=\n match l.slice with\n | none => some hyps\n | some is => lemmaSlice hyps is\n\ndef checkLemma (tab : List VDef) (hyps : List C) (l : CutLemma) : Bool :=\n match lemmaHyps hyps l with\n | some hs => checkT tab hs ((l.cut, false) :: l.when.map (fun w => (w, true))) l.tree\n | none => false\n\n-- Eligibility reads only the original split path, never the cuts being made available.\ndef lemmaActive (path : Path) (l : CutLemma) : Bool :=\n l.when.all (fun w => dec path w == some true)\n\ndef lemmaPath (lemmas : List CutLemma) (path : Path) : Path :=\n (lemmas.filter (lemmaActive path)).map (fun l => (l.cut, true)) ++ path\n\ndef checkTLemmas (tab : List VDef) (hyps : List C) (lemmas : List CutLemma) : Path → Tree → Bool\n | path, .split l y n => checkTLemmas tab hyps lemmas ((l, true) :: path) y && checkTLemmas tab hyps lemmas ((l, false) :: path) n\n | path, t => checkT tab hyps (lemmaPath lemmas path) t\n\ndef checkGoalLemmas (g : Goal) (t : Tree) (lemmas : List CutLemma) : Bool :=\n wfTab 0 g.tab && lemmas.all (checkLemma g.tab g.hyps) && checkTLemmas g.tab g.hyps lemmas [] t\n\n@[simp] theorem lemmaPath_nil (path : Path) : lemmaPath [] path = path := rfl\n\n@[simp] theorem checkTLemmas_nil (tab : List VDef) (hyps : List C) (t : Tree) (path : Path) :\n checkTLemmas tab hyps [] path t = checkT tab hyps path t := by\n induction t generalizing path with\n | split l y n ihy ihn => simp only [checkTLemmas, checkT, ihy, ihn]\n | leaf rows steps eqs prods => rfl\n | leafAt rows steps eqs prods => rfl\n | leafSq rows sqs steps eqs prods => rfl\n\n@[simp] theorem checkGoalLemmas_nil (g : Goal) (t : Tree) : checkGoalLemmas g t [] = checkGoal g t := by\n simp [checkGoalLemmas, checkGoal]\n\ntheorem lemmaSlice_sub {hyps : List C} : ∀ {is : List Nat} {hs : List C},\n lemmaSlice hyps is = some hs → ∀ h ∈ hs, h ∈ hyps\n | [], hs, he => by simp only [lemmaSlice, Option.some.injEq] at he; subst he; simp\n | i :: is, hs, he => by\n cases hi : hyps[i]? with\n | none => simp [lemmaSlice, hi] at he\n | some c =>\n cases ht : lemmaSlice hyps is with\n | none => simp [lemmaSlice, hi, ht] at he\n | some cs =>\n simp only [lemmaSlice, hi, ht, Option.some.injEq] at he\n subst he\n intro h hh\n rcases List.mem_cons.mp hh with rfl | hh\n · exact List.mem_of_getElem? hi\n · exact lemmaSlice_sub ht h hh\n\ntheorem lemmaHyps_sub {hyps hs : List C} {l : CutLemma} (he : lemmaHyps hyps l = some hs) :\n ∀ h ∈ hs, h ∈ hyps := by\n cases sl : l.slice with\n | none => simp only [lemmaHyps, sl, Option.some.injEq] at he; subst he; exact fun _ hh => hh\n | some is => exact lemmaSlice_sub (by simpa only [lemmaHyps, sl] using he)\n\ndef CutHolds (l : CutLemma) (x : List Int) : Prop :=\n (∀ w ∈ l.when, Cert.eval w x ≤ 0) → Cert.eval l.cut x ≤ 0\n\n/-- A checked lemma proves its cut under exactly its declared linear conditions. -/\ntheorem lemma_sound {tab : List VDef} {hyps : List C} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int}\n (hM : Model tab env maps x) (hH : ∀ c ∈ hyps, evalC env maps c = true)\n {l : CutLemma} (hck : checkLemma tab hyps l = true) : CutHolds l x := by\n intro hw\n apply Int.not_lt.mp\n intro hc\n cases hs : lemmaHyps hyps l with\n | none => simp [checkLemma, hs] at hck\n | some cs =>\n simp only [checkLemma, hs] at hck\n have hp : PathHolds ((l.cut, false) :: l.when.map (fun w => (w, true))) x := by\n intro a ha\n rcases List.mem_cons.mp ha with rfl | ha\n · have hn : ¬ Cert.eval l.cut x ≤ 0 := by omega\n simpa using hn\n · obtain ⟨w, hwm, rfl⟩ := List.mem_map.mp ha\n simpa using hw w hwm\n exact checkT_sound hM (fun c hc => hH c (lemmaHyps_sub hs c hc)) l.tree _ hp hck\n\ntheorem lemmaPath_holds {lemmas : List CutLemma} {path : Path} {x : List Int}\n (hP : PathHolds path x) (hL : ∀ l ∈ lemmas, CutHolds l x) : PathHolds (lemmaPath lemmas path) x := by\n intro a ha\n rcases List.mem_append.mp ha with ha | ha\n · obtain ⟨l, hl, rfl⟩ := List.mem_map.mp ha\n obtain ⟨hlm, hactive⟩ := List.mem_filter.mp hl\n have hc : Cert.eval l.cut x ≤ 0 := hL l hlm (fun w hw => by\n have hd : dec path w = some true := by\n simpa only [lemmaActive, List.all_eq_true, beq_iff_eq] using (List.all_eq_true.mp hactive w hw)\n have := dec_sound hP hd\n simpa using this)\n simpa using hc\n · exact hP a ha\n\ntheorem checkTLemmas_sound {tab : List VDef} {hyps : List C} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int}\n (hM : Model tab env maps x) (hH : ∀ c ∈ hyps, evalC env maps c = true)\n {lemmas : List CutLemma} (hL : ∀ l ∈ lemmas, CutHolds l x) :\n ∀ (t : Tree) (path : Path), PathHolds path x → checkTLemmas tab hyps lemmas path t = true → False\n | .split l y n, path, hP, h => by\n simp only [checkTLemmas, Bool.and_eq_true] at h\n by_cases hl : Cert.eval l x ≤ 0\n · refine checkTLemmas_sound hM hH hL y _ ?_ h.1\n intro a ha\n rcases List.mem_cons.mp ha with rfl | ha\n · simpa using hl\n · exact hP a ha\n · refine checkTLemmas_sound hM hH hL n _ ?_ h.2\n intro a ha\n rcases List.mem_cons.mp ha with rfl | ha\n · simpa using hl\n · exact hP a ha\n | .leaf rows steps eqs prods, path, hP, h =>\n checkT_sound hM hH _ _ (lemmaPath_holds hP hL) h\n | .leafAt rows steps eqs prods, path, hP, h =>\n checkT_sound hM hH _ _ (lemmaPath_holds hP hL) h\n | .leafSq rows sqs steps eqs prods, path, hP, h =>\n checkT_sound hM hH _ _ (lemmaPath_holds hP hL) h\n\n/-- The extended goal checker has the original unsatisfiability conclusion. -/\ntheorem goalLemmas_sound (g : Goal) (t : Tree) (lemmas : List CutLemma)\n (h : checkGoalLemmas g t lemmas = true) (env : Nat → Nat) (maps : Nat → Nat → Nat) :\n ¬ ∀ c ∈ g.hyps, evalC env maps c = true := by\n intro hH\n simp only [checkGoalLemmas, Bool.and_eq_true, List.all_eq_true] at h\n obtain ⟨⟨hw, hl⟩, ht⟩ := h\n have hv := build_valid env maps g.tab [] [] ⟨rfl, by simp, by simp⟩ (by simpa using hw)\n simp only [List.nil_append] at hv\n have hM := model_of_valid hv\n exact checkTLemmas_sound hM hH (fun l hm => lemma_sound hM hH (hl l hm)) t [] (by simp [PathHolds]) ht\n\nend LemmaCuts\n\n/-! Conditional count frames (MLDR-DESIGN.md Section 15.7). A frame cut names two counts of the goal by their\nvariables, a post count and its pre count, and linear conditions `when` over the goal's table. It is accepted when,\nwith every `if` whose condition reads no count key and is decided under `when` resolved (`simpE`), the two counts have\nthe same key, bound and body. No tree is checked: the two sums are equal because their bounds and summands are\n(`sumBelow_congr`). Where a leaf's original split path decides every condition, the two rows `post − pre ≤ 0` and\n`pre − post ≤ 0` are available to it, as a lemma cut's row is. Nothing else changes: with no frames the checkers\nbelow are the lemma-cut checkers (`checkGoalFrames_nil`). -/\n\nsection FrameCuts\nset_option autoImplicit false\n\nstructure FrameCut where\n when : List Cert.Row\n post : Nat\n pre : Nat\n\n/-! Section 17 (MLDR-DESIGN.md): the simplifier decides conditions that read the key from their key-free parts, prunes\ndecided conjuncts and disjuncts, and folds `(if C then 1 else 0) = 1` to `C`, so a step's write tree substituted into a\ncount's body collapses to the pre body where the step does not write the map. -/\n\n-- A term that only rises with any variable: variables, constants, sums, scalings, products, minima, maxima.\ndef monoE : E → Bool\n | .var _ => true\n | .const _ => true\n | .add a b => monoE a && monoE b\n | .mul _ a => monoE a\n | .min a b => monoE a && monoE b\n | .max a b => monoE a && monoE b\n | .prod a b => monoE a && monoE b\n | _ => false\n\n-- The variable `k` replaced by 0.\ndef zeroK (k : Nat) : E → E\n | .var i => if i = k then .const 0 else .var i\n | .const n => .const n\n | .add a b => .add (zeroK k a) (zeroK k b)\n | .sub a b => .sub (zeroK k a) (zeroK k b)\n | .mul m a => .mul m (zeroK k a)\n | .min a b => .min (zeroK k a) (zeroK k b)\n | .max a b => .max (zeroK k a) (zeroK k b)\n | .prod a b => .prod (zeroK k a) (zeroK k b)\n | .ite c t f => .ite c (zeroK k t) (zeroK k f)\n | .get m key => .get m (zeroK k key)\n | .tup a b => .tup (zeroK k a) (zeroK k b)\n | .proj j a => .proj j (zeroK k a)\n\ntheorem occE_zeroK (k : Nat) : (e : E) → monoE e = true → occE k (zeroK k e) = false\n | .var i, _ => by simp only [zeroK]; split <;> simp [occE, *]\n | .const _, _ => by simp [zeroK, occE]\n | .add a b, h => by\n simp only [monoE, Bool.and_eq_true] at h\n simp [zeroK, occE, occE_zeroK k a h.1, occE_zeroK k b h.2]\n | .mul _ a, h => by simp only [monoE] at h; simp [zeroK, occE, occE_zeroK k a h]\n | .min a b, h => by\n simp only [monoE, Bool.and_eq_true] at h\n simp [zeroK, occE, occE_zeroK k a h.1, occE_zeroK k b h.2]\n | .max a b, h => by\n simp only [monoE, Bool.and_eq_true] at h\n simp [zeroK, occE, occE_zeroK k a h.1, occE_zeroK k b h.2]\n | .prod a b, h => by\n simp only [monoE, Bool.and_eq_true] at h\n simp [zeroK, occE, occE_zeroK k a h.1, occE_zeroK k b h.2]\n | .sub _ _, h => by simp [monoE] at h\n | .ite _ _ _, h => by simp [monoE] at h\n | .get _ _, h => by simp [monoE] at h\n | .tup _ _, h => by simp [monoE] at h\n | .proj _ _, h => by simp [monoE] at h\n\ntheorem zeroK_eval (ρ : Nat → Nat) (M : Nat → Nat → Nat) (k : Nat) :\n (e : E) → monoE e = true → evalE ρ M (zeroK k e) = evalE (upd ρ k 0) M e\n | .var i, _ => by simp only [zeroK]; split <;> simp_all [evalE, upd]\n | .const _, _ => rfl\n | .add a b, h => by\n simp only [monoE, Bool.and_eq_true] at h\n simp only [zeroK, evalE, zeroK_eval ρ M k a h.1, zeroK_eval ρ M k b h.2]\n | .mul m a, h => by simp only [monoE] at h; simp only [zeroK, evalE, zeroK_eval ρ M k a h]\n | .min a b, h => by\n simp only [monoE, Bool.and_eq_true] at h\n simp only [zeroK, evalE, zeroK_eval ρ M k a h.1, zeroK_eval ρ M k b h.2]\n | .max a b, h => by\n simp only [monoE, Bool.and_eq_true] at h\n simp only [zeroK, evalE, zeroK_eval ρ M k a h.1, zeroK_eval ρ M k b h.2]\n | .prod a b, h => by\n simp only [monoE, Bool.and_eq_true] at h\n simp only [zeroK, evalE, zeroK_eval ρ M k a h.1, zeroK_eval ρ M k b h.2]\n | .sub _ _, h => by simp [monoE] at h\n | .ite _ _ _, h => by simp [monoE] at h\n | .get _ _, h => by simp [monoE] at h\n | .tup _ _, h => by simp [monoE] at h\n | .proj _ _, h => by simp [monoE] at h\n\ntheorem monoE_ge (ρ : Nat → Nat) (M : Nat → Nat → Nat) (k : Nat) :\n (e : E) → monoE e = true → evalE (upd ρ k 0) M e ≤ evalE ρ M e\n | .var i, _ => by simp only [evalE, upd]; split <;> simp\n | .const _, _ => Nat.le_refl _\n | .add a b, h => by\n simp only [monoE, Bool.and_eq_true] at h\n simp only [evalE]; exact Nat.add_le_add (monoE_ge ρ M k a h.1) (monoE_ge ρ M k b h.2)\n | .mul m a, h => by\n simp only [monoE] at h\n simp only [evalE]; exact Nat.mul_le_mul (Nat.le_refl m) (monoE_ge ρ M k a h)\n | .min a b, h => by\n simp only [monoE, Bool.and_eq_true] at h\n simp only [evalE]\n have ha := monoE_ge ρ M k a h.1; have hb := monoE_ge ρ M k b h.2; omega\n | .max a b, h => by\n simp only [monoE, Bool.and_eq_true] at h\n simp only [evalE]\n have ha := monoE_ge ρ M k a h.1; have hb := monoE_ge ρ M k b h.2; omega\n | .prod a b, h => by\n simp only [monoE, Bool.and_eq_true] at h\n simp only [evalE]; exact Nat.mul_le_mul (monoE_ge ρ M k a h.1) (monoE_ge ρ M k b h.2)\n | .sub _ _, h => by simp [monoE] at h\n | .ite _ _ _, h => by simp [monoE] at h\n | .get _ _, h => by simp [monoE] at h\n | .tup _ _, h => by simp [monoE] at h\n | .proj _ _, h => by simp [monoE] at h\n\n-- An atom reading the key, decided for every value of the key from its key-free instance at 0: with the key only on\n-- the left and the left rising with it, false at 0 is false everywhere; with the key only on the right, true at 0 is\n-- true everywhere. Anything else is undecided.\ndef atomK (tab : List VDef) (path : Path) (k : Nat) : C → Option Bool\n | .le a b =>\n if occE k a && !occE k b && monoE a then\n (match truth tab path (.le (zeroK k a) b) with | some false => some false | _ => none)\n else if !occE k a && occE k b && monoE b then\n (match truth tab path (.le a (zeroK k b)) with | some true => some true | _ => none)\n else none\n | .lt a b =>\n if occE k a && !occE k b && monoE a then\n (match truth tab path (.lt (zeroK k a) b) with | some false => some false | _ => none)\n else if !occE k a && occE k b && monoE b then\n (match truth tab path (.lt a (zeroK k b)) with | some true => some true | _ => none)\n else none\n | _ => none\n\n-- A condition decided for every value of the key: atoms reading no key by `truth`, atoms reading it by `atomK`,\n-- `and`, `or` and `not` three-valued.\ndef truthK (tab : List VDef) (path : Path) (k : Nat) : C → Option Bool\n | .le a b => if occC k (.le a b) then atomK tab path k (.le a b) else truth tab path (.le a b)\n | .lt a b => if occC k (.lt a b) then atomK tab path k (.lt a b) else truth tab path (.lt a b)\n | .eq a b => if occC k (.eq a b) then\n (match atomK tab path k (.le a b), atomK tab path k (.le b a) with\n | some false, _ => some false\n | _, some false => some false\n | _, _ => none)\n else truth tab path (.eq a b)\n | .and a b => match truthK tab path k a, truthK tab path k b with\n | some false, _ => some false\n | _, some false => some false\n | some true, some true => some true\n | _, _ => none\n | .or a b => match truthK tab path k a, truthK tab path k b with\n | some true, _ => some true\n | _, some true => some true\n | some false, some false => some false\n | _, _ => none\n | .not a => match truthK tab path k a with\n | some b => some (!b)\n | none => none\n\ntheorem atomK_sound {tab : List VDef} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int} {path : Path}\n (hM : Model tab env maps x) (hP : PathHolds path x) (k : Nat) (env' : Nat → Nat) (hk : ∀ i, i ≠ k → env' i = env i) :\n (c : C) → (b : Bool) → atomK tab path k c = some b → evalC env' maps c = b\n | .le a b', r, h => by\n simp only [atomK] at h\n split at h\n · rename_i hc\n simp only [Bool.and_eq_true, Bool.not_eq_true'] at hc\n obtain ⟨⟨hoa, hob⟩, hma⟩ := hc\n split at h\n · rename_i hT\n simp only [Option.some.injEq] at h; subst h\n have ht := truth_sound hM hP _ false hT\n have hcg : evalC env maps (.le (zeroK k a) b') = evalC env' maps (.le (zeroK k a) b') := by\n apply congrC\n intro i hi\n by_cases hik : i = k\n · subst hik; simp [occC, occE_zeroK i a hma, hob] at hi\n · exact (hk i hik).symm\n rw [hcg] at ht\n simp only [evalC, decide_eq_false_iff_not, Nat.not_le] at ht ⊢\n have h0 := zeroK_eval env' maps k a hma\n have hge := monoE_ge env' maps k a hma\n omega\n · simp at h\n · split at h\n · rename_i hc\n simp only [Bool.and_eq_true, Bool.not_eq_true'] at hc\n obtain ⟨⟨hoa, hob⟩, hmb⟩ := hc\n split at h\n · rename_i hT\n simp only [Option.some.injEq] at h; subst h\n have ht := truth_sound hM hP _ true hT\n have hcg : evalC env maps (.le a (zeroK k b')) = evalC env' maps (.le a (zeroK k b')) := by\n apply congrC\n intro i hi\n by_cases hik : i = k\n · subst hik; simp [occC, occE_zeroK i b' hmb, hoa] at hi\n · exact (hk i hik).symm\n rw [hcg] at ht\n simp only [evalC, decide_eq_true_eq] at ht ⊢\n have h0 := zeroK_eval env' maps k b' hmb\n have hge := monoE_ge env' maps k b' hmb\n omega\n · simp at h\n · simp at h\n | .lt a b', r, h => by\n simp only [atomK] at h\n split at h\n · rename_i hc\n simp only [Bool.and_eq_true, Bool.not_eq_true'] at hc\n obtain ⟨⟨hoa, hob⟩, hma⟩ := hc\n split at h\n · rename_i hT\n simp only [Option.some.injEq] at h; subst h\n have ht := truth_sound hM hP _ false hT\n have hcg : evalC env maps (.lt (zeroK k a) b') = evalC env' maps (.lt (zeroK k a) b') := by\n apply congrC\n intro i hi\n by_cases hik : i = k\n · subst hik; simp [occC, occE_zeroK i a hma, hob] at hi\n · exact (hk i hik).symm\n rw [hcg] at ht\n simp only [evalC, decide_eq_false_iff_not, Nat.not_lt] at ht ⊢\n have h0 := zeroK_eval env' maps k a hma\n have hge := monoE_ge env' maps k a hma\n omega\n · simp at h\n · split at h\n · rename_i hc\n simp only [Bool.and_eq_true, Bool.not_eq_true'] at hc\n obtain ⟨⟨hoa, hob⟩, hmb⟩ := hc\n split at h\n · rename_i hT\n simp only [Option.some.injEq] at h; subst h\n have ht := truth_sound hM hP _ true hT\n have hcg : evalC env maps (.lt a (zeroK k b')) = evalC env' maps (.lt a (zeroK k b')) := by\n apply congrC\n intro i hi\n by_cases hik : i = k\n · subst hik; simp [occC, occE_zeroK i b' hmb, hoa] at hi\n · exact (hk i hik).symm\n rw [hcg] at ht\n simp only [evalC, decide_eq_true_eq] at ht ⊢\n have h0 := zeroK_eval env' maps k b' hmb\n have hge := monoE_ge env' maps k b' hmb\n omega\n · simp at h\n · simp at h\n | .eq _ _, _, h => by simp [atomK] at h\n | .and _ _, _, h => by simp [atomK] at h\n | .or _ _, _, h => by simp [atomK] at h\n | .not _, _, h => by simp [atomK] at h\n\ntheorem truthK_sound {tab : List VDef} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int} {path : Path}\n (hM : Model tab env maps x) (hP : PathHolds path x) (k : Nat) (env' : Nat → Nat) (hk : ∀ i, i ≠ k → env' i = env i) :\n (c : C) → (b : Bool) → truthK tab path k c = some b → evalC env' maps c = b\n | .le a b', r, h => by\n simp only [truthK] at h\n split at h\n · exact atomK_sound hM hP k env' hk _ r h\n · rename_i hocc\n rw [← truth_sound hM hP _ r h]\n exact congrC env' env maps _ (fun i hi => hk i (fun he => by subst he; exact hocc hi))\n | .lt a b', r, h => by\n simp only [truthK] at h\n split at h\n · exact atomK_sound hM hP k env' hk _ r h\n · rename_i hocc\n rw [← truth_sound hM hP _ r h]\n exact congrC env' env maps _ (fun i hi => hk i (fun he => by subst he; exact hocc hi))\n | .eq a b', r, h => by\n simp only [truthK] at h\n split at h\n · split at h\n · rename_i hA\n simp only [Option.some.injEq] at h; subst h\n have := atomK_sound hM hP k env' hk _ false hA\n simp only [evalC, decide_eq_false_iff_not, Nat.not_le] at this\n simp only [evalC, decide_eq_false_iff_not]; omega\n · rename_i hB _\n simp only [Option.some.injEq] at h; subst h\n have := atomK_sound hM hP k env' hk _ false hB\n simp only [evalC, decide_eq_false_iff_not, Nat.not_le] at this\n simp only [evalC, decide_eq_false_iff_not]; omega\n · simp at h\n · rename_i hocc\n rw [← truth_sound hM hP _ r h]\n exact congrC env' env maps _ (fun i hi => hk i (fun he => by subst he; exact hocc hi))\n | .and a b', r, h => by\n simp only [truthK] at h\n simp only [evalC]\n split at h\n · rename_i h1; simp only [Option.some.injEq] at h; subst h; simp [truthK_sound hM hP k env' hk a false h1]\n · rename_i h2 _; simp only [Option.some.injEq] at h; subst h; simp [truthK_sound hM hP k env' hk b' false h2]\n · rename_i h1 h2; simp only [Option.some.injEq] at h; subst h; simp [truthK_sound hM hP k env' hk a true h1, truthK_sound hM hP k env' hk b' true h2]\n · simp at h\n | .or a b', r, h => by\n simp only [truthK] at h\n simp only [evalC]\n split at h\n · rename_i h1; simp only [Option.some.injEq] at h; subst h; simp [truthK_sound hM hP k env' hk a true h1]\n · rename_i h2 _; simp only [Option.some.injEq] at h; subst h; simp [truthK_sound hM hP k env' hk b' true h2]\n · rename_i h1 h2; simp only [Option.some.injEq] at h; subst h; simp [truthK_sound hM hP k env' hk a false h1, truthK_sound hM hP k env' hk b' false h2]\n · simp at h\n | .not a, r, h => by\n simp only [truthK] at h\n split at h\n · rename_i r' h1; simp only [Option.some.injEq] at h; subst h; simp [evalC, truthK_sound hM hP k env' hk a r' h1]\n · simp at h\n\n-- The decided conditions, as terms: 0 ≤ 0 and 0 < 0.\ndef cTrue : C := .le (.const 0) (.const 0)\ndef cFalse : C := .lt (.const 0) (.const 0)\ndef decideC (tab : List VDef) (path : Path) (k : Nat) (c : C) : C :=\n match truthK tab path k c with\n | some true => cTrue\n | some false => cFalse\n | none => c\ndef andC : C → C → C\n | .lt (.const 0) (.const 0), _ => cFalse\n | _, .lt (.const 0) (.const 0) => cFalse\n | .le (.const 0) (.const 0), y => y\n | x, .le (.const 0) (.const 0) => x\n | x, y => .and x y\ndef orC : C → C → C\n | .le (.const 0) (.const 0), _ => cTrue\n | _, .le (.const 0) (.const 0) => cTrue\n | .lt (.const 0) (.const 0), y => y\n | x, .lt (.const 0) (.const 0) => x\n | x, y => .or x y\ndef notC : C → C\n | .le (.const 0) (.const 0) => cFalse\n | .lt (.const 0) (.const 0) => cTrue\n | .not y => y\n | y => .not y\n-- `(if C then 1 else 0) = 1` is C, `= 0` is ¬C; any other equation is decided as it stands.\ndef foldEq (tab : List VDef) (path : Path) (k : Nat) : E → E → C\n | .ite c (.const 1) (.const 0), .const 1 => c\n | .ite c (.const 1) (.const 0), .const 0 => notC c\n | .const 1, .ite c (.const 1) (.const 0) => c\n | .const 0, .ite c (.const 1) (.const 0) => notC c\n | a, b => decideC tab path k (.eq a b)\n\ntheorem decideC_eval {tab : List VDef} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int} {path : Path}\n (hM : Model tab env maps x) (hP : PathHolds path x) (k : Nat) (env' : Nat → Nat) (hk : ∀ i, i ≠ k → env' i = env i)\n (c : C) : evalC env' maps (decideC tab path k c) = evalC env' maps c := by\n unfold decideC\n split\n · rename_i hT; rw [truthK_sound hM hP k env' hk c true hT]; simp [cTrue, evalC]\n · rename_i hT; rw [truthK_sound hM hP k env' hk c false hT]; simp [cFalse, evalC]\n · rfl\ntheorem andC_eval (ρ : Nat → Nat) (M : Nat → Nat → Nat) (a b : C) : evalC ρ M (andC a b) = (evalC ρ M a && evalC ρ M b) := by\n unfold andC; split <;> simp_all [evalC, cTrue, cFalse]\ntheorem orC_eval (ρ : Nat → Nat) (M : Nat → Nat → Nat) (a b : C) : evalC ρ M (orC a b) = (evalC ρ M a || evalC ρ M b) := by\n unfold orC; split <;> simp_all [evalC, cTrue, cFalse]\ntheorem notC_eval (ρ : Nat → Nat) (M : Nat → Nat → Nat) (a : C) : evalC ρ M (notC a) = !evalC ρ M a := by\n unfold notC; split <;> simp_all [evalC, cTrue, cFalse]\ntheorem foldEq_eval {tab : List VDef} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int} {path : Path}\n (hM : Model tab env maps x) (hP : PathHolds path x) (k : Nat) (env' : Nat → Nat) (hk : ∀ i, i ≠ k → env' i = env i)\n (a b : E) : evalC env' maps (foldEq tab path k a b) = evalC env' maps (.eq a b) := by\n unfold foldEq\n split\n · simp only [evalC, evalE]; split <;> simp_all\n · rw [notC_eval]; simp only [evalC, evalE]; split <;> simp_all\n · simp only [evalC, evalE]; split <;> simp_all\n · rw [notC_eval]; simp only [evalC, evalE]; split <;> simp_all\n · exact decideC_eval hM hP k env' hk _\n\nmutual\n-- Each `if` whose condition is decided for every value of the key `k` under the path, resolved; the terms inside\n-- conditions simplified and decided parts pruned; nothing else changes.\ndef simpE (tab : List VDef) (path : Path) (k : Nat) : E → E\n | .var i => .var i\n | .const n => .const n\n | .add a b => .add (simpE tab path k a) (simpE tab path k b)\n | .sub a b => .sub (simpE tab path k a) (simpE tab path k b)\n | .mul m a => .mul m (simpE tab path k a)\n | .min a b => .min (simpE tab path k a) (simpE tab path k b)\n | .max a b => .max (simpE tab path k a) (simpE tab path k b)\n | .prod a b => .prod (simpE tab path k a) (simpE tab path k b)\n | .ite c t f =>\n match simpC tab path k c with\n | .le (.const 0) (.const 0) => simpE tab path k t\n | .lt (.const 0) (.const 0) => simpE tab path k f\n | c' => .ite c' (simpE tab path k t) (simpE tab path k f)\n | .get m key => .get m (simpE tab path k key)\n | .tup a b => .tup (simpE tab path k a) (simpE tab path k b)\n | .proj j a => .proj j (simpE tab path k a)\ndef simpC (tab : List VDef) (path : Path) (k : Nat) : C → C\n | .le a b => decideC tab path k (.le (simpE tab path k a) (simpE tab path k b))\n | .lt a b => decideC tab path k (.lt (simpE tab path k a) (simpE tab path k b))\n | .eq a b => foldEq tab path k (simpE tab path k a) (simpE tab path k b)\n | .and a b => andC (simpC tab path k a) (simpC tab path k b)\n | .or a b => orC (simpC tab path k a) (simpC tab path k b)\n | .not a => notC (simpC tab path k a)\nend\n\ndef whenPath (f : FrameCut) : Path := f.when.map (fun w => (w, true))\n\n-- The two counts share their key, and under `when` their bounds and bodies are the same terms.\ndef frameOk (tab : List VDef) (cs : List Count) (f : FrameCut) : Bool :=\n match findCount cs f.post, findCount cs f.pre with\n | some c₁, some c₀ => c₁.key == c₀.key\n && beqE (simpE tab (whenPath f) c₁.key c₁.below) (simpE tab (whenPath f) c₁.key c₀.below)\n && beqE (simpE tab (whenPath f) c₁.key c₁.body) (simpE tab (whenPath f) c₁.key c₀.body)\n | _, _ => false\n\n-- The rows a frame gives a leaf: post − pre ≤ 0 and pre − post ≤ 0, over the table's columns of the two variables.\ndef frameRows (tab : List VDef) (f : FrameCut) : List Cert.Row :=\n match findIdx (isVar f.post) tab, findIdx (isVar f.pre) tab with\n | some j₁, some j₀ => [lsub (lunit j₁) (lunit j₀), lsub (lunit j₀) (lunit j₁)]\n | _, _ => []\n\n-- Eligibility reads only the original split path.\ndef frameActive (path : Path) (f : FrameCut) : Bool := f.when.all (fun w => dec path w == some true)\n\n/-! Section 17.4 (MLDR-DESIGN.md): the per-key cut. A claim `post ≤ pre` between two counts of the same key and bound,\nproved for every value of the key by the kernel's own goal checker on an auxiliary goal — hypotheses: the cut's conditions\n(reading no key), the key below the bound, and the pre body below the post body at the key — and lifted to the sums by\n`sumBelow_mono`. Nothing new is trusted: the auxiliary goal is checked by `checkGoal`. -/\n\nstructure MonoCut where\n when : List C\n post : Nat\n pre : Nat\n tab : List VDef\n tree : Tree\n\ndef monoHyps (m : MonoCut) (c₁ c₀ : Count) : List C := m.when ++ [.lt (.var c₁.key) c₁.below, .lt c₀.body c₁.body]\n\ndef monoOk (cs : List Count) (m : MonoCut) : Bool :=\n match findCount cs m.post, findCount cs m.pre with\n | some c₁, some c₀ => c₁.key == c₀.key && beqE c₁.below c₀.below && !occE c₁.key c₁.below\n && m.when.all (fun c => !occC c₁.key c) && checkGoal ⟨m.tab, monoHyps m c₁ c₀⟩ m.tree\n | _, _ => false\n\n-- The row a cut gives a leaf: post − pre ≤ 0, over the table's columns of the two variables.\ndef monoRows (tab : List VDef) (m : MonoCut) : List Cert.Row :=\n match findIdx (isVar m.post) tab, findIdx (isVar m.pre) tab with\n | some j₁, some j₀ => [lsub (lunit j₁) (lunit j₀)]\n | _, _ => []\n\n-- Eligibility: every condition decided true on the original split path.\ndef monoActive (tab : List VDef) (path : Path) (m : MonoCut) : Bool := m.when.all (fun c => truth tab path c == some true)\n\ndef MonoHolds (tab : List VDef) (env : Nat → Nat) (maps : Nat → Nat → Nat) (m : MonoCut) (x : List Int) : Prop :=\n (∀ c ∈ m.when, evalC env maps c = true) → ∀ r ∈ monoRows tab m, Cert.eval r x ≤ 0\n\n/-- An accepted cut's row holds under its conditions, wherever both counts are their sums. -/\ntheorem mono_sound {tab : List VDef} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int}\n (hM : Model tab env maps x) {cs : List Count} (hc : ∀ c ∈ cs, c.Holds env maps)\n {m : MonoCut} (hok : monoOk cs m = true) : MonoHolds tab env maps m x := by\n intro hw r hr\n simp only [monoOk] at hok\n split at hok\n · rename_i c₁ c₀ h₁ h₀\n simp only [Bool.and_eq_true, beq_iff_eq, Bool.not_eq_true', List.all_eq_true] at hok\n obtain ⟨⟨⟨⟨hkey, hbelow⟩, hob⟩, hwhen⟩, hchk⟩ := hok\n have hb := beqE_eq hbelow\n have hm₁ := lookup_some h₁\n have hm₀ := lookup_some h₀\n have hv₁ : c₁.v = m.post := by simpa using hm₁.2\n have hv₀ : c₀.v = m.pre := by simpa using hm₀.2\n have H₁ : env c₁.v = sumBelow (fun kk => evalE (upd env c₁.key kk) maps c₁.body) (evalE env maps c₁.below) := hc c₁ hm₁.1\n have H₀ : env c₀.v = sumBelow (fun kk => evalE (upd env c₀.key kk) maps c₀.body) (evalE env maps c₀.below) := hc c₀ hm₀.1\n have hpt : ∀ kk, kk < evalE env maps c₁.below →\n evalE (upd env c₁.key kk) maps c₁.body ≤ evalE (upd env c₁.key kk) maps c₀.body := by\n intro kk hkk\n apply Classical.byContradiction\n intro hnot\n have hlt := Nat.lt_of_not_le hnot\n apply sound ⟨m.tab, monoHyps m c₁ c₀⟩ m.tree hchk (upd env c₁.key kk) maps\n intro c hcm\n simp only [monoHyps, List.mem_append, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hcm\n rcases hcm with hcm | rfl | rfl\n · have hk : ∀ i, occC i c = true → upd env c₁.key kk i = env i := fun i hi => by\n have hne : i ≠ c₁.key := fun he => by subst he; simp [hwhen c hcm] at hi\n simp [upd, hne]\n rw [congrC (upd env c₁.key kk) env maps c hk]\n exact hw c hcm\n · have hk : ∀ i, occE i c₁.below = true → upd env c₁.key kk i = env i := fun i hi => by\n have hne : i ≠ c₁.key := fun he => by subst he; simp [hob] at hi\n simp [upd, hne]\n simp only [evalC, evalE, decide_eq_true_eq]\n rw [congrE (upd env c₁.key kk) env maps c₁.below hk]\n simpa [upd] using hkk\n · simp only [evalC, decide_eq_true_eq]; exact hlt\n have hle : env c₁.v ≤ env c₀.v := by\n rw [H₁, H₀, ← hb, ← hkey]\n exact sumBelow_mono _ hpt\n simp only [monoRows] at hr\n split at hr\n · rename_i j₁ j₀ hj₁ hj₀\n have e₁ := var_col hM hj₁\n have e₀ := var_col hM hj₀\n simp only [List.mem_singleton] at hr\n subst hr\n rw [eval_lsub, eval_lunit, eval_lunit, e₁, e₀]\n rw [hv₁, hv₀] at hle\n omega\n · simp at hr\n · simp at hok\n\n/-! Section 17.5 (MLDR-DESIGN.md): the linear per-key cut. A claim Σ pos m·x_v ≤ Σ neg m·x_v over counts of one key and\nbound, proved for every value of the key by `checkGoal` on the auxiliary goal — the cut's conditions (reading no key), the key\nbelow the bound, and Σ neg m·body_v(k) < Σ pos m·body_v(k) — and lifted to the sums by the linearity of `sumBelow`. The per-key\ncut (MonoCut) is its one-term-a-side case. -/\n\nstructure LinCut where\n when : List C\n pos : List (Nat × Nat) -- (coefficient, count variable)\n neg : List (Nat × Nat)\n tab : List VDef\n tree : Tree\n\n-- The named counts with their coefficients, in order, or none.\ndef linCounts (cs : List Count) : List (Nat × Nat) → Option (List (Nat × Count))\n | [] => some []\n | (m, v) :: rest => match findCount cs v, linCounts cs rest with\n | some c, some tl => some ((m, c) :: tl)\n | _, _ => none\n\n-- Σ m·body, as a term; the counts share their key, so every body reads it as written.\ndef linTerm : List (Nat × Count) → E\n | [] => .const 0\n | (m, c) :: rest => .add (.mul m c.body) (linTerm rest)\n\n-- Σ m·x_v as a row over the table's columns of the variables, or none.\ndef linRow (tab : List VDef) : List (Nat × Nat) → Option Cert.Row\n | [] => some (lconst 0)\n | (m, v) :: rest => match findIdx (isVar v) tab, linRow tab rest with\n | some j, some r => some (ladd (lscale (m : Int) (lunit j)) r)\n | _, _ => none\n\ndef sameShape (c₀ : Count) (xs : List (Nat × Count)) : Bool := xs.all (fun p => p.2.key == c₀.key && beqE p.2.below c₀.below)\n\ndef linHyps (l : LinCut) (c₀ : Count) (ps ns : List (Nat × Count)) : List C :=\n l.when ++ [.lt (.var c₀.key) c₀.below, .lt (linTerm ns) (linTerm ps)]\n\ndef linOk (cs : List Count) (l : LinCut) : Bool :=\n match linCounts cs l.pos, linCounts cs l.neg with\n | some ps, some ns => match ps ++ ns with\n | [] => false\n | (_, c₀) :: _ => sameShape c₀ ps && sameShape c₀ ns && !occE c₀.key c₀.below && l.when.all (fun c => !occC c₀.key c)\n && checkGoal ⟨l.tab, linHyps l c₀ ps ns⟩ l.tree\n | _, _ => false\n\ndef linRows (tab : List VDef) (l : LinCut) : List Cert.Row :=\n match linRow tab l.pos, linRow tab l.neg with\n | some rp, some rn => [lsub rp rn]\n | _, _ => []\n\ndef linActive (tab : List VDef) (path : Path) (l : LinCut) : Bool := l.when.all (fun c => truth tab path c == some true)\n\ndef LinHolds (tab : List VDef) (env : Nat → Nat) (maps : Nat → Nat → Nat) (l : LinCut) (x : List Int) : Prop :=\n (∀ c ∈ l.when, evalC env maps c = true) → ∀ r ∈ linRows tab l, Cert.eval r x ≤ 0\n\n-- Σ m·(sum of the body below the bound), in Nat, and Σ m·(the variable), in Int.\ndef linSumN (env : Nat → Nat) (maps : Nat → Nat → Nat) (key n : Nat) : List (Nat × Count) → Nat\n | [] => 0\n | (m, c) :: rest => m * sumBelow (fun kk => evalE (upd env key kk) maps c.body) n + linSumN env maps key n rest\ndef linSumZ (env : Nat → Nat) : List (Nat × Nat) → Int\n | [] => 0\n | (m, v) :: rest => (m : Int) * ((env v : Nat) : Int) + linSumZ env rest\n\ntheorem linTerm_eval (ρ : Nat → Nat) (M : Nat → Nat → Nat) : ∀ xs : List (Nat × Count),\n evalE ρ M (linTerm xs) = (xs.map (fun p => p.1 * evalE ρ M p.2.body)).sum\n | [] => by simp [linTerm, evalE]\n | (m, c) :: rest => by simp [linTerm, evalE, linTerm_eval ρ M rest]\n\ntheorem sumBelow_linTerm (env : Nat → Nat) (maps : Nat → Nat → Nat) (key n : Nat) : ∀ xs : List (Nat × Count),\n sumBelow (fun kk => evalE (upd env key kk) maps (linTerm xs)) n = linSumN env maps key n xs\n | [] => by simp [linTerm, evalE, linSumN, sumBelow_zero_fn]\n | (m, c) :: rest => by\n have h : (fun kk => evalE (upd env key kk) maps (linTerm ((m, c) :: rest)))\n = fun kk => m * evalE (upd env key kk) maps c.body + evalE (upd env key kk) maps (linTerm rest) := by\n funext kk; simp [linTerm, evalE]\n rw [h, sumBelow_add, sumBelow_mul, sumBelow_linTerm env maps key n rest]; rfl\n\n-- The row's value is Σ m·x[j] = Σ m·env v.\ntheorem linRow_eval {tab : List VDef} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int} (hM : Model tab env maps x) :\n ∀ (xs : List (Nat × Nat)) (r : Cert.Row), linRow tab xs = some r → Cert.eval r x = linSumZ env xs\n | [], r, h => by simp only [linRow, Option.some.injEq] at h; subst h; simp [linSumZ, eval_lconst]\n | (m, v) :: rest, r, h => by\n simp only [linRow] at h\n split at h\n · rename_i j r' hj hr\n simp only [Option.some.injEq] at h; subst h\n rw [eval_ladd, eval_lscale, eval_lunit, var_col hM hj, linRow_eval hM rest r' hr]; rfl\n · simp at h\n\n-- With every named count its sum (of the shared key and bound), Σ m·env v is Σ m·(its body summed below the bound).\ntheorem linSum_holds {env : Nat → Nat} {maps : Nat → Nat → Nat} {cs : List Count} (hc : ∀ c ∈ cs, c.Holds env maps) (c₀ : Count) :\n ∀ (vs : List (Nat × Nat)) (ps : List (Nat × Count)), linCounts cs vs = some ps → sameShape c₀ ps = true →\n linSumZ env vs = ((linSumN env maps c₀.key (evalE env maps c₀.below) ps : Nat) : Int)\n | [], ps, h, _ => by simp only [linCounts, Option.some.injEq] at h; subst h; simp [linSumZ, linSumN]\n | (m, v) :: rest, ps, h, hs => by\n simp only [linCounts] at h\n split at h\n · rename_i c tl hfind htl\n simp only [Option.some.injEq] at h; subst h\n simp only [sameShape, List.all_cons, Bool.and_eq_true, beq_iff_eq] at hs\n obtain ⟨⟨hkey, hbelow⟩, hrest⟩ := hs\n have hb := beqE_eq hbelow\n have hm := lookup_some hfind\n have hv : c.v = v := by simpa using hm.2\n have H : env c.v = sumBelow (fun kk => evalE (upd env c.key kk) maps c.body) (evalE env maps c.below) := hc c hm.1\n simp only [linSumZ, linSumN]\n rw [← hv, H, hkey, hb, linSum_holds hc c₀ rest tl htl (by simpa [sameShape] using hrest)]\n simp [Int.natCast_add, Int.natCast_mul]\n · simp at h\n\n/-- An accepted linear cut's row holds under its conditions, wherever the named counts are their sums. -/\ntheorem lin_sound {tab : List VDef} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int}\n (hM : Model tab env maps x) {cs : List Count} (hc : ∀ c ∈ cs, c.Holds env maps)\n {l : LinCut} (hok : linOk cs l = true) : LinHolds tab env maps l x := by\n intro hw r hr\n simp only [linOk] at hok\n split at hok\n · rename_i ps ns hps hns\n split at hok\n · simp at hok\n · rename_i c₀ tl hcons\n simp only [Bool.and_eq_true, Bool.not_eq_true', List.all_eq_true] at hok\n obtain ⟨⟨⟨⟨hsp, hsn⟩, hob⟩, hwhen⟩, hchk⟩ := hok\n -- pointwise: Σ pos ≤ Σ neg at every key below the bound\n have hpt : ∀ kk, kk < evalE env maps c₀.below →\n evalE (upd env c₀.key kk) maps (linTerm ps) ≤ evalE (upd env c₀.key kk) maps (linTerm ns) := by\n intro kk hkk\n apply Classical.byContradiction\n intro hnot\n have hlt := Nat.lt_of_not_le hnot\n apply sound ⟨l.tab, linHyps l c₀ ps ns⟩ l.tree hchk (upd env c₀.key kk) maps\n intro c hcm\n simp only [linHyps, List.mem_append, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hcm\n rcases hcm with hcm | rfl | rfl\n · have hk : ∀ i, occC i c = true → upd env c₀.key kk i = env i := fun i hi => by\n have hne : i ≠ c₀.key := fun he => by subst he; simp [hwhen c hcm] at hi\n simp [upd, hne]\n rw [congrC (upd env c₀.key kk) env maps c hk]\n exact hw c hcm\n · have hk : ∀ i, occE i c₀.below = true → upd env c₀.key kk i = env i := fun i hi => by\n have hne : i ≠ c₀.key := fun he => by subst he; simp [hob] at hi\n simp [upd, hne]\n simp only [evalC, evalE, decide_eq_true_eq]\n rw [congrE (upd env c₀.key kk) env maps c₀.below hk]\n simpa [upd] using hkk\n · simp only [evalC, decide_eq_true_eq]; exact hlt\n have hsum := sumBelow_mono (evalE env maps c₀.below) hpt\n rw [sumBelow_linTerm, sumBelow_linTerm] at hsum\n -- the row\n simp only [linRows] at hr\n split at hr\n · rename_i rp rn hrp hrn\n simp only [List.mem_singleton] at hr\n subst hr\n rw [eval_lsub, linRow_eval hM l.pos rp hrp, linRow_eval hM l.neg rn hrn,\n linSum_holds hc c₀ l.pos ps hps hsp, linSum_holds hc c₀ l.neg ns hns hsn]\n have hz : ((linSumN env maps c₀.key (evalE env maps c₀.below) ps : Nat) : Int) ≤ ((linSumN env maps c₀.key (evalE env maps c₀.below) ns : Nat) : Int) := Int.ofNat_le.mpr hsum\n omega\n · simp at hr\n · simp at hok\n\n-- The active frames' rows in front of the lemma path.\ndef framePath (tab : List VDef) (frames : List FrameCut) (monos : List MonoCut) (lemmas : List CutLemma) (path : Path) (lins : List LinCut := []) : Path :=\n (lins.filter (linActive tab path)).flatMap (fun l => (linRows tab l).map (fun r => (r, true)))\n ++ ((monos.filter (monoActive tab path)).flatMap (fun m => (monoRows tab m).map (fun r => (r, true)))\n ++ ((frames.filter (frameActive path)).flatMap (fun f => (frameRows tab f).map (fun r => (r, true))) ++ lemmaPath lemmas path))\n\ndef checkTFrames (tab : List VDef) (hyps : List C) (lemmas : List CutLemma) (frames : List FrameCut) (monos : List MonoCut) (lins : List LinCut) : Path → Tree → Bool\n | path, .split l y n => checkTFrames tab hyps lemmas frames monos lins ((l, true) :: path) y && checkTFrames tab hyps lemmas frames monos lins ((l, false) :: path) n\n | path, t => checkT tab hyps (framePath tab frames monos lemmas path lins) t\n\ndef checkGoalFrames (g : Goal) (cs : List Count) (t : Tree) (lemmas : List CutLemma) (frames : List FrameCut) (monos : List MonoCut := []) (lins : List LinCut := []) : Bool :=\n wfTab 0 g.tab && lemmas.all (checkLemma g.tab g.hyps) && frames.all (frameOk g.tab cs) && monos.all (monoOk cs) && lins.all (linOk cs) && checkTFrames g.tab g.hyps lemmas frames monos lins [] t\n\n@[simp] theorem framePath_nil (tab : List VDef) (lemmas : List CutLemma) (path : Path) : framePath tab [] [] lemmas path [] = lemmaPath lemmas path := rfl\n\n@[simp] theorem checkTFrames_nil (tab : List VDef) (hyps : List C) (lemmas : List CutLemma) (t : Tree) (path : Path) :\n checkTFrames tab hyps lemmas [] [] [] path t = checkTLemmas tab hyps lemmas path t := by\n induction t generalizing path with\n | split l y n ihy ihn => simp only [checkTFrames, checkTLemmas, ihy, ihn]\n | leaf rows steps eqs prods => rfl\n | leafAt rows steps eqs prods => rfl\n | leafSq rows sqs steps eqs prods => rfl\n\n@[simp] theorem checkGoalFrames_nil (g : Goal) (cs : List Count) (t : Tree) (lemmas : List CutLemma) :\n checkGoalFrames g cs t lemmas [] = checkGoalLemmas g t lemmas := by\n simp [checkGoalFrames, checkGoalLemmas]\n\nmutual\n/-- Resolving decided conditions keeps a term's value, at any environment that differs from the model's only at the\nkey. -/\ntheorem simpE_eval {tab : List VDef} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int} {path : Path}\n (hM : Model tab env maps x) (hP : PathHolds path x) (k : Nat) (env' : Nat → Nat) (hk : ∀ i, i ≠ k → env' i = env i) :\n (e : E) → evalE env' maps (simpE tab path k e) = evalE env' maps e\n | .var i => rfl\n | .const n => rfl\n | .add a b => by simp only [simpE, evalE, simpE_eval hM hP k env' hk a, simpE_eval hM hP k env' hk b]\n | .sub a b => by simp only [simpE, evalE, simpE_eval hM hP k env' hk a, simpE_eval hM hP k env' hk b]\n | .mul m a => by simp only [simpE, evalE, simpE_eval hM hP k env' hk a]\n | .min a b => by simp only [simpE, evalE, simpE_eval hM hP k env' hk a, simpE_eval hM hP k env' hk b]\n | .max a b => by simp only [simpE, evalE, simpE_eval hM hP k env' hk a, simpE_eval hM hP k env' hk b]\n | .prod a b => by simp only [simpE, evalE, simpE_eval hM hP k env' hk a, simpE_eval hM hP k env' hk b]\n | .get m key => by simp only [simpE, evalE, simpE_eval hM hP k env' hk key]\n | .tup a b => by simp only [simpE, evalE, simpE_eval hM hP k env' hk a, simpE_eval hM hP k env' hk b]\n | .proj j a => by simp only [simpE, evalE, simpE_eval hM hP k env' hk a]\n | .ite c t f => by\n have ht := simpE_eval hM hP k env' hk t\n have hf := simpE_eval hM hP k env' hk f\n have hc := simpC_eval hM hP k env' hk c\n simp only [simpE]\n split\n · rename_i heq\n rw [heq] at hc\n have hc' : evalC env' maps c = true := by simpa [evalC] using hc.symm\n simp only [evalE, hc', ite_true, ht]\n · rename_i heq\n rw [heq] at hc\n have hc' : evalC env' maps c = false := by simpa [evalC] using hc.symm\n simp only [evalE, hc', Bool.false_eq_true, ite_false, hf]\n · simp only [evalE, hc, ht, hf]\ntheorem simpC_eval {tab : List VDef} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int} {path : Path}\n (hM : Model tab env maps x) (hP : PathHolds path x) (k : Nat) (env' : Nat → Nat) (hk : ∀ i, i ≠ k → env' i = env i) :\n (c : C) → evalC env' maps (simpC tab path k c) = evalC env' maps c\n | .le a b => by\n have ha := simpE_eval hM hP k env' hk a\n have hb := simpE_eval hM hP k env' hk b\n simp only [simpC]; rw [decideC_eval hM hP k env' hk]; simp only [evalC, ha, hb]\n | .lt a b => by\n have ha := simpE_eval hM hP k env' hk a\n have hb := simpE_eval hM hP k env' hk b\n simp only [simpC]; rw [decideC_eval hM hP k env' hk]; simp only [evalC, ha, hb]\n | .eq a b => by\n have ha := simpE_eval hM hP k env' hk a\n have hb := simpE_eval hM hP k env' hk b\n simp only [simpC]; rw [foldEq_eval hM hP k env' hk]; simp only [evalC, ha, hb]\n | .and a b => by simp only [simpC, andC_eval, evalC, simpC_eval hM hP k env' hk a, simpC_eval hM hP k env' hk b]\n | .or a b => by simp only [simpC, orC_eval, evalC, simpC_eval hM hP k env' hk a, simpC_eval hM hP k env' hk b]\n | .not a => by simp only [simpC, notC_eval, evalC, simpC_eval hM hP k env' hk a]\nend\n\ndef FrameHolds (tab : List VDef) (f : FrameCut) (x : List Int) : Prop :=\n (∀ w ∈ f.when, Cert.eval w x ≤ 0) → ∀ r ∈ frameRows tab f, Cert.eval r x ≤ 0\n\n/-- An accepted frame's rows hold under its conditions, wherever both counts are their sums. -/\ntheorem frame_sound {tab : List VDef} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int}\n (hM : Model tab env maps x) {cs : List Count} (hc : ∀ c ∈ cs, c.Holds env maps)\n {f : FrameCut} (hok : frameOk tab cs f = true) : FrameHolds tab f x := by\n intro hw\n have hP : PathHolds (whenPath f) x := by\n intro a ha\n obtain ⟨w, hwm, rfl⟩ := List.mem_map.mp ha\n simpa using hw w hwm\n simp only [frameOk] at hok\n split at hok\n · rename_i c₁ c₀ h₁ h₀\n simp only [Bool.and_eq_true, beq_iff_eq] at hok\n obtain ⟨⟨hkey, hbelow⟩, hbody⟩ := hok\n have hb := beqE_eq hbelow\n have hd := beqE_eq hbody\n have hm₁ := lookup_some h₁\n have hm₀ := lookup_some h₀\n have hv₁ : c₁.v = f.post := by simpa using hm₁.2\n have hv₀ : c₀.v = f.pre := by simpa using hm₀.2\n have H₁ : env c₁.v = sumBelow (fun kk => evalE (upd env c₁.key kk) maps c₁.body) (evalE env maps c₁.below) := hc c₁ hm₁.1\n have H₀ : env c₀.v = sumBelow (fun kk => evalE (upd env c₀.key kk) maps c₀.body) (evalE env maps c₀.below) := hc c₀ hm₀.1\n have heq : env f.post = env f.pre := by\n rw [← hv₁, ← hv₀, H₁, H₀]\n have eb : evalE env maps c₁.below = evalE env maps c₀.below := by\n rw [← simpE_eval hM hP c₁.key env (fun _ _ => rfl) c₁.below, hb, simpE_eval hM hP c₁.key env (fun _ _ => rfl) c₀.below]\n rw [eb]\n apply sumBelow_congr\n intro kk _\n have hk' : ∀ i, i ≠ c₁.key → upd env c₁.key kk i = env i := fun i hi => by simp [upd, hi]\n rw [← simpE_eval hM hP c₁.key (upd env c₁.key kk) hk' c₁.body, hd, simpE_eval hM hP c₁.key (upd env c₁.key kk) hk' c₀.body, hkey]\n intro r hr\n simp only [frameRows] at hr\n split at hr\n · rename_i j₁ j₀ hj₁ hj₀\n have e₁ := var_col hM hj₁\n have e₀ := var_col hM hj₀\n simp only [List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hr\n rcases hr with rfl | rfl\n · rw [eval_lsub, eval_lunit, eval_lunit, e₁, e₀, heq]; omega\n · rw [eval_lsub, eval_lunit, eval_lunit, e₁, e₀, heq]; omega\n · simp at hr\n · simp at hok\n\ntheorem framePath_holds {tab : List VDef} {env : Nat → Nat} {maps : Nat → Nat → Nat} {frames : List FrameCut} {monos : List MonoCut}\n {lins : List LinCut} {lemmas : List CutLemma} {path : Path} {x : List Int}\n (hM : Model tab env maps x) (hP : PathHolds path x) (hL : ∀ l ∈ lemmas, CutHolds l x) (hF : ∀ f ∈ frames, FrameHolds tab f x)\n (hMo : ∀ m ∈ monos, MonoHolds tab env maps m x) (hLi : ∀ l ∈ lins, LinHolds tab env maps l x) :\n PathHolds (framePath tab frames monos lemmas path lins) x := by\n intro a ha\n rcases List.mem_append.mp ha with ha | ha\n · obtain ⟨l, hl, ha⟩ := List.mem_flatMap.mp ha\n obtain ⟨hlm, hactive⟩ := List.mem_filter.mp hl\n obtain ⟨r, hr, rfl⟩ := List.mem_map.mp ha\n have hwhen : ∀ c ∈ l.when, evalC env maps c = true := fun c hc => by\n have ht : truth tab path c = some true := by\n simpa only [linActive, List.all_eq_true, beq_iff_eq] using (List.all_eq_true.mp hactive c hc)\n exact truth_sound hM hP c true ht\n simpa using hLi l hlm hwhen r hr\n rcases List.mem_append.mp ha with ha | ha\n · obtain ⟨m, hm, ha⟩ := List.mem_flatMap.mp ha\n obtain ⟨hmm, hactive⟩ := List.mem_filter.mp hm\n obtain ⟨r, hr, rfl⟩ := List.mem_map.mp ha\n have hwhen : ∀ c ∈ m.when, evalC env maps c = true := fun c hc => by\n have ht : truth tab path c = some true := by\n simpa only [monoActive, List.all_eq_true, beq_iff_eq] using (List.all_eq_true.mp hactive c hc)\n exact truth_sound hM hP c true ht\n simpa using hMo m hmm hwhen r hr\n rcases List.mem_append.mp ha with ha | ha\n · obtain ⟨f, hf, ha⟩ := List.mem_flatMap.mp ha\n obtain ⟨hfm, hactive⟩ := List.mem_filter.mp hf\n obtain ⟨r, hr, rfl⟩ := List.mem_map.mp ha\n have hwhen : ∀ w ∈ f.when, Cert.eval w x ≤ 0 := fun w hw => by\n have hd : dec path w = some true := by\n simpa only [frameActive, List.all_eq_true, beq_iff_eq] using (List.all_eq_true.mp hactive w hw)\n have := dec_sound hP hd\n simpa using this\n simpa using hF f hfm hwhen r hr\n · exact lemmaPath_holds hP hL a ha\n\ntheorem checkTFrames_sound {tab : List VDef} {hyps : List C} {env : Nat → Nat} {maps : Nat → Nat → Nat} {x : List Int}\n (hM : Model tab env maps x) (hH : ∀ c ∈ hyps, evalC env maps c = true)\n {lemmas : List CutLemma} (hL : ∀ l ∈ lemmas, CutHolds l x) {frames : List FrameCut} (hF : ∀ f ∈ frames, FrameHolds tab f x)\n {monos : List MonoCut} (hMo : ∀ m ∈ monos, MonoHolds tab env maps m x) {lins : List LinCut} (hLi : ∀ l ∈ lins, LinHolds tab env maps l x) :\n ∀ (t : Tree) (path : Path), PathHolds path x → checkTFrames tab hyps lemmas frames monos lins path t = true → False\n | .split l y n, path, hP, h => by\n simp only [checkTFrames, Bool.and_eq_true] at h\n by_cases hl : Cert.eval l x ≤ 0\n · refine checkTFrames_sound hM hH hL hF hMo hLi y _ ?_ h.1\n intro a ha\n rcases List.mem_cons.mp ha with rfl | ha\n · simpa using hl\n · exact hP a ha\n · refine checkTFrames_sound hM hH hL hF hMo hLi n _ ?_ h.2\n intro a ha\n rcases List.mem_cons.mp ha with rfl | ha\n · simpa using hl\n · exact hP a ha\n | .leaf rows steps eqs prods, path, hP, h =>\n checkT_sound hM hH _ _ (framePath_holds hM hP hL hF hMo hLi) h\n | .leafAt rows steps eqs prods, path, hP, h =>\n checkT_sound hM hH _ _ (framePath_holds hM hP hL hF hMo hLi) h\n | .leafSq rows sqs steps eqs prods, path, hP, h =>\n checkT_sound hM hH _ _ (framePath_holds hM hP hL hF hMo hLi) h\n\n/-- The goal checker with frames has the original unsatisfiability conclusion, wherever the named counts are their\nsums. -/\ntheorem goalFrames_sound (g : Goal) (cs : List Count) (t : Tree) (lemmas : List CutLemma) (frames : List FrameCut) (monos : List MonoCut) (lins : List LinCut)\n (h : checkGoalFrames g cs t lemmas frames monos lins = true) (env : Nat → Nat) (maps : Nat → Nat → Nat)\n (hc : ∀ c ∈ cs, c.Holds env maps) : ¬ ∀ c ∈ g.hyps, evalC env maps c = true := by\n intro hH\n simp only [checkGoalFrames, Bool.and_eq_true, List.all_eq_true] at h\n obtain ⟨⟨⟨⟨⟨hw, hl⟩, hf⟩, hmo⟩, hli⟩, ht⟩ := h\n have hv := build_valid env maps g.tab [] [] ⟨rfl, by simp, by simp⟩ (by simpa using hw)\n simp only [List.nil_append] at hv\n have hM := model_of_valid hv\n exact checkTFrames_sound hM hH (fun l hm => lemma_sound hM hH (hl l hm)) (fun f hm => frame_sound hM hc (hf f hm)) (fun m hm => mono_sound hM hc (hmo m hm)) (fun l hm => lin_sound hM hc (hli l hm)) t [] (by simp [PathHolds]) ht\n\nend FrameCuts\n\n-- The check: fresh witnesses, every instance built, then the same goal extended by checked conditional cuts.\ndef checkCounted (g : CGoal) (is : List CInst) (tab : List VDef) (t : Tree) (lemmas : List CutLemma := []) : Bool :=\n countedOk g.hyps g.counts is && match countHyps g.counts is with\n | some hs => checkGoalLemmas ⟨tab, g.hyps ++ hs⟩ t lemmas\n | none => false\n\n/-- With no lemma entries the old counted check is unchanged. -/\ntheorem checkCounted_nil (g : CGoal) (is : List CInst) (tab : List VDef) (t : Tree) :\n checkCounted g is tab t [] = (countedOk g.hyps g.counts is && match countHyps g.counts is with\n | some hs => checkGoal ⟨tab, g.hyps ++ hs⟩ t\n | none => false) := by\n simp only [checkCounted, checkGoalLemmas_nil]\n\n/-! Soundness -/\n\ntheorem cDistinct_cons {a : Nat} {as : List Nat} (h : cDistinct (a :: as) = true) : a ∉ as ∧ cDistinct as = true := by\n simp only [cDistinct, Bool.and_eq_true] at h\n refine ⟨fun hm => ?_, h.2⟩\n have h1 := h.1\n simp at h1\n exact h1 hm\n\ntheorem applyS_one (k : Nat) (t : E) (ρ : Nat → Nat) (M : Nat → Nat → Nat) : applyS [(k, t)] ρ M = upd ρ k (evalE ρ M t) := by\n funext i\n simp only [applyS, assoc, lookup, upd]\n by_cases h : i = k\n · subst h; simp\n · have hb : (k == i) = false := by simp; omega\n simp [hb, h]\n\ntheorem resolve_mem {cs : List Count} {B : E} : ∀ {ts : List (Int × Nat)} {rs : List (Int × Count)},\n resolve cs B ts = some rs → ∀ r ∈ rs, r.2 ∈ cs ∧ r.2.below = B\n | [], rs, h => by simp only [resolve, Option.some.injEq] at h; subst h; simp\n | t :: ts, rs, h => by\n cases hc : findCount cs t.2 with\n | none => simp [resolve, hc] at h\n | some c =>\n by_cases hb : beqE c.below B = true\n · cases hr : resolve cs B ts with\n | none => simp [resolve, hc, hb, hr] at h\n | some rs' =>\n simp [resolve, hc, hb, hr] at h\n subst h\n intro r hr'\n rcases List.mem_cons.mp hr' with rfl | hr'\n · exact ⟨(lookup_some hc).1, beqE_eq hb⟩\n · exact resolve_mem hr r hr'\n · simp [resolve, hc, hb] at h\n\ntheorem countHyps_mem {cs : List Count} : ∀ {is : List CInst} {hs : List C}, countHyps cs is = some hs → ∀ h ∈ hs, ∃ i ∈ is, countHyp cs i = some h\n | [], hs, hh => by simp only [countHyps, Option.some.injEq] at hh; subst hh; simp\n | i :: is, hs, hh => by\n cases e1 : countHyp cs i with\n | none => simp [countHyps, e1] at hh\n | some h1 =>\n cases e2 : countHyps cs is with\n | none => simp [countHyps, e1, e2] at hh\n | some hs' =>\n simp [countHyps, e1, e2] at hh\n subst hh\n intro h hm\n rcases List.mem_cons.mp hm with rfl | hm\n · exact ⟨i, List.mem_cons_self, e1⟩\n · obtain ⟨j, hj, hj'⟩ := countHyps_mem e2 h hm\n exact ⟨j, List.mem_cons_of_mem _ hj, hj'⟩\n\n-- The two sides, evaluated: the counts' combination, and the bodies' at a key.\ndef sumSide (part : Int → Nat) (ρ : Nat → Nat) : List (Int × Count) → Nat\n | [] => 0\n | r :: rs => part r.1 * ρ r.2.v + sumSide part ρ rs\ndef ptSide (part : Int → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat) : List (Int × Count) → Nat → Nat\n | [], _ => 0\n | r :: rs, k => part r.1 * evalE (upd ρ r.2.key k) M r.2.body + ptSide part ρ M rs k\n\ntheorem eval_sumE_count (part : Int → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat) : ∀ rs : List (Int × Count),\n evalE ρ M (sumE (rs.map fun r => .mul (part r.1) (atCount r.2))) = sumSide part ρ rs\n | [] => by simp [sumE, evalE, sumSide]\n | r :: rs => by\n simp only [List.map_cons, sumE, evalE, eval_sumE_count part ρ M rs]\n simp [atCount, evalE, sumSide]\n\ntheorem eval_sumE_wit (part : Int → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (w : Nat) : ∀ rs : List (Int × Count),\n evalE ρ M (sumE (rs.map fun r => .mul (part r.1) (atWit w r.2))) = ptSide part ρ M rs (ρ w)\n | [] => by simp [sumE, evalE, ptSide]\n | r :: rs => by\n simp only [List.map_cons, sumE, evalE, eval_sumE_wit part ρ M w rs]\n simp only [ptSide, atWit, subst_evalE, applyS_one, evalE]\n\n-- With every count its sum below one bound, the counts' combination sums the bodies' over the keys below it.\ntheorem sumSide_eq (part : Int → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (n : Nat) : ∀ rs : List (Int × Count),\n (∀ r ∈ rs, ρ r.2.v = sumBelow (fun k => evalE (upd ρ r.2.key k) M r.2.body) n) →\n sumSide part ρ rs = sumBelow (ptSide part ρ M rs) n\n | [], _ => by\n have : ptSide part ρ M [] = fun _ => 0 := funext fun k => by simp [ptSide]\n simp [sumSide, this, sumBelow_const]\n | r :: rs, h => by\n simp only [sumSide]\n have hp : ptSide part ρ M (r :: rs) = fun k => part r.1 * evalE (upd ρ r.2.key k) M r.2.body + ptSide part ρ M rs k := rfl\n rw [hp, sumBelow_add, sumBelow_mul, ← h r List.mem_cons_self, sumSide_eq part ρ M n rs (fun r' hr' => h r' (List.mem_cons_of_mem _ hr'))]\n\n-- The witness values a state gives the instances' witnesses.\ndef setWits (ρ : Nat → Nat) (ws : List (Nat × Nat)) : Nat → Nat := fun j =>\n match lookup (fun p => p.1 == j) ws with\n | some p => p.2\n | none => ρ j\n\ntheorem setWits_other {ρ : Nat → Nat} {ws : List (Nat × Nat)} {j : Nat} (h : j ∉ ws.map (·.1)) : setWits ρ ws j = ρ j := by\n have hl : lookup (fun p => p.1 == j) ws = none :=\n lookup_none (fun p hp => by simp only [beq_eq_false_iff_ne]; intro he; exact h (by rw [← he]; exact List.mem_map_of_mem hp))\n simp [setWits, hl]\n\ntheorem setWits_at {ρ : Nat → Nat} : ∀ {ws : List (Nat × Nat)}, cDistinct (ws.map (·.1)) = true → ∀ {p : Nat × Nat}, p ∈ ws → setWits ρ ws p.1 = p.2\n | [], _, _, hp => by simp at hp\n | a :: as, hd, p, hp => by\n simp only [List.map_cons] at hd\n obtain ⟨hna, hd'⟩ := cDistinct_cons hd\n rcases List.mem_cons.mp hp with rfl | hp'\n · simp [setWits, lookup]\n · have hne : (a.1 == p.1) = false := by\n simp only [beq_eq_false_iff_ne]; intro he; exact hna (by rw [he]; exact List.mem_map_of_mem hp')\n have ih := setWits_at (ρ := ρ) hd' hp'\n simp only [setWits, lookup, hne, Bool.false_eq_true, ite_false] at ih ⊢\n exact ih\n\ntheorem witFresh_parts {hyps : List C} {cs : List Count} {is : List CInst} {w : Nat} (h : witFresh hyps cs is w = true) :\n (∀ h' ∈ hyps, occC w h' = false) ∧ (∀ c ∈ cs, c.v ≠ w ∧ occE w c.below = false ∧ occE w c.body = false) ∧ (∀ j ∈ is, occE w j.below = false) := by\n simp only [witFresh, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at h\n exact ⟨h.1.1, fun c hc => ⟨(h.1.2 c hc).1.1, (h.1.2 c hc).1.2, (h.1.2 c hc).2⟩, h.2⟩\n\n/-- The kind is sound: an accepted counted goal's hypotheses hold at no naturals and maps where every count is its\nsum. -/\ntheorem counted_sound (g : CGoal) (is : List CInst) (tab : List VDef) (t : Tree) {lemmas : List CutLemma}\n (hck : checkCounted g is tab t lemmas = true)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hc : ∀ c ∈ g.counts, c.Holds ρ M) : ¬ ∀ h ∈ g.hyps, evalC ρ M h = true := by\n intro hH\n simp only [checkCounted, Bool.and_eq_true] at hck\n obtain ⟨hok, hgoal⟩ := hck\n simp only [countedOk, Bool.and_eq_true, List.all_eq_true] at hok\n obtain ⟨hdist, hfresh⟩ := hok\n cases hhs : countHyps g.counts is with\n | none => simp [hhs] at hgoal\n | some hs =>\n simp only [hhs] at hgoal\n -- Each instance's witness value, chosen at ρ: a key below the bound where the combination is positive, when its sum is.\n have hx : ∀ i : CInst, ∃ x : Nat, ∀ rs, resolve g.counts i.below i.terms = some rs →\n sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below) ≤ sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below)\n ∨ (x < evalE ρ M i.below ∧ ptSide negP ρ M rs x + negP i.unit < ptSide posP ρ M rs x + posP i.unit) := by\n intro i\n cases hr : resolve g.counts i.below i.terms with\n | none => exact ⟨0, fun rs h => by simp at h⟩\n | some rs =>\n by_cases hlt : sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below) < sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below)\n · obtain ⟨k, hk, hk'⟩ := exists_lt_of_sumBelow_lt hlt\n exact ⟨k, fun rs' h => by simp only [Option.some.injEq] at h; subst h; exact Or.inr ⟨hk, hk'⟩⟩\n · exact ⟨0, fun rs' h => by simp only [Option.some.injEq] at h; subst h; exact Or.inl (Nat.le_of_not_lt hlt)⟩\n obtain ⟨xs, hxs⟩ : ∃ xs : CInst → Nat, ∀ i rs, resolve g.counts i.below i.terms = some rs →\n sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below) ≤ sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below)\n ∨ (xs i < evalE ρ M i.below ∧ ptSide negP ρ M rs (xs i) + negP i.unit < ptSide posP ρ M rs (xs i) + posP i.unit) :=\n ⟨fun i => Classical.choose (hx i), fun i => Classical.choose_spec (hx i)⟩\n -- ρs: ρ with each witness set to its value.\n obtain ⟨ρs, hother, hat⟩ : ∃ ρs : Nat → Nat, (∀ j, (∀ i ∈ is, i.wit ≠ j) → ρs j = ρ j) ∧ (∀ i ∈ is, ρs i.wit = xs i) := by\n have hws : (is.map fun i => (i.wit, xs i)).map (·.1) = is.map (·.wit) := by induction is <;> simp_all\n refine ⟨setWits ρ (is.map fun i => (i.wit, xs i)), fun j hj => setWits_other ?_, fun i hi => ?_⟩\n · rw [hws]; intro hm; obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hm; exact hj i hi rfl\n · exact setWits_at (ρ := ρ) (ws := is.map fun i => (i.wit, xs i)) (by rw [hws]; exact hdist) (p := (i.wit, xs i)) (List.mem_map.mpr ⟨i, hi, rfl⟩)\n -- What the witnesses' freshness gives: counts and bounds read alike at ρs and ρ.\n have hvar : ∀ c ∈ g.counts, ρs c.v = ρ c.v := fun c hc =>\n hother c.v (fun i hi he => ((witFresh_parts (hfresh i hi)).2.1 c hc).1 he.symm)\n have hbound : ∀ e : E, (∀ i ∈ is, occE i.wit e = false) → evalE ρs M e = evalE ρ M e := fun e he =>\n congrE ρs ρ M e (fun j hj => hother j (fun i hi hij => by have := he i hi; rw [hij] at this; simp [this] at hj))\n have hbody : ∀ c ∈ g.counts, ∀ k, evalE (upd ρs c.key k) M c.body = evalE (upd ρ c.key k) M c.body := fun c hc k =>\n congrE _ _ M c.body (fun j hj => by\n simp only [upd]; split\n · rfl\n · exact hother j (fun i hi hij => by\n have := ((witFresh_parts (hfresh i hi)).2.1 c hc).2.2; rw [hij] at this; simp [this] at hj))\n have hpt : ∀ (part : Int → Nat) (rs : List (Int × Count)), (∀ r ∈ rs, r.2 ∈ g.counts) → ∀ k, ptSide part ρs M rs k = ptSide part ρ M rs k := by\n intro part rs hrs k\n induction rs with\n | nil => rfl\n | cons r rs ih =>\n simp only [ptSide, hbody r.2 (hrs r List.mem_cons_self) k, ih (fun r' hr' => hrs r' (List.mem_cons_of_mem _ hr'))]\n -- Every instance's hypothesis holds at ρs.\n have hinst : ∀ i ∈ is, ∀ h, countHyp g.counts i = some h → evalC ρs M h = true := by\n intro i hi h hh\n simp only [countHyp, Option.map_eq_some_iff] at hh\n obtain ⟨rs, hr, rfl⟩ := hh\n have hrm := resolve_mem hr\n have hB : evalE ρs M i.below = evalE ρ M i.below := hbound i.below (fun j hj => (witFresh_parts (hfresh j hj)).2.2 i hi)\n have hcnt : ∀ r ∈ rs, ρs r.2.v = sumBelow (fun k => evalE (upd ρs r.2.key k) M r.2.body) (evalE ρ M i.below) := by\n intro r hr'\n obtain ⟨hcm, hcb⟩ := hrm r hr'\n have h1 : ρ r.2.v = sumBelow (fun k => evalE (upd ρ r.2.key k) M r.2.body) (evalE ρ M r.2.below) := hc r.2 hcm\n rw [hvar r.2 hcm, h1, hcb]\n exact sumBelow_congr _ (fun k _ => (hbody r.2 hcm k).symm)\n have hS : ∀ part, evalE ρs M (side part atCount i.below i.unit rs)\n = sumBelow (fun k => ptSide part ρ M rs k + part i.unit) (evalE ρ M i.below) := by\n intro part\n have e1 : evalE ρs M (side part atCount i.below i.unit rs) = sumSide part ρs rs + part i.unit * evalE ρ M i.below := by\n simp only [side, evalE, eval_sumE_count, hB]\n have e2 : sumBelow (fun k => ptSide part ρ M rs k + part i.unit) (evalE ρ M i.below)\n = sumBelow (ptSide part ρ M rs) (evalE ρ M i.below) + part i.unit * evalE ρ M i.below := by\n rw [sumBelow_add (ptSide part ρ M rs) (fun _ => part i.unit), sumBelow_const]\n have e3 : sumSide part ρs rs = sumBelow (ptSide part ρ M rs) (evalE ρ M i.below) := by\n rw [sumSide_eq part ρs M _ rs hcnt]\n exact sumBelow_congr _ (fun k _ => hpt part rs (fun r hr' => (hrm r hr').1) k)\n rw [e1, e2, e3]\n have hW : ∀ part, evalE ρs M (side part (atWit i.wit) (.const 1) i.unit rs) = ptSide part ρ M rs (xs i) + part i.unit := by\n intro part\n simp only [side, evalE, eval_sumE_wit, hat i hi, hpt part rs (fun r hr' => (hrm r hr').1), Nat.mul_one]\n have hv := hxs i rs hr\n simp only [evalC, hS, hW, evalE, hat i hi, hB, Bool.or_eq_true, Bool.and_eq_true, decide_eq_true_eq]\n exact hv\n -- The goal's hypotheses hold at ρs too: no witness is read there.\n have hhyp : ∀ h ∈ g.hyps, evalC ρs M h = true := fun h hm => by\n rw [congrC ρs ρ M h (fun j hj => hother j (fun i hi hij => by\n have := (witFresh_parts (hfresh i hi)).1 h hm; rw [hij] at this; simp [this] at hj))]\n exact hH h hm\n exact goalLemmas_sound ⟨tab, g.hyps ++ hs⟩ t lemmas hgoal ρs M (fun h hm => by\n rcases List.mem_append.mp hm with hm | hm\n · exact hhyp h hm\n · obtain ⟨i, hi, hh⟩ := countHyps_mem hhs h hm\n exact hinst i hi h hh)\n\n\n-- The counted check with frames: fresh witnesses, every instance built, the goal extended by checked lemma cuts and\n-- frames over its own counts.\ndef checkCountedF (g : CGoal) (is : List CInst) (tab : List VDef) (t : Tree) (frames : List FrameCut) (lemmas : List CutLemma := []) (monos : List MonoCut := []) (lins : List LinCut := []) : Bool :=\n countedOk g.hyps g.counts is && match countHyps g.counts is with\n | some hs => checkGoalFrames ⟨tab, g.hyps ++ hs⟩ g.counts t lemmas frames monos lins\n | none => false\n\n/-- With no frames the counted check with lemma cuts is unchanged. -/\ntheorem checkCountedF_nil (g : CGoal) (is : List CInst) (tab : List VDef) (t : Tree) (lemmas : List CutLemma) :\n checkCountedF g is tab t [] lemmas = checkCounted g is tab t lemmas := by\n cases h : countHyps g.counts is <;> simp [checkCountedF, checkCounted, h]\n\n/-- The kind with frames is sound: an accepted counted goal's hypotheses hold at no naturals and maps where every\ncount is its sum. -/\ntheorem countedF_sound (g : CGoal) (is : List CInst) (tab : List VDef) (t : Tree) (frames : List FrameCut) {lemmas : List CutLemma} {monos : List MonoCut} {lins : List LinCut}\n (hck : checkCountedF g is tab t frames lemmas monos lins = true)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hc : ∀ c ∈ g.counts, c.Holds ρ M) : ¬ ∀ h ∈ g.hyps, evalC ρ M h = true := by\n intro hH\n simp only [checkCountedF, Bool.and_eq_true] at hck\n obtain ⟨hok, hgoal⟩ := hck\n simp only [countedOk, Bool.and_eq_true, List.all_eq_true] at hok\n obtain ⟨hdist, hfresh⟩ := hok\n cases hhs : countHyps g.counts is with\n | none => simp [hhs] at hgoal\n | some hs =>\n simp only [hhs] at hgoal\n -- Each instance's witness value, chosen at ρ: a key below the bound where the combination is positive, when its sum is.\n have hx : ∀ i : CInst, ∃ x : Nat, ∀ rs, resolve g.counts i.below i.terms = some rs →\n sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below) ≤ sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below)\n ∨ (x < evalE ρ M i.below ∧ ptSide negP ρ M rs x + negP i.unit < ptSide posP ρ M rs x + posP i.unit) := by\n intro i\n cases hr : resolve g.counts i.below i.terms with\n | none => exact ⟨0, fun rs h => by simp at h⟩\n | some rs =>\n by_cases hlt : sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below) < sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below)\n · obtain ⟨k, hk, hk'⟩ := exists_lt_of_sumBelow_lt hlt\n exact ⟨k, fun rs' h => by simp only [Option.some.injEq] at h; subst h; exact Or.inr ⟨hk, hk'⟩⟩\n · exact ⟨0, fun rs' h => by simp only [Option.some.injEq] at h; subst h; exact Or.inl (Nat.le_of_not_lt hlt)⟩\n obtain ⟨xs, hxs⟩ : ∃ xs : CInst → Nat, ∀ i rs, resolve g.counts i.below i.terms = some rs →\n sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below) ≤ sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below)\n ∨ (xs i < evalE ρ M i.below ∧ ptSide negP ρ M rs (xs i) + negP i.unit < ptSide posP ρ M rs (xs i) + posP i.unit) :=\n ⟨fun i => Classical.choose (hx i), fun i => Classical.choose_spec (hx i)⟩\n -- ρs: ρ with each witness set to its value.\n obtain ⟨ρs, hother, hat⟩ : ∃ ρs : Nat → Nat, (∀ j, (∀ i ∈ is, i.wit ≠ j) → ρs j = ρ j) ∧ (∀ i ∈ is, ρs i.wit = xs i) := by\n have hws : (is.map fun i => (i.wit, xs i)).map (·.1) = is.map (·.wit) := by induction is <;> simp_all\n refine ⟨setWits ρ (is.map fun i => (i.wit, xs i)), fun j hj => setWits_other ?_, fun i hi => ?_⟩\n · rw [hws]; intro hm; obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hm; exact hj i hi rfl\n · exact setWits_at (ρ := ρ) (ws := is.map fun i => (i.wit, xs i)) (by rw [hws]; exact hdist) (p := (i.wit, xs i)) (List.mem_map.mpr ⟨i, hi, rfl⟩)\n -- What the witnesses' freshness gives: counts and bounds read alike at ρs and ρ.\n have hvar : ∀ c ∈ g.counts, ρs c.v = ρ c.v := fun c hc =>\n hother c.v (fun i hi he => ((witFresh_parts (hfresh i hi)).2.1 c hc).1 he.symm)\n have hbound : ∀ e : E, (∀ i ∈ is, occE i.wit e = false) → evalE ρs M e = evalE ρ M e := fun e he =>\n congrE ρs ρ M e (fun j hj => hother j (fun i hi hij => by have := he i hi; rw [hij] at this; simp [this] at hj))\n have hbody : ∀ c ∈ g.counts, ∀ k, evalE (upd ρs c.key k) M c.body = evalE (upd ρ c.key k) M c.body := fun c hc k =>\n congrE _ _ M c.body (fun j hj => by\n simp only [upd]; split\n · rfl\n · exact hother j (fun i hi hij => by\n have := ((witFresh_parts (hfresh i hi)).2.1 c hc).2.2; rw [hij] at this; simp [this] at hj))\n have hpt : ∀ (part : Int → Nat) (rs : List (Int × Count)), (∀ r ∈ rs, r.2 ∈ g.counts) → ∀ k, ptSide part ρs M rs k = ptSide part ρ M rs k := by\n intro part rs hrs k\n induction rs with\n | nil => rfl\n | cons r rs ih =>\n simp only [ptSide, hbody r.2 (hrs r List.mem_cons_self) k, ih (fun r' hr' => hrs r' (List.mem_cons_of_mem _ hr'))]\n -- Every instance's hypothesis holds at ρs.\n have hinst : ∀ i ∈ is, ∀ h, countHyp g.counts i = some h → evalC ρs M h = true := by\n intro i hi h hh\n simp only [countHyp, Option.map_eq_some_iff] at hh\n obtain ⟨rs, hr, rfl⟩ := hh\n have hrm := resolve_mem hr\n have hB : evalE ρs M i.below = evalE ρ M i.below := hbound i.below (fun j hj => (witFresh_parts (hfresh j hj)).2.2 i hi)\n have hcnt : ∀ r ∈ rs, ρs r.2.v = sumBelow (fun k => evalE (upd ρs r.2.key k) M r.2.body) (evalE ρ M i.below) := by\n intro r hr'\n obtain ⟨hcm, hcb⟩ := hrm r hr'\n have h1 : ρ r.2.v = sumBelow (fun k => evalE (upd ρ r.2.key k) M r.2.body) (evalE ρ M r.2.below) := hc r.2 hcm\n rw [hvar r.2 hcm, h1, hcb]\n exact sumBelow_congr _ (fun k _ => (hbody r.2 hcm k).symm)\n have hS : ∀ part, evalE ρs M (side part atCount i.below i.unit rs)\n = sumBelow (fun k => ptSide part ρ M rs k + part i.unit) (evalE ρ M i.below) := by\n intro part\n have e1 : evalE ρs M (side part atCount i.below i.unit rs) = sumSide part ρs rs + part i.unit * evalE ρ M i.below := by\n simp only [side, evalE, eval_sumE_count, hB]\n have e2 : sumBelow (fun k => ptSide part ρ M rs k + part i.unit) (evalE ρ M i.below)\n = sumBelow (ptSide part ρ M rs) (evalE ρ M i.below) + part i.unit * evalE ρ M i.below := by\n rw [sumBelow_add (ptSide part ρ M rs) (fun _ => part i.unit), sumBelow_const]\n have e3 : sumSide part ρs rs = sumBelow (ptSide part ρ M rs) (evalE ρ M i.below) := by\n rw [sumSide_eq part ρs M _ rs hcnt]\n exact sumBelow_congr _ (fun k _ => hpt part rs (fun r hr' => (hrm r hr').1) k)\n rw [e1, e2, e3]\n have hW : ∀ part, evalE ρs M (side part (atWit i.wit) (.const 1) i.unit rs) = ptSide part ρ M rs (xs i) + part i.unit := by\n intro part\n simp only [side, evalE, eval_sumE_wit, hat i hi, hpt part rs (fun r hr' => (hrm r hr').1), Nat.mul_one]\n have hv := hxs i rs hr\n simp only [evalC, hS, hW, evalE, hat i hi, hB, Bool.or_eq_true, Bool.and_eq_true, decide_eq_true_eq]\n exact hv\n -- The goal's hypotheses hold at ρs too: no witness is read there.\n have hhyp : ∀ h ∈ g.hyps, evalC ρs M h = true := fun h hm => by\n rw [congrC ρs ρ M h (fun j hj => hother j (fun i hi hij => by\n have := (witFresh_parts (hfresh i hi)).1 h hm; rw [hij] at this; simp [this] at hj))]\n exact hH h hm\n have hholds' : ∀ c ∈ g.counts, c.Holds ρs M := by\n intro c hcm\n have h1 : ρ c.v = sumBelow (fun k => evalE (upd ρ c.key k) M c.body) (evalE ρ M c.below) := hc c hcm\n simp only [Count.Holds]\n rw [hvar c hcm, h1, hbound c.below (fun i hi => ((witFresh_parts (hfresh i hi)).2.1 c hcm).2.1)]\n exact sumBelow_congr _ (fun k _ => (hbody c hcm k).symm)\n exact goalFrames_sound ⟨tab, g.hyps ++ hs⟩ g.counts t lemmas frames monos lins hgoal ρs M hholds' (fun h hm => by\n rcases List.mem_append.mp hm with hm | hm\n · exact hhyp h hm\n · obtain ⟨i, hi, hh⟩ := countHyps_mem hhs h hm\n exact hinst i hi h hh)\n\nend Kern\n\n#print axioms Kern.exists_lt_of_sumBelow_lt\n#print axioms Kern.pigeonhole\n#print axioms Kern.majorities_meet\n#print axioms Kern.quorums_meet_outside\n#print axioms Kern.lemma_sound\n#print axioms Kern.goalLemmas_sound\n#print axioms Kern.counted_sound\n#print axioms Kern.frame_sound\n#print axioms Kern.goalFrames_sound\n#print axioms Kern.countedF_sound\n",
22
+ "CountMachine.lean": "import Sets\nimport Count\n\n/-!\nCountMachine: counts in a machine's laws and steps, proven sound. Lean 4.34.0, core only; on top of `Sets.lean` (the\nmachines with sets) and `Count.lean` (the counted goal and `counted_sound`), neither changed.\n\n**What a machine may count.** A count declaration (`CDecl`) names a map `mp` whose cell at x is the number Σ_{k < below}\nbody(k), with the declaration's parameters at x and its key variable `key` at k (a 0/1 body is a set's size: the\nvotes for x, the members of a request's set). One parameter: `j` at x. Two (`atJ`): `j` at x / base and `lo` at\nx % base, so a count over a pair (a, b), the nodes that voted b at round a, is read at a relation's composed key base·a\n+ b; a certificate's read of it at a key term written base·a + b gives Count.lean the count with j at a and lo at b,\nunder the hypothesis `base ≤ b ∨ the cell` (`countKeyParts`, `readHyp`), so a key past the base reads nothing. The map is one the request carries (`mp ∈ s.carried`), so the machine\nitself is an `SMachine` as it was: its runs (`CReach`) are `SReach`'s with each request's count maps at their counts,\nread at the request's view (its inputs set, over the state's maps and the maps it carries; a count reads no flag,\nquantified flag or witness, so the view's flags don't change it). A guard (the assumption)\nreads a count there: `2·|Q| > size` for a request's set Q. A law reads a count of the state: a declaration whose bound\nand body read no request (`stateOnly`: no input, quantified flag, witness, flag variable or carried map), whose value\nat a state is `withCnt` (each count map at its count there): `2·|{n < size: vote[n] = x + 1}| > size` for a decided x.\n\n**The goals** are `Sets.lean`'s, with the counts read twice in a step. Before the step a law and the guard read each\ncount map as the request carries it (its count at the view, which for a state-only count is its count at the state).\nAfter the step, the law is read with each count map renamed to its `post` name (`frameRd`), and the goal declares the\npost name a count too, its bound and body read across the step (`afterDecl`: substituted by the step, as the law is,\nwith `j` and `key` kept). The start goal reads the law at the start the same way. A goal is a `CGoalM`: hypotheses\nand the count maps it declares (`GHolds`: each map at its count, at every key).\n\n**The certificate** (`CCert`, checked by `checkMC`) names the goal's hypotheses it uses (each one Lean builds), the\ncells it reads (`reads`: a fresh variable for a count map's cell at a key term), and Count.lean's instances and tree.\n`checkMC` turns it into Count.lean's counted goal: the named hypotheses, each read variable equal to its cell, and a\ncount per read (its declaration with `j` at the key term), and checks it as Count.lean does, but with each instance's\nwitness fresh for the counts and the instances' bounds only (`checkCountedW`): a goal's hypotheses may read a witness\nin their instances of the laws, facts and quantified flags (the voters of Q at the key two majorities share), which\nhold at every value of a variable the machine never reads (`witsOk`). `mc_sound`: an accepted goal's hypotheses do not\nhold at every value of the witnesses, at naturals and maps where each declared map is its count.\n\n**Soundness.** `cmachine_sound`: every entry of an accepted proof holds in every reachable state, its laws reading\neach count map as the state's count (`withCnt`). The proof is `Sets.lean`'s `smachine_sound` with the counted goals in\nplace of `checkIn`: the goals are refuted where the count maps before the step are what the request carried (`CReach`),\nand the post names are the counts of the state after it.\n-/\n\nnamespace Kern\nopen Classical\n\n/-! Counts of a map, and the counted goals over them -/\n\n-- A count map: `mp` at x is Σ_{k < below} body(k), read with its parameters at x and key at k; `post` the name a step's\n-- goal reads it by after the step. Its parameters: j at x / base and lo at x % base, so a count over two parameters\n-- (a, b) is read at the key base·a + b with b < base (a relation's composed key); one parameter is lo = j and base = 0\n-- (j at x).\nstructure CDecl where\n mp : Nat\n post : Nat\n j : Nat\n key : Nat\n below : E\n body : E\n lo : Nat\n base : Nat\n\n-- The environment with the parameters at x.\ndef atJ (d : CDecl) (ρ : Nat → Nat) (x : Nat) : Nat → Nat := upd (upd ρ d.j (x / d.base)) d.lo (x % d.base)\n\n-- The count at x.\ndef cntOf (d : CDecl) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (x : Nat) : Nat :=\n sumBelow (fun k => evalE (upd (atJ d ρ x) d.key k) M d.body) (evalE (atJ d ρ x) M d.below)\n\n-- Each declared map is its count, at every key.\ndef GHolds (ds : List CDecl) (ρ : Nat → Nat) (M : Nat → Nat → Nat) : Prop := ∀ d ∈ ds, ∀ x, M d.mp x = cntOf d ρ M x\n\n-- A certificate for a counted goal: the goal's hypotheses it names, the cells it reads (a variable, a count map, a key\n-- term), Count.lean's instances, the table and the tree.\nstructure CCert where\n hyps : List C\n reads : List (Nat × Nat × E)\n insts : List CInst\n tab : List VDef\n tree : Tree\n picks : List (Nat × List E)\n lemmas : List CutLemma := []\n\n/-! A count at least its body at distinct keys: a read's count picked at key terms (`picks`) gives the hypothesis that,\nwhere the terms are distinct and below the bound, the count is at least the sum of its body at them (`pickHyp`). It\nholds wherever the count is its sum (`pickHyp_true`), so a certificate may name any terms. -/\n\ndef allNe (k : E) : List E → C\n | [] => .le (.const 0) (.const 0)\n | k' :: ks => .and (.not (.eq k k')) (allNe k ks)\n\ndef distinctBelow (b : E) : List E → C\n | [] => .le (.const 0) (.const 0)\n | k :: ks => .and (.lt k b) (.and (allNe k ks) (distinctBelow b ks))\n\ndef pickHyp (c : Count) (ks : List E) : C :=\n .or (.not (distinctBelow c.below ks)) (.le (sumE (ks.map fun k => substE [(c.key, k)] c.body)) (.var c.v))\n\ntheorem evalE_sumEs (X : Nat → Nat) (M : Nat → Nat → Nat) : ∀ es : List E, evalE X M (sumE es) = (es.map (evalE X M)).sum\n | [] => by simp [sumE, evalE]\n | e :: es => by simp [sumE, evalE, evalE_sumEs X M es]\n\ntheorem allNe_ok (X : Nat → Nat) (M : Nat → Nat → Nat) (k : E) : ∀ ks : List E, evalC X M (allNe k ks) = true →\n ∀ k' ∈ ks, evalE X M k ≠ evalE X M k'\n | [], _ => by simp\n | k' :: ks, h => by\n simp only [allNe, evalC, Bool.and_eq_true, Bool.not_eq_true', decide_eq_false_iff_not] at h\n intro k'' hk\n rcases List.mem_cons.mp hk with rfl | hk\n · exact h.1\n · exact allNe_ok X M k ks h.2 k'' hk\n\ntheorem distinctBelow_ok (X : Nat → Nat) (M : Nat → Nat → Nat) (b : E) : ∀ ks : List E, evalC X M (distinctBelow b ks) = true →\n (ks.map (evalE X M)).Pairwise (· ≠ ·) ∧ ∀ k ∈ ks, evalE X M k < evalE X M b\n | [], _ => by simp\n | k :: ks, h => by\n simp only [distinctBelow, evalC, Bool.and_eq_true, decide_eq_true_eq] at h\n obtain ⟨hlt, hne, hrest⟩ := h\n obtain ⟨hp, hb⟩ := distinctBelow_ok X M b ks hrest\n refine ⟨?_, ?_⟩\n · simp only [List.map_cons, List.pairwise_cons, List.mem_map]\n exact ⟨fun a ⟨k', hk', he⟩ => he ▸ allNe_ok X M k ks hne k' hk', hp⟩\n · intro k' hk'\n rcases List.mem_cons.mp hk' with rfl | hk'\n · exact hlt\n · exact hb k' hk'\n\ntheorem sum_split (f : Nat → Nat) (n : Nat) : ∀ ks : List Nat, ks.Pairwise (· ≠ ·) → n ∈ ks →\n (ks.map f).sum = f n + ((ks.filter (· != n)).map f).sum\n | [], _, h => by simp at h\n | a :: t, hp, h => by\n rw [List.pairwise_cons] at hp\n by_cases ha : a = n\n · subst ha\n have ht : t.filter (· != a) = t := List.filter_eq_self.mpr (fun x hx => by simpa using (hp.1 x hx).symm)\n rw [List.filter_cons_of_neg (by simp), ht]\n simp\n · have hn : n ∈ t := by rcases List.mem_cons.mp h with h | h; exact absurd h.symm ha; exact h\n have ih := sum_split f n t hp.2 hn\n simp only [List.map_cons, List.sum_cons, List.filter_cons, bne_iff_ne, ne_eq, ha, not_false_eq_true, ite_true]\n rw [ih]; omega\n\n-- A sum below n is at least its terms at distinct keys below n.\ntheorem sum_le_sumBelow (f : Nat → Nat) : ∀ (n : Nat) (ks : List Nat), ks.Pairwise (· ≠ ·) → (∀ k ∈ ks, k < n) →\n (ks.map f).sum ≤ sumBelow f n\n | 0, ks, _, hb => by\n cases ks with\n | nil => simp [sumBelow]\n | cons k _ => exact absurd (hb k List.mem_cons_self) (Nat.not_lt_zero k)\n | n + 1, ks, hp, hb => by\n simp only [sumBelow]\n by_cases hn : n ∈ ks\n · rw [sum_split f n ks hp hn]\n have := sum_le_sumBelow f n (ks.filter (· != n)) (hp.filter _) (fun k hk => by\n obtain ⟨hk, hne⟩ := List.mem_filter.mp hk\n have := hb k hk; simp only [bne_iff_ne, ne_eq, decide_eq_true_eq] at hne; omega)\n omega\n · have := sum_le_sumBelow f n ks hp (fun k hk => by have := hb k hk; have : k ≠ n := fun h => hn (h ▸ hk); omega)\n omega\n\ntheorem pickHyp_true (c : Count) (ks : List E) (X : Nat → Nat) (M : Nat → Nat → Nat) (h : c.Holds X M) :\n evalC X M (pickHyp c ks) = true := by\n simp only [pickHyp, evalC, Bool.or_eq_true, Bool.not_eq_true', decide_eq_true_eq]\n by_cases hg : evalC X M (distinctBelow c.below ks) = true\n · right\n obtain ⟨hp, hb⟩ := distinctBelow_ok X M c.below ks hg\n rw [evalE_sumEs]\n simp only [evalE]\n rw [h, List.map_map]\n have he : (ks.map ((evalE X M) ∘ fun k => substE [(c.key, k)] c.body)) = ((ks.map (evalE X M)).map fun k => evalE (upd X c.key k) M c.body) := by\n rw [List.map_map]; congr 1; funext k; simp only [Function.comp, subst_evalE, applyS_one]\n rw [he]\n exact sum_le_sumBelow _ _ _ hp (fun k hk => by obtain ⟨k', hk', rfl⟩ := List.mem_map.mp hk; exact hb k' hk')\n · left; simpa using hg\n\n-- A key term's parts, the terms the parameters take: one parameter, the term (j a constant 0); two, the term written\n-- base·a + b (j at a, lo at b), which is the count at (a, b) where b < base.\ndef countKeyParts (d : CDecl) (e : E) : Option (E × E) :=\n if d.base == 0 then some (.const 0, e) else match e with\n | .add (.mul b a) c => if b == d.base then some (a, c) else none\n | _ => none\n\n-- A read cell as Count.lean's count: its variable, the declaration with its parameters at the key term's parts.\ndef toCount (ds : List CDecl) (r : Nat × Nat × E) : Option Count :=\n match lookup (fun d => d.mp == r.2.1) ds with\n | some d => (countKeyParts d r.2.2).map fun p => ⟨r.1, d.key, substE [(d.lo, p.2), (d.j, p.1)] d.below, substE [(d.lo, p.2), (d.j, p.1)] d.body⟩\n | none => none\n\ndef toCounts (ds : List CDecl) : List (Nat × Nat × E) → Option (List Count)\n | [] => some []\n | r :: rs => match toCount ds r with\n | none => none\n | some c => (toCounts ds rs).map (c :: ·)\n\n-- A read's hypothesis: its variable is the cell; for two parameters, where the second part is below the base.\ndef readHyp (ds : List CDecl) (r : Nat × Nat × E) : C :=\n match lookup (fun d => d.mp == r.2.1) ds with\n | some d => if d.base == 0 then .eq (.var r.1) (.get r.2.1 r.2.2) else match countKeyParts d r.2.2 with\n | some p => .or (.le (.const d.base) p.2) (.eq (.var r.1) (.get r.2.1 r.2.2))\n | none => .eq (.var r.1) (.get r.2.1 r.2.2)\n | none => .eq (.var r.1) (.get r.2.1 r.2.2)\n\n-- The picks' hypotheses: each pick of a read, at its count.\ndef pickHyps (ds : List CDecl) (rs : List (Nat × Nat × E)) (ps : List (Nat × List E)) : List C :=\n ps.filterMap fun p => match lookup (fun r => r.1 == p.1) rs with\n | some r => (toCount ds r).map fun c => pickHyp c p.2\n | none => none\n\n-- A read's variable is fresh: no named hypothesis, declaration or key term reads it, and it is no declaration's j, lo or\n-- key.\ndef readFresh (hyps : List C) (ds : List CDecl) (rs : List (Nat × Nat × E)) (v : Nat) : Bool :=\n hyps.all (fun h => !occC v h) && ds.all (fun d => !occE v d.below && !occE v d.body && d.j != v && d.lo != v && d.key != v)\n && rs.all (fun r => !occE v r.2.2)\n\n-- The reads: distinct fresh variables, each key term reading no declaration's key.\ndef readsOk (hyps : List C) (ds : List CDecl) (rs : List (Nat × Nat × E)) : Bool :=\n cDistinct (rs.map (·.1)) && rs.all (fun r => readFresh hyps ds rs r.1 && ds.all (fun d => !occE d.key r.2.2))\n\n-- Count.lean's check with the witnesses fresh for the counts and the instances' bounds only: a machine's goal may read\n-- a witness in its instances of laws and flags, which hold at every value of a variable the machine never reads, so the\n-- goal's hypotheses are asked to hold at every value of the witnesses (`countedW_sound`).\ndef witFreshW (cs : List Count) (is : List CInst) (w : Nat) : Bool :=\n cs.all (fun c => c.v != w && !occE w c.below && !occE w c.body) && is.all (fun j => !occE w j.below)\n\ndef countedOkW (cs : List Count) (is : List CInst) : Bool :=\n cDistinct (is.map (·.wit)) && is.all (fun i => witFreshW cs is i.wit)\n\ndef checkCountedW (hyps : List C) (cs : List Count) (is : List CInst) (tab : List VDef) (t : Tree) (lemmas : List CutLemma := []) : Bool :=\n countedOkW cs is && match countHyps cs is with\n | some hs => checkGoalLemmas ⟨tab, hyps ++ hs⟩ t lemmas\n | none => false\n\n/-- The witness-generalized wrapper conserves the original checker on empty lemma lists. -/\ntheorem checkCountedW_nil (hyps : List C) (cs : List Count) (is : List CInst) (tab : List VDef) (t : Tree) :\n checkCountedW hyps cs is tab t [] = (countedOkW cs is && match countHyps cs is with\n | some hs => checkGoal ⟨tab, hyps ++ hs⟩ t\n | none => false) := by\n simp only [checkCountedW, checkGoalLemmas_nil]\n\ntheorem countedW_sound (hyps : List C) (cs : List Count) (is : List CInst) (tab : List VDef) (t : Tree) {lemmas : List CutLemma}\n (hck : checkCountedW hyps cs is tab t lemmas = true)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hc : ∀ c ∈ cs, c.Holds ρ M)\n (hH : ∀ ρw : Nat → Nat, (∀ j, (∀ i ∈ is, i.wit ≠ j) → ρw j = ρ j) → ∀ h ∈ hyps, evalC ρw M h = true) : False := by\n simp only [checkCountedW, Bool.and_eq_true] at hck\n obtain ⟨hok, hgoal⟩ := hck\n simp only [countedOkW, Bool.and_eq_true, List.all_eq_true] at hok\n obtain ⟨hdist, hfresh⟩ := hok\n have hfr : ∀ i ∈ is, (∀ c ∈ cs, c.v ≠ i.wit ∧ occE i.wit c.below = false ∧ occE i.wit c.body = false) ∧ (∀ j ∈ is, occE i.wit j.below = false) := by\n intro i hi\n have := hfresh i hi\n simp only [witFreshW, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at this\n exact ⟨fun c hc => ⟨(this.1 c hc).1.1, (this.1 c hc).1.2, (this.1 c hc).2⟩, this.2⟩\n cases hhs : countHyps cs is with\n | none => simp [hhs] at hgoal\n | some hs =>\n simp only [hhs] at hgoal\n have hx : ∀ i : CInst, ∃ x : Nat, ∀ rs, resolve cs i.below i.terms = some rs →\n sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below) ≤ sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below)\n ∨ (x < evalE ρ M i.below ∧ ptSide negP ρ M rs x + negP i.unit < ptSide posP ρ M rs x + posP i.unit) := by\n intro i\n cases hr : resolve cs i.below i.terms with\n | none => exact ⟨0, fun rs h => by simp at h⟩\n | some rs =>\n by_cases hlt : sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below) < sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below)\n · obtain ⟨k, hk, hk'⟩ := exists_lt_of_sumBelow_lt hlt\n exact ⟨k, fun rs' h => by simp only [Option.some.injEq] at h; subst h; exact Or.inr ⟨hk, hk'⟩⟩\n · exact ⟨0, fun rs' h => by simp only [Option.some.injEq] at h; subst h; exact Or.inl (Nat.le_of_not_lt hlt)⟩\n obtain ⟨xs, hxs⟩ : ∃ xs : CInst → Nat, ∀ i rs, resolve cs i.below i.terms = some rs →\n sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below) ≤ sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below)\n ∨ (xs i < evalE ρ M i.below ∧ ptSide negP ρ M rs (xs i) + negP i.unit < ptSide posP ρ M rs (xs i) + posP i.unit) :=\n ⟨fun i => Classical.choose (hx i), fun i => Classical.choose_spec (hx i)⟩\n obtain ⟨ρs, hother, hat⟩ : ∃ ρs : Nat → Nat, (∀ j, (∀ i ∈ is, i.wit ≠ j) → ρs j = ρ j) ∧ (∀ i ∈ is, ρs i.wit = xs i) := by\n have hws : (is.map fun i => (i.wit, xs i)).map (·.1) = is.map (·.wit) := by induction is <;> simp_all\n refine ⟨setWits ρ (is.map fun i => (i.wit, xs i)), fun j hj => setWits_other ?_, fun i hi => ?_⟩\n · rw [hws]; intro hm; obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hm; exact hj i hi rfl\n · exact setWits_at (ρ := ρ) (ws := is.map fun i => (i.wit, xs i)) (by rw [hws]; exact hdist) (p := (i.wit, xs i)) (List.mem_map.mpr ⟨i, hi, rfl⟩)\n have hvar : ∀ c ∈ cs, ρs c.v = ρ c.v := fun c hc => hother c.v (fun i hi he => ((hfr i hi).1 c hc).1 he.symm)\n have hbound : ∀ e : E, (∀ i ∈ is, occE i.wit e = false) → evalE ρs M e = evalE ρ M e := fun e he =>\n congrE ρs ρ M e (fun j hj => hother j (fun i hi hij => by have := he i hi; rw [hij] at this; simp [this] at hj))\n have hbody : ∀ c ∈ cs, ∀ k, evalE (upd ρs c.key k) M c.body = evalE (upd ρ c.key k) M c.body := fun c hc k =>\n congrE _ _ M c.body (fun j hj => by\n simp only [upd]; split\n · rfl\n · exact hother j (fun i hi hij => by\n have := ((hfr i hi).1 c hc).2.2; rw [hij] at this; simp [this] at hj))\n have hpt : ∀ (part : Int → Nat) (rs : List (Int × Count)), (∀ r ∈ rs, r.2 ∈ cs) → ∀ k, ptSide part ρs M rs k = ptSide part ρ M rs k := by\n intro part rs hrs k\n induction rs with\n | nil => rfl\n | cons r rs ih =>\n simp only [ptSide, hbody r.2 (hrs r List.mem_cons_self) k, ih (fun r' hr' => hrs r' (List.mem_cons_of_mem _ hr'))]\n have hinst : ∀ i ∈ is, ∀ h, countHyp cs i = some h → evalC ρs M h = true := by\n intro i hi h hh\n simp only [countHyp, Option.map_eq_some_iff] at hh\n obtain ⟨rs, hr, rfl⟩ := hh\n have hrm := resolve_mem hr\n have hB : evalE ρs M i.below = evalE ρ M i.below := hbound i.below (fun j hj => (hfr j hj).2 i hi)\n have hcnt : ∀ r ∈ rs, ρs r.2.v = sumBelow (fun k => evalE (upd ρs r.2.key k) M r.2.body) (evalE ρ M i.below) := by\n intro r hr'\n obtain ⟨hcm, hcb⟩ := hrm r hr'\n have h1 : ρ r.2.v = sumBelow (fun k => evalE (upd ρ r.2.key k) M r.2.body) (evalE ρ M r.2.below) := hc r.2 hcm\n rw [hvar r.2 hcm, h1, hcb]\n exact sumBelow_congr _ (fun k _ => (hbody r.2 hcm k).symm)\n have hS : ∀ part, evalE ρs M (side part atCount i.below i.unit rs)\n = sumBelow (fun k => ptSide part ρ M rs k + part i.unit) (evalE ρ M i.below) := by\n intro part\n have e1 : evalE ρs M (side part atCount i.below i.unit rs) = sumSide part ρs rs + part i.unit * evalE ρ M i.below := by\n simp only [side, evalE, eval_sumE_count, hB]\n have e2 : sumBelow (fun k => ptSide part ρ M rs k + part i.unit) (evalE ρ M i.below)\n = sumBelow (ptSide part ρ M rs) (evalE ρ M i.below) + part i.unit * evalE ρ M i.below := by\n rw [sumBelow_add (ptSide part ρ M rs) (fun _ => part i.unit), sumBelow_const]\n have e3 : sumSide part ρs rs = sumBelow (ptSide part ρ M rs) (evalE ρ M i.below) := by\n rw [sumSide_eq part ρs M _ rs hcnt]\n exact sumBelow_congr _ (fun k _ => hpt part rs (fun r hr' => (hrm r hr').1) k)\n rw [e1, e2, e3]\n have hW : ∀ part, evalE ρs M (side part (atWit i.wit) (.const 1) i.unit rs) = ptSide part ρ M rs (xs i) + part i.unit := by\n intro part\n simp only [side, evalE, eval_sumE_wit, hat i hi, hpt part rs (fun r hr' => (hrm r hr').1), Nat.mul_one]\n have hv := hxs i rs hr\n simp only [evalC, hS, hW, evalE, hat i hi, hB, Bool.or_eq_true, Bool.and_eq_true, decide_eq_true_eq]\n exact hv\n exact goalLemmas_sound ⟨tab, hyps ++ hs⟩ t lemmas hgoal ρs M (fun h hm => by\n rcases List.mem_append.mp hm with hm | hm\n · exact hH ρs hother h hm\n · obtain ⟨i, hi, hh⟩ := countHyps_mem hhs h hm\n exact hinst i hi h hh)\n\n-- The check: the named hypotheses are the goal's, each declaration's j and lo differ from its key, the reads are fresh\n-- and their key terms read no witness, and Count.lean's check (witnesses fresh for the counts) accepts the counted goal\n-- they make.\ndef checkMC (hyps : List C) (ds : List CDecl) (k : CCert) : Bool :=\n namedIn hyps k.hyps hyps && ds.all (fun d => d.j != d.key && d.lo != d.key) && readsOk k.hyps ds k.reads\n && k.reads.all (fun r => k.insts.all (fun i => i.wit != r.1 && !occE i.wit r.2.2))\n && match toCounts ds k.reads with\n | some cs => checkCountedW (k.hyps ++ k.reads.map (readHyp ds) ++ pickHyps ds k.reads k.picks) cs k.insts k.tab k.tree k.lemmas\n | none => false\n\n/-! The counted goal's soundness -/\n\ntheorem toCounts_mem {ds : List CDecl} : ∀ {rs : List (Nat × Nat × E)} {cs : List Count}, toCounts ds rs = some cs →\n ∀ c ∈ cs, ∃ r ∈ rs, toCount ds r = some c\n | [], cs, h => by simp only [toCounts, Option.some.injEq] at h; subst h; simp\n | r :: rs, cs, h => by\n cases e1 : toCount ds r with\n | none => simp [toCounts, e1] at h\n | some c1 =>\n cases e2 : toCounts ds rs with\n | none => simp [toCounts, e1, e2] at h\n | some cs' =>\n simp [toCounts, e1, e2] at h\n subst h\n intro c hc\n rcases List.mem_cons.mp hc with rfl | hc\n · exact ⟨r, List.mem_cons_self, e1⟩\n · obtain ⟨r', hr', h'⟩ := toCounts_mem e2 c hc\n exact ⟨r', List.mem_cons_of_mem _ hr', h'⟩\n\n-- The environment with two parameters set at once by a substitution.\ntheorem applyS_two (lo j : Nat) (a b : E) (ρ : Nat → Nat) (M : Nat → Nat → Nat) :\n applyS [(lo, b), (j, a)] ρ M = upd (upd ρ j (evalE ρ M a)) lo (evalE ρ M b) := by\n funext i\n simp only [applyS, assoc, lookup, upd]\n by_cases h1 : i = lo\n · subst h1; simp\n · by_cases h2 : i = j\n · subst h2; simp [h1, Ne.symm h1]\n · simp [h1, h2, Ne.symm h1, Ne.symm h2]\n\ntheorem atJ_congr (d : CDecl) (x : Nat) {ρ ρ' : Nat → Nat} (i : Nat) (h : i ≠ d.j → i ≠ d.lo → ρ i = ρ' i) :\n atJ d ρ x i = atJ d ρ' x i := by\n simp only [atJ, upd]\n by_cases h2 : i = d.lo\n · simp [h2]\n · by_cases h1 : i = d.j\n · simp [h1, h2]\n · simp only [if_neg h1, if_neg h2]; exact h h1 h2\n\n-- A key term's parts read the key term's variables only, and are the parameters where the second is below the base.\ntheorem keyParts_occ {d : CDecl} {e : E} {p : E × E} (h : countKeyParts d e = some p) (i : Nat) :\n (occE i p.1 = true → occE i e = true) ∧ (occE i p.2 = true → occE i e = true) := by\n unfold countKeyParts at h\n by_cases hb : d.base = 0\n · simp only [hb, beq_self_eq_true, ite_true, Option.some.injEq] at h; subst h; simp [occE]\n · rw [if_neg (by simp [hb])] at h\n split at h\n · split at h\n · simp only [Option.some.injEq] at h; subst h; simp only [occE, Bool.or_eq_true]\n exact ⟨fun h => Or.inl h, fun h => Or.inr h⟩\n · cases h\n · cases h\n\ntheorem keyParts_eval {d : CDecl} {e : E} {p : E × E} (h : countKeyParts d e = some p) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (hg : d.base = 0 ∨ evalE ρ M p.2 < d.base) : evalE ρ M p.1 = evalE ρ M e / d.base ∧ evalE ρ M p.2 = evalE ρ M e % d.base := by\n unfold countKeyParts at h\n by_cases hb : d.base = 0\n · simp only [hb, beq_self_eq_true, ite_true, Option.some.injEq] at h; subst h; simp [evalE, hb]\n · have hpos : 0 < d.base := Nat.pos_of_ne_zero hb\n have hg' : evalE ρ M p.2 < d.base := hg.resolve_left hb\n rw [if_neg (by simp [hb])] at h\n split at h\n · split at h\n · rename_i hbe\n simp only [Option.some.injEq] at h; subst h\n simp only [beq_iff_eq] at hbe\n simp only [evalE, hbe] at hg' ⊢\n constructor\n · rw [Nat.add_comm, Nat.add_mul_div_left _ _ hpos, Nat.div_eq_of_lt hg', Nat.zero_add]\n · rw [Nat.add_comm, Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hg']\n · cases h\n · cases h\n\n-- A term read across the parameters' substitution, at two environments that agree where it matters.\ntheorem subst2_congr {lo j : Nat} {a b : E} {X X' : Nat → Nat} {M : Nat → Nat → Nat} (t : E)\n (ht : ∀ i, occE i t = true → i ≠ lo → i ≠ j → X i = X' i) (ha : evalE X M a = evalE X' M a) (hb : evalE X M b = evalE X' M b) :\n evalE X M (substE [(lo, b), (j, a)] t) = evalE X' M (substE [(lo, b), (j, a)] t) := by\n rw [subst_evalE, subst_evalE, applyS_two, applyS_two, ha, hb]\n exact congrE _ _ M t (fun i hi => by\n simp only [upd]\n by_cases h1 : i = lo\n · simp [h1]\n · by_cases h2 : i = j\n · simp [h1, h2]\n · simp only [if_neg h1, if_neg h2]; exact ht i hi h1 h2)\n\n-- A read's count, its parameters at the key term's parts, is the declaration's count at the key term's value, where the\n-- second part is below the base.\ntheorem cnt_read {d : CDecl} {e : E} {p : E × E} (hp : countKeyParts d e = some p) (hjk : d.j ≠ d.key) (hlk : d.lo ≠ d.key)\n (hke : occE d.key e = false) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hg : d.base = 0 ∨ evalE ρ M p.2 < d.base) :\n sumBelow (fun k => evalE (upd ρ d.key k) M (substE [(d.lo, p.2), (d.j, p.1)] d.body)) (evalE ρ M (substE [(d.lo, p.2), (d.j, p.1)] d.below))\n = cntOf d ρ M (evalE ρ M e) := by\n obtain ⟨h1, h2⟩ := keyParts_eval hp ρ M hg\n simp only [cntOf]\n have hB : evalE ρ M (substE [(d.lo, p.2), (d.j, p.1)] d.below) = evalE (atJ d ρ (evalE ρ M e)) M d.below := by\n rw [subst_evalE, applyS_two, h1, h2]; rfl\n rw [hB]\n refine sumBelow_congr _ (fun k _ => ?_)\n have hk : ∀ t : E, (occE d.key t = true → occE d.key e = true) → evalE (upd ρ d.key k) M t = evalE ρ M t := fun t ht =>\n congrE _ _ M t (fun i hi => by\n simp only [upd]\n by_cases hi' : i = d.key\n · subst hi'; rw [ht hi] at hke; cases hke\n · simp [hi'])\n rw [subst_evalE, applyS_two, hk p.1 (keyParts_occ hp d.key).1, hk p.2 (keyParts_occ hp d.key).2, h1, h2]\n refine congrArg (fun f => evalE f M d.body) (funext fun i => ?_)\n simp only [atJ, upd]\n by_cases h3 : i = d.lo\n · subst h3; simp [hlk]\n · by_cases h4 : i = d.j\n · subst h4; simp [h3, hjk]\n · simp [h3, h4]\n\ntheorem toCounts_some {ds : List CDecl} : ∀ {rs : List (Nat × Nat × E)} {cs : List Count}, toCounts ds rs = some cs →\n ∀ r ∈ rs, ∃ c, toCount ds r = some c\n | [], _, _ => by simp\n | r :: rs, cs, h => by\n cases e1 : toCount ds r with\n | none => simp [toCounts, e1] at h\n | some c1 =>\n cases e2 : toCounts ds rs with\n | none => simp [toCounts, e1, e2] at h\n | some cs' =>\n intro r' hr'\n rcases List.mem_cons.mp hr' with rfl | hr'\n · exact ⟨c1, e1⟩\n · exact toCounts_some e2 r' hr'\n\ntheorem toCounts_in {ds : List CDecl} : ∀ {rs : List (Nat × Nat × E)} {cs : List Count}, toCounts ds rs = some cs →\n ∀ {r c}, r ∈ rs → toCount ds r = some c → c ∈ cs\n | [], _, _, _, _, h, _ => by simp at h\n | r0 :: rs, cs, h, r, c, hr, hc => by\n cases e1 : toCount ds r0 with\n | none => simp [toCounts, e1] at h\n | some c1 =>\n cases e2 : toCounts ds rs with\n | none => simp [toCounts, e1, e2] at h\n | some cs' =>\n simp only [toCounts, e1, e2, Option.map_some, Option.some.injEq] at h\n subst h\n rcases List.mem_cons.mp hr with rfl | hr\n · rw [e1] at hc; cases hc; exact List.mem_cons_self\n · exact List.mem_cons_of_mem _ (toCounts_in e2 hr hc)\n\n-- A read's value: its count at ρ.\ndef rval (ds : List CDecl) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (r : Nat × Nat × E) : Nat :=\n match toCount ds r with\n | some c => sumBelow (fun k => evalE (upd ρ c.key k) M c.body) (evalE ρ M c.below)\n | none => 0\n\n-- Each read's variable set to its count, the rest of the environment kept.\ndef setReads (ds : List CDecl) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (rs : List (Nat × Nat × E)) : Nat → Nat :=\n setWits ρ (rs.map fun r => (r.1, rval ds ρ M r))\n\ntheorem mc_sound (hyps : List C) (ds : List CDecl) (k : CCert) (hck : checkMC hyps ds k = true)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hd : GHolds ds ρ M)\n (hH : ∀ ρw : Nat → Nat, (∀ j, (∀ i ∈ k.insts, i.wit ≠ j) → ρw j = ρ j) → ∀ h ∈ hyps, evalC ρw M h = true) : False := by\n simp only [checkMC, Bool.and_eq_true] at hck\n obtain ⟨⟨⟨⟨hnamed, hjk⟩, hrok⟩, hrw⟩, hcc⟩ := hck\n have hjk' : ∀ d ∈ ds, d.j ≠ d.key ∧ d.lo ≠ d.key := fun d hdm => by\n have := List.all_eq_true.mp hjk d hdm; simpa using this\n have hrw' : ∀ r ∈ k.reads, ∀ i ∈ k.insts, i.wit ≠ r.1 ∧ occE i.wit r.2.2 = false := by\n intro r hr i hi\n have := List.all_eq_true.mp (List.all_eq_true.mp hrw r hr) i hi\n simp only [Bool.and_eq_true, bne_iff_ne, ne_eq, Bool.not_eq_true'] at this\n exact this\n cases hcs : toCounts ds k.reads with\n | none => simp [hcs] at hcc\n | some cs =>\n simp only [hcs] at hcc\n simp only [readsOk, Bool.and_eq_true, List.all_eq_true] at hrok\n obtain ⟨hdist, hrs⟩ := hrok\n have hmap : (k.reads.map fun r => (r.1, rval ds ρ M r)).map (·.1) = k.reads.map (·.1) := by\n induction k.reads <;> simp_all\n -- ρ' : ρ with each read's variable at its count.\n let ρ' := setReads ds ρ M k.reads\n have hother : ∀ i, (∀ r ∈ k.reads, r.1 ≠ i) → ρ' i = ρ i := fun i hi => setWits_other (by\n rw [hmap]; intro hm; obtain ⟨r, hr, he⟩ := List.mem_map.mp hm; exact hi r hr he)\n have hat : ∀ r ∈ k.reads, ρ' r.1 = rval ds ρ M r := by\n intro r hr\n have h := setWits_at (ρ := ρ) (ws := k.reads.map fun r => (r.1, rval ds ρ M r)) (by rw [hmap]; exact hdist)\n (p := (r.1, rval ds ρ M r)) (List.mem_map.mpr ⟨r, hr, rfl⟩)\n exact h\n have hfr : ∀ r ∈ k.reads, readFresh k.hyps ds k.reads r.1 = true := fun r hr => (hrs r hr).1\n have hfr' : ∀ r ∈ k.reads, (∀ h ∈ k.hyps, occC r.1 h = false)\n ∧ (∀ d ∈ ds, occE r.1 d.below = false ∧ occE r.1 d.body = false ∧ d.j ≠ r.1 ∧ d.lo ≠ r.1 ∧ d.key ≠ r.1)\n ∧ (∀ r' ∈ k.reads, occE r.1 r'.2.2 = false) := by\n intro r hr\n have := hfr r hr\n simp only [readFresh, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at this\n exact ⟨this.1.1, fun d hd => ⟨(this.1.2 d hd).1.1.1.1, (this.1.2 d hd).1.1.1.2, (this.1.2 d hd).1.1.2, (this.1.2 d hd).1.2,\n (this.1.2 d hd).2⟩, this.2⟩\n -- A term no read's variable occurs in reads alike at ρ' and ρ.\n have hcong : ∀ e : E, (∀ r ∈ k.reads, occE r.1 e = false) → evalE ρ' M e = evalE ρ M e := fun e he =>\n congrE ρ' ρ M e (fun i hi => hother i (fun r hr hri => by have := he r hr; rw [hri] at this; simp [this] at hi))\n -- A read's parts: its declaration and the key term's parts.\n have hparts : ∀ r ∈ k.reads, ∀ c, toCount ds r = some c → ∃ d ∈ ds, ∃ p, lookup (fun d => d.mp == r.2.1) ds = some d\n ∧ d.mp = r.2.1 ∧ countKeyParts d r.2.2 = some p\n ∧ c = ⟨r.1, d.key, substE [(d.lo, p.2), (d.j, p.1)] d.below, substE [(d.lo, p.2), (d.j, p.1)] d.body⟩ := by\n intro r _ c hc\n simp only [toCount] at hc\n split at hc\n · rename_i d hl\n obtain ⟨hdm, hdq⟩ := lookup_some hl\n simp only [beq_iff_eq] at hdq\n cases hk : countKeyParts d r.2.2 with\n | none => simp [hk] at hc\n | some p =>\n rw [hk] at hc\n exact ⟨d, hdm, p, hl, hdq, hk, (Option.some.inj hc).symm⟩\n · cases hc\n -- The key term's parts read no read's variable, and a read's count reads none.\n have hpr : ∀ r ∈ k.reads, ∀ d p, countKeyParts d r.2.2 = some p → ∀ r' ∈ k.reads, occE r'.1 p.1 = false ∧ occE r'.1 p.2 = false := by\n intro r hr d p hp r' hr'\n have h0 := (hfr' r' hr').2.2 r hr\n refine ⟨?_, ?_⟩\n · cases h1 : occE r'.1 p.1\n · rfl\n · rw [(keyParts_occ hp r'.1).1 h1] at h0; cases h0\n · cases h1 : occE r'.1 p.2\n · rfl\n · rw [(keyParts_occ hp r'.1).2 h1] at h0; cases h0\n -- every count is its sum at ρ'\n have hholds : ∀ c ∈ cs, c.Holds ρ' M := by\n intro c hc\n obtain ⟨r, hr, hrc⟩ := toCounts_mem hcs c hc\n obtain ⟨d, hdm, p, _, _, hp, rfl⟩ := hparts r hr c hrc\n have hvr : ∀ t : E, (t = d.below ∨ t = d.body) → ∀ i, occE i t = true → (∀ r' ∈ k.reads, r'.1 ≠ i) := by\n intro t ht i hi r' hr' he\n have := (hfr' r' hr').2.1 d hdm\n rcases ht with rfl | rfl\n · rw [he, hi] at this; exact absurd this.1 (by simp)\n · rw [he, hi] at this; exact absurd this.2.1 (by simp)\n simp only [Count.Holds]\n rw [hat r hr]\n simp only [rval, hrc]\n have hp1 : evalE ρ M p.1 = evalE ρ' M p.1 := (hcong p.1 (fun r' hr' => (hpr r hr d p hp r' hr').1)).symm\n have hp2 : evalE ρ M p.2 = evalE ρ' M p.2 := (hcong p.2 (fun r' hr' => (hpr r hr d p hp r' hr').2)).symm\n rw [subst2_congr d.below (fun i hi _ _ => (hother i (hvr d.below (Or.inl rfl) i hi)).symm) hp1 hp2]\n refine sumBelow_congr _ (fun kk _ => ?_)\n refine subst2_congr d.body (fun i hi _ _ => ?_) ?_ ?_\n · simp only [upd]; split\n · rfl\n · exact (hother i (hvr d.body (Or.inr rfl) i hi)).symm\n · exact congrE _ _ M p.1 (fun i hi => by\n simp only [upd]; split\n · rfl\n · exact (hother i (fun r' hr' he => by have := (hpr r hr d p hp r' hr').1; rw [he, hi] at this; cases this)).symm)\n · exact congrE _ _ M p.2 (fun i hi => by\n simp only [upd]; split\n · rfl\n · exact (hother i (fun r' hr' he => by have := (hpr r hr d p hp r' hr').2; rw [he, hi] at this; cases this)).symm)\n have hwf : ∀ c ∈ cs, ∀ i ∈ k.insts, c.v ≠ i.wit ∧ occE i.wit c.below = false ∧ occE i.wit c.body = false := by\n have h1 := hcc\n simp only [checkCountedW, countedOkW, Bool.and_eq_true, List.all_eq_true] at h1\n intro c hc i hi\n have := h1.1.2 i hi\n simp only [witFreshW, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at this\n exact ⟨fun he => (this.1 c hc).1.1 he, (this.1 c hc).1.2, (this.1 c hc).2⟩\n refine countedW_sound _ _ _ _ _ hcc ρ' M hholds ?_\n intro ρw hρw h hm\n rcases List.mem_append.mp hm with hm | hm\n · rcases List.mem_append.mp hm with hm | hm\n · -- a named hypothesis: it reads no read variable, and holds where the witnesses are anything\n let ρw2 : Nat → Nat := fun j => if (k.reads.map (·.1)).contains j then ρ j else ρw j\n have h2 := hH ρw2 (fun j hj => by\n simp only [ρw2]\n split\n · rfl\n · rename_i hn\n rw [hρw j hj]\n exact hother j (fun r hr hrj => hn (List.contains_iff_mem.mpr (List.mem_map.mpr ⟨r, hr, hrj⟩))))\n h (namedIn_sound hyps k.hyps hyps (fun _ hx => hx) hnamed h hm)\n rw [congrC ρw ρw2 M h (fun i hi => by\n simp only [ρw2]\n split\n · rename_i hc\n obtain ⟨r, hr, hri⟩ := List.mem_map.mp (List.contains_iff_mem.mp hc)\n have := (hfr' r hr).1 h hm; rw [hri] at this; simp [this] at hi\n · rfl)]\n exact h2\n · obtain ⟨r, hr, rfl⟩ := List.mem_map.mp hm\n have hw1 : ρw r.1 = ρ' r.1 := hρw r.1 (fun i hi he => (hrw' r hr i hi).1 he)\n -- a term inside the key term reads alike at ρw and ρ\n have hwk : ∀ t : E, (∀ i, occE i t = true → occE i r.2.2 = true) → evalE ρw M t = evalE ρ M t := fun t ht => by\n rw [← hcong t (fun r' hr' => by\n cases h1 : occE r'.1 t\n · rfl\n · have := (hfr' r' hr').2.2 r hr; rw [ht _ h1] at this; cases this)]\n exact congrE _ _ M t (fun j hj => hρw j (fun i hi he => by\n have := (hrw' r hr i hi).2; rw [he, ht j hj] at this; cases this))\n obtain ⟨c, hc⟩ := toCounts_some hcs r hr\n obtain ⟨d, hdm, p, hl, hdq, hp, rfl⟩ := hparts r hr c hc\n have hkey : occE d.key r.2.2 = false := by have := (hrs r hr).2 d hdm; simpa using this\n have hval : ∀ hg : d.base = 0 ∨ evalE ρ M p.2 < d.base, ρw r.1 = M r.2.1 (evalE ρw M r.2.2) := fun hg => by\n rw [hw1, hat r hr, hwk r.2.2 (fun _ h => h)]\n simp only [rval, hc]\n rw [cnt_read hp (hjk' d hdm).1 (hjk' d hdm).2 hkey ρ M hg, ← hd d hdm, hdq]\n simp only [readHyp, hl]\n by_cases hb : d.base = 0\n · simp only [hb, beq_self_eq_true, ite_true, evalC, evalE]\n exact decide_eq_true (hval (Or.inl hb))\n · rw [if_neg (by simp [hb])]\n simp only [hp, evalC, evalE, Bool.or_eq_true]\n by_cases hlt : evalE ρ M p.2 < d.base\n · exact Or.inr (decide_eq_true (hval (Or.inr hlt)))\n · exact Or.inl (decide_eq_true (by rw [hwk p.2 (fun i => (keyParts_occ hp i).2)]; omega))\n · -- a pick: its count at ρw is its sum, as at ρ' (it reads no witness)\n obtain ⟨p, _, hph⟩ := List.mem_filterMap.mp hm\n split at hph\n · rename_i r hl\n obtain ⟨c, hc, rfl⟩ := Option.map_eq_some_iff.mp hph\n have hcm : c ∈ cs := toCounts_in hcs (lookup_some hl).1 hc\n have hc' := hholds c hcm\n have hag : ∀ j, (∀ i ∈ k.insts, i.wit ≠ j) → ρw j = ρ' j := hρw\n refine pickHyp_true c p.2 ρw M ?_\n simp only [Count.Holds] at hc' ⊢\n rw [hag c.v (fun i hi he => (hwf c hcm i hi).1 he.symm), hc']\n have hB : evalE ρ' M c.below = evalE ρw M c.below := congrE _ _ M c.below (fun j hj => (hag j (fun i hi he => by\n have := (hwf c hcm i hi).2.1; rw [he, hj] at this; cases this)).symm)\n rw [hB]\n exact sumBelow_congr _ (fun kk _ => congrE _ _ M c.body (fun j hj => by\n simp only [upd]; split\n · rfl\n · exact (hag j (fun i hi he => by have := (hwf c hcm i hi).2.2; rw [he, hj] at this; cases this)).symm))\n · cases hph\n\n/-! Frames (Count.lean's FrameCuts) at the machine's counted goals: the same checks with frames over the certificate's reads. -/\n\n-- The witness-generalized counted check with frames over the goal's own counts.\ndef checkCountedWF (hyps : List C) (cs : List Count) (is : List CInst) (tab : List VDef) (t : Tree) (frames : List FrameCut) (lemmas : List CutLemma := []) (monos : List MonoCut := []) (lins : List LinCut := []) : Bool :=\n countedOkW cs is && match countHyps cs is with\n | some hs => checkGoalFrames ⟨tab, hyps ++ hs⟩ cs t lemmas frames monos lins\n | none => false\n\n/-- With no frames the witness-generalized check is unchanged. -/\ntheorem checkCountedWF_nil (hyps : List C) (cs : List Count) (is : List CInst) (tab : List VDef) (t : Tree) (lemmas : List CutLemma) :\n checkCountedWF hyps cs is tab t [] lemmas = checkCountedW hyps cs is tab t lemmas := by\n cases h : countHyps cs is <;> simp [checkCountedWF, checkCountedW, h]\n\ntheorem countedWF_sound (hyps : List C) (cs : List Count) (is : List CInst) (tab : List VDef) (t : Tree) (frames : List FrameCut) {lemmas : List CutLemma} {monos : List MonoCut} {lins : List LinCut}\n (hck : checkCountedWF hyps cs is tab t frames lemmas monos lins = true)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hc : ∀ c ∈ cs, c.Holds ρ M)\n (hH : ∀ ρw : Nat → Nat, (∀ j, (∀ i ∈ is, i.wit ≠ j) → ρw j = ρ j) → ∀ h ∈ hyps, evalC ρw M h = true) : False := by\n simp only [checkCountedWF, Bool.and_eq_true] at hck\n obtain ⟨hok, hgoal⟩ := hck\n simp only [countedOkW, Bool.and_eq_true, List.all_eq_true] at hok\n obtain ⟨hdist, hfresh⟩ := hok\n have hfr : ∀ i ∈ is, (∀ c ∈ cs, c.v ≠ i.wit ∧ occE i.wit c.below = false ∧ occE i.wit c.body = false) ∧ (∀ j ∈ is, occE i.wit j.below = false) := by\n intro i hi\n have := hfresh i hi\n simp only [witFreshW, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at this\n exact ⟨fun c hc => ⟨(this.1 c hc).1.1, (this.1 c hc).1.2, (this.1 c hc).2⟩, this.2⟩\n cases hhs : countHyps cs is with\n | none => simp [hhs] at hgoal\n | some hs =>\n simp only [hhs] at hgoal\n have hx : ∀ i : CInst, ∃ x : Nat, ∀ rs, resolve cs i.below i.terms = some rs →\n sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below) ≤ sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below)\n ∨ (x < evalE ρ M i.below ∧ ptSide negP ρ M rs x + negP i.unit < ptSide posP ρ M rs x + posP i.unit) := by\n intro i\n cases hr : resolve cs i.below i.terms with\n | none => exact ⟨0, fun rs h => by simp at h⟩\n | some rs =>\n by_cases hlt : sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below) < sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below)\n · obtain ⟨k, hk, hk'⟩ := exists_lt_of_sumBelow_lt hlt\n exact ⟨k, fun rs' h => by simp only [Option.some.injEq] at h; subst h; exact Or.inr ⟨hk, hk'⟩⟩\n · exact ⟨0, fun rs' h => by simp only [Option.some.injEq] at h; subst h; exact Or.inl (Nat.le_of_not_lt hlt)⟩\n obtain ⟨xs, hxs⟩ : ∃ xs : CInst → Nat, ∀ i rs, resolve cs i.below i.terms = some rs →\n sumBelow (fun k => ptSide posP ρ M rs k + posP i.unit) (evalE ρ M i.below) ≤ sumBelow (fun k => ptSide negP ρ M rs k + negP i.unit) (evalE ρ M i.below)\n ∨ (xs i < evalE ρ M i.below ∧ ptSide negP ρ M rs (xs i) + negP i.unit < ptSide posP ρ M rs (xs i) + posP i.unit) :=\n ⟨fun i => Classical.choose (hx i), fun i => Classical.choose_spec (hx i)⟩\n obtain ⟨ρs, hother, hat⟩ : ∃ ρs : Nat → Nat, (∀ j, (∀ i ∈ is, i.wit ≠ j) → ρs j = ρ j) ∧ (∀ i ∈ is, ρs i.wit = xs i) := by\n have hws : (is.map fun i => (i.wit, xs i)).map (·.1) = is.map (·.wit) := by induction is <;> simp_all\n refine ⟨setWits ρ (is.map fun i => (i.wit, xs i)), fun j hj => setWits_other ?_, fun i hi => ?_⟩\n · rw [hws]; intro hm; obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hm; exact hj i hi rfl\n · exact setWits_at (ρ := ρ) (ws := is.map fun i => (i.wit, xs i)) (by rw [hws]; exact hdist) (p := (i.wit, xs i)) (List.mem_map.mpr ⟨i, hi, rfl⟩)\n have hvar : ∀ c ∈ cs, ρs c.v = ρ c.v := fun c hc => hother c.v (fun i hi he => ((hfr i hi).1 c hc).1 he.symm)\n have hbound : ∀ e : E, (∀ i ∈ is, occE i.wit e = false) → evalE ρs M e = evalE ρ M e := fun e he =>\n congrE ρs ρ M e (fun j hj => hother j (fun i hi hij => by have := he i hi; rw [hij] at this; simp [this] at hj))\n have hbody : ∀ c ∈ cs, ∀ k, evalE (upd ρs c.key k) M c.body = evalE (upd ρ c.key k) M c.body := fun c hc k =>\n congrE _ _ M c.body (fun j hj => by\n simp only [upd]; split\n · rfl\n · exact hother j (fun i hi hij => by\n have := ((hfr i hi).1 c hc).2.2; rw [hij] at this; simp [this] at hj))\n have hpt : ∀ (part : Int → Nat) (rs : List (Int × Count)), (∀ r ∈ rs, r.2 ∈ cs) → ∀ k, ptSide part ρs M rs k = ptSide part ρ M rs k := by\n intro part rs hrs k\n induction rs with\n | nil => rfl\n | cons r rs ih =>\n simp only [ptSide, hbody r.2 (hrs r List.mem_cons_self) k, ih (fun r' hr' => hrs r' (List.mem_cons_of_mem _ hr'))]\n have hinst : ∀ i ∈ is, ∀ h, countHyp cs i = some h → evalC ρs M h = true := by\n intro i hi h hh\n simp only [countHyp, Option.map_eq_some_iff] at hh\n obtain ⟨rs, hr, rfl⟩ := hh\n have hrm := resolve_mem hr\n have hB : evalE ρs M i.below = evalE ρ M i.below := hbound i.below (fun j hj => (hfr j hj).2 i hi)\n have hcnt : ∀ r ∈ rs, ρs r.2.v = sumBelow (fun k => evalE (upd ρs r.2.key k) M r.2.body) (evalE ρ M i.below) := by\n intro r hr'\n obtain ⟨hcm, hcb⟩ := hrm r hr'\n have h1 : ρ r.2.v = sumBelow (fun k => evalE (upd ρ r.2.key k) M r.2.body) (evalE ρ M r.2.below) := hc r.2 hcm\n rw [hvar r.2 hcm, h1, hcb]\n exact sumBelow_congr _ (fun k _ => (hbody r.2 hcm k).symm)\n have hS : ∀ part, evalE ρs M (side part atCount i.below i.unit rs)\n = sumBelow (fun k => ptSide part ρ M rs k + part i.unit) (evalE ρ M i.below) := by\n intro part\n have e1 : evalE ρs M (side part atCount i.below i.unit rs) = sumSide part ρs rs + part i.unit * evalE ρ M i.below := by\n simp only [side, evalE, eval_sumE_count, hB]\n have e2 : sumBelow (fun k => ptSide part ρ M rs k + part i.unit) (evalE ρ M i.below)\n = sumBelow (ptSide part ρ M rs) (evalE ρ M i.below) + part i.unit * evalE ρ M i.below := by\n rw [sumBelow_add (ptSide part ρ M rs) (fun _ => part i.unit), sumBelow_const]\n have e3 : sumSide part ρs rs = sumBelow (ptSide part ρ M rs) (evalE ρ M i.below) := by\n rw [sumSide_eq part ρs M _ rs hcnt]\n exact sumBelow_congr _ (fun k _ => hpt part rs (fun r hr' => (hrm r hr').1) k)\n rw [e1, e2, e3]\n have hW : ∀ part, evalE ρs M (side part (atWit i.wit) (.const 1) i.unit rs) = ptSide part ρ M rs (xs i) + part i.unit := by\n intro part\n simp only [side, evalE, eval_sumE_wit, hat i hi, hpt part rs (fun r hr' => (hrm r hr').1), Nat.mul_one]\n have hv := hxs i rs hr\n simp only [evalC, hS, hW, evalE, hat i hi, hB, Bool.or_eq_true, Bool.and_eq_true, decide_eq_true_eq]\n exact hv\n have hholds' : ∀ c ∈ cs, c.Holds ρs M := by\n intro c hcm\n have h1 : ρ c.v = sumBelow (fun k => evalE (upd ρ c.key k) M c.body) (evalE ρ M c.below) := hc c hcm\n simp only [Count.Holds]\n rw [hvar c hcm, h1, hbound c.below (fun i hi => ((hfr i hi).1 c hcm).2.1)]\n exact sumBelow_congr _ (fun k _ => (hbody c hcm k).symm)\n exact goalFrames_sound ⟨tab, hyps ++ hs⟩ cs t lemmas frames monos lins hgoal ρs M hholds' (fun h hm => by\n rcases List.mem_append.mp hm with hm | hm\n · exact hH ρs hother h hm\n · obtain ⟨i, hi, hh⟩ := countHyps_mem hhs h hm\n exact hinst i hi h hh)\n\n\n-- checkMC with frames: the same conditions, the counted goal checked with the frames.\ndef checkMCF (hyps : List C) (ds : List CDecl) (k : CCert) (frames : List FrameCut) (monos : List MonoCut := []) (lins : List LinCut := []) : Bool :=\n namedIn hyps k.hyps hyps && ds.all (fun d => d.j != d.key && d.lo != d.key) && readsOk k.hyps ds k.reads\n && k.reads.all (fun r => k.insts.all (fun i => i.wit != r.1 && !occE i.wit r.2.2))\n && match toCounts ds k.reads with\n | some cs => checkCountedWF (k.hyps ++ k.reads.map (readHyp ds) ++ pickHyps ds k.reads k.picks) cs k.insts k.tab k.tree frames k.lemmas monos lins\n | none => false\n\n/-- With no frames checkMC is unchanged. -/\ntheorem checkMCF_nil (hyps : List C) (ds : List CDecl) (k : CCert) : checkMCF hyps ds k [] = checkMC hyps ds k := by\n cases h : toCounts ds k.reads <;> simp [checkMCF, checkMC, h, checkCountedWF_nil]\n\ntheorem mcF_sound (hyps : List C) (ds : List CDecl) (k : CCert) (frames : List FrameCut) (monos : List MonoCut) (lins : List LinCut) (hck : checkMCF hyps ds k frames monos lins = true)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hd : GHolds ds ρ M)\n (hH : ∀ ρw : Nat → Nat, (∀ j, (∀ i ∈ k.insts, i.wit ≠ j) → ρw j = ρ j) → ∀ h ∈ hyps, evalC ρw M h = true) : False := by\n simp only [checkMCF, Bool.and_eq_true] at hck\n obtain ⟨⟨⟨⟨hnamed, hjk⟩, hrok⟩, hrw⟩, hcc⟩ := hck\n have hjk' : ∀ d ∈ ds, d.j ≠ d.key ∧ d.lo ≠ d.key := fun d hdm => by\n have := List.all_eq_true.mp hjk d hdm; simpa using this\n have hrw' : ∀ r ∈ k.reads, ∀ i ∈ k.insts, i.wit ≠ r.1 ∧ occE i.wit r.2.2 = false := by\n intro r hr i hi\n have := List.all_eq_true.mp (List.all_eq_true.mp hrw r hr) i hi\n simp only [Bool.and_eq_true, bne_iff_ne, ne_eq, Bool.not_eq_true'] at this\n exact this\n cases hcs : toCounts ds k.reads with\n | none => simp [hcs] at hcc\n | some cs =>\n simp only [hcs] at hcc\n simp only [readsOk, Bool.and_eq_true, List.all_eq_true] at hrok\n obtain ⟨hdist, hrs⟩ := hrok\n have hmap : (k.reads.map fun r => (r.1, rval ds ρ M r)).map (·.1) = k.reads.map (·.1) := by\n induction k.reads <;> simp_all\n -- ρ' : ρ with each read's variable at its count.\n let ρ' := setReads ds ρ M k.reads\n have hother : ∀ i, (∀ r ∈ k.reads, r.1 ≠ i) → ρ' i = ρ i := fun i hi => setWits_other (by\n rw [hmap]; intro hm; obtain ⟨r, hr, he⟩ := List.mem_map.mp hm; exact hi r hr he)\n have hat : ∀ r ∈ k.reads, ρ' r.1 = rval ds ρ M r := by\n intro r hr\n have h := setWits_at (ρ := ρ) (ws := k.reads.map fun r => (r.1, rval ds ρ M r)) (by rw [hmap]; exact hdist)\n (p := (r.1, rval ds ρ M r)) (List.mem_map.mpr ⟨r, hr, rfl⟩)\n exact h\n have hfr : ∀ r ∈ k.reads, readFresh k.hyps ds k.reads r.1 = true := fun r hr => (hrs r hr).1\n have hfr' : ∀ r ∈ k.reads, (∀ h ∈ k.hyps, occC r.1 h = false)\n ∧ (∀ d ∈ ds, occE r.1 d.below = false ∧ occE r.1 d.body = false ∧ d.j ≠ r.1 ∧ d.lo ≠ r.1 ∧ d.key ≠ r.1)\n ∧ (∀ r' ∈ k.reads, occE r.1 r'.2.2 = false) := by\n intro r hr\n have := hfr r hr\n simp only [readFresh, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at this\n exact ⟨this.1.1, fun d hd => ⟨(this.1.2 d hd).1.1.1.1, (this.1.2 d hd).1.1.1.2, (this.1.2 d hd).1.1.2, (this.1.2 d hd).1.2,\n (this.1.2 d hd).2⟩, this.2⟩\n -- A term no read's variable occurs in reads alike at ρ' and ρ.\n have hcong : ∀ e : E, (∀ r ∈ k.reads, occE r.1 e = false) → evalE ρ' M e = evalE ρ M e := fun e he =>\n congrE ρ' ρ M e (fun i hi => hother i (fun r hr hri => by have := he r hr; rw [hri] at this; simp [this] at hi))\n -- A read's parts: its declaration and the key term's parts.\n have hparts : ∀ r ∈ k.reads, ∀ c, toCount ds r = some c → ∃ d ∈ ds, ∃ p, lookup (fun d => d.mp == r.2.1) ds = some d\n ∧ d.mp = r.2.1 ∧ countKeyParts d r.2.2 = some p\n ∧ c = ⟨r.1, d.key, substE [(d.lo, p.2), (d.j, p.1)] d.below, substE [(d.lo, p.2), (d.j, p.1)] d.body⟩ := by\n intro r _ c hc\n simp only [toCount] at hc\n split at hc\n · rename_i d hl\n obtain ⟨hdm, hdq⟩ := lookup_some hl\n simp only [beq_iff_eq] at hdq\n cases hk : countKeyParts d r.2.2 with\n | none => simp [hk] at hc\n | some p =>\n rw [hk] at hc\n exact ⟨d, hdm, p, hl, hdq, hk, (Option.some.inj hc).symm⟩\n · cases hc\n -- The key term's parts read no read's variable, and a read's count reads none.\n have hpr : ∀ r ∈ k.reads, ∀ d p, countKeyParts d r.2.2 = some p → ∀ r' ∈ k.reads, occE r'.1 p.1 = false ∧ occE r'.1 p.2 = false := by\n intro r hr d p hp r' hr'\n have h0 := (hfr' r' hr').2.2 r hr\n refine ⟨?_, ?_⟩\n · cases h1 : occE r'.1 p.1\n · rfl\n · rw [(keyParts_occ hp r'.1).1 h1] at h0; cases h0\n · cases h1 : occE r'.1 p.2\n · rfl\n · rw [(keyParts_occ hp r'.1).2 h1] at h0; cases h0\n -- every count is its sum at ρ'\n have hholds : ∀ c ∈ cs, c.Holds ρ' M := by\n intro c hc\n obtain ⟨r, hr, hrc⟩ := toCounts_mem hcs c hc\n obtain ⟨d, hdm, p, _, _, hp, rfl⟩ := hparts r hr c hrc\n have hvr : ∀ t : E, (t = d.below ∨ t = d.body) → ∀ i, occE i t = true → (∀ r' ∈ k.reads, r'.1 ≠ i) := by\n intro t ht i hi r' hr' he\n have := (hfr' r' hr').2.1 d hdm\n rcases ht with rfl | rfl\n · rw [he, hi] at this; exact absurd this.1 (by simp)\n · rw [he, hi] at this; exact absurd this.2.1 (by simp)\n simp only [Count.Holds]\n rw [hat r hr]\n simp only [rval, hrc]\n have hp1 : evalE ρ M p.1 = evalE ρ' M p.1 := (hcong p.1 (fun r' hr' => (hpr r hr d p hp r' hr').1)).symm\n have hp2 : evalE ρ M p.2 = evalE ρ' M p.2 := (hcong p.2 (fun r' hr' => (hpr r hr d p hp r' hr').2)).symm\n rw [subst2_congr d.below (fun i hi _ _ => (hother i (hvr d.below (Or.inl rfl) i hi)).symm) hp1 hp2]\n refine sumBelow_congr _ (fun kk _ => ?_)\n refine subst2_congr d.body (fun i hi _ _ => ?_) ?_ ?_\n · simp only [upd]; split\n · rfl\n · exact (hother i (hvr d.body (Or.inr rfl) i hi)).symm\n · exact congrE _ _ M p.1 (fun i hi => by\n simp only [upd]; split\n · rfl\n · exact (hother i (fun r' hr' he => by have := (hpr r hr d p hp r' hr').1; rw [he, hi] at this; cases this)).symm)\n · exact congrE _ _ M p.2 (fun i hi => by\n simp only [upd]; split\n · rfl\n · exact (hother i (fun r' hr' he => by have := (hpr r hr d p hp r' hr').2; rw [he, hi] at this; cases this)).symm)\n have hwf : ∀ c ∈ cs, ∀ i ∈ k.insts, c.v ≠ i.wit ∧ occE i.wit c.below = false ∧ occE i.wit c.body = false := by\n have h1 := hcc\n simp only [checkCountedWF, countedOkW, Bool.and_eq_true, List.all_eq_true] at h1\n intro c hc i hi\n have := h1.1.2 i hi\n simp only [witFreshW, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at this\n exact ⟨fun he => (this.1 c hc).1.1 he, (this.1 c hc).1.2, (this.1 c hc).2⟩\n refine countedWF_sound _ _ _ _ _ _ hcc ρ' M hholds ?_\n intro ρw hρw h hm\n rcases List.mem_append.mp hm with hm | hm\n · rcases List.mem_append.mp hm with hm | hm\n · -- a named hypothesis: it reads no read variable, and holds where the witnesses are anything\n let ρw2 : Nat → Nat := fun j => if (k.reads.map (·.1)).contains j then ρ j else ρw j\n have h2 := hH ρw2 (fun j hj => by\n simp only [ρw2]\n split\n · rfl\n · rename_i hn\n rw [hρw j hj]\n exact hother j (fun r hr hrj => hn (List.contains_iff_mem.mpr (List.mem_map.mpr ⟨r, hr, hrj⟩))))\n h (namedIn_sound hyps k.hyps hyps (fun _ hx => hx) hnamed h hm)\n rw [congrC ρw ρw2 M h (fun i hi => by\n simp only [ρw2]\n split\n · rename_i hc\n obtain ⟨r, hr, hri⟩ := List.mem_map.mp (List.contains_iff_mem.mp hc)\n have := (hfr' r hr).1 h hm; rw [hri] at this; simp [this] at hi\n · rfl)]\n exact h2\n · obtain ⟨r, hr, rfl⟩ := List.mem_map.mp hm\n have hw1 : ρw r.1 = ρ' r.1 := hρw r.1 (fun i hi he => (hrw' r hr i hi).1 he)\n -- a term inside the key term reads alike at ρw and ρ\n have hwk : ∀ t : E, (∀ i, occE i t = true → occE i r.2.2 = true) → evalE ρw M t = evalE ρ M t := fun t ht => by\n rw [← hcong t (fun r' hr' => by\n cases h1 : occE r'.1 t\n · rfl\n · have := (hfr' r' hr').2.2 r hr; rw [ht _ h1] at this; cases this)]\n exact congrE _ _ M t (fun j hj => hρw j (fun i hi he => by\n have := (hrw' r hr i hi).2; rw [he, ht j hj] at this; cases this))\n obtain ⟨c, hc⟩ := toCounts_some hcs r hr\n obtain ⟨d, hdm, p, hl, hdq, hp, rfl⟩ := hparts r hr c hc\n have hkey : occE d.key r.2.2 = false := by have := (hrs r hr).2 d hdm; simpa using this\n have hval : ∀ hg : d.base = 0 ∨ evalE ρ M p.2 < d.base, ρw r.1 = M r.2.1 (evalE ρw M r.2.2) := fun hg => by\n rw [hw1, hat r hr, hwk r.2.2 (fun _ h => h)]\n simp only [rval, hc]\n rw [cnt_read hp (hjk' d hdm).1 (hjk' d hdm).2 hkey ρ M hg, ← hd d hdm, hdq]\n simp only [readHyp, hl]\n by_cases hb : d.base = 0\n · simp only [hb, beq_self_eq_true, ite_true, evalC, evalE]\n exact decide_eq_true (hval (Or.inl hb))\n · rw [if_neg (by simp [hb])]\n simp only [hp, evalC, evalE, Bool.or_eq_true]\n by_cases hlt : evalE ρ M p.2 < d.base\n · exact Or.inr (decide_eq_true (hval (Or.inr hlt)))\n · exact Or.inl (decide_eq_true (by rw [hwk p.2 (fun i => (keyParts_occ hp i).2)]; omega))\n · -- a pick: its count at ρw is its sum, as at ρ' (it reads no witness)\n obtain ⟨p, _, hph⟩ := List.mem_filterMap.mp hm\n split at hph\n · rename_i r hl\n obtain ⟨c, hc, rfl⟩ := Option.map_eq_some_iff.mp hph\n have hcm : c ∈ cs := toCounts_in hcs (lookup_some hl).1 hc\n have hc' := hholds c hcm\n have hag : ∀ j, (∀ i ∈ k.insts, i.wit ≠ j) → ρw j = ρ' j := hρw\n refine pickHyp_true c p.2 ρw M ?_\n simp only [Count.Holds] at hc' ⊢\n rw [hag c.v (fun i hi he => (hwf c hcm i hi).1 he.symm), hc']\n have hB : evalE ρ' M c.below = evalE ρw M c.below := congrE _ _ M c.below (fun j hj => (hag j (fun i hi he => by\n have := (hwf c hcm i hi).2.1; rw [he, hj] at this; cases this)).symm)\n rw [hB]\n exact sumBelow_congr _ (fun kk _ => congrE _ _ M c.body (fun j hj => by\n simp only [upd]; split\n · rfl\n · exact (hag j (fun i hi he => by have := (hwf c hcm i hi).2.2; rw [he, hj] at this; cases this)).symm))\n · cases hph\n\n\n/-! Counts in a machine -/\n\n-- The maps with each count map at its count at ρ, M.\ndef withCnt (ds : List CDecl) (ρ : Nat → Nat) (M : Nat → Nat → Nat) : Nat → Nat → Nat := fun mp =>\n match lookup (fun d => d.mp == mp) ds with\n | some d => cntOf d ρ M\n | none => M mp\n\n-- The runs: `SReach`'s, each request carrying each count map at its count at the request's view.\ninductive CReach (s : SMachine) (ds : List CDecl) : (Nat → Nat) → (Nat → Nat → Nat) → Prop\n | start (ρ : Nat → Nat) (M : Nat → Nat → Nat) : StartMaps s.f.m M → evalC ρ M s.f.m.pre = true → (∀ l ∈ s.facts, l.Holds ρ M) →\n s.PFacts ρ M → CReach s ds (applyS s.f.m.init ρ M) M\n | step (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat) : CReach s ds ρ M →\n GHolds ds (withInputs s.f.m.inputs ρ ι) (withCarried s M κ) →\n evalC (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 s.f.m.assume = true → CReach s ds (sNext s ρ M ι κ).1 (sNext s ρ M ι κ).2\n\ntheorem creach_sreach {s : SMachine} {ds : List CDecl} : ∀ {ρ M}, CReach s ds ρ M → SReach s ρ M := by\n intro ρ M h\n induction h with\n | start ρ M hM h0 hf hp => exact .start ρ M hM h0 hf hp\n | step ρ M ι κ _ _ ha ih => exact .step ρ M ι κ ih ha\n\n-- A count of the state alone: its bound and body read no request (input, quantified flag, witness), no flag and no\n-- carried map. A law reads only these.\ndef stateOnly (s : SMachine) (d : CDecl) : Bool :=\n avoidsE (s.extVars ++ flagVars s.f.flags) d.below && avoidsE (s.extVars ++ flagVars s.f.flags) d.body\n && avoidsMapsE s.carried d.below && avoidsMapsE s.carried d.body\n\ndef cMaps (ds : List CDecl) : List Nat := ds.map (·.mp)\ndef cPosts (ds : List CDecl) : List Nat := ds.map (·.post)\ndef cren (ds : List CDecl) : List (Nat × Nat) := ds.map fun d => (d.mp, d.post)\ndef stateMaps (s : SMachine) (ds : List CDecl) : List Nat := (ds.filter (stateOnly s)).map (·.mp)\n\n-- A law with each count map read by its post name.\ndef renLaw (ds : List CDecl) (l : MLaw) : MLaw := ⟨substRC [] (frameRd (cren ds) getRd) l.holds, l.key⟩\n\n-- σ with the parameters and key kept.\ndef keepJ (d : CDecl) (σ : List (Nat × E)) : List (Nat × E) := (d.j, .var d.j) :: (d.lo, .var d.lo) :: (d.key, .var d.key) :: σ\n\n-- A count declared after σ, rd: its bound and body read across them, its parameters and key kept.\ndef afterDecl (σ : List (Nat × E)) (rd : Nat → E → E) (d : CDecl) : CDecl :=\n ⟨d.post, d.post, d.j, d.key, substRE (keepJ d σ) rd d.below, substRE (keepJ d σ) rd d.body, d.lo, d.base⟩\n\ntheorem cntOf_after (σ : List (Nat × E)) (rd : Nat → E → E) (d : CDecl) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (x : Nat) :\n cntOf (afterDecl σ rd d) ρ M x = sumBelow (fun k => evalE (upd (atJ d ρ x) d.key k) M (substRE (keepJ d σ) rd d.body))\n (evalE (atJ d ρ x) M (substRE (keepJ d σ) rd d.below)) := rfl\n\n-- The goals: Sets.lean's, the law proven read with its count maps renamed; the counts the goals declare: at the start,\n-- each state count after the start; at a step, each count as the request carries it, and each state count after it.\ndef cStartGoal (s : SMachine) (ds : List CDecl) (e : SEntry) : List C := sStartGoal s { e with law := renLaw ds e.law }\ndef cStartDecls (s : SMachine) (ds : List CDecl) : List CDecl := (ds.filter (stateOnly s)).map (afterDecl s.f.m.init (rdStart s.f.m))\ndef cStepGoal (s : SMachine) (ds : List CDecl) (ps : List SEntry) (e : SEntry) : List C := sStepGoal s ps { e with law := renLaw ds e.law }\ndef cStepDecls (s : SMachine) (ds : List CDecl) : List CDecl :=\n ds ++ (ds.filter (stateOnly s)).map (afterDecl (stepSub s.f (frameSub [] []) (frameRd [] getRd)) (stepRdS s (frameSub [] []) (frameRd [] getRd)))\n\n-- A variable no part of the machine reads or binds (as a skolem is).\ndef mFresh (s : SMachine) (x : Nat) : Bool :=\n skFresh s x && s.f.m.init.all (fun p => !occE x p.2) && !(s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains x\n\n-- What the machine's own parts may not read: the post names (nothing reads them but the goals), which are none of its\n-- maps.\ndef cApart (s : SMachine) (ds : List CDecl) : Bool :=\n s.f.flags.all (fun p => avoidsMaps (cPosts ds) p.2) && s.qflags.all (fun q => avoidsMaps (cPosts ds) q.2.2)\n && s.f.m.step.all (fun p => avoidsMapsE (cPosts ds) p.2)\n && s.f.m.writes.all (fun w => avoidsMapsE (cPosts ds) w.2.1 && avoidsMapsE (cPosts ds) w.2.2)\n && s.every.all (fun w => avoidsMapsE (cPosts ds) w.2.2)\n && s.f.m.init.all (fun p => avoidsMapsE (cPosts ds) p.2) && avoidsMaps (cPosts ds) s.f.m.assume\n && s.facts.all (fun l => avoidsMaps (cPosts ds) l.holds) && s.pfacts.all (fun f => avoidsMaps (cPosts ds) f.1.holds)\n && (cPosts ds).all (fun mp => !s.carried.contains mp && !(s.f.m.maps0.map (·.1)).contains mp\n && !(s.every.map (·.1)).contains mp && !(s.f.m.writes.map (·.1)).contains mp)\n\n-- A declaration's parameters as the runtime reads them: one, lo = j and base 0; two, lo ≠ j (and base > 0).\ndef canonOk (d : CDecl) : Bool := if d.base == 0 then d.lo == d.j else d.lo != d.j\n\n-- Each declaration: its map carried, its j, lo and key fresh, j and lo not its key, one parameter lo = j and base 0 and\n-- two lo ≠ j (what the runtime computes), its bound and body reading no flag,\n-- quantified flag, witness, count map or post name, and no entry's skolem, key or further key (nor having them as j or\n-- key): a law reads a count at the state, its own keys set after (withCnt).\ndef cDeclOk (s : SMachine) (ds : List CDecl) (ps : List SEntry) (d : CDecl) : Bool :=\n s.carried.contains d.mp && d.j != d.key && mFresh s d.j && mFresh s d.key && !occE d.key d.below\n && avoidsE (s.qVars ++ s.wVars ++ flagVars s.f.flags) d.below && avoidsE (s.qVars ++ s.wVars ++ flagVars s.f.flags) d.body\n && avoidsMapsE (cMaps ds ++ cPosts ds) d.below && avoidsMapsE (cMaps ds ++ cPosts ds) d.body\n && ps.all (fun e => (e.sk :: (e.keys2 ++ e.law.key.toList)).all (fun g => !occE g d.below && !occE g d.body && g != d.j && g != d.key))\n && d.lo != d.key && mFresh s d.lo && canonOk d\n\n-- The entries' own conditions (Sets.lean's checkSMachine's), a law reading count maps of the state only, and no post name.\ndef cEntryOk (s : SMachine) (ds : List CDecl) (ps : List SEntry) (e : SEntry) : Bool :=\n avoids (s.extVars ++ flagVars s.f.flags) e.law.holds && avoidsMaps (s.carried.filter (fun mp => !(stateMaps s ds).contains mp) ++ cPosts ds) e.law.holds\n && !(s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains e.sk\n && ps.all (fun e' => !occC e.sk e'.law.holds) && !occC e.sk s.f.m.pre && s.f.m.init.all (fun p => !occE e.sk p.2)\n && skFresh s e.sk && key2Ok s ps e\n\n-- A certificate's witnesses: variables no part of the machine or law reads (a goal reads them only in its instances,\n-- which hold at every value), none an entry's skolem or further key.\ndef witsOk (s : SMachine) (ps : List SEntry) (k : CCert) : Bool :=\n k.insts.all fun i => mFresh s i.wit && !occC i.wit s.f.m.pre\n && ps.all (fun e => !occC i.wit e.law.holds && e.sk != i.wit && !e.keys2.contains i.wit)\n\nstructure CEntry where\n e : SEntry -- the law, its skolem and further keys, and where its goals assume the laws and facts (its certs unused)\n start : CCert\n step : CCert\n\ndef checkCMachine (s : SMachine) (ds : List CDecl) (ps : List CEntry) : Bool :=\n sOk s && avoids (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)) s.f.m.pre && !readsC s.f.m.pre\n && sTermsOk s (flagVars s.f.flags) && factsOk s\n && cDistinct (cMaps ds ++ cPosts ds) && cApart s ds && ds.all (cDeclOk s ds (ps.map (·.e)))\n && ps.all (fun ce => cEntryOk s ds (ps.map (·.e)) ce.e && witsOk s (ps.map (·.e)) ce.start && witsOk s (ps.map (·.e)) ce.step\n && checkMC (cStartGoal s ds ce.e) (cStartDecls s ds) ce.start\n && checkMC (cStepGoal s ds (ps.map (·.e)) ce.e) (cStepDecls s ds) ce.step)\n\n-- The cuts of one counted certificate (frames, per-key monotone cuts, per-key linear cuts), as the single-goal check\n-- checkMCF takes them. A family entry carries its two certificates' cuts beside them.\nstructure CAux where\n frames : List FrameCut := []\n monos : List MonoCut := []\n lins : List LinCut := []\n\nstructure CEntryF where\n e : SEntry\n start : CCert\n step : CCert\n startAux : CAux\n stepAux : CAux\n\n-- An entry without cuts, as an entry with empty cuts.\ndef CEntry.toF (ce : CEntry) : CEntryF := ⟨ce.e, ce.start, ce.step, {}, {}⟩\n\n-- checkCMachine with each certificate's cuts: the same conditions, each goal checked by checkMCF.\ndef checkCMachineF (s : SMachine) (ds : List CDecl) (ps : List CEntryF) : Bool :=\n sOk s && avoids (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)) s.f.m.pre && !readsC s.f.m.pre\n && sTermsOk s (flagVars s.f.flags) && factsOk s\n && cDistinct (cMaps ds ++ cPosts ds) && cApart s ds && ds.all (cDeclOk s ds (ps.map (·.e)))\n && ps.all (fun ce => cEntryOk s ds (ps.map (·.e)) ce.e && witsOk s (ps.map (·.e)) ce.start && witsOk s (ps.map (·.e)) ce.step\n && checkMCF (cStartGoal s ds ce.e) (cStartDecls s ds) ce.start ce.startAux.frames ce.startAux.monos ce.startAux.lins\n && checkMCF (cStepGoal s ds (ps.map (·.e)) ce.e) (cStepDecls s ds) ce.step ce.stepAux.frames ce.stepAux.monos ce.stepAux.lins)\n\n-- The family check in parts, so a large family can be decided entry by entry (each part its own `decide`): the\n-- conditions on the machine and declarations, and one entry's conditions and two goals. `es` is the entries' laws.\ndef cGlobalOkF (s : SMachine) (ds : List CDecl) (es : List SEntry) : Bool :=\n sOk s && avoids (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)) s.f.m.pre && !readsC s.f.m.pre\n && sTermsOk s (flagVars s.f.flags) && factsOk s\n && cDistinct (cMaps ds ++ cPosts ds) && cApart s ds && ds.all (cDeclOk s ds es)\n\ndef cEntryCheckF (s : SMachine) (ds : List CDecl) (es : List SEntry) (ce : CEntryF) : Bool :=\n cEntryOk s ds es ce.e && witsOk s es ce.start && witsOk s es ce.step\n && checkMCF (cStartGoal s ds ce.e) (cStartDecls s ds) ce.start ce.startAux.frames ce.startAux.monos ce.startAux.lins\n && checkMCF (cStepGoal s ds es ce.e) (cStepDecls s ds) ce.step ce.stepAux.frames ce.stepAux.monos ce.stepAux.lins\n\n/-- The family check is its parts: nothing is added or dropped by deciding them separately. -/\ntheorem checkCMachineF_split (s : SMachine) (ds : List CDecl) (ps : List CEntryF) :\n checkCMachineF s ds ps = (cGlobalOkF s ds (ps.map (·.e)) && ps.all (cEntryCheckF s ds (ps.map (·.e)))) := rfl\n\n/-- From the parts: the machine's conditions and every entry's check give the family check. -/\ntheorem checkCMachineF_of_parts (s : SMachine) (ds : List CDecl) (ps : List CEntryF)\n (hg : cGlobalOkF s ds (ps.map (·.e)) = true) (he : ∀ ce ∈ ps, cEntryCheckF s ds (ps.map (·.e)) ce = true) :\n checkCMachineF s ds ps = true := by\n rw [checkCMachineF_split, hg, Bool.true_and]\n exact List.all_eq_true.mpr he\n\ntheorem CEntry.toF_map_e (ps : List CEntry) : (ps.map CEntry.toF).map (·.e) = ps.map (·.e) := by\n rw [List.map_map]; rfl\n\n/-- With no cuts the family check is the old one. -/\ntheorem checkCMachineF_noAux (s : SMachine) (ds : List CDecl) (ps : List CEntry) :\n checkCMachineF s ds (ps.map CEntry.toF) = checkCMachine s ds ps := by\n have hf : ((fun ce : CEntryF => cEntryOk s ds (ps.map (·.e)) ce.e && witsOk s (ps.map (·.e)) ce.start && witsOk s (ps.map (·.e)) ce.step\n && checkMCF (cStartGoal s ds ce.e) (cStartDecls s ds) ce.start ce.startAux.frames ce.startAux.monos ce.startAux.lins\n && checkMCF (cStepGoal s ds (ps.map (·.e)) ce.e) (cStepDecls s ds) ce.step ce.stepAux.frames ce.stepAux.monos ce.stepAux.lins) ∘ CEntry.toF)\n = (fun ce : CEntry => cEntryOk s ds (ps.map (·.e)) ce.e && witsOk s (ps.map (·.e)) ce.start && witsOk s (ps.map (·.e)) ce.step\n && checkMC (cStartGoal s ds ce.e) (cStartDecls s ds) ce.start\n && checkMC (cStepGoal s ds (ps.map (·.e)) ce.e) (cStepDecls s ds) ce.step) := by\n funext ce\n show (cEntryOk s ds (ps.map (·.e)) ce.e && witsOk s (ps.map (·.e)) ce.start && witsOk s (ps.map (·.e)) ce.step\n && checkMCF (cStartGoal s ds ce.e) (cStartDecls s ds) ce.start [] [] []\n && checkMCF (cStepGoal s ds (ps.map (·.e)) ce.e) (cStepDecls s ds) ce.step [] [] []) = _\n rw [checkMCF_nil, checkMCF_nil]\n unfold checkCMachineF checkCMachine\n rw [CEntry.toF_map_e, List.all_map, hf]\n\n/-! Reading a law with its count maps renamed -/\n\n-- The maps a renamed term reads: a renamed map's cells are its new name's.\ndef renM (mr : List (Nat × Nat)) (N : Nat → Nat → Nat) : Nat → Nat → Nat := fun mp =>\n match lookup (fun p => p.1 == mp) mr with\n | some p => N p.2\n | none => N mp\n\ntheorem ren_evalC (mr : List (Nat × Nat)) (X : Nat → Nat) (N : Nat → Nat → Nat) (c : C) :\n evalC X N (substRC [] (frameRd mr getRd) c) = evalC X (renM mr N) c := by\n rw [substR_evalC [] (frameRd mr getRd) X N (renM mr N) (fun m k => by\n simp only [frameRd, renM]; cases h : lookup (fun p => p.1 == m) mr <;> simp [getRd, evalE]), applyS_nil']\n\nmutual\ntheorem occ_renE (mr : List (Nat × Nat)) (i : Nat) : (e : E) → occE i (substRE [] (frameRd mr getRd) e) = occE i e\n | .var j => by simp [substRE, assoc, lookup, occE]\n | .const _ => by simp [substRE, occE]\n | .add a b => by simp [substRE, occE, occ_renE mr i a, occ_renE mr i b]\n | .sub a b => by simp [substRE, occE, occ_renE mr i a, occ_renE mr i b]\n | .mul _ a => by simp [substRE, occE, occ_renE mr i a]\n | .min a b => by simp [substRE, occE, occ_renE mr i a, occ_renE mr i b]\n | .max a b => by simp [substRE, occE, occ_renE mr i a, occ_renE mr i b]\n | .prod a b => by simp [substRE, occE, occ_renE mr i a, occ_renE mr i b]\n | .ite c t f => by simp [substRE, occE, occ_renC mr i c, occ_renE mr i t, occ_renE mr i f]\n | .get m key => by\n simp only [substRE, frameRd]\n split <;> simp [getRd, occE, occ_renE mr i key]\n | .tup a b => by simp [substRE, occE, occ_renE mr i a, occ_renE mr i b]\n | .proj _ a => by simp [substRE, occE, occ_renE mr i a]\ntheorem occ_renC (mr : List (Nat × Nat)) (i : Nat) : (c : C) → occC i (substRC [] (frameRd mr getRd) c) = occC i c\n | .le a b => by simp [substRC, occC, occ_renE mr i a, occ_renE mr i b]\n | .lt a b => by simp [substRC, occC, occ_renE mr i a, occ_renE mr i b]\n | .eq a b => by simp [substRC, occC, occ_renE mr i a, occ_renE mr i b]\n | .and a b => by simp [substRC, occC, occ_renC mr i a, occ_renC mr i b]\n | .or a b => by simp [substRC, occC, occ_renC mr i a, occ_renC mr i b]\n | .not a => by simp [substRC, occC, occ_renC mr i a]\nend\n\n-- A renamed law holds where the law holds with its maps renamed.\ntheorem renLaw_holds (ds : List CDecl) (l : MLaw) (X : Nat → Nat) (N : Nat → Nat → Nat) :\n (renLaw ds l).Holds X N ↔ l.Holds X (renM (cren ds) N) := by\n unfold MLaw.Holds\n simp only [renLaw]\n split <;> simp [ren_evalC]\n\n/-! Counts read where a fresh variable is set -/\n\ntheorem cntOf_upd {d : CDecl} {g : Nat} (hb : occE g d.below = false) (hd : occE g d.body = false) (X : Nat → Nat) (N : Nat → Nat → Nat) (w x : Nat) :\n cntOf d (upd X g w) N x = cntOf d X N x := by\n simp only [cntOf]\n have hB : evalE (atJ d (upd X g w) x) N d.below = evalE (atJ d X x) N d.below :=\n congrE _ _ N d.below (fun i hi => atJ_congr d x i (fun _ _ => by\n have hig : i ≠ g := fun h => by rw [h, hb] at hi; cases hi\n simp [upd, hig]))\n rw [hB]\n exact sumBelow_congr _ (fun k _ => congrE _ _ N d.body (fun i hi => by\n have hig : i ≠ g := fun h => by rw [h, hd] at hi; cases hi\n simp only [upd]; split\n · rfl\n · exact atJ_congr d x i (fun _ _ => by simp [upd, hig])))\n\ntheorem withCnt_upd {ds : List CDecl} {g : Nat} (h : ∀ d ∈ ds, occE g d.below = false ∧ occE g d.body = false) (X : Nat → Nat) (N : Nat → Nat → Nat) (w : Nat) :\n withCnt ds (upd X g w) N = withCnt ds X N := by\n funext mp\n simp only [withCnt]\n split\n · rename_i d hd\n have := h d (lookup_some hd).1\n funext x; exact cntOf_upd this.1 this.2 X N w x\n · rfl\n\ntheorem withCnt_at {ds : List CDecl} (hd : cDistinct (cMaps ds) = true) {d : CDecl} (hm : d ∈ ds) (X : Nat → Nat) (N : Nat → Nat → Nat) :\n withCnt ds X N d.mp = cntOf d X N := by\n simp only [withCnt]\n have : lookup (fun d' => d'.mp == d.mp) ds = some d := by\n induction ds with\n | nil => simp at hm\n | cons a as ih =>\n simp only [cMaps, List.map_cons] at hd\n obtain ⟨hna, hd'⟩ := cDistinct_cons hd\n rcases List.mem_cons.mp hm with rfl | hm'\n · simp [lookup]\n · have hne : (a.mp == d.mp) = false := by\n simp only [beq_eq_false_iff_ne]; intro he; exact hna (by rw [he]; exact List.mem_map_of_mem hm')\n simp only [lookup, hne, Bool.false_eq_true, ite_false]\n exact ih hd' hm'\n rw [this]\n\ntheorem withCnt_other {ds : List CDecl} {mp : Nat} (h : mp ∉ cMaps ds) (X : Nat → Nat) (N : Nat → Nat → Nat) : withCnt ds X N mp = N mp := by\n simp only [withCnt]\n rw [lookup_none (fun d hd => by simp only [beq_eq_false_iff_ne]; intro he; exact h (by rw [← he]; exact List.mem_map_of_mem hd))]\n\n/-! A request's view, read where a fresh variable is set -/\n\ntheorem witnessKeys_congr {X X' : Nat → Nat} {N N' : Nat → Nat → Nat} {q : Nat × List Nat × C}\n (h : ∀ k, holdsC (atKeys X q.2.1 k) N q.2.2 ↔ holdsC (atKeys X' q.2.1 k) N' q.2.2) : witnessKeys X N q = witnessKeys X' N' q := by\n have hp : (fun k => ¬holdsC (atKeys X q.2.1 k) N q.2.2) = (fun k => ¬holdsC (atKeys X' q.2.1 k) N' q.2.2) := funext fun k => by rw [h k]\n unfold witnessKeys\n split\n · rename_i h1\n have h2 : ∃ k, ¬holdsC (atKeys X' q.2.1 k) N' q.2.2 := by obtain ⟨k, hk⟩ := h1; exact ⟨k, by rwa [← h k]⟩\n rw [dif_pos h2]\n have : ∀ (p p' : (Nat → Nat) → Prop) (e : p = p') (h1 : ∃ k, p k) (h2 : ∃ k, p' k), Classical.choose h1 = Classical.choose h2 := by\n intro p p' e h1 h2; subst e; rfl\n exact this _ _ hp h1 h2\n · rename_i h1\n have h2 : ¬∃ k, ¬holdsC (atKeys X' q.2.1 k) N' q.2.2 := fun ⟨k, hk⟩ => h1 ⟨k, by rwa [h k]⟩\n rw [dif_neg h2]\n\ntheorem sReq_upd {s : SMachine} {g : Nat} (hi : g ∉ s.f.m.inputs) (hq : g ∉ s.qVars) (hb : ∀ q ∈ s.qflags, occC g q.2.2 = false)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat) (w : Nat) :\n sReq s (upd ρ g w) M ι κ = sReq s ρ M ι κ := by\n funext v\n simp only [sReq]\n split\n · rfl\n · split\n · rename_i q hql\n have hvq : v ≠ g := fun h => hq (by\n have := lookup_some hql; simp only [beq_iff_eq] at this; rw [← h, ← this.2]; exact List.mem_map_of_mem this.1)\n rw [withInputs_upd hi, decideQ_upd hq hb]\n simp only [upd, hvq, ite_false]\n · split\n · split\n · rename_i q hq'\n split\n · apply congrFun\n apply witnessKeys_congr\n intro k\n rw [withInputs_upd hi]\n simp only [← evalC_iff]\n rw [congrC _ (atKeys (withInputs s.f.m.inputs ρ ι) q.2.1 k) _ q.2.2 (fun i hi' => by\n have hig : i ≠ g := fun h => by rw [h, hb q (lookup_some hq').1] at hi'; cases hi'\n simp only [atKeys]; split\n · rfl\n · simp [upd, hig])]\n · rfl\n · rfl\n · rfl\n\n/-! The check, taken apart -/\n\ntheorem cDistinct_append {a b : List Nat} (h : cDistinct (a ++ b) = true) : cDistinct a = true ∧ cDistinct b = true ∧ ∀ x ∈ a, x ∉ b := by\n induction a with\n | nil => exact ⟨rfl, h, by simp⟩\n | cons x xs ih =>\n obtain ⟨hx, hr⟩ := cDistinct_cons h\n obtain ⟨h1, h2, h3⟩ := ih hr\n refine ⟨?_, h2, fun y hy => ?_⟩\n · simp only [cDistinct, Bool.and_eq_true, Bool.not_eq_true']\n exact ⟨by simpa [List.contains_iff_mem] using fun hm => hx (List.mem_append_left _ hm), h1⟩\n · rcases List.mem_cons.mp hy with rfl | hy\n · exact fun hm => hx (List.mem_append_right _ hm)\n · exact h3 y hy\n\nstructure CParts (s : SMachine) (ds : List CDecl) (ps : List CEntryF) : Prop where\n sok : sOk s = true\n pre : avoids (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)) s.f.m.pre = true\n preR : readsC s.f.m.pre = false\n terms : sTermsOk s (flagVars s.f.flags) = true\n facts : factsOk s = true\n dist : cDistinct (cMaps ds ++ cPosts ds) = true\n apart : cApart s ds = true\n decls : ∀ d ∈ ds, cDeclOk s ds (ps.map (·.e)) d = true\n entries : ∀ ce ∈ ps, cEntryOk s ds (ps.map (·.e)) ce.e = true ∧ checkMCF (cStartGoal s ds ce.e) (cStartDecls s ds) ce.start ce.startAux.frames ce.startAux.monos ce.startAux.lins = true\n ∧ checkMCF (cStepGoal s ds (ps.map (·.e)) ce.e) (cStepDecls s ds) ce.step ce.stepAux.frames ce.stepAux.monos ce.stepAux.lins = true\n wits : ∀ ce ∈ ps, witsOk s (ps.map (·.e)) ce.start = true ∧ witsOk s (ps.map (·.e)) ce.step = true\n\ntheorem cparts {s : SMachine} {ds : List CDecl} {ps : List CEntryF} (h : checkCMachineF s ds ps = true) : CParts s ds ps := by\n simp only [checkCMachineF, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true'] at h\n obtain ⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩, h9⟩ := h\n exact ⟨h1, h2, h3, h4, h5, h6, h7, h8, fun ce hce => ⟨(h9 ce hce).1.1.1.1, (h9 ce hce).1.2, (h9 ce hce).2⟩,\n fun ce hce => ⟨(h9 ce hce).1.1.1.2, (h9 ce hce).1.1.2⟩⟩\n\nstructure ApartParts (s : SMachine) (ds : List CDecl) : Prop where\n flags : ∀ p ∈ s.f.flags, avoidsMaps (cPosts ds) p.2 = true\n qflags : ∀ q ∈ s.qflags, avoidsMaps (cPosts ds) q.2.2 = true\n step : ∀ p ∈ s.f.m.step, avoidsMapsE (cPosts ds) p.2 = true\n writes : ∀ w ∈ s.f.m.writes, avoidsMapsE (cPosts ds) w.2.1 = true ∧ avoidsMapsE (cPosts ds) w.2.2 = true\n every : ∀ w ∈ s.every, avoidsMapsE (cPosts ds) w.2.2 = true\n init : ∀ p ∈ s.f.m.init, avoidsMapsE (cPosts ds) p.2 = true\n assume : avoidsMaps (cPosts ds) s.f.m.assume = true\n facts : ∀ l ∈ s.facts, avoidsMaps (cPosts ds) l.holds = true\n pfacts : ∀ f ∈ s.pfacts, avoidsMaps (cPosts ds) f.1.holds = true\n posts : ∀ mp ∈ cPosts ds, mp ∉ s.carried ∧ mp ∉ s.f.m.maps0.map (·.1) ∧ mp ∉ s.every.map (·.1) ∧ mp ∉ s.f.m.writes.map (·.1)\n\ntheorem apart_parts {s : SMachine} {ds : List CDecl} (h : cApart s ds = true) : ApartParts s ds := by\n simp only [cApart, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true'] at h\n obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩, h9⟩, h10⟩ := h\n exact ⟨h1, h2, h3, fun w hw => ⟨(h4 w hw).1, (h4 w hw).2⟩, h5, h6, h7, h8, h9, fun mp hm =>\n ⟨by simpa [List.contains_iff_mem] using (h10 mp hm).1.1.1, by simpa [List.contains_iff_mem] using (h10 mp hm).1.1.2,\n by simpa [List.contains_iff_mem] using (h10 mp hm).1.2, by simpa [List.contains_iff_mem] using (h10 mp hm).2⟩⟩\n\nstructure FreshParts (s : SMachine) (x : Nat) : Prop where\n sk : skFresh s x = true\n init : ∀ p ∈ s.f.m.init, occE x p.2 = false\n out : (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains x = false\n\ntheorem mfresh_parts {s : SMachine} {x : Nat} (h : mFresh s x = true) : FreshParts s x := by\n simp only [mFresh, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true'] at h\n exact ⟨h.1.1, h.1.2, h.2⟩\n\ntheorem fresh_out {s : SMachine} {x : Nat} (h : (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains x = false) :\n x ∉ s.extVars ∧ x ∉ flagVars s.f.flags ∧ x ∉ s.f.m.init.map (·.1) ∧ x ∉ s.f.m.step.map (·.1) ∧ x ∉ s.f.m.inputs ∧ x ∉ s.qVars ∧ x ∉ s.wVars := by\n have hn : x ∉ s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1) := fun hm => by\n rw [List.contains_iff_mem.mpr hm] at h; cases h\n simp only [List.mem_append, not_or] at hn\n obtain ⟨⟨⟨hE, hF⟩, hI⟩, hS⟩ := hn\n simp only [SMachine.extVars, List.mem_append, not_or] at hE\n exact ⟨by simp only [SMachine.extVars, List.mem_append, not_or]; exact hE, hF, hI, hS, hE.1.1, hE.1.2, hE.2⟩\n\nstructure DeclParts (s : SMachine) (ds : List CDecl) (ps : List SEntry) (d : CDecl) : Prop where\n carried : d.mp ∈ s.carried\n jk : d.j ≠ d.key\n jf : FreshParts s d.j\n kf : FreshParts s d.key\n kB : occE d.key d.below = false\n qwB : avoidsE (s.qVars ++ s.wVars ++ flagVars s.f.flags) d.below = true\n qwD : avoidsE (s.qVars ++ s.wVars ++ flagVars s.f.flags) d.body = true\n mB : avoidsMapsE (cMaps ds ++ cPosts ds) d.below = true\n mD : avoidsMapsE (cMaps ds ++ cPosts ds) d.body = true\n ent : ∀ e ∈ ps, ∀ g ∈ e.sk :: (e.keys2 ++ e.law.key.toList), occE g d.below = false ∧ occE g d.body = false ∧ g ≠ d.j ∧ g ≠ d.key\n lk : d.lo ≠ d.key\n lf : FreshParts s d.lo\n canon : canonOk d = true\n\ntheorem decl_parts {s : SMachine} {ds : List CDecl} {ps : List SEntry} {d : CDecl} (h : cDeclOk s ds ps d = true) : DeclParts s ds ps d := by\n simp only [cDeclOk, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at h\n obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h0⟩, h5⟩, h6⟩, h7⟩, h8⟩, h9⟩, h10⟩, h11⟩, h12⟩ := h\n exact ⟨by simpa [List.contains_iff_mem] using h1, h2, mfresh_parts h3, mfresh_parts h4, h0, h5, h6, h7, h8,\n fun e he g hg => ⟨(h9 e he g hg).1.1.1, (h9 e he g hg).1.1.2, (h9 e he g hg).1.2, (h9 e he g hg).2⟩, h10, mfresh_parts h11, h12⟩\n\nstructure EntryParts (s : SMachine) (ds : List CDecl) (ps : List SEntry) (e : SEntry) : Prop where\n lx : avoids (s.extVars ++ flagVars s.f.flags) e.law.holds = true\n lm : avoidsMaps (s.carried.filter (fun mp => !(stateMaps s ds).contains mp) ++ cPosts ds) e.law.holds = true\n fresh : (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains e.sk = false\n slaw : ∀ e' ∈ ps, occC e.sk e'.law.holds = false\n spre : occC e.sk s.f.m.pre = false\n sinit : ∀ p ∈ s.f.m.init, occE e.sk p.2 = false\n skf : skFresh s e.sk = true\n k2 : key2Ok s ps e = true\n\ntheorem entry_parts {s : SMachine} {ds : List CDecl} {ps : List SEntry} {e : SEntry} (h : cEntryOk s ds ps e = true) : EntryParts s ds ps e := by\n simp only [cEntryOk, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true'] at h\n obtain ⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩ := h\n exact ⟨h1, h2, h3, h4, h5, h6, h7, h8⟩\n\n-- The entries, as checkSMachine's lemmas read them.\ntheorem key2_parts {s : SMachine} {ds : List CDecl} {ps : List SEntry} (hk : ∀ e ∈ ps, cEntryOk s ds ps e = true) {e : SEntry} (he : e ∈ ps) {g : Nat} (hg : g ∈ e.keys2) :\n skFresh s g = true ∧ (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains g = false\n ∧ occC g s.f.m.pre = false ∧ (∀ p ∈ s.f.m.init, occE g p.2 = false) ∧ (∀ e' ∈ ps, occC g e'.law.holds = false ∨ g ∈ e'.keys2)\n ∧ e.law.key ≠ some g := by\n have hk' := (entry_parts (hk e he)).k2\n simp only [key2Ok, List.all_eq_true, Bool.and_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq, Bool.or_eq_true, List.contains_iff_mem] at hk'\n obtain ⟨⟨⟨⟨⟨hkey, hf⟩, hc⟩, hp⟩, hi⟩, hall⟩ := hk' g hg\n exact ⟨hf, by simpa [List.contains_iff_mem] using hc, hp, hi, fun e' he' => (by have := (hall e' he').1; simpa using this), hkey⟩\n\n/-! Variables set at once: a certificate's witnesses -/\n\ndef setAll (X : Nat → Nat) : List Nat → (Nat → Nat) → Nat → Nat\n | [], _ => X\n | v :: vs, f => upd (setAll X vs f) v (f v)\n\ntheorem setAll_at (X : Nat → Nat) (f : Nat → Nat) : ∀ (vs : List Nat) (i : Nat), setAll X vs f i = if i ∈ vs then f i else X i\n | [], i => by simp [setAll]\n | v :: vs, i => by\n simp only [setAll, upd, List.mem_cons]\n by_cases h : i = v\n · subst h; simp\n · rw [setAll_at X f vs i]; simp [h]\n\n-- A state that agrees with X off vs is X with vs set at its values.\ntheorem setAll_self {X Y : Nat → Nat} {vs : List Nat} (h : ∀ i, i ∉ vs → Y i = X i) : setAll X vs Y = Y := by\n funext i; rw [setAll_at]; split\n · rfl\n · rename_i hi; exact (h i hi).symm\n\nstructure WitParts (s : SMachine) (ps : List SEntry) (w : Nat) : Prop where\n fr : FreshParts s w\n pre : occC w s.f.m.pre = false\n laws : ∀ e ∈ ps, occC w e.law.holds = false ∧ e.sk ≠ w ∧ w ∉ e.keys2\n\ntheorem wits_parts {s : SMachine} {ps : List SEntry} {k : CCert} (h : witsOk s ps k = true) : ∀ i ∈ k.insts, WitParts s ps i.wit := by\n intro i hi\n have := List.all_eq_true.mp h i hi\n simp only [Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true', bne_iff_ne, ne_eq] at this\n exact ⟨mfresh_parts this.1.1, this.1.2, fun e he => ⟨(this.2 e he).1.1, (this.2 e he).1.2, by simpa [List.contains_iff_mem] using (this.2 e he).2⟩⟩\n\ntheorem sNext_setAll {s : SMachine} {vs : List Nat} (hv : ∀ v ∈ vs, FreshParts s v) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat)\n (κ : Nat → Nat → Nat) (f : Nat → Nat) :\n sNext s (setAll ρ vs f) M ι κ = (setAll (sNext s ρ M ι κ).1 vs f, (sNext s ρ M ι κ).2)\n ∧ sView s (setAll ρ vs f) M ι κ = (setAll (sView s ρ M ι κ).1 vs f, (sView s ρ M ι κ).2) := by\n induction vs with\n | nil => simp [setAll]\n | cons v vs ih =>\n obtain ⟨h1, h2⟩ := ih (fun v' hv' => hv v' (List.mem_cons_of_mem _ hv'))\n have F := hv v List.mem_cons_self\n obtain ⟨hN, hV, _⟩ := fresh_parts F.sk F.out (setAll ρ vs f) M ι κ (f v)\n simp only [setAll]\n rw [hN, hV, h1, h2]\n exact ⟨rfl, rfl⟩\n\ntheorem sReq_setAll {s : SMachine} {vs : List Nat} (hv : ∀ v ∈ vs, FreshParts s v) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat)\n (κ : Nat → Nat → Nat) (f : Nat → Nat) : sReq s (setAll ρ vs f) M ι κ = sReq s ρ M ι κ := by\n induction vs with\n | nil => rfl\n | cons v vs ih =>\n have F := hv v List.mem_cons_self\n have o := fresh_out F.out\n simp only [setAll]\n rw [sReq_upd o.2.2.2.2.1 o.2.2.2.2.2.1 (skFresh_parts F.sk).2.1, ih (fun v' hv' => hv v' (List.mem_cons_of_mem _ hv'))]\n\ntheorem withExt_upd {s : SMachine} {g : Nat} (hg : g ∉ s.extVars) (ρ R : Nat → Nat) (w : Nat) : withExt s (upd ρ g w) R = upd (withExt s ρ R) g w := by\n funext i\n simp only [withExt, upd]\n by_cases h : i = g\n · subst h; simp [List.contains_iff_mem, hg]\n · simp [h]\n\ntheorem withExt_setAll {s : SMachine} {vs : List Nat} (hv : ∀ v ∈ vs, v ∉ s.extVars) (ρ R : Nat → Nat) (f : Nat → Nat) :\n withExt s (setAll ρ vs f) R = setAll (withExt s ρ R) vs f := by\n induction vs with\n | nil => rfl\n | cons v vs ih =>\n simp only [setAll]\n rw [withExt_upd (hv v List.mem_cons_self), ih (fun v' hv' => hv v' (List.mem_cons_of_mem _ hv'))]\n\ntheorem applyS_setAll {σ : List (Nat × E)} {vs : List Nat} (hv : ∀ v ∈ vs, v ∉ σ.map (·.1) ∧ ∀ p ∈ σ, occE v p.2 = false)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (f : Nat → Nat) : applyS σ (setAll ρ vs f) M = setAll (applyS σ ρ M) vs f := by\n induction vs with\n | nil => rfl\n | cons v vs ih =>\n simp only [setAll]\n rw [applyS_upd (hv v List.mem_cons_self).1 (by simpa [List.all_eq_true] using (hv v List.mem_cons_self).2),\n ih (fun v' hv' => hv v' (List.mem_cons_of_mem _ hv'))]\n\ntheorem sentry_setAll {e : SEntry} {vs : List Nat} (hv : ∀ v ∈ vs, occC v e.law.holds = false) {ρ : Nat → Nat} {M : Nat → Nat → Nat} (f : Nat → Nat) :\n e.Holds ρ M → e.Holds (setAll ρ vs f) M := by\n induction vs with\n | nil => exact id\n | cons v vs ih =>\n intro h\n simp only [setAll]\n exact sentry_upd (Or.inl (hv v List.mem_cons_self)) (f v) (ih (fun v' hv' => hv v' (List.mem_cons_of_mem _ hv')) h)\n\n/-! Maps read off a list's names -/\n\n-- A map with the names a declaration list posts at its post counts.\ndef atPosts (ds : List CDecl) (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) : Nat → Nat → Nat := fun mp =>\n match lookup (fun d => d.post == mp) ds with\n | some d => F d\n | none => N mp\n\ntheorem atPosts_other {ds : List CDecl} {mp : Nat} (h : mp ∉ cPosts ds) (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) : atPosts ds F N mp = N mp := by\n simp only [atPosts]\n rw [lookup_none (fun d hd => by simp only [beq_eq_false_iff_ne]; intro he; exact h (by rw [← he]; exact List.mem_map_of_mem hd))]\n\ntheorem atPosts_at {ds : List CDecl} (hd : cDistinct (cPosts ds) = true) {d : CDecl} (hm : d ∈ ds) (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) :\n atPosts ds F N d.post = F d := by\n simp only [atPosts]\n have : lookup (fun d' => d'.post == d.post) ds = some d := by\n induction ds with\n | nil => simp at hm\n | cons a as ih =>\n simp only [cPosts, List.map_cons] at hd\n obtain ⟨hna, hd'⟩ := cDistinct_cons hd\n rcases List.mem_cons.mp hm with rfl | hm'\n · simp [lookup]\n · have hne : (a.post == d.post) = false := by\n simp only [beq_eq_false_iff_ne]; intro he; exact hna (by rw [he]; exact List.mem_map_of_mem hm')\n simp only [lookup, hne, Bool.false_eq_true, ite_false]\n exact ih hd' hm'\n rw [this]\n\n-- Renamed, the post counts read as the counts: a count map read by its post name.\ntheorem renM_atPosts {ds : List CDecl} (hd : cDistinct (cMaps ds ++ cPosts ds) = true) (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) :\n ∀ mp, mp ∉ cPosts ds → renM (cren ds) (atPosts ds F N) mp = match lookup (fun d => d.mp == mp) ds with\n | some d => F d\n | none => N mp := by\n obtain ⟨hdm, hdp, hap⟩ := cDistinct_append hd\n intro mp hmp\n simp only [renM]\n have hl : ∀ (ds' : List CDecl), (∀ d ∈ ds', d ∈ ds) → (lookup (fun p => p.1 == mp) (cren ds')).map (·.2) = (lookup (fun d => d.mp == mp) ds').map (·.post) := by\n intro ds' _\n induction ds' with\n | nil => rfl\n | cons a as ih =>\n simp only [cren, List.map_cons, lookup] at ih ⊢\n by_cases ha : a.mp = mp\n · simp [ha]\n · simp only [ha, beq_self_eq_true, beq_iff_eq, ite_false]; exact ih (fun d hd => by simp_all)\n have := hl ds (fun d hd => hd)\n cases h1 : lookup (fun d => d.mp == mp) ds with\n | none =>\n rw [h1] at this\n cases h2 : lookup (fun p => p.1 == mp) (cren ds) with\n | none => simp only []; exact atPosts_other hmp F N\n | some p => rw [h2] at this; simp at this\n | some d =>\n rw [h1] at this\n cases h2 : lookup (fun p => p.1 == mp) (cren ds) with\n | none => rw [h2] at this; simp at this\n | some p =>\n rw [h2] at this\n simp only [Option.map_some, Option.some.injEq] at this\n simp only []\n rw [this]\n exact atPosts_at hdp (lookup_some h1).1 F N\n\n/-! Terms read across a substitution that keeps j and key -/\n\ntheorem assoc_term {σ : List (Nat × E)} {i : Nat} {t : E} (h : assoc σ i = some t) : (i, t) ∈ σ := by\n simp only [assoc, Option.map_eq_some_iff] at h\n obtain ⟨a, ha, rfl⟩ := h\n have ⟨hm, hp⟩ := lookup_some ha\n simp only [beq_iff_eq] at hp\n rw [← hp]; exact hm\n\ntheorem applyS_congrM {σ : List (Nat × E)} {X : List Nat} (h : ∀ p ∈ σ, avoidsMapsE X p.2 = true) (ρ : Nat → Nat) {M M' : Nat → Nat → Nat}\n (hm : ∀ mp, mp ∉ X → M mp = M' mp) : applyS σ ρ M = applyS σ ρ M' := by\n funext i\n simp only [applyS]\n cases ha : assoc σ i with\n | none => rfl\n | some t => exact congrME ρ M M' t (fun mp hmp => hm mp (avoidsMapsE_occ (h _ (assoc_term ha)) hmp))\n\ntheorem applyS_keep (d : CDecl) (σ : List (Nat × E)) (Y : Nat → Nat) (N : Nat → Nat → Nat) (i : Nat) :\n applyS (keepJ d σ) Y N i = if i = d.j ∨ i = d.lo ∨ i = d.key then Y i else applyS σ Y N i := by\n simp only [keepJ, applyS, assoc, lookup, beq_iff_eq]\n by_cases h1 : d.j = i\n · subst h1; simp [evalE]\n · by_cases h2 : d.lo = i\n · subst h2; simp [h1, Ne.symm h1, evalE]\n · by_cases h3 : d.key = i\n · subst h3; simp [h1, h2, Ne.symm h1, Ne.symm h2, evalE]\n · simp [h1, h2, h3, Ne.symm h1, Ne.symm h2, Ne.symm h3]\n\ntheorem avoidsMaps_right {A B : List Nat} {c : C} (h : avoidsMaps (A ++ B) c = true) : avoidsMaps B c = true := by\n simp only [avoidsMaps, List.all_append, Bool.and_eq_true] at h; exact h.2\ntheorem avoidsMapsE_right {A B : List Nat} {e : E} (h : avoidsMapsE (A ++ B) e = true) : avoidsMapsE B e = true := by\n simp only [avoidsMapsE, List.all_append, Bool.and_eq_true] at h; exact h.2\n\n/-! The start -/\n\ntheorem cstart_case (s : SMachine) (ds : List CDecl) (ps : List CEntryF) (h : checkCMachineF s ds ps = true) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (hM : StartMaps s.f.m M) (h0 : evalC ρ M s.f.m.pre = true) (hfa : ∀ l ∈ s.facts, l.Holds ρ M) (hpf : s.PFacts ρ M) :\n ∀ ce ∈ ps, ce.e.law.Holds (applyS s.f.m.init ρ M) (withCnt ds (applyS s.f.m.init ρ M) M) := by\n have P := cparts h\n have A := apart_parts P.apart\n obtain ⟨_, hdp, _⟩ := cDistinct_append P.dist\n intro ce hce\n obtain ⟨hent, hst, _⟩ := P.entries ce hce\n have E' := entry_parts hent\n have hskI : ce.e.sk ∉ s.f.m.init.map (·.1) := (fresh_out E'.fresh).2.2.1\n let X0 := applyS s.f.m.init ρ M\n let M2 := atPosts ds (fun d => cntOf d X0 M) M\n have hM2 : ∀ mp, mp ∉ cPosts ds → M2 mp = M mp := fun mp h => atPosts_other h _ M\n have hlp : avoidsMaps (cPosts ds) ce.e.law.holds = true := avoidsMaps_right E'.lm\n -- The law at the start reads as the renamed law with the post names at the counts.\n refine holds_transfer (V := []) (MS := cPosts ds) ce.e.law (by simp [avoids]) hlp (fun _ _ => rfl)\n (fun mp hmp => (renM_atPosts P.dist (fun d => cntOf d X0 M) M mp hmp).symm) ?_\n rw [← renLaw_holds]\n refine goalOf_holds (renLaw ds ce.e.law) (by simp only [renLaw, occ_renC]; exact E'.slaw ce.e (List.mem_map_of_mem hce)) X0 M2 (fun v => ?_)\n apply Decidable.byContradiction; intro hn\n -- The start's reads: a declared map's constant, any other map as M2 holds it.\n have hrdS : ∀ (Y : Nat → Nat) mp k, mp ∉ cPosts ds → evalE Y M2 (rdStart s.f.m mp k) = M mp (evalE Y M2 k) := by\n intro Y mp k hmp\n simp only [rdStart]\n split\n · rename_i p hp\n have ⟨hm, hq⟩ := lookup_some hp\n simp only [beq_iff_eq] at hq\n simp only [evalE]; rw [← hq, hM p hm]\n · simp only [evalE]; rw [hM2 mp hmp]\n have hrd2 : ∀ (Y : Nat → Nat) mp k, evalE Y M2 (rdStart s.f.m mp k) = M2 mp (evalE Y M2 k) := by\n intro Y mp k\n simp only [rdStart]\n split\n · rename_i p hp\n have ⟨hm, hq⟩ := lookup_some hp\n simp only [beq_iff_eq] at hq\n have hp1 : p.1 ∉ cPosts ds := fun hc => (A.posts p.1 hc).2.1 (List.mem_map_of_mem hm)\n simp only [evalE]; rw [← hq, hM2 _ hp1, hM p hm]\n · rfl\n have hX0 : applyS s.f.m.init ρ M2 = X0 := applyS_congrM A.init ρ (fun mp hmp => hM2 mp hmp)\n apply mcF_sound _ _ _ _ _ _ hst (upd ρ ce.e.sk v) M2\n · -- Each post count: its bound and body, read across the start, are the declaration's at the start state.\n intro d' hd' x\n obtain ⟨d, hdf, rfl⟩ := List.mem_map.mp hd'\n have hd := (List.mem_filter.mp hdf).1\n have D := decl_parts (P.decls d hd)\n obtain ⟨hskB, hskD, hskj, hskk⟩ := D.ent ce.e (List.mem_map_of_mem hce) ce.e.sk List.mem_cons_self\n have hpB : avoidsMapsE (cPosts ds) d.below = true := avoidsMapsE_right D.mB\n have hpD : avoidsMapsE (cPosts ds) d.body = true := avoidsMapsE_right D.mD\n have hkI := (fresh_out D.kf.out).2.2.1\n show M2 d.post x = cntOf (afterDecl s.f.m.init (rdStart s.f.m) d) (upd ρ ce.e.sk v) M2 x\n rw [cntOf_after, show M2 d.post = cntOf d X0 M from atPosts_at hdp hd _ M]\n simp only [cntOf]\n -- reading across the start at Y (the goal's state with the parameters, and key, set): the start state with them set\n have hacross : ∀ (Y T : Nat → Nat) (e : E), avoidsMapsE (cPosts ds) e = true → occE ce.e.sk e = false →\n (∀ i, i ≠ d.j → i ≠ d.lo → i ≠ d.key → Y i = upd ρ ce.e.sk v i) → T d.j = Y d.j → T d.lo = Y d.lo → T d.key = Y d.key →\n (∀ i, i ≠ d.j → i ≠ d.lo → i ≠ d.key → T i = X0 i) →\n evalE Y M2 (substRE (keepJ d s.f.m.init) (rdStart s.f.m) e) = evalE T M e := by\n intro Y T e hpe hske hY hTj hTl hTk hT\n rw [substR_evalE_on _ _ Y M2 M (cPosts ds) (fun mp k hmp => hrdS Y mp k hmp) e hpe]\n refine congrE _ _ M e (fun i hi => ?_)\n rw [applyS_keep]\n by_cases h1 : i = d.j\n · subst h1; simp [hTj]\n · by_cases h1' : i = d.lo\n · subst h1'; simp [hTl]\n · by_cases h2 : i = d.key\n · subst h2; simp [hTk]\n · rw [if_neg (by simp [h1, h1', h2])]\n have hik : i ≠ ce.e.sk := fun h' => by rw [h', hske] at hi; cases hi\n rw [hT i h1 h1' h2, ← hX0]\n simp only [applyS]\n cases ha : assoc s.f.m.init i with\n | none => simp [hY i h1 h1' h2, upd, hik]\n | some t =>\n have hmem := assoc_term ha\n refine congrE _ _ M2 t (fun i' hi' => ?_)\n have hi'j : i' ≠ d.j := fun h' => by rw [h', D.jf.init _ hmem] at hi'; cases hi'\n have hi'l : i' ≠ d.lo := fun h' => by rw [h', D.lf.init _ hmem] at hi'; cases hi'\n have hi'k : i' ≠ d.key := fun h' => by rw [h', D.kf.init _ hmem] at hi'; cases hi'\n have hi's : i' ≠ ce.e.sk := fun h' => by rw [h', E'.sinit _ hmem] at hi'; cases hi'\n rw [hY i' hi'j hi'l hi'k]; simp [upd, hi's]\n have hkey : X0 d.key = upd ρ ce.e.sk v d.key := by\n show applyS s.f.m.init ρ M d.key = upd ρ ce.e.sk v d.key\n simp only [upd, if_neg (Ne.symm hskk)]; exact applyS_other hkI ρ M\n have hB := hacross (atJ d (upd ρ ce.e.sk v) x) (atJ d X0 x) d.below hpB hskB\n (fun i h1 h2 _ => by simp [atJ, upd, h1, h2])\n (atJ_congr d x d.j (fun h _ => absurd rfl h)) (atJ_congr d x d.lo (fun _ h => absurd rfl h))\n (atJ_congr d x d.key (fun _ _ => hkey))\n (fun i h1 h2 _ => by simp [atJ, upd, h1, h2])\n rw [hB]\n refine sumBelow_congr _ (fun k _ => ?_)\n exact (hacross (upd (atJ d (upd ρ ce.e.sk v) x) d.key k) (upd (atJ d X0 x) d.key k) d.body hpD hskD\n (fun i h1 h2 h3 => by simp [atJ, upd, h1, h2, h3])\n (by simp only [upd, if_neg D.jk]; exact atJ_congr d x d.j (fun h _ => absurd rfl h))\n (by simp only [upd, if_neg D.lk]; exact atJ_congr d x d.lo (fun _ h => absurd rfl h))\n (by simp [upd]) (fun i h1 h2 h3 => by simp [atJ, upd, h1, h2, h3])).symm\n · -- The goal's hypotheses, wherever the witnesses are.\n have Wt := wits_parts (P.wits ce hce).1\n intro ρw hρw c hc\n have hw : ∀ i, (∀ i' ∈ ce.start.insts, i'.wit ≠ i) → i ≠ ce.e.sk → ρw i = ρ i := fun i hi hik => by\n rw [hρw i hi]; simp [upd, hik]\n have hwsk : ρw ce.e.sk = v := by\n rw [hρw ce.e.sk (fun i hi he => (Wt i hi).laws ce.e (List.mem_map_of_mem hce) |>.2.1 he.symm)]; simp [upd]\n simp only [cStartGoal, sStartGoal, List.mem_append, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false] at hc\n rcases hc with (rfl | hc) | rfl\n · rw [noReadsC _ M2 M s.f.m.pre P.preR, congrC _ ρ M s.f.m.pre (fun i hi => hw i\n (fun i' hi' he => by rw [← he, (Wt i' hi').pre] at hi; cases hi)\n (fun h' => by rw [h', E'.spre] at hi; cases hi))]\n exact h0\n · exact facthyps_true s ce.e.finsts ce.e.pfinsts _ M2 (fun f hf => (pfactsOk_parts P.facts f hf).2.2)\n (facts_frame s P.facts (ce.e.sk :: ce.start.insts.map (·.wit)) (cPosts ds)\n (fun l hl => by\n simp only [avoids, List.all_cons, List.all_map, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true']\n exact ⟨(skFresh_parts E'.skf).2.2.2.2.2.2 l hl, fun i hi => by simp [(skFresh_parts (Wt i hi).fr.sk).2.2.2.2.2.2 l hl]⟩) A.facts\n (fun i _ hik => hw i (fun i' hi' he => hik (List.mem_cons_of_mem _ (List.mem_map.mpr ⟨i', hi', he⟩))) (fun h' => hik (h' ▸ List.mem_cons_self)))\n (fun mp _ hmp => hM2 mp hmp) hfa)\n (pfacts_frame s P.facts (ce.e.sk :: ce.start.insts.map (·.wit)) (cPosts ds)\n (fun f hf => by\n simp only [avoids, List.all_cons, List.all_map, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true']\n exact ⟨skFresh_pfacts E'.skf f hf, fun i hi => by simp [skFresh_pfacts (Wt i hi).fr.sk f hf]⟩) A.pfacts\n (fun i _ hik => hw i (fun i' hi' he => hik (List.mem_cons_of_mem _ (List.mem_map.mpr ⟨i', hi', he⟩))) (fun h' => hik (h' ▸ List.mem_cons_self)))\n (fun mp _ hmp => hM2 mp hmp) hpf) c hc\n · simp only [evalC, substR_evalC _ _ _ M2 M2 (hrd2 ρw)]\n have hρw' : ρw = setAll (upd ρ ce.e.sk v) (ce.start.insts.map (·.wit)) ρw := (setAll_self (fun i hi => by\n rw [hρw i (fun i' hi' he => hi (List.mem_map.mpr ⟨i', hi', he⟩))])).symm\n rw [hρw', applyS_setAll (fun w hw' => by\n obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hw'\n exact ⟨(fresh_out (Wt i hi).fr.out).2.2.1, (Wt i hi).fr.init⟩),\n applyS_upd hskI (by simpa [List.all_eq_true] using E'.sinit), hX0]\n rw [goalOf_agree (renLaw ds ce.e.law) ce.e.sk M2 (X' := upd X0 ce.e.sk v)\n (by rw [setAll_at]; split\n · rename_i hm; obtain ⟨i, hi, he⟩ := List.mem_map.mp hm\n exact absurd he.symm ((Wt i hi).laws ce.e (List.mem_map_of_mem hce)).2.1\n · rfl)\n (fun i hi => by\n rw [setAll_at]; split\n · rename_i hm; obtain ⟨i', hi', he⟩ := List.mem_map.mp hm\n have := ((Wt i' hi').laws ce.e (List.mem_map_of_mem hce)).1\n simp only [renLaw, occ_renC] at hi; rw [← he, this] at hi; cases hi\n · rfl)]\n simpa using hn\n\n/-! A state with the post names set: the machine reads them nowhere -/\n\ntheorem withCarried_posts {s : SMachine} {ds : List CDecl} (hpc : ∀ mp ∈ cPosts ds, mp ∉ s.carried) (F : CDecl → Nat → Nat)\n (M κ : Nat → Nat → Nat) : withCarried s (atPosts ds F M) κ = atPosts ds F (withCarried s M κ) := by\n funext mp\n by_cases hmp : mp ∈ cPosts ds\n · have hc : mp ∉ s.carried := hpc mp hmp\n have e1 : withCarried s (atPosts ds F M) κ mp = atPosts ds F M mp := by simp [withCarried, List.contains_iff_mem, hc]\n have e2 : withCarried s M κ mp = M mp := by simp [withCarried, List.contains_iff_mem, hc]\n rw [e1]\n cases hl : lookup (fun d => d.post == mp) ds with\n | none => simp only [atPosts, hl]; exact e2.symm\n | some d => simp only [atPosts, hl]\n · rw [atPosts_other hmp]; simp only [withCarried]; split\n · rfl\n · exact atPosts_other hmp F M\n\ntheorem posts_evalC {ds : List CDecl} {c : C} (h : avoidsMaps (cPosts ds) c = true) (X : Nat → Nat) (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) :\n evalC X (atPosts ds F N) c = evalC X N c :=\n congrMC X _ N c (fun mp hm => atPosts_other (avoidsMaps_occ h hm) F N)\ntheorem posts_evalE {ds : List CDecl} {e : E} (h : avoidsMapsE (cPosts ds) e = true) (X : Nat → Nat) (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) :\n evalE X (atPosts ds F N) e = evalE X N e :=\n congrME X _ N e (fun mp hm => atPosts_other (avoidsMapsE_occ h hm) F N)\n\ntheorem decideQ_posts {s : SMachine} {ds : List CDecl} (hq : ∀ q ∈ s.qflags, avoidsMaps (cPosts ds) q.2.2 = true) (X : Nat → Nat)\n (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) : decideQ s X (atPosts ds F N) = decideQ s X N := by\n funext v\n simp only [decideQ]\n split\n · rename_i q hl\n have hb := hq q (lookup_some hl).1\n have : (∀ k, holdsC (atKeys X q.2.1 k) (atPosts ds F N) q.2.2) ↔ (∀ k, holdsC (atKeys X q.2.1 k) N q.2.2) := by\n simp only [← evalC_iff, posts_evalC hb]\n simp only [this]\n · rfl\n\ntheorem decideFlags_posts {fl : List (Nat × C)} {ds : List CDecl} (hf : ∀ p ∈ fl, avoidsMaps (cPosts ds) p.2 = true) (X : Nat → Nat)\n (F : CDecl → Nat → Nat) (N : Nat → Nat → Nat) : decideFlags fl X (atPosts ds F N) = decideFlags fl X N :=\n applyS_congrM (X := cPosts ds) (fun p hp => by\n obtain ⟨q, hq, rfl⟩ := List.mem_map.mp hp\n have := hf q hq\n simp only [avoidsMapsE, avoidsMaps, List.all_eq_true, Bool.not_eq_true'] at this ⊢\n intro mp hm; simp [occME, this mp hm]) X (fun mp hmp => atPosts_other hmp F N)\n\ntheorem sView_posts {s : SMachine} {ds : List CDecl} (A : ApartParts s ds) (F : CDecl → Nat → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) : sView s ρ (atPosts ds F M) ι κ = ((sView s ρ M ι κ).1, atPosts ds F (sView s ρ M ι κ).2) := by\n simp only [sView, withCarried_posts (fun mp hm => (A.posts mp hm).1), decideQ_posts A.qflags, decideFlags_posts A.flags]\n\ntheorem sNext_posts {s : SMachine} {ds : List CDecl} (A : ApartParts s ds) (F : CDecl → Nat → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) : sNext s ρ (atPosts ds F M) ι κ = ((sNext s ρ M ι κ).1, atPosts ds F (sNext s ρ M ι κ).2) := by\n simp only [sNext, sView_posts A]\n congr 1\n · exact applyS_congrM A.step _ (fun mp hmp => atPosts_other hmp F _)\n · funext mp key\n by_cases hmp : mp ∈ cPosts ds\n · have he : lookup (fun w => w.1 == mp) s.every = none := lookup_none (fun w hw => by\n simp only [beq_eq_false_iff_ne]; intro h'; exact (A.posts mp hmp).2.2.1 (by rw [← h']; exact List.mem_map_of_mem hw))\n have hw : lookup (fun w : Nat × E × E => w.1 == mp) s.f.m.writes = none := lookup_none (fun w hw => by\n simp only [beq_eq_false_iff_ne]; intro h'; exact (A.posts mp hmp).2.2.2 (by rw [← h']; exact List.mem_map_of_mem hw))\n have hE : everyMaps s (sView s ρ M ι κ).1 (atPosts ds F (sView s ρ M ι κ).2) mp key = atPosts ds F (sView s ρ M ι κ).2 mp key := by\n simp only [everyMaps, he, writeMaps, hw]\n have hE' : everyMaps s (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 mp key = (sView s ρ M ι κ).2 mp key := by\n simp only [everyMaps, he, writeMaps, hw]\n rw [hE]\n cases hl : lookup (fun d => d.post == mp) ds with\n | none => simp only [atPosts, hl]; exact hE'.symm\n | some d => simp only [atPosts, hl]\n · rw [atPosts_other hmp]\n simp only [everyMaps]\n split\n · rename_i w hw\n exact posts_evalE (A.every w (lookup_some hw).1) _ F _\n · simp only [writeMaps]\n split\n · rename_i w hw\n have ⟨h1, h2⟩ := A.writes w (lookup_some hw).1\n rw [posts_evalE h1, posts_evalE h2, atPosts_other hmp]\n · rw [atPosts_other hmp]\n\ntheorem sReq_posts {s : SMachine} {ds : List CDecl} (A : ApartParts s ds) (F : CDecl → Nat → Nat) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) : sReq s ρ (atPosts ds F M) ι κ = sReq s ρ M ι κ := by\n funext v\n simp only [sReq, withCarried_posts (fun mp hm => (A.posts mp hm).1), decideQ_posts A.qflags]\n split\n · rfl\n · split\n · rfl\n · split\n · split\n · rename_i q hq'\n split\n · apply congrFun\n apply witnessKeys_congr\n intro k\n simp only [← evalC_iff, posts_evalC (A.qflags q (lookup_some hq').1)]\n · rfl\n · rfl\n · rfl\n\n/-! One step's frame, at any state (Sets.lean's sstep_case builds the same) -/\n\ntheorem cframe {s : SMachine} (hs : sOk s = true) (hterms : sTermsOk s (flagVars s.f.flags) = true) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) :\n (∀ Z, SHead s Z [] (withExt s ρ (sReq s ρ M ι κ)) (withCarried s M κ) [] getRd ρ M [] [] ι κ)\n ∧ SDenotes s (flagVars s.f.flags) [] (withExt s ρ (sReq s ρ M ι κ)) (withCarried s M κ)\n (stepSub s.f (frameSub [] []) (frameRd [] getRd)) (stepRdS s (frameSub [] []) (frameRd [] getRd)) (sNext s ρ M ι κ).1 (sNext s ρ M ι κ).2 := by\n obtain ⟨hfav, hstp, hwr, hev⟩ := sTermsOk_parts hterms\n let W := withExt s ρ (sReq s ρ M ι κ)\n let M0 := withCarried s M κ\n have hH : ∀ Z, SHead s Z [] W M0 [] getRd ρ M [] [] ι κ := fun Z => by\n refine ⟨fun i _ => ?_, fun mp k _ => ?_⟩\n · show applyS (frameSub [] []) W M0 i = W i\n simp only [frameSub, List.map_nil, List.append_nil, applyS_nil']\n · simp [frameRd, getRd, lookup, evalE, M0]\n have hD : SDenotes s (flagVars s.f.flags) [] W M0 [] getRd ρ M := by\n refine ⟨fun i hie _ => ?_, fun mp k hmp _ => ?_⟩\n · rw [applyS_nil']; simp only [W, withExt]; rw [if_neg (by simpa [List.contains_iff_mem] using hie)]\n · simp only [getRd, evalE, M0, withCarried]; rw [if_neg (by simpa [List.contains_iff_mem] using hmp)]\n exact ⟨hH, sstep_denotes s (flagVars s.f.flags) [] W M0 hs (fun v hv => hv) hfav [] [] ι κ hD (hH _) (fun p hp => by simp at hp)\n hstp (fun w hw => (hwr w hw).1) hev (fun _ _ => by simp [avoidsMapsE]) (fun _ _ => by simp [avoidsMapsE]) (fun _ _ => by simp [avoidsMapsE])⟩\n\n/-! Terms across a step that keeps the parameters and key -/\n\n-- A term of the state read across the step, the parameters and key kept: its value at the state after the step, where\n-- the frame reads them as the state after it does.\ntheorem across_step {s : SMachine} (hs : sOk s = true) (hterms : sTermsOk s (flagVars s.f.flags) = true) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) (d : CDecl) (e : E) (he : avoidsE (s.extVars ++ flagVars s.f.flags) e = true)\n (hem : avoidsMapsE s.carried e = true)\n (hj : (sNext s ρ M ι κ).1 d.j = withExt s ρ (sReq s ρ M ι κ) d.j) (hl : (sNext s ρ M ι κ).1 d.lo = withExt s ρ (sReq s ρ M ι κ) d.lo)\n (hk : (sNext s ρ M ι κ).1 d.key = withExt s ρ (sReq s ρ M ι κ) d.key) :\n evalE (withExt s ρ (sReq s ρ M ι κ)) (withCarried s M κ)\n (substRE (keepJ d (stepSub s.f (frameSub [] []) (frameRd [] getRd))) (stepRdS s (frameSub [] []) (frameRd [] getRd)) e)\n = evalE (sNext s ρ M ι κ).1 (sNext s ρ M ι κ).2 e := by\n obtain ⟨_, hD⟩ := cframe hs hterms ρ M ι κ\n rw [substR_evalE_on _ _ _ _ (sNext s ρ M ι κ).2 s.carried (fun mp k hmp => hD.2 mp k hmp (by simp)) e hem]\n refine congrE _ _ _ e (fun i hi => ?_)\n rw [applyS_keep]\n by_cases h1 : i = d.j\n · subst h1; simp [hj]\n · by_cases h1' : i = d.lo\n · subst h1'; simp [hl]\n · by_cases h2 : i = d.key\n · subst h2; simp [hk]\n · rw [if_neg (by simp [h1, h1', h2])]\n have hx := avoidsE_occ he hi\n exact hD.1 i (fun h => hx (List.mem_append_left _ h)) (fun h => hx (List.mem_append_right _ h))\n\n-- Two reads of a count agree where its bound and body read alike.\ntheorem cntOf_congr (d : CDecl) (hkB : occE d.key d.below = false) {X X' : Nat → Nat} {N N' : Nat → Nat → Nat}\n (hv : ∀ i, i ≠ d.j → i ≠ d.lo → i ≠ d.key → occE i d.below = true ∨ occE i d.body = true → X i = X' i)\n (hm : ∀ mp, occME mp d.below = true ∨ occME mp d.body = true → N mp = N' mp) (x : Nat) : cntOf d X N x = cntOf d X' N' x := by\n simp only [cntOf]\n have hB : evalE (atJ d X x) N d.below = evalE (atJ d X' x) N' d.below := by\n rw [congrME _ N N' d.below (fun mp h => hm mp (Or.inl h))]\n exact congrE _ _ _ d.below (fun i hi => atJ_congr d x i (fun h1 h1' => by\n have h2 : i ≠ d.key := fun h => by rw [h, hkB] at hi; cases hi\n exact hv i h1 h1' h2 (Or.inl hi)))\n rw [hB]\n exact sumBelow_congr _ (fun k _ => by\n rw [congrME _ N N' d.body (fun mp h => hm mp (Or.inr h))]\n exact congrE _ _ _ d.body (fun i hi => by\n simp only [upd]\n by_cases h2 : i = d.key\n · simp [h2]\n · simp only [if_neg h2]; exact atJ_congr d x i (fun h1 h1' => hv i h1 h1' h2 (Or.inr hi))))\n\n/-! One step -/\n\n-- A variable no step sets, decides or reads from the request: the state after a step keeps it.\ntheorem sNext_other {s : SMachine} {x : Nat} (h : (s.extVars ++ flagVars s.f.flags ++ s.f.m.init.map (·.1) ++ s.f.m.step.map (·.1)).contains x = false)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat) : (sNext s ρ M ι κ).1 x = ρ x := by\n obtain ⟨_, hF, _, hS, hI, hQ, _⟩ := fresh_out h\n simp only [sNext, sView]\n rw [applyS_other hS, decide_other hF]\n simp only [decideQ]\n rw [lookup_none (fun q hq => by\n simp only [beq_eq_false_iff_ne]; intro he\n exact hQ (by simp only [SMachine.qVars, List.mem_map]; exact ⟨q, hq, he⟩))]\n exact withInputs_other hI ρ ι\n\ntheorem avoids_left {A B : List Nat} {c : C} (h : avoids (A ++ B) c = true) : avoids A c = true := by\n simp only [avoids, List.all_append, Bool.and_eq_true] at h; exact h.1\ntheorem cstep_case (s : SMachine) (ds : List CDecl) (ps : List CEntryF) (h : checkCMachineF s ds ps = true) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) (hp0 : evalC ρ M s.f.m.pre = true) (hfa : ∀ l ∈ s.facts, l.Holds ρ M) (hpf : s.PFacts ρ M)\n (ih : ∀ ce ∈ ps, ce.e.Holds ρ (withCnt ds ρ M)) (hG : GHolds ds (withInputs s.f.m.inputs ρ ι) (withCarried s M κ))\n (ha : evalC (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 s.f.m.assume = true) :\n ∀ ce ∈ ps, ce.e.law.Holds (sNext s ρ M ι κ).1 (withCnt ds (sNext s ρ M ι κ).1 (sNext s ρ M ι κ).2) := by\n have P := cparts h\n have A := apart_parts P.apart\n have hs := P.sok\n obtain ⟨hdm, hdp, hap⟩ := cDistinct_append P.dist\n have hentry : ∀ e ∈ ps.map (·.e), cEntryOk s ds (ps.map (·.e)) e = true := fun e he => by\n obtain ⟨ce, hce, rfl⟩ := List.mem_map.mp he; exact (P.entries ce hce).1\n have hkk : ∀ e ∈ ps.map (·.e), ∀ k, e.law.key = some k → k ∉ e.keys2 := fun e he k hk hg => (key2_parts hentry he hg).2.2.2.2.2 hk\n intro ce hce\n obtain ⟨hent, _, hstep⟩ := P.entries ce hce\n have E' := entry_parts hent\n have hsk := fresh_out E'.fresh\n let Nx := sNext s ρ M ι κ\n let F : CDecl → Nat → Nat := fun d => cntOf d Nx.1 Nx.2\n let M' := atPosts ds F M\n have hNx' : sNext s ρ M' ι κ = (Nx.1, atPosts ds F Nx.2) := sNext_posts A F ρ M ι κ\n have hpc : ∀ mp ∈ cPosts ds, mp ∉ s.carried := fun mp hm => (A.posts mp hm).1\n let Mq := withCarried s (atPosts ds F Nx.2) κ\n have hMq : Mq = atPosts ds F (withCarried s Nx.2 κ) := withCarried_posts hpc F Nx.2 κ\n -- The maps a law reads count maps of the state in: those the request carries but those, and the post names.\n let MS := s.carried.filter (fun mp => !(stateMaps s ds).contains mp) ++ cPosts ds\n have hMS : ∀ mp, mp ∉ MS → mp ∈ s.carried → ∃ d ∈ ds, d.mp = mp ∧ stateOnly s d = true := by\n intro mp hmp hc\n have : (stateMaps s ds).contains mp = true := by\n apply Classical.byContradiction; intro hn\n exact hmp (List.mem_append_left _ (List.mem_filter.mpr ⟨hc, by simpa using hn⟩))\n obtain ⟨d, hd, hdmp⟩ := List.mem_map.mp (List.contains_iff_mem.mp this)\n exact ⟨d, (List.mem_filter.mp hd).1, hdmp, (List.mem_filter.mp hd).2⟩\n have hnotP : ∀ mp, mp ∉ MS → mp ∉ cPosts ds := fun mp hmp h' => hmp (List.mem_append_right _ h')\n -- A state count read at the view is the count at the state.\n have hview : ∀ d ∈ ds, stateOnly s d = true → ∀ x, κ d.mp x = cntOf d ρ M x := by\n intro d hd hso x\n have hc : d.mp ∈ s.carried := (decl_parts (P.decls d hd)).carried\n have := hG d hd x\n simp only [withCarried, List.contains_iff_mem.mpr hc, ite_true] at this\n rw [this]\n simp only [stateOnly, Bool.and_eq_true] at hso\n obtain ⟨⟨⟨hvB, hvD⟩, hmB⟩, hmD⟩ := hso\n refine cntOf_congr d (decl_parts (P.decls d hd)).kB (fun i _ _ _ hi => ?_) (fun mp hm => ?_) x\n · have hx : i ∉ s.extVars := fun h' => by\n rcases hi with hi | hi\n · exact avoidsE_occ hvB hi (List.mem_append_left _ h')\n · exact avoidsE_occ hvD hi (List.mem_append_left _ h')\n exact withInputs_other (fun h' => hx (by simp only [SMachine.extVars, List.mem_append]; exact Or.inl (Or.inl h'))) ρ ι\n · have hx : mp ∉ s.carried := by\n rcases hm with hm | hm\n · exact avoidsMapsE_occ hmB hm\n · exact avoidsMapsE_occ hmD hm\n simp [withCarried, List.contains_iff_mem, hx]\n -- The law after the step: the renamed law, with the post names at the counts after it.\n refine holds_transfer (V := []) (MS := MS) (M' := renM (cren ds) Mq) ce.e.law (by simp [avoids]) E'.lm (fun _ _ => rfl) (fun mp hmp => ?_) ?_\n · rw [hMq, renM_atPosts P.dist F _ mp (hnotP mp hmp)]\n simp only [withCnt]\n cases hl : lookup (fun d => d.mp == mp) ds with\n | some d => rfl\n | none =>\n have hnc : mp ∉ s.carried := fun hc => by\n obtain ⟨d, hd, hdmp, _⟩ := hMS mp hmp hc\n have := lookup_none_all hl d hd\n simp [hdmp] at this\n show (sNext s ρ M ι κ).2 mp = withCarried s (sNext s ρ M ι κ).2 κ mp\n simp [withCarried, List.contains_iff_mem, hnc]\n rw [← renLaw_holds]\n refine goalOf_holds (renLaw ds ce.e.law) (by simp only [renLaw, occ_renC]; exact E'.slaw ce.e (List.mem_map_of_mem hce)) Nx.1 Mq (fun v => ?_)\n apply Decidable.byContradiction; intro hn\n obtain ⟨hNext, hView, _⟩ := fresh_parts E'.skf E'.fresh ρ M' ι κ v\n let ρ' := upd ρ ce.e.sk v\n let W := withExt s ρ' (sReq s ρ' M' ι κ)\n let M0 := withCarried s M' κ\n obtain ⟨hH, hD'⟩ := cframe hs P.terms ρ' M' ι κ\n have hM0 : ∀ mp, mp ∉ cPosts ds → M0 mp = withCarried s M κ mp := fun mp hmp => by\n show withCarried s M' κ mp = _\n rw [withCarried_posts hpc F M κ, atPosts_other hmp]\n apply mcF_sound _ _ _ _ _ _ hstep W M0\n · -- The counts the goal declares.\n intro d' hd' x\n rcases List.mem_append.mp hd' with hd | hd'\n · -- before the step: the request's count at its view\n have D := decl_parts (P.decls d' hd)\n obtain ⟨hskB, hskD, _, _⟩ := D.ent ce.e (List.mem_map_of_mem hce) ce.e.sk List.mem_cons_self\n rw [hM0 d'.mp (fun h' => hap d'.mp (List.mem_map_of_mem hd) h'), hG d' hd x]\n refine cntOf_congr d' D.kB (fun i _ _ _ hi => ?_) (fun mp hm => ?_) x\n · show withInputs s.f.m.inputs ρ ι i = withExt s ρ' (sReq s ρ' M' ι κ) i\n have hq : i ∉ s.qVars ++ s.wVars := by\n rcases hi with hi | hi\n · exact fun h' => avoidsE_occ D.qwB hi (List.mem_append_left _ h')\n · exact fun h' => avoidsE_occ D.qwD hi (List.mem_append_left _ h')\n have hik : i ≠ ce.e.sk := fun h' => by rcases hi with hi | hi <;> (rw [h'] at hi; simp_all)\n simp only [withExt]\n by_cases hie : s.extVars.contains i = true\n · simp only [hie, ite_true, sReq]\n have hin : s.f.m.inputs.contains i = true := by\n simp only [SMachine.extVars, List.contains_iff_mem, List.mem_append] at hie\n rcases hie with (h1 | h1) | h1\n · exact List.contains_iff_mem.mpr h1\n · exact absurd (List.mem_append_left _ h1) hq\n · exact absurd (List.mem_append_right _ h1) hq\n simp only [hin, ite_true, withInputs]\n · simp only [hie, Bool.false_eq_true, ite_false]\n have hin : i ∉ s.f.m.inputs := by\n simp only [SMachine.extVars, List.contains_iff_mem, List.mem_append, not_or] at hie\n exact hie.1.1\n rw [withInputs_other hin]\n simp [ρ', upd, hik]\n · have hx : mp ∉ cPosts ds := by\n rcases hm with hm | hm\n · exact fun h' => avoidsMapsE_occ D.mB hm (List.mem_append_right _ h')\n · exact fun h' => avoidsMapsE_occ D.mD hm (List.mem_append_right _ h')\n exact (hM0 mp hx).symm\n · -- after the step: a state count read across it\n obtain ⟨d, hdf, rfl⟩ := List.mem_map.mp hd'\n have hd := (List.mem_filter.mp hdf).1\n have hso := (List.mem_filter.mp hdf).2\n have D := decl_parts (P.decls d hd)\n obtain ⟨hskB, hskD, _, hskk⟩ := D.ent ce.e (List.mem_map_of_mem hce) ce.e.sk List.mem_cons_self\n simp only [stateOnly, Bool.and_eq_true] at hso\n obtain ⟨⟨⟨hvB, hvD⟩, hmB⟩, hmD⟩ := hso\n have hjo := fresh_out D.jf.out\n have hlo := fresh_out D.lf.out\n have hko := fresh_out D.kf.out\n have hpB : avoidsMapsE (cPosts ds) d.below = true := avoidsMapsE_right D.mB\n have hpD : avoidsMapsE (cPosts ds) d.body = true := avoidsMapsE_right D.mD\n show M0 d.post x = cntOf (afterDecl _ _ d) W M0 x\n rw [cntOf_after, show M0 d.post = F d from by\n show withCarried s M' κ d.post = F d\n rw [withCarried_posts hpc F M κ]; exact atPosts_at hdp hd F _]\n -- reading a term of the state across the step at a state with fresh variables set: its value after the step there\n have hacross : ∀ (ρx : Nat → Nat) (Y : Nat → Nat) (e : E), avoidsE (s.extVars ++ flagVars s.f.flags) e = true → avoidsMapsE s.carried e = true →\n avoidsMapsE (cPosts ds) e = true →\n withExt s ρx (sReq s ρx M' ι κ) = Y →\n (sNext s ρx M' ι κ).1 d.j = Y d.j → (sNext s ρx M' ι κ).1 d.lo = Y d.lo → (sNext s ρx M' ι κ).1 d.key = Y d.key →\n (sNext s ρx M' ι κ).2 = atPosts ds F Nx.2 →\n evalE Y M0 (substRE (keepJ d (stepSub s.f (frameSub [] []) (frameRd [] getRd)))\n (stepRdS s (frameSub [] []) (frameRd [] getRd)) e) = evalE (sNext s ρx M' ι κ).1 Nx.2 e := by\n intro ρx Y e he hem hpe hY hj hl hk hM\n have := across_step hs P.terms ρx M' ι κ d e he hem (by rw [hj, hY]) (by rw [hl, hY]) (by rw [hk, hY])\n rw [hY, hM] at this\n rw [this, posts_evalE hpe]\n -- the state with the parameters at x (the bound), and with key at k too (the body)\n have hsj : sReq s (atJ d ρ' x) M' ι κ = sReq s ρ' M' ι κ := by\n simp only [atJ]\n rw [sReq_upd hlo.2.2.2.2.1 hlo.2.2.2.2.2.1 (skFresh_parts D.lf.sk).2.1, sReq_upd hjo.2.2.2.2.1 hjo.2.2.2.2.2.1 (skFresh_parts D.jf.sk).2.1]\n have hsk : ∀ k, sReq s (upd (atJ d ρ' x) d.key k) M' ι κ = sReq s ρ' M' ι κ := fun k => by\n rw [sReq_upd hko.2.2.2.2.1 hko.2.2.2.2.2.1 (skFresh_parts D.kf.sk).2.1, hsj]\n have hWj : withExt s (atJ d ρ' x) (sReq s ρ' M' ι κ) = atJ d W x := by\n simp only [atJ]; rw [withExt_upd hlo.1, withExt_upd hjo.1]\n have hNj : sNext s (atJ d ρ' x) M' ι κ = (atJ d (upd Nx.1 ce.e.sk v) x, atPosts ds F Nx.2) := by\n simp only [atJ]\n rw [(fresh_parts D.lf.sk D.lf.out _ M' ι κ _).1, (fresh_parts D.jf.sk D.jf.out _ M' ι κ _).1, hNext, hNx']\n have hNk : ∀ k, sNext s (upd (atJ d ρ' x) d.key k) M' ι κ = (upd (atJ d (upd Nx.1 ce.e.sk v) x) d.key k, atPosts ds F Nx.2) := fun k => by\n rw [(fresh_parts D.kf.sk D.kf.out _ M' ι κ k).1, hNj]\n have hkey : upd (sNext s ρ M ι κ).1 ce.e.sk v d.key = withExt s ρ' (sReq s ρ' M' ι κ) d.key := by\n simp only [upd, if_neg (Ne.symm hskk)]\n rw [sNext_other D.kf.out]; simp only [withExt]\n rw [if_neg (by simpa [List.contains_iff_mem] using hko.1)]; simp [ρ', upd, Ne.symm hskk]\n have hB := hacross (atJ d ρ' x) (atJ d W x) d.below hvB hmB hpB\n (by rw [hsj, hWj])\n (by rw [hNj]; exact atJ_congr d x d.j (fun h _ => absurd rfl h))\n (by rw [hNj]; exact atJ_congr d x d.lo (fun _ h => absurd rfl h))\n (by rw [hNj]; exact atJ_congr d x d.key (fun _ _ => hkey))\n (by rw [hNj])\n rw [hB, hNj]\n have hB' : evalE (atJ d (upd Nx.1 ce.e.sk v) x) Nx.2 d.below = evalE (atJ d Nx.1 x) Nx.2 d.below :=\n congrE _ _ _ _ (fun i hi => atJ_congr d x i (fun _ _ => by\n have hik : i ≠ ce.e.sk := fun h' => by rw [h', hskB] at hi; cases hi\n simp [upd, hik]))\n simp only [] at hB' ⊢\n rw [hB']\n refine sumBelow_congr _ (fun k _ => ?_)\n have hD := hacross (upd (atJ d ρ' x) d.key k) (upd (atJ d W x) d.key k) d.body hvD hmD hpD\n (by rw [hsk k, withExt_upd hko.1, hWj])\n (by rw [hNk k]; simp only [upd, if_neg D.jk]; exact atJ_congr d x d.j (fun h _ => absurd rfl h))\n (by rw [hNk k]; simp only [upd, if_neg D.lk]; exact atJ_congr d x d.lo (fun _ h => absurd rfl h))\n (by rw [hNk k]; simp [upd]) (by rw [hNk k])\n rw [hD, hNk k]\n dsimp only\n exact congrE _ _ _ _ (fun i hi => by\n have hik : i ≠ ce.e.sk := fun h' => by rw [h', hskD] at hi; cases hi\n simp only [upd]\n by_cases h2 : i = d.key\n · simp [h2]\n · simp only [if_neg h2]; exact atJ_congr d x i (fun _ _ => by simp [upd, hik]))\n · -- The goal's hypotheses hold where the frame is read, wherever the witnesses are: the state with them set.\n obtain ⟨hfav, hstp, hwr, hev⟩ := sTermsOk_parts P.terms\n have Wt := wits_parts (P.wits ce hce).2\n let ws := ce.step.insts.map (·.wit)\n have hwsF : ∀ w ∈ ws, FreshParts s w := fun w hw => by obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hw; exact (Wt i hi).fr\n have hwsL : ∀ w ∈ ws, ∀ e ∈ ps.map (·.e), occC w e.law.holds = false ∧ e.sk ≠ w := fun w hw e he => by\n obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hw; exact ⟨((Wt i hi).laws e he).1, ((Wt i hi).laws e he).2.1⟩\n have hwsP : ∀ w ∈ ws, occC w s.f.m.pre = false := fun w hw => by obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hw; exact (Wt i hi).pre\n have hskw : ce.e.sk ∉ ws := fun h' => (hwsL _ h' ce.e (List.mem_map_of_mem hce)).2 rfl\n intro ρw hρw c hc\n have hρw' : ∀ i, i ∉ ws → ρw i = W i := fun i hi => hρw i (fun i' hi' he => hi (List.mem_map.mpr ⟨i', hi', he⟩))\n let ρ'' := setAll ρ' ws ρw\n have hext : ∀ w ∈ ws, w ∉ s.extVars := fun w hw => (fresh_out (hwsF w hw).out).1\n have hWw : withExt s ρ'' (sReq s ρ'' M' ι κ) = ρw := by\n rw [sReq_setAll hwsF, withExt_setAll hext]; exact setAll_self hρw'\n obtain ⟨hNw, hVw⟩ := sNext_setAll hwsF ρ' M' ι κ ρw\n obtain ⟨hH2, hD2⟩ := cframe hs P.terms ρ'' M' ι κ\n rw [hWw] at hH2 hD2\n have hρ'' : ∀ i, i ∉ ws → i ≠ ce.e.sk → ρ'' i = ρ i := fun i hi hik => by\n simp only [ρ'']; rw [setAll_at, if_neg hi]; simp [ρ', upd, hik]\n -- (ρw off the request's variables is ρ'')\n have hwx : ∀ i, i ∉ s.extVars → ρw i = ρ'' i := fun i hi => by\n rw [← hWw]; simp only [withExt]; rw [if_neg (by simpa [List.contains_iff_mem] using hi)]\n simp only [cStepGoal, sStepGoal, List.mem_append, List.mem_cons, List.mem_singleton, List.not_mem_nil, or_false, List.mem_map] at hc\n rcases hc with ((rfl | hc) | ⟨c', hc', rfl⟩) | rfl\n · rw [noReadsC ρw M0 M s.f.m.pre P.preR, congrC ρw ρ M s.f.m.pre (fun i hi => ?_)]\n · exact hp0\n · have hi1 := avoids_occ P.pre hi\n have hik : i ≠ ce.e.sk := fun h' => by rw [h'] at hi; simp [E'.spre] at hi\n have hiw : i ∉ ws := fun h' => by rw [hwsP i h'] at hi; cases hi\n rw [hwx i (fun h' => hi1 (List.mem_append_left _ (List.mem_append_left _ (List.mem_append_left _ h')))), hρ'' i hiw hik]\n · have hX : ∀ i, i ∉ s.extVars → i ∉ ce.e.sk :: ws → ρw i = ρ i := fun i hie hik => by\n rw [hwx i hie, hρ'' i (fun h' => hik (List.mem_cons_of_mem _ h')) (fun h' => hik (h' ▸ List.mem_cons_self))]\n exact facthyps_true s ce.e.finsts ce.e.pfinsts ρw M0 (fun f hf => (pfactsOk_parts P.facts f hf).2.2)\n (facts_frame s P.facts (ce.e.sk :: ws) (cPosts ds)\n (fun l hl => by\n simp only [avoids, List.all_cons, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true']\n exact ⟨(skFresh_parts E'.skf).2.2.2.2.2.2 l hl, fun w hw => (skFresh_parts (hwsF w hw).sk).2.2.2.2.2.2 l hl⟩) A.facts\n hX (fun mp hmc hmp => by rw [hM0 mp hmp]; simp only [withCarried]; rw [if_neg (by simpa [List.contains_iff_mem] using hmc)]) hfa)\n (pfacts_frame s P.facts (ce.e.sk :: ws) (cPosts ds)\n (fun f hf => by\n simp only [avoids, List.all_cons, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true']\n exact ⟨skFresh_pfacts E'.skf f hf, fun w hw => skFresh_pfacts (hwsF w hw).sk f hf⟩) A.pfacts\n hX (fun mp hmc hmp => by rw [hM0 mp hmp]; simp only [withCarried]; rw [if_neg (by simpa [List.contains_iff_mem] using hmc)]) hpf) c hc\n · have hA : evalC (sView s ρ'' M' ι κ).1 (sView s ρ'' M' ι κ).2 s.f.m.assume = true := by\n rw [hVw, hView]; dsimp only\n rw [sView_posts A F ρ M ι κ]; dsimp only\n rw [posts_evalC A.assume]\n rw [congrC _ (sView s ρ M ι κ).1 _ _ (fun i hi => by\n have hik : i ≠ ce.e.sk := fun h' => by rw [h', (skFresh_parts E'.skf).2.2.1] at hi; cases hi\n have hiw : i ∉ ws := fun h' => by rw [(skFresh_parts (hwsF i h').sk).2.2.1] at hi; cases hi\n rw [setAll_at, if_neg hiw]; simp only [upd, if_neg hik])]\n exact ha\n have hallY : ∀ e' ∈ ps.map (·.e), e'.Holds ρw M0 := fun e' he' => by\n obtain ⟨ce', hce', rfl⟩ := List.mem_map.mp he'\n have E2 := entry_parts (P.entries ce' hce').1\n refine sentry_transfer (V := s.extVars) (MS := MS) (ρ' := ρ'') (avoids_left E2.lx) E2.lm (fun i hi => hwx i hi) (fun mp hmp => ?_)\n (sentry_setAll (fun w hw => (hwsL w hw ce'.e (List.mem_map_of_mem hce')).1) ρw\n (sentry_upd (Or.inl (E'.slaw ce'.e (List.mem_map_of_mem hce'))) v (ih ce' hce')))\n rw [hM0 mp (hnotP mp hmp)]\n by_cases hc : mp ∈ s.carried\n · obtain ⟨d, hd, hdmp, hso⟩ := hMS mp hmp hc\n subst hdmp\n rw [withCnt_at hdm hd]\n funext x\n simp only [withCarried, List.contains_iff_mem.mpr hc, ite_true]\n exact hview d hd hso x\n · rw [withCnt_other (fun h' => by\n obtain ⟨d, hd, hdmp⟩ := List.mem_map.mp h'\n exact hc (by rw [← hdmp]; exact (decl_parts (P.decls d hd)).carried))]\n simp [withCarried, List.contains_iff_mem, hc]\n have hfr := sframe_hyps s [] [] ρw M0 hs (sLaws (ps.map (·.e)) ce.e.pinsts) (sInsts (ps.map (·.e)) ce.e.insts ce.e.pinsts) ce.e.qinsts\n (ρ := ρ'') (M := M') (ι := ι) (κ := κ) (σ := []) (rd := getRd) (r := []) (mr := []) (w := trueC)\n (fun l hl => by\n rw [hWw]\n rcases List.mem_append.mp hl with hl | hl\n · obtain ⟨e', he', rfl⟩ := List.mem_map.mp hl; exact SEntry.holds_law (hallY e' he')\n · exact pairLaws_hold _ ce.e.pinsts hkk hallY l hl)\n (hH2 []) (fun _ _ => by simp [avoids]) (fun _ _ => by simp [avoids]) (fun _ _ => by simp [avoidsMaps]) hA rfl\n exact hfr c' hc'\n · have hrd' : ∀ mp k, evalE ρw M0 (stepRdS s (frameSub [] []) (frameRd [] getRd) mp k) = Mq mp (evalE ρw M0 k) := by\n intro mp k\n by_cases hmp : mp ∈ s.carried\n · have hne : lookup (fun w => w.1 == mp) s.every = none := lookup_none (fun w hw => by\n simp only [beq_eq_false_iff_ne]; intro h'; exact (hev w hw).2.2.2.2.1 (by rw [h']; exact hmp))\n have hnw : lookup (fun w : Nat × E × E => w.1 == mp) s.f.m.writes = none := lookup_none (fun w hw => by\n simp only [beq_eq_false_iff_ne]; intro h'; exact (hwr w hw).2 (by rw [h']; exact hmp))\n simp only [stepRdS, hne, stepRd, hnw]\n simp [frameRd, getRd, lookup, evalE, M0, Mq, withCarried, hmp]\n · rw [hD2.2 mp k hmp (by simp), hNw, hNext]; dsimp only; rw [hNx']\n simp only [Mq, withCarried]; rw [if_neg (by simpa [List.contains_iff_mem] using hmp)]\n simp only [evalC]\n have hpost : ∀ i, i ∉ ws → i ∉ s.extVars → i ∉ flagVars s.f.flags →\n applyS (stepSub s.f (frameSub [] []) (frameRd [] getRd)) ρw M0 i = upd Nx.1 ce.e.sk v i := fun i hiw hie hif => by\n rw [hD2.1 i hie hif, hNw, hNext]; dsimp only; rw [hNx', setAll_at, if_neg hiw]\n rw [substR_evalC _ _ ρw M0 _ hrd', goalOf_agree (renLaw ds ce.e.law) ce.e.sk _ (X' := upd Nx.1 ce.e.sk v)\n (hpost ce.e.sk hskw hsk.1 hsk.2.1) (fun i hi => ?_)]\n · simpa using hn\n · have hi' : occC i ce.e.law.holds = true := by simpa [renLaw, occ_renC] using hi\n have hi1 := avoids_occ E'.lx hi'\n exact hpost i (fun h' => by rw [(hwsL i h' ce.e (List.mem_map_of_mem hce)).1] at hi'; cases hi')\n (fun h' => hi1 (List.mem_append_left _ h')) (fun h' => hi1 (List.mem_append_right _ h'))\n\n/-! Soundness -/\n\n/-- The induction rule with counts: for params that meet the precondition, maps that start as declared and functions\nthat meet the facts, every entry of an accepted proof holds in every reachable state (each request carrying its count\nmaps at their counts), each count map read as the state's count, a law about several keys at every value of its\nfurther keys. -/\ntheorem cmachineF_sound (s : SMachine) (ds : List CDecl) (ps : List CEntryF) (h : checkCMachineF s ds ps = true) :\n ∀ ρ M, CReach s ds ρ M → ∀ ce ∈ ps, ce.e.Holds ρ (withCnt ds ρ M) := by\n have P := cparts h\n have hfok := P.facts\n have hentry : ∀ e ∈ ps.map (·.e), cEntryOk s ds (ps.map (·.e)) e = true := fun e he => by\n obtain ⟨ce, hce, rfl⟩ := List.mem_map.mp he; exact (P.entries ce hce).1\n have hfacts : ∀ {ρ : Nat → Nat} {M : Nat → Nat → Nat} {g : Nat}, skFresh s g = true → (∀ l ∈ s.facts, l.Holds ρ M) → ∀ w, ∀ l ∈ s.facts, l.Holds (upd ρ g w) M := by\n intro ρ M g hf hfa w\n exact facts_frame s hfok [g] [] (fun l hl => by simp [avoids, (skFresh_parts hf).2.2.2.2.2.2 l hl]) (fun _ _ => by simp [avoidsMaps])\n (fun i _ hig' => by simp only [upd]; rw [if_neg (by simpa using hig')]) (fun _ _ _ => rfl) hfa\n have hpfacts : ∀ {ρ : Nat → Nat} {M : Nat → Nat → Nat} {g : Nat}, skFresh s g = true → s.PFacts ρ M → ∀ w, s.PFacts (upd ρ g w) M := by\n intro ρ M g hf hpf w\n exact pfacts_frame s hfok [g] [] (fun f hfm => by simp [avoids, skFresh_pfacts hf f hfm]) (fun _ _ => by simp [avoidsMaps])\n (fun i _ hig' => by simp only [upd]; rw [if_neg (by simpa using hig')]) (fun _ _ _ => rfl) hpf\n have hpreu : ∀ {ρ : Nat → Nat} {M : Nat → Nat → Nat} {g : Nat}, occC g s.f.m.pre = false → evalC ρ M s.f.m.pre = true → ∀ w, evalC (upd ρ g w) M s.f.m.pre = true := by\n intro ρ M g hpg h0 w\n rw [congrC _ ρ M s.f.m.pre (fun i hi => by have hig' : i ≠ g := (fun h' => by rw [h', hpg] at hi; cases hi); simp only [upd, if_neg hig'])]; exact h0\n -- The counts read no further key.\n have hcg : ∀ ce ∈ ps, ∀ g ∈ ce.e.keys2, ∀ d ∈ ds, occE g d.below = false ∧ occE g d.body = false := fun ce hce g hg d hd =>\n ⟨((decl_parts (P.decls d hd)).ent ce.e (List.mem_map_of_mem hce) g (List.mem_cons_of_mem _ (List.mem_append_left _ hg))).1,\n ((decl_parts (P.decls d hd)).ent ce.e (List.mem_map_of_mem hce) g (List.mem_cons_of_mem _ (List.mem_append_left _ hg))).2.1⟩\n intro ρ M hr\n induction hr with\n | start ρ M hM h0 hfa hpf =>\n intro ce hce\n suffices hs : ∀ gs : List Nat, (∀ g ∈ gs, g ∈ ce.e.keys2) → ∀ ρ', evalC ρ' M s.f.m.pre = true → (∀ l ∈ s.facts, l.Holds ρ' M) →\n s.PFacts ρ' M → holdsOver ce.e.law (withCnt ds (applyS s.f.m.init ρ' M) M) gs (applyS s.f.m.init ρ' M) from\n hs ce.e.keys2 (fun g hg => hg) ρ h0 hfa hpf\n intro gs\n induction gs with\n | nil => intro _ ρ' hp hf hq; exact cstart_case s ds ps h ρ' M hM hp hf hq ce hce\n | cons g gs ih =>\n intro hsub ρ' hp hf hq w\n obtain ⟨hfr, hc, hpg, hig, _, _⟩ := key2_parts hentry (List.mem_map_of_mem hce) (hsub g List.mem_cons_self)\n have hI := (fresh_parts hfr hc ρ' M (fun _ => 0) (fun _ _ => 0) 0).2.2\n have := ih (fun g' hg' => hsub g' (List.mem_cons_of_mem _ hg')) (upd ρ' g w) (hpreu hpg hp w) (hfacts hfr hf w) (hpfacts hfr hq w)\n rw [applyS_upd hI (by simpa [List.all_eq_true] using hig), withCnt_upd (hcg ce hce g (hsub g List.mem_cons_self))] at this\n exact this\n | step ρ M ι κ hr hG ha ih =>\n intro ce hce\n suffices hs : ∀ gs : List Nat, (∀ g ∈ gs, g ∈ ce.e.keys2) → ∀ ρ', evalC ρ' M s.f.m.pre = true → (∀ l ∈ s.facts, l.Holds ρ' M) →\n s.PFacts ρ' M → (∀ ce' ∈ ps, ce'.e.Holds ρ' (withCnt ds ρ' M)) → GHolds ds (withInputs s.f.m.inputs ρ' ι) (withCarried s M κ) →\n evalC (sView s ρ' M ι κ).1 (sView s ρ' M ι κ).2 s.f.m.assume = true →\n holdsOver ce.e.law (withCnt ds (sNext s ρ' M ι κ).1 (sNext s ρ' M ι κ).2) gs (sNext s ρ' M ι κ).1 from\n hs ce.e.keys2 (fun g hg => hg) ρ (pre_sreach s P.pre P.preR (creach_sreach hr)) (facts_sreach s hfok (creach_sreach hr))\n (pfacts_sreach s hfok (creach_sreach hr)) ih hG ha\n intro gs\n induction gs with\n | nil => intro _ ρ' hp hf hq hi hg ha'; exact cstep_case s ds ps h ρ' M ι κ hp hf hq hi hg ha' ce hce\n | cons g gs ihg =>\n intro hsub ρ' hp hf hq hi hg ha' w\n have hgk := hsub g List.mem_cons_self\n obtain ⟨hfr, hc, hpg, _, hall, _⟩ := key2_parts hentry (List.mem_map_of_mem hce) hgk\n obtain ⟨hNext, hView, _⟩ := fresh_parts hfr hc ρ' M ι κ w\n have hgi := (fresh_out hc).2.2.2.2.1\n have := ihg (fun g' hg' => hsub g' (List.mem_cons_of_mem _ hg')) (upd ρ' g w) (hpreu hpg hp w) (hfacts hfr hf w) (hpfacts hfr hq w)\n (fun ce' hce' => by\n rw [withCnt_upd (hcg ce hce g hgk)]\n exact sentry_upd (hall ce'.e (List.mem_map_of_mem hce')) w (hi ce' hce'))\n (fun d hd x => by\n rw [hg d hd x, withInputs_upd hgi, cntOf_upd (hcg ce hce g hgk d hd).1 (hcg ce hce g hgk d hd).2])\n (by\n rw [hView]; dsimp only\n rw [congrC _ (sView s ρ' M ι κ).1 _ _ (fun i hi => by\n have hig' : i ≠ g := fun h' => by rw [h', (skFresh_parts hfr).2.2.1] at hi; cases hi\n simp only [upd, if_neg hig'])]\n exact ha')\n rw [hNext] at this; dsimp only at this\n rw [withCnt_upd (hcg ce hce g hgk)] at this\n exact this\n\n/-- `CReach` is the rule's own runs: at any state and request, the maps the request carries can be set at the count\nmaps to their counts (what the runtimes compute) and kept as they are elsewhere. -/\ntheorem counts_exist (s : SMachine) (ds : List CDecl) (hd : cDistinct (cMaps ds) = true) (hc : ∀ d ∈ ds, d.mp ∈ s.carried)\n (hav : ∀ d ∈ ds, avoidsMapsE (cMaps ds) d.below = true ∧ avoidsMapsE (cMaps ds) d.body = true)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat) :\n ∃ κ' : Nat → Nat → Nat, (∀ mp, mp ∉ cMaps ds → withCarried s M κ' mp = withCarried s M κ mp)\n ∧ GHolds ds (withInputs s.f.m.inputs ρ ι) (withCarried s M κ') := by\n let X := withInputs s.f.m.inputs ρ ι\n let κ' := withCnt ds X (withCarried s M κ)\n have hoff : ∀ mp, mp ∉ cMaps ds → withCarried s M κ' mp = withCarried s M κ mp := by\n intro mp hmp\n simp only [withCarried]; split\n · rename_i hcm\n show withCnt ds X (withCarried s M κ) mp = κ mp\n rw [withCnt_other hmp]; simp only [withCarried, hcm, ite_true]\n · rfl\n refine ⟨κ', hoff, fun d hdm x => ?_⟩\n have hcd : s.carried.contains d.mp = true := List.contains_iff_mem.mpr (hc d hdm)\n show (if s.carried.contains d.mp then κ' d.mp else M d.mp) x = _\n rw [if_pos hcd]\n show withCnt ds X (withCarried s M κ) d.mp x = _\n rw [withCnt_at hd hdm]\n unfold cntOf\n have hB : evalE (atJ d X x) (withCarried s M κ) d.below = evalE (atJ d X x) (withCarried s M κ') d.below :=\n congrME _ _ _ d.below (fun mp hm => (hoff mp (avoidsMapsE_occ (hav d hdm).1 hm)).symm)\n rw [hB]\n exact sumBelow_congr _ (fun k _ => congrME _ _ _ d.body (fun mp hm => (hoff mp (avoidsMapsE_occ (hav d hdm).2 hm)).symm))\n\n\n/-- The family check without cuts, as before: its soundness is the cut-carrying check's at empty cuts. -/\ntheorem cmachine_sound (s : SMachine) (ds : List CDecl) (ps : List CEntry) (h : checkCMachine s ds ps = true) :\n ∀ ρ M, CReach s ds ρ M → ∀ ce ∈ ps, ce.e.Holds ρ (withCnt ds ρ M) := by\n intro ρ M hr ce hce\n exact cmachineF_sound s ds (ps.map CEntry.toF) (by rw [checkCMachineF_noAux]; exact h) ρ M hr ce.toF (List.mem_map_of_mem hce)\n\nend Kern\n\n#print axioms Kern.mc_sound\n#print axioms Kern.cmachine_sound\n#print axioms Kern.cmachineF_sound\n#print axioms Kern.checkCMachineF_noAux\n#print axioms Kern.checkCMachineF_split\n#print axioms Kern.checkCMachineF_of_parts\n#print axioms Kern.counts_exist\n#print axioms Kern.pickHyp_true\n#print axioms Kern.countedWF_sound\n#print axioms Kern.mcF_sound\n",
23
23
  "GhostMap.lean": "import Ghost\n\n/-!\nGhostMap: ghost maps, proven. Ghost.lean's `sghost_reach` lets a machine gain ghost values (scalars the step keeps);\nthis file lets it gain ghost maps too: maps the original never reads, each starting at a constant and written by the\nstep at one key (`gwrites`) or at every key (`gevery`). A ghost map is a Skolem function the step keeps: a law of the\nghosted machine about every key k, reading the ghost map W at k, says that every k has a witness, W[k].\n\nLean checks that a ghosted machine is the original's parts plus each ghost's start and step (`SGhostedM.full`), with\nnew names read by no part of the original (`smghostOk`), and proves, for machines with maps, flags and sets:\n- `smghost_reach`: every reachable state of the original is, outside the ghost variables and the ghost maps, a\n reachable state of the ghosted machine (the generalization of `sghost_reach` from ghost values to ghost maps);\n- `smghost_laws`: a law of the ghosted machine that reads no ghost holds of the original;\n- `some_of_ghostmap`: the laws of the ghosted machine give, at every reachable state of the original, ghost values and\n ghost maps (Skolem functions of the keys) that agree with the state elsewhere and where every law holds;\n- `forall_some_of_ghostmap`: the ∀∃ reading. A law about every key kv that reads the ghost map W only at one key term t\n gives: for every value of kv, some natural x satisfies the law with each read of W replaced by x (`substRC [] (rdW W\n x)`), a statement about the original alone when that law reads no other ghost.\n-/\n\nnamespace Kern\nopen Classical\n\nstructure SGhostedM where\n orig : SMachine\n ghosts : List (Nat × E × E) -- ghost values: (variable, start over the params, step), as SGhosted's\n gmaps : List (Nat × Nat) -- ghost maps: (map, its value at every key at the start)\n gwrites : List (Nat × E × E) -- (ghost map, key, value): a write at one key\n gevery : List (Nat × Nat × E) -- (ghost map, bound key, value): a write at every key\n\ndef SGhostedM.vars (g : SGhostedM) : List Nat := g.ghosts.map (·.1)\ndef SGhostedM.maps (g : SGhostedM) : List Nat := g.gmaps.map (·.1)\n\n-- The ghosted machine: the original, each ghost's start and step added after the original's.\ndef SGhostedM.full (g : SGhostedM) : SMachine :=\n ⟨⟨⟨g.orig.f.m.inputs, g.orig.f.m.init ++ g.ghosts.map (fun x => (x.1, x.2.1)), g.orig.f.m.maps0 ++ g.gmaps,\n g.orig.f.m.step ++ g.ghosts.map (fun x => (x.1, x.2.2)), g.orig.f.m.writes ++ g.gwrites, g.orig.f.m.pre, g.orig.f.m.assume⟩, g.orig.f.flags⟩,\n g.orig.carried, g.orig.every ++ g.gevery, g.orig.qflags, g.orig.wits, g.orig.facts, g.orig.pfacts⟩\n\n-- The original's maps, in any role: started, written at a key, written at every key, carried.\ndef origMaps (s : SMachine) : List Nat := s.f.m.maps0.map (·.1) ++ s.f.m.writes.map (·.1) ++ s.every.map (·.1) ++ s.carried\n\n-- Reads none of the variables V and none of the maps MS.\ndef apartC (V MS : List Nat) (c : C) : Bool := avoids V c && avoidsMaps MS c\ndef apartE (V MS : List Nat) (e : E) : Bool := avoidsE V e && avoidsMapsE MS e\n\n-- The ghosts are new names (variables and maps), the ghost writes write ghost maps, and no part of the original reads a\n-- ghost.\ndef smghostOk (g : SGhostedM) : Bool :=\n distinct g.vars && distinct g.maps\n && g.vars.all (fun v => !(g.orig.extVars ++ g.orig.f.m.init.map (·.1) ++ g.orig.f.m.step.map (·.1) ++ flagVars g.orig.f.flags ++ bkeys g.orig).contains v)\n && g.maps.all (fun mp => !(origMaps g.orig).contains mp)\n && (g.gwrites.map (·.1) ++ g.gevery.map (·.1)).all (fun mp => g.maps.contains mp)\n && apartC g.vars g.maps g.orig.f.m.pre && apartC g.vars g.maps g.orig.f.m.assume\n && g.orig.f.flags.all (fun p => apartC g.vars g.maps p.2) && g.orig.qflags.all (fun q => apartC g.vars g.maps q.2.2)\n && g.orig.f.m.init.all (fun p => apartE g.vars g.maps p.2) && g.orig.f.m.step.all (fun p => apartE g.vars g.maps p.2)\n && g.orig.f.m.writes.all (fun w => apartE g.vars g.maps w.2.1 && apartE g.vars g.maps w.2.2)\n && g.orig.every.all (fun w => apartE g.vars g.maps w.2.2)\n && g.orig.facts.all (fun l => apartC g.vars g.maps l.holds) && g.orig.pfacts.all (fun f => apartC g.vars g.maps f.1.holds)\n\n/-! Reading alike outside the ghosts -/\n\ntheorem apartC_parts {V MS : List Nat} {c : C} (h : apartC V MS c = true) : avoids V c = true ∧ avoidsMaps MS c = true := by\n simpa [apartC] using h\ntheorem apartE_parts {V MS : List Nat} {e : E} (h : apartE V MS e = true) : avoidsE V e = true ∧ avoidsMapsE MS e = true := by\n simpa [apartE] using h\n\ntheorem evalC_apart {V MS : List Nat} {c : C} (h : apartC V MS c = true) {ρ ρ' : Nat → Nat} {M M' : Nat → Nat → Nat}\n (hag : Agree V ρ ρ') (hm : ∀ mp, mp ∉ MS → M mp = M' mp) : evalC ρ M c = evalC ρ' M' c := by\n obtain ⟨hv, hmm⟩ := apartC_parts h\n rw [congrC ρ ρ' M c (fun i hi => hag i (avoids_occ hv hi)), congrMC ρ' M M' c (fun mp hmp => hm mp (avoidsMaps_occ hmm hmp))]\n\ntheorem evalE_apart {V MS : List Nat} {e : E} (h : apartE V MS e = true) {ρ ρ' : Nat → Nat} {M M' : Nat → Nat → Nat}\n (hag : Agree V ρ ρ') (hm : ∀ mp, mp ∉ MS → M mp = M' mp) : evalE ρ M e = evalE ρ' M' e := by\n obtain ⟨hv, hmm⟩ := apartE_parts h\n rw [congrE ρ ρ' M e (fun i hi => hag i (avoidsE_occ hv hi)), congrME ρ' M M' e (fun mp hmp => hm mp (avoidsMapsE_occ hmm hmp))]\n\n-- Flags decided over states and maps that agree outside the ghosts, by conditions that read no ghost, agree there.\ntheorem decide_apart {fl : List (Nat × C)} {V MS : List Nat} (hav : ∀ p ∈ fl, apartC V MS p.2 = true) {X X' : Nat → Nat}\n {N N' : Nat → Nat → Nat} (h : Agree V X X') (hN : ∀ mp, mp ∉ MS → N mp = N' mp) : Agree V (decideFlags fl X N) (decideFlags fl X' N') := by\n intro i hi\n simp only [decideFlags, applyS, assoc_flagSub]\n cases hc : flagOf fl i with\n | none => exact h i hi\n | some c =>\n obtain ⟨p, hp, rfl⟩ := flagOf_some hc\n simp only [Option.map_some, evalE]\n rw [evalC_apart (hav p hp) h hN]\n\ntheorem lookup_append_none {α : Type} (p : α → Bool) (l1 l2 : List α) (h : lookup p l2 = none) : lookup p (l1 ++ l2) = lookup p l1 := by\n rw [lookup_append]; cases lookup p l1 <;> simp [h]\n\n-- The ghost maps at their starts, every other map as it is.\ndef startWith (gm : List (Nat × Nat)) (M : Nat → Nat → Nat) : Nat → Nat → Nat := fun mp =>\n match lookup (fun p => p.1 == mp) gm with\n | some p => fun _ => p.2\n | none => M mp\n\n-- The facts about several keys, read where maps agree on what they read.\ntheorem holdsOver_maps {l : MLaw} {MS : List Nat} (hm : avoidsMaps MS l.holds = true) {M M' : Nat → Nat → Nat}\n (hmag : ∀ mp, mp ∉ MS → M mp = M' mp) : ∀ (gs : List Nat) (ρ : Nat → Nat), holdsOver l M' gs ρ → holdsOver l M gs ρ\n | [], ρ, h => holds_transfer (V := []) l (by simp [avoids]) hm (fun _ _ => rfl) hmag h\n | _ :: gs, ρ, h => fun w => holdsOver_maps hm hmag gs _ (h w)\n\nsection smghost\nvariable (g : SGhostedM) (hg : smghostOk g = true)\ninclude hg\n\ntheorem smghostOk_parts :\n distinct g.vars = true ∧ distinct g.maps = true\n ∧ (∀ mp ∈ g.maps, mp ∉ origMaps g.orig)\n ∧ (∀ mp ∈ g.gwrites.map (·.1) ++ g.gevery.map (·.1), mp ∈ g.maps)\n ∧ apartC g.vars g.maps g.orig.f.m.pre = true ∧ apartC g.vars g.maps g.orig.f.m.assume = true\n ∧ (∀ p ∈ g.orig.f.flags, apartC g.vars g.maps p.2 = true) ∧ (∀ q ∈ g.orig.qflags, apartC g.vars g.maps q.2.2 = true)\n ∧ (∀ p ∈ g.orig.f.m.init, apartE g.vars g.maps p.2 = true) ∧ (∀ p ∈ g.orig.f.m.step, apartE g.vars g.maps p.2 = true)\n ∧ (∀ w ∈ g.orig.f.m.writes, apartE g.vars g.maps w.2.1 = true ∧ apartE g.vars g.maps w.2.2 = true)\n ∧ (∀ w ∈ g.orig.every, apartE g.vars g.maps w.2.2 = true)\n ∧ (∀ l ∈ g.orig.facts, apartC g.vars g.maps l.holds = true) ∧ (∀ f ∈ g.orig.pfacts, apartC g.vars g.maps f.1.holds = true) := by\n simp only [smghostOk, Bool.and_eq_true, List.all_eq_true, Bool.not_eq_true'] at hg\n obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨hdv, hdm⟩, _⟩, hom⟩, hw⟩, hp⟩, ha⟩, hf⟩, hq⟩, hi⟩, hs⟩, hwr⟩, he⟩, hfa⟩, hpf⟩ := hg\n exact ⟨hdv, hdm, fun mp hm => by simpa using hom mp hm, fun mp hm => by simpa using hw mp hm, hp, ha, hf, hq, hi, hs, hwr, he, hfa, hpf⟩\n\n/-- One step from states and maps that agree outside the ghosts, with the same request: allowed alike, and to states\nand maps that agree outside the ghosts. -/\ntheorem smghost_step {ρg ρ : Nat → Nat} {Mg M : Nat → Nat → Nat} (hag : Agree g.vars ρg ρ) (hmag : ∀ mp, mp ∉ g.maps → Mg mp = M mp)\n (ι : Nat → Nat) (κ : Nat → Nat → Nat) :\n evalC (sView g.full ρg Mg ι κ).1 (sView g.full ρg Mg ι κ).2 g.full.f.m.assume = evalC (sView g.orig ρ M ι κ).1 (sView g.orig ρ M ι κ).2 g.orig.f.m.assume\n ∧ Agree g.vars (sNext g.full ρg Mg ι κ).1 (sNext g.orig ρ M ι κ).1\n ∧ ∀ mp, mp ∉ g.maps → (sNext g.full ρg Mg ι κ).2 mp = (sNext g.orig ρ M ι κ).2 mp := by\n obtain ⟨_, _, _, hw, _, ha, hf, hq, _, hs, hwr, he, _, _⟩ := smghostOk_parts g hg\n have hX : Agree g.vars (withInputs g.orig.f.m.inputs ρg ι) (withInputs g.orig.f.m.inputs ρ ι) := withInputs_agree hag ι\n have hN : ∀ mp, mp ∉ g.maps → withCarried g.orig Mg κ mp = withCarried g.orig M κ mp := fun mp hmp => by\n simp only [withCarried]; split\n · rfl\n · exact hmag mp hmp\n have hQ : Agree g.vars (decideQ g.orig (withInputs g.orig.f.m.inputs ρg ι) (withCarried g.orig Mg κ))\n (decideQ g.orig (withInputs g.orig.f.m.inputs ρ ι) (withCarried g.orig M κ)) := by\n intro v hv\n rw [decideQ_of, decideQ_of]\n cases hl : lookup (fun q => q.1 == v) g.orig.qflags with\n | some q =>\n obtain ⟨hqv, hqm⟩ := apartC_parts (hq q (lookup_some hl).1)\n exact ite_all_congr (fun i hi _ => hX i (avoids_occ hqv hi)) (fun mp hm => hN mp (avoidsMaps_occ hqm hm))\n | none => exact hX v hv\n have hD := decide_apart hf hQ hN\n -- The ghosted machine's lists are the original's with the ghosts' after them.\n have hstep : g.full.f.m.step = g.orig.f.m.step ++ g.ghosts.map (fun x => (x.1, x.2.2)) := rfl\n have hevery : g.full.every = g.orig.every ++ g.gevery := rfl\n have hwrites : g.full.f.m.writes = g.orig.f.m.writes ++ g.gwrites := rfl\n refine ⟨?_, fun i hi => ?_, fun mp hmp => ?_⟩\n · show evalC (decideFlags g.orig.f.flags (decideQ g.orig (withInputs g.orig.f.m.inputs ρg ι) (withCarried g.orig Mg κ)) (withCarried g.orig Mg κ)) (withCarried g.orig Mg κ) g.orig.f.m.assume = _\n exact evalC_apart ha hD hN\n · show applyS g.full.f.m.step (decideFlags g.orig.f.flags (decideQ g.orig (withInputs g.orig.f.m.inputs ρg ι) (withCarried g.orig Mg κ)) (withCarried g.orig Mg κ)) (withCarried g.orig Mg κ) i = _\n rw [hstep, applyS_append_other (by simpa [SGhostedM.vars] using hi)]\n simp only [sNext, sView, applyS]\n cases hst : assoc g.orig.f.m.step i with\n | none => exact hD i hi\n | some e =>\n have hm : (i, e) ∈ g.orig.f.m.step := by\n simp only [assoc, Option.map_eq_some_iff] at hst\n obtain ⟨q, hq', rfl⟩ := hst\n obtain ⟨hqm, hqv⟩ := lookup_some hq'\n simp only [beq_iff_eq] at hqv\n rw [← hqv]; exact hqm\n exact evalE_apart (hs (i, e) hm) hD hN\n · funext key\n show everyMaps g.full (decideFlags g.orig.f.flags (decideQ g.orig (withInputs g.orig.f.m.inputs ρg ι) (withCarried g.orig Mg κ)) (withCarried g.orig Mg κ)) (withCarried g.orig Mg κ) mp key\n = everyMaps g.orig (decideFlags g.orig.f.flags (decideQ g.orig (withInputs g.orig.f.m.inputs ρ ι) (withCarried g.orig M κ)) (withCarried g.orig M κ)) (withCarried g.orig M κ) mp key\n have hge : lookup (fun w => w.1 == mp) g.gevery = none :=\n lookup_none (fun w hw' => by\n simp only [beq_eq_false_iff_ne]; intro he'\n exact hmp (by rw [← he']; exact hw w.1 (List.mem_append_right _ (List.mem_map_of_mem hw'))))\n have hgw : lookup (fun w => w.1 == mp) g.gwrites = none :=\n lookup_none (fun w hw' => by\n simp only [beq_eq_false_iff_ne]; intro he'\n exact hmp (by rw [← he']; exact hw w.1 (List.mem_append_left _ (List.mem_map_of_mem hw'))))\n simp only [everyMaps, hevery, lookup_append_none _ g.orig.every _ hge]\n cases hl : lookup (fun w => w.1 == mp) g.orig.every with\n | some w => exact evalE_apart (he w (lookup_some hl).1) (upd_agree hD w.2.1 key) hN\n | none =>\n simp only [writeMaps, hwrites, lookup_append_none _ g.orig.f.m.writes _ hgw]\n cases hl2 : lookup (fun w => w.1 == mp) g.orig.f.m.writes with\n | none => exact congrFun (hN mp hmp) key\n | some w =>\n obtain ⟨h1, h2⟩ := hwr w (lookup_some hl2).1\n dsimp only\n rw [evalE_apart h1 hD hN, evalE_apart h2 hD hN, hN mp hmp]\n\n/-- Every reachable state of the original is, outside the ghost variables and the ghost maps, a reachable state of the\nghosted machine. -/\ntheorem smghost_reach : ∀ {ρ M}, SReach g.orig ρ M → ∃ ρg Mg, SReach g.full ρg Mg ∧ Agree g.vars ρg ρ ∧ ∀ mp, mp ∉ g.maps → Mg mp = M mp := by\n obtain ⟨_, hdm, hom, _, hp, _, _, _, hi, _, _, _, hfa, hpf⟩ := smghostOk_parts g hg\n intro ρ M hr\n induction hr with\n | start ρ0 M0 hM h0 hfa0 hpf0 =>\n have hout : ∀ mp, mp ∉ g.maps → startWith g.gmaps M0 mp = M0 mp := fun mp hmp => by\n have hl : lookup (fun p => p.1 == mp) g.gmaps = none := lookup_none (fun p hp' => by\n simp only [beq_eq_false_iff_ne]; intro he'; exact hmp (by rw [← he']; exact List.mem_map_of_mem hp'))\n simp only [startWith, hl]\n have hstart : StartMaps g.full.f.m (startWith g.gmaps M0) := by\n intro p hp' key\n rcases List.mem_append.mp hp' with hp' | hp'\n · have hpo : p.1 ∉ g.maps := fun hm => hom p.1 hm (List.mem_append_left _ (List.mem_append_left _ (List.mem_append_left _ (List.mem_map_of_mem hp'))))\n rw [hout p.1 hpo]; exact hM p hp' key\n · have hl : lookup (fun q => q.1 == p.1) g.gmaps = some p := lookup_unique (by simpa [SGhostedM.maps] using hdm) hp'\n simp only [startWith, hl]\n obtain ⟨_, hpm⟩ := apartC_parts hp\n refine ⟨applyS g.full.f.m.init ρ0 (startWith g.gmaps M0), startWith g.gmaps M0, SReach.start ρ0 _ hstart ?_ ?_ ?_, fun i hi' => ?_, hout⟩\n · show evalC ρ0 (startWith g.gmaps M0) g.orig.f.m.pre = true\n rw [congrMC ρ0 _ M0 _ (fun mp hm => hout mp (avoidsMaps_occ hpm hm))]; exact h0\n · intro l hl\n exact holds_transfer (V := []) l (by simp [avoids]) (apartC_parts (hfa l hl)).2 (fun _ _ => rfl) hout (hfa0 l hl)\n · intro f hf\n exact holdsOver_maps (apartC_parts (hpf f hf)).2 hout f.2 ρ0 (hpf0 f hf)\n · show applyS (g.orig.f.m.init ++ g.ghosts.map (fun x => (x.1, x.2.1))) ρ0 (startWith g.gmaps M0) i = applyS g.orig.f.m.init ρ0 M0 i\n rw [applyS_append_other (by simpa [SGhostedM.vars] using hi')]\n simp only [applyS]\n cases hst : assoc g.orig.f.m.init i with\n | none => rfl\n | some e =>\n have hm : (i, e) ∈ g.orig.f.m.init := by\n simp only [assoc, Option.map_eq_some_iff] at hst\n obtain ⟨q, hq', rfl⟩ := hst\n obtain ⟨hqm, hqv⟩ := lookup_some hq'\n simp only [beq_iff_eq] at hqv\n rw [← hqv]; exact hqm\n exact evalE_apart (hi (i, e) hm) (fun _ _ => rfl) hout\n | step ρ M ι κ _ ha ih =>\n obtain ⟨ρg, Mg, hrg, hag, hmag⟩ := ih\n obtain ⟨hA, hS, hW⟩ := smghost_step g hg hag hmag ι κ\n exact ⟨_, _, SReach.step ρg Mg ι κ hrg (by rw [hA]; exact ha), hS, hW⟩\n\n/-- A law of the ghosted machine that reads no ghost holds in every reachable state of the original. -/\ntheorem smghost_laws (ps : List SEntry) (hl : checkSMachine g.full ps = true) :\n ∀ ρ M, SReach g.orig ρ M → ∀ e ∈ ps, avoids g.vars e.law.holds = true → avoidsMaps g.maps e.law.holds = true → e.Holds ρ M := by\n intro ρ M hr e he hav ham\n obtain ⟨ρg, Mg, hrg, hag, hmag⟩ := smghost_reach g hg hr\n exact sentry_transfer (V := g.vars) (MS := g.maps) hav ham (fun i hi => (hag i hi).symm) (fun mp hmp => (hmag mp hmp).symm)\n (smachine_sound g.full ps hl ρg Mg hrg e he)\n\n/-- The laws of the ghosted machine, at every reachable state of the original: some ghost values and some ghost maps\n(Skolem functions of the keys), the state and maps as they are elsewhere, where every law holds. -/\ntheorem some_of_ghostmap (ps : List SEntry) (hl : checkSMachine g.full ps = true) :\n ∀ ρ M, SReach g.orig ρ M → ∃ ρg Mg, Agree g.vars ρg ρ ∧ (∀ mp, mp ∉ g.maps → Mg mp = M mp) ∧ ∀ e ∈ ps, e.Holds ρg Mg := by\n intro ρ M hr\n obtain ⟨ρg, Mg, hrg, hag, hmag⟩ := smghost_reach g hg hr\n exact ⟨ρg, Mg, hag, hmag, smachine_sound g.full ps hl ρg Mg hrg⟩\nend smghost\n\n/-! The ∀∃ reading: a ghost map read at one key, as a natural -/\n\n-- Every read of the map W is at the key term t.\nmutual\ndef atKeyE (W : Nat) (t : E) : E → Bool\n | .var _ => true\n | .const _ => true\n | .add a b => atKeyE W t a && atKeyE W t b\n | .sub a b => atKeyE W t a && atKeyE W t b\n | .mul _ a => atKeyE W t a\n | .min a b => atKeyE W t a && atKeyE W t b\n | .max a b => atKeyE W t a && atKeyE W t b\n | .prod a b => atKeyE W t a && atKeyE W t b\n | .ite c a b => atKeyC W t c && atKeyE W t a && atKeyE W t b\n | .get m key => if m == W then beqE key t else atKeyE W t key\n | .tup a b => atKeyE W t a && atKeyE W t b\n | .proj _ a => atKeyE W t a\ndef atKeyC (W : Nat) (t : E) : C → Bool\n | .le a b => atKeyE W t a && atKeyE W t b\n | .lt a b => atKeyE W t a && atKeyE W t b\n | .eq a b => atKeyE W t a && atKeyE W t b\n | .and a b => atKeyC W t a && atKeyC W t b\n | .or a b => atKeyC W t a && atKeyC W t b\n | .not a => atKeyC W t a\nend\n\n-- A read of W as the variable x; any other read as it is.\ndef rdW (W x : Nat) : Nat → E → E := fun m k => if m == W then .var x else .get m k\n\n-- The maps with W the constant v.\ndef withConst (W v : Nat) (M : Nat → Nat → Nat) : Nat → Nat → Nat := fun m => if m == W then fun _ => v else M m\n\nsection atkey\nvariable (W : Nat) (t : E) (ρ : Nat → Nat) (M : Nat → Nat → Nat)\nmutual\ntheorem atKey_evalE : (e : E) → atKeyE W t e = true → evalE ρ M e = evalE ρ (withConst W (M W (evalE ρ M t)) M) e\n | .var _, _ => rfl\n | .const _, _ => rfl\n | .add a b, h => by simp only [atKeyE, Bool.and_eq_true] at h; simp only [evalE, atKey_evalE a h.1, atKey_evalE b h.2]\n | .sub a b, h => by simp only [atKeyE, Bool.and_eq_true] at h; simp only [evalE, atKey_evalE a h.1, atKey_evalE b h.2]\n | .mul _ a, h => by simp only [atKeyE] at h; simp only [evalE, atKey_evalE a h]\n | .min a b, h => by simp only [atKeyE, Bool.and_eq_true] at h; simp only [evalE, atKey_evalE a h.1, atKey_evalE b h.2]\n | .max a b, h => by simp only [atKeyE, Bool.and_eq_true] at h; simp only [evalE, atKey_evalE a h.1, atKey_evalE b h.2]\n | .prod a b, h => by simp only [atKeyE, Bool.and_eq_true] at h; simp only [evalE, atKey_evalE a h.1, atKey_evalE b h.2]\n | .ite c a b, h => by\n simp only [atKeyE, Bool.and_eq_true] at h\n simp only [evalE, atKey_evalC c h.1.1, atKey_evalE a h.1.2, atKey_evalE b h.2]\n | .get m key, h => by\n simp only [atKeyE] at h\n by_cases hm : m = W\n · subst hm\n simp only [beq_self_eq_true, ite_true] at h\n rw [beqE_eq h]\n simp [evalE, withConst]\n · have hb : (m == W) = false := by simp [hm]\n simp only [hb, Bool.false_eq_true, ite_false] at h\n simp only [evalE, withConst, hb, Bool.false_eq_true, ite_false, ← atKey_evalE key h]\n | .tup a b, h => by simp only [atKeyE, Bool.and_eq_true] at h; simp only [evalE, atKey_evalE a h.1, atKey_evalE b h.2]\n | .proj _ a, h => by simp only [atKeyE] at h; simp only [evalE, atKey_evalE a h]\ntheorem atKey_evalC : (c : C) → atKeyC W t c = true → evalC ρ M c = evalC ρ (withConst W (M W (evalE ρ M t)) M) c\n | .le a b, h => by simp only [atKeyC, Bool.and_eq_true] at h; simp only [evalC, atKey_evalE a h.1, atKey_evalE b h.2]\n | .lt a b, h => by simp only [atKeyC, Bool.and_eq_true] at h; simp only [evalC, atKey_evalE a h.1, atKey_evalE b h.2]\n | .eq a b, h => by simp only [atKeyC, Bool.and_eq_true] at h; simp only [evalC, atKey_evalE a h.1, atKey_evalE b h.2]\n | .and a b, h => by simp only [atKeyC, Bool.and_eq_true] at h; simp only [evalC, atKey_evalC a h.1, atKey_evalC b h.2]\n | .or a b, h => by simp only [atKeyC, Bool.and_eq_true] at h; simp only [evalC, atKey_evalC a h.1, atKey_evalC b h.2]\n | .not a, h => by simp only [atKeyC] at h; simp only [evalC, atKey_evalC a h]\nend\nend atkey\n\n-- A condition that reads W only at t, with each read of W replaced by a fresh x, read where x is W's value at t.\ntheorem rdW_evalC (W x : Nat) (t : E) (c : C) (hat : atKeyC W t c = true) (hx : occC x c = false) (ρ : Nat → Nat) (M : Nat → Nat → Nat) :\n evalC (upd ρ x (M W (evalE ρ M t))) M (substRC [] (rdW W x) c) = evalC ρ M c := by\n have hrd : ∀ m k, evalE (upd ρ x (M W (evalE ρ M t))) M (rdW W x m k)\n = withConst W (M W (evalE ρ M t)) M m (evalE (upd ρ x (M W (evalE ρ M t))) M k) := by\n intro m k\n by_cases hm : m = W\n · subst hm; simp [rdW, withConst, evalE, upd]\n · have hb : (m == W) = false := by simp [hm]\n simp [rdW, withConst, evalE, hb]\n rw [substR_evalC [] (rdW W x) _ M _ hrd c, applyS_nil, atKey_evalC W t ρ M c hat]\n exact congrC _ _ _ c (fun i hi => by\n simp only [upd]; split\n · rename_i hix; subst hix; simp [hx] at hi\n · rfl)\n\n/-- The ∀∃ reading of a ghost map: a law of the ghosted machine about every value of kv (no further keys) that reads\nthe ghost map W only at the key term t gives, at every reachable state of the original, for every value of kv some\nnatural x where the law holds with each read of W replaced by x; when that condition reads no ghost, it is a statement\nabout the original alone. -/\ntheorem forall_some_of_ghostmap (g : SGhostedM) (hg : smghostOk g = true) (ps : List SEntry) (hl : checkSMachine g.full ps = true)\n (e : SEntry) (he : e ∈ ps) (kv : Nat) (hk : e.law.key = some kv) (hk2 : e.keys2 = []) (W x : Nat) (t : E)\n (hat : atKeyC W t e.law.holds = true) (hx : occC x e.law.holds = false)\n (hav : avoids g.vars (substRC [] (rdW W x) e.law.holds) = true) (ham : avoidsMaps g.maps (substRC [] (rdW W x) e.law.holds) = true) :\n ∀ ρ M, SReach g.orig ρ M → ∀ v, ∃ val, evalC (upd (upd ρ kv v) x val) M (substRC [] (rdW W x) e.law.holds) = true := by\n intro ρ M hr v\n obtain ⟨ρg, Mg, hrg, hag, hmag⟩ := smghost_reach g hg hr\n have hall := smachine_sound g.full ps hl ρg Mg hrg e he\n simp only [SEntry.Holds, hk2, holdsOver, MLaw.Holds, hk] at hall\n refine ⟨Mg W (evalE (upd ρg kv v) Mg t), ?_⟩\n have h1 := rdW_evalC W x t e.law.holds hat hx (upd ρg kv v) Mg\n rw [hall v] at h1\n have hagx : Agree g.vars (upd (upd ρ kv v) x (Mg W (evalE (upd ρg kv v) Mg t))) (upd (upd ρg kv v) x (Mg W (evalE (upd ρg kv v) Mg t))) :=\n upd_agree (upd_agree (fun i hi => (hag i hi).symm) kv v) x _\n rw [congrC _ _ M _ (fun i hi => hagx i (avoids_occ hav hi)),\n congrMC _ M Mg _ (fun mp hmp => (hmag mp (avoidsMaps_occ ham hmp)).symm)]\n exact h1\n\n/-! The ∃ reading of witness terms over the ghosts: any number of bound naturals, any number of keys -/\n\n-- An ∃ law at a state, read as MLaw.Holds and holdsOver read a law: each further key at every value, then its key at\n-- every value, then some natural for each of xs (written over the state) where c holds.\ndef ExHolds (c : C) (key : Option Nat) (xs : List Nat) (M : Nat → Nat → Nat) : List Nat → (Nat → Nat) → Prop\n | [], ρ => match key with\n | none => ∃ f : Nat → Nat, evalC (updAll ρ (xs.map fun i => (i, f i))) M c = true\n | some kv => ∀ v, ∃ f : Nat → Nat, evalC (updAll (upd ρ kv v) (xs.map fun i => (i, f i))) M c = true\n | g :: gs, ρ => ∀ w, ExHolds c key xs M gs (upd ρ g w)\n\ntheorem updAll_agree {V : List Nat} {X X' : Nat → Nat} (h : Agree V X X') : ∀ (l : List (Nat × Nat)), Agree V (updAll X l) (updAll X' l)\n | [] => h\n | p :: ps => updAll_agree (upd_agree h p.1 p.2) ps\n\n-- Witness terms σ in place, read over a ghosted state: the terms' values there, written over a state that agrees with\n-- it outside the ghosts, satisfy c where c reads no ghost.\ntheorem some_of_subst_apart {V MS : List Nat} (σ : List (Nat × E)) (c : C) (hav : avoids V c = true) (ham : avoidsMaps MS c = true)\n {ρg ρ : Nat → Nat} {Mg M : Nat → Nat → Nat} (hag : Agree V ρg ρ) (hmag : ∀ mp, mp ∉ MS → Mg mp = M mp)\n (h : evalC ρg Mg (substC σ c) = true) :\n ∃ f : Nat → Nat, evalC (updAll ρ ((σ.map (·.1)).map fun i => (i, f i))) M c = true := by\n refine ⟨fun i => applyS σ ρg Mg i, ?_⟩\n have h1 := some_of_subst σ c ρg Mg h\n have hx := updAll_agree hag ((σ.map (·.1)).map fun i => (i, applyS σ ρg Mg i))\n rw [congrC _ _ M _ (fun i hi => (hx i (avoids_occ hav hi)).symm),\n congrMC _ M Mg _ (fun mp hmp => (hmag mp (avoidsMaps_occ ham hmp)).symm)]\n exact h1\n\n/-- The ∀∃ reading of witness terms over ghosts: a law of the ghosted machine that is c with each bound natural x\nreplaced by a term σ x (`substC σ c`), where c reads no ghost (variable or map), gives at every reachable state of the\noriginal, for every value of its keys, some natural for each bound name where c holds: a statement about the original\nalone. A term may read anything of the ghosted machine (ghost maps at any key, the state, the law's keys), so one\nghost map per bound name (forall_some_of_ghostmap's), several of them, a disjunction of ∃s (their bound names together)\nand a witness built of ghost reads are all instances. -/\ntheorem forall_some_of_ghostsubst (g : SGhostedM) (hg : smghostOk g = true) (ps : List SEntry) (hl : checkSMachine g.full ps = true)\n (e : SEntry) (he : e ∈ ps) (σ : List (Nat × E)) (c : C) (hsub : e.law.holds = substC σ c)\n (hav : avoids g.vars c = true) (ham : avoidsMaps g.maps c = true) :\n ∀ ρ M, SReach g.orig ρ M → ExHolds c e.law.key (σ.map (·.1)) M e.keys2 ρ := by\n intro ρ M hr\n obtain ⟨ρg, Mg, hrg, hag, hmag⟩ := smghost_reach g hg hr\n have hall := smachine_sound g.full ps hl ρg Mg hrg e he\n simp only [SEntry.Holds] at hall\n -- (along the further keys, each at the same value on both sides)\n have go : ∀ (gs : List Nat) (ρg ρ : Nat → Nat), Agree g.vars ρg ρ → holdsOver e.law Mg gs ρg → ExHolds c e.law.key (σ.map (·.1)) M gs ρ := by\n intro gs\n induction gs with\n | nil =>\n intro ρg ρ hag h\n simp only [holdsOver, MLaw.Holds] at h\n cases hk : e.law.key with\n | none =>\n simp only [hk, hsub] at h\n simp only [ExHolds]\n exact some_of_subst_apart σ c hav ham hag hmag h\n | some kv =>\n simp only [hk, hsub] at h\n simp only [ExHolds]\n intro v\n exact some_of_subst_apart σ c hav ham (upd_agree hag kv v) hmag (h v)\n | cons k gs ih =>\n intro ρg ρ hag h w\n exact ih (upd ρg k w) (upd ρ k w) (upd_agree hag k w) (h w)\n exact go e.keys2 ρg ρ hag hall\n\nend Kern\n\n#print axioms Kern.forall_some_of_ghostsubst\n#print axioms Kern.smghost_reach\n#print axioms Kern.smghost_laws\n#print axioms Kern.some_of_ghostmap\n#print axioms Kern.forall_some_of_ghostmap\n",
24
- "QAlpha.lean": "import CountMachine\n\n/-! A semantic bridge for capture-avoiding alpha conversion of quantified flags.\nOnly qflags change; no checker or proof rule is modified. -/\nnamespace Kern.QAlpha\nopen Classical\n\nstructure Rename where\n flag : Nat\n old : Nat\n fresh : Nat\n deriving DecidableEq, Repr\n\ndef keys (ks : List Nat) (a b : Nat) : List Nat :=\n ks.map (fun i => if i = a then b else i)\n\ndef body (c : C) (a b : Nat) : C := substC [(a, .var b)] c\n\ndef validQ (q : Nat × List Nat × C) (r : Rename) : Bool :=\n if q.1 = r.flag then q.2.1.contains r.old && !q.2.1.contains r.fresh && !occC r.fresh q.2.2 else true\n\ndef renameQ (q : Nat × List Nat × C) (r : Rename) : Nat × List Nat × C :=\n if q.1 = r.flag then (q.1, keys q.2.1 r.old r.fresh, body q.2.2 r.old r.fresh) else q\n\ndef valid (s : SMachine) (r : Rename) : Bool := s.qflags.all (fun q => validQ q r)\ndef rename (s : SMachine) (r : Rename) : SMachine :=\n { s with qflags := s.qflags.map (fun q => renameQ q r) }\n\ndef renameAll : SMachine → List Rename → SMachine\n | s, [] => s\n | s, r :: rs => renameAll (rename s r) rs\n\ndef validAll : SMachine → List Rename → Bool\n | _, [] => true\n | s, r :: rs => valid s r && validAll (rename s r) rs\n\ntheorem mem_keys {ks : List Nat} {a b i : Nat} (hi : i ≠ b) :\n i ∈ keys ks a b ↔ i ∈ ks ∧ i ≠ a := by\n simp only [keys, List.mem_map]\n constructor\n · rintro ⟨j, hj, he⟩\n split at he <;> grind\n · rintro ⟨h, hia⟩\n exact ⟨i, h, by simp [hia]⟩\n\ntheorem eval_body (ks : List Nat) (c : C) (a b : Nat)\n (ha : a ∈ ks) (hb : b ∉ ks) (hc : occC b c = false)\n (X u v : Nat → Nat) (N : Nat → Nat → Nat)\n (hab : u a = v b) (huv : ∀ i ∈ ks, i ≠ a → u i = v i) :\n evalC (atKeys X (keys ks a b) v) N (body c a b) = evalC (atKeys X ks u) N c := by\n have hne : a ≠ b := by intro h; subst b; exact hb ha\n unfold body\n rw [subst_evalC]\n apply congrC\n intro i hi\n have hib : i ≠ b := by intro h; subst i; simp [hc] at hi\n by_cases hia : i = a\n · subst i\n have hbm : b ∈ keys ks a b := List.mem_map.mpr ⟨a, ha, by simp⟩\n simp [applyS, assoc, lookup, evalE, atKeys_in hbm, atKeys_in ha, hab]\n · have hm := mem_keys (ks := ks) (a := a) hib\n by_cases hik : i ∈ ks\n · have hmk : i ∈ keys ks a b := hm.mpr ⟨hik, hia⟩\n simp [applyS, assoc, lookup, hia, Ne.symm hia, atKeys_in hmk, atKeys_in hik, huv i hik hia]\n · have hmk : i ∉ keys ks a b := fun h => hik (hm.mp h).1\n simp [applyS, assoc, lookup, hia, Ne.symm hia, atKeys_out hmk, atKeys_out hik]\n\ntheorem quantified (ks : List Nat) (c : C) (a b : Nat)\n (ha : a ∈ ks) (hb : b ∉ ks) (hc : occC b c = false)\n (X : Nat → Nat) (N : Nat → Nat → Nat) :\n (∀ v, holdsC (atKeys X (keys ks a b) v) N (body c a b)) ↔\n (∀ u, holdsC (atKeys X ks u) N c) := by\n have hne : a ≠ b := by intro h; subst b; exact hb ha\n constructor\n · intro h u\n have hv := h (upd u b (u a))\n rw [← evalC_iff, eval_body ks c a b ha hb hc X u (upd u b (u a)) N\n (by simp [upd]) (by\n intro i hi hia\n have hib : i ≠ b := by\n intro e\n subst i\n exact hb hi\n simp [upd, hib])] at hv\n exact (evalC_iff _ _ _).mp hv\n · intro h v\n rw [← evalC_iff, eval_body ks c a b ha hb hc X (upd v a (v b)) v N\n (by simp [upd]) (by intro i hi hia; simp [upd, hia])]\n exact (evalC_iff _ _ _).mpr (h _)\n\n@[simp] theorem renameQ_flag (q : Nat × List Nat × C) (r : Rename) : (renameQ q r).1 = q.1 := by\n unfold renameQ; split <;> rfl\n\ntheorem quantifiedQ (q : Nat × List Nat × C) (r : Rename) (h : validQ q r = true)\n (X : Nat → Nat) (N : Nat → Nat → Nat) :\n (∀ k, holdsC (atKeys X (renameQ q r).2.1 k) N (renameQ q r).2.2) ↔\n (∀ k, holdsC (atKeys X q.2.1 k) N q.2.2) := by\n by_cases he : q.1 = r.flag\n · have hp : r.old ∈ q.2.1 ∧ r.fresh ∉ q.2.1 ∧ occC r.fresh q.2.2 = false := by\n simpa [validQ, he, Bool.and_eq_true, List.contains_iff_mem, and_assoc] using h\n simpa [renameQ, he] using quantified q.2.1 q.2.2 r.old r.fresh hp.1 hp.2.1 hp.2.2 X N\n · simp [renameQ, he]\n\ntheorem lookup_value (qs : List (Nat × List Nat × C)) (r : Rename)\n (h : qs.all (fun q => validQ q r) = true) (X : Nat → Nat) (N : Nat → Nat → Nat) (i : Nat) :\n (match lookup (fun q => q.1 == i) (qs.map (fun q => renameQ q r)) with\n | some q => if ∀ k, holdsC (atKeys X q.2.1 k) N q.2.2 then 1 else 0\n | none => X i) =\n (match lookup (fun q => q.1 == i) qs with\n | some q => if ∀ k, holdsC (atKeys X q.2.1 k) N q.2.2 then 1 else 0\n | none => X i) := by\n classical\n induction qs with\n | nil => rfl\n | cons q qs ih =>\n have hp : validQ q r = true ∧ qs.all (fun q => validQ q r) = true := by\n simpa only [List.all_cons, Bool.and_eq_true] using h\n by_cases hi : (q.1 == i) = true\n · simp only [List.map_cons, lookup, renameQ_flag, hi, ite_true]\n rw [quantifiedQ q r hp.1 X N]\n · simpa [List.map_cons, lookup, hi] using ih hp.2\n\ntheorem decideQ_rename (s : SMachine) (r : Rename) (h : valid s r = true)\n (X : Nat → Nat) (N : Nat → Nat → Nat) : decideQ (rename s r) X N = decideQ s X N := by\n classical\n funext i\n exact lookup_value s.qflags r h X N i\n\n/-- The complete semantic interface, independent of checker acceptance. -/\nstructure Equiv (s t : SMachine) : Prop where\n f : s.f = t.f\n carried : s.carried = t.carried\n every : s.every = t.every\n facts : s.facts = t.facts\n pfacts : s.pfacts = t.pfacts\n flags : ∀ X N, decideQ s X N = decideQ t X N\n\ntheorem Equiv.refl (s : SMachine) : Equiv s s := ⟨rfl, rfl, rfl, rfl, rfl, fun _ _ => rfl⟩\ntheorem Equiv.trans {s t u : SMachine} (h : Equiv s t) (g : Equiv t u) : Equiv s u :=\n ⟨h.f.trans g.f, h.carried.trans g.carried, h.every.trans g.every,\n h.facts.trans g.facts, h.pfacts.trans g.pfacts, fun X N => (h.flags X N).trans (g.flags X N)⟩\ntheorem rename_equiv (s : SMachine) (r : Rename) (h : valid s r = true) : Equiv (rename s r) s :=\n ⟨rfl, rfl, rfl, rfl, rfl, decideQ_rename s r h⟩\n\ntheorem renameAll_equiv (s : SMachine) (rs : List Rename) (h : validAll s rs = true) :\n Equiv (renameAll s rs) s := by\n induction rs generalizing s with\n | nil => exact Equiv.refl s\n | cons r rs ih =>\n have hp : valid s r = true ∧ validAll (rename s r) rs = true := by\n simpa only [validAll, Bool.and_eq_true] using h\n exact (ih (rename s r) hp.2).trans (rename_equiv s r hp.1)\n\ntheorem Equiv.withCarried {s t : SMachine} (h : Equiv s t) (M κ : Nat → Nat → Nat) :\n Kern.withCarried s M κ = Kern.withCarried t M κ := by\n funext mp key\n change (if s.carried.contains mp then κ mp else M mp) key =\n (if t.carried.contains mp then κ mp else M mp) key\n rw [h.carried]\n\ntheorem Equiv.view {s t : SMachine} (h : Equiv s t) (ρ ι : Nat → Nat) (M κ : Nat → Nat → Nat) :\n sView s ρ M ι κ = sView t ρ M ι κ := by\n simp only [sView, h.f, h.withCarried, h.flags]\n\ntheorem Equiv.next {s t : SMachine} (h : Equiv s t) (ρ ι : Nat → Nat) (M κ : Nat → Nat → Nat) :\n sNext s ρ M ι κ = sNext t ρ M ι κ := by\n simp only [sNext, h.view]\n have he : Kern.everyMaps s = Kern.everyMaps t := by\n funext D N mp key\n unfold Kern.everyMaps\n rw [h.every, h.f]\n rw [h.f, he]\n\ntheorem Equiv.sreach_imp {s t : SMachine} (h : Equiv s t) {ρ M} (hr : SReach s ρ M) : SReach t ρ M := by\n induction hr with\n | start ρ M hm hp hf hpf =>\n have hh := SReach.start (s := t) ρ M (by simpa only [h.f] using hm)\n (by simpa only [h.f] using hp) (by simpa only [h.facts] using hf)\n (by simpa only [SMachine.PFacts, h.pfacts] using hpf)\n simpa only [h.f] using hh\n | step ρ M ι κ hr ha ih =>\n have hh := SReach.step ρ M ι κ ih (by simpa only [h.view, h.f] using ha)\n simpa only [h.next] using hh\n\ntheorem Equiv.creach_imp {s t : SMachine} (h : Equiv s t) (ds : List CDecl) {ρ M}\n (hr : CReach s ds ρ M) : CReach t ds ρ M := by\n induction hr with\n | start ρ M hm hp hf hpf =>\n have hh := CReach.start (s := t) (ds := ds) ρ M (by simpa only [h.f] using hm)\n (by simpa only [h.f] using hp) (by simpa only [h.facts] using hf)\n (by simpa only [SMachine.PFacts, h.pfacts] using hpf)\n simpa only [h.f] using hh\n | step ρ M ι κ hr hg ha ih =>\n have hh := CReach.step ρ M ι κ ih (by simpa only [h.f, h.withCarried] using hg)\n (by simpa only [h.view, h.f] using ha)\n simpa only [h.next] using hh\n\ntheorem Equiv.symm {s t : SMachine} (h : Equiv s t) : Equiv t s :=\n ⟨h.f.symm, h.carried.symm, h.every.symm, h.facts.symm, h.pfacts.symm, fun X N => (h.flags X N).symm⟩\n\ntheorem Equiv.sreach {s t : SMachine} (h : Equiv s t) (ρ M) : SReach s ρ M ↔ SReach t ρ M :=\n ⟨h.sreach_imp, h.symm.sreach_imp⟩\n\ntheorem Equiv.creach {s t : SMachine} (h : Equiv s t) (ds : List CDecl) (ρ M) : CReach s ds ρ M ↔ CReach t ds ρ M :=\n ⟨h.creach_imp ds, h.symm.creach_imp ds⟩\n\n/-- Transport the existing count-machine checker soundness to the ORIGINAL machine. -/\ntheorem cmachine_sound (s : SMachine) (rs : List Rename) (ds : List CDecl) (ps : List CEntry)\n (hv : validAll s rs = true) (hc : checkCMachine (renameAll s rs) ds ps = true) :\n ∀ ρ M, CReach s ds ρ M → ∀ ce ∈ ps, ce.e.Holds ρ (withCnt ds ρ M) := by\n intro ρ M hr\n exact Kern.cmachine_sound (renameAll s rs) ds ps hc ρ M\n (((renameAll_equiv s rs hv).creach ds ρ M).mpr hr)\n\n/-- Transport the existing set-machine checker soundness to the ORIGINAL machine. -/\ntheorem smachine_sound (s : SMachine) (rs : List Rename) (ps : List SEntry)\n (hv : validAll s rs = true) (hc : checkSMachine (renameAll s rs) ps = true) :\n ∀ ρ M, SReach s ρ M → ∀ e ∈ ps, e.Holds ρ M := by\n intro ρ M hr\n exact Kern.smachine_sound (renameAll s rs) ps hc ρ M\n (((renameAll_equiv s rs hv).sreach ρ M).mpr hr)\n\nend Kern.QAlpha\n",
24
+ "QAlpha.lean": "import CountMachine\n\n/-! A semantic bridge for capture-avoiding alpha conversion of quantified flags.\nOnly qflags change; no checker or proof rule is modified. -/\nnamespace Kern.QAlpha\nopen Classical\n\nstructure Rename where\n flag : Nat\n old : Nat\n fresh : Nat\n deriving DecidableEq, Repr\n\ndef keys (ks : List Nat) (a b : Nat) : List Nat :=\n ks.map (fun i => if i = a then b else i)\n\ndef body (c : C) (a b : Nat) : C := substC [(a, .var b)] c\n\ndef validQ (q : Nat × List Nat × C) (r : Rename) : Bool :=\n if q.1 = r.flag then q.2.1.contains r.old && !q.2.1.contains r.fresh && !occC r.fresh q.2.2 else true\n\ndef renameQ (q : Nat × List Nat × C) (r : Rename) : Nat × List Nat × C :=\n if q.1 = r.flag then (q.1, keys q.2.1 r.old r.fresh, body q.2.2 r.old r.fresh) else q\n\ndef valid (s : SMachine) (r : Rename) : Bool := s.qflags.all (fun q => validQ q r)\ndef rename (s : SMachine) (r : Rename) : SMachine :=\n { s with qflags := s.qflags.map (fun q => renameQ q r) }\n\ndef renameAll : SMachine → List Rename → SMachine\n | s, [] => s\n | s, r :: rs => renameAll (rename s r) rs\n\ndef validAll : SMachine → List Rename → Bool\n | _, [] => true\n | s, r :: rs => valid s r && validAll (rename s r) rs\n\ntheorem mem_keys {ks : List Nat} {a b i : Nat} (hi : i ≠ b) :\n i ∈ keys ks a b ↔ i ∈ ks ∧ i ≠ a := by\n simp only [keys, List.mem_map]\n constructor\n · rintro ⟨j, hj, he⟩\n split at he <;> grind\n · rintro ⟨h, hia⟩\n exact ⟨i, h, by simp [hia]⟩\n\ntheorem eval_body (ks : List Nat) (c : C) (a b : Nat)\n (ha : a ∈ ks) (hb : b ∉ ks) (hc : occC b c = false)\n (X u v : Nat → Nat) (N : Nat → Nat → Nat)\n (hab : u a = v b) (huv : ∀ i ∈ ks, i ≠ a → u i = v i) :\n evalC (atKeys X (keys ks a b) v) N (body c a b) = evalC (atKeys X ks u) N c := by\n have hne : a ≠ b := by intro h; subst b; exact hb ha\n unfold body\n rw [subst_evalC]\n apply congrC\n intro i hi\n have hib : i ≠ b := by intro h; subst i; simp [hc] at hi\n by_cases hia : i = a\n · subst i\n have hbm : b ∈ keys ks a b := List.mem_map.mpr ⟨a, ha, by simp⟩\n simp [applyS, assoc, lookup, evalE, atKeys_in hbm, atKeys_in ha, hab]\n · have hm := mem_keys (ks := ks) (a := a) hib\n by_cases hik : i ∈ ks\n · have hmk : i ∈ keys ks a b := hm.mpr ⟨hik, hia⟩\n simp [applyS, assoc, lookup, hia, Ne.symm hia, atKeys_in hmk, atKeys_in hik, huv i hik hia]\n · have hmk : i ∉ keys ks a b := fun h => hik (hm.mp h).1\n simp [applyS, assoc, lookup, hia, Ne.symm hia, atKeys_out hmk, atKeys_out hik]\n\ntheorem quantified (ks : List Nat) (c : C) (a b : Nat)\n (ha : a ∈ ks) (hb : b ∉ ks) (hc : occC b c = false)\n (X : Nat → Nat) (N : Nat → Nat → Nat) :\n (∀ v, holdsC (atKeys X (keys ks a b) v) N (body c a b)) ↔\n (∀ u, holdsC (atKeys X ks u) N c) := by\n have hne : a ≠ b := by intro h; subst b; exact hb ha\n constructor\n · intro h u\n have hv := h (upd u b (u a))\n rw [← evalC_iff, eval_body ks c a b ha hb hc X u (upd u b (u a)) N\n (by simp [upd]) (by\n intro i hi hia\n have hib : i ≠ b := by\n intro e\n subst i\n exact hb hi\n simp [upd, hib])] at hv\n exact (evalC_iff _ _ _).mp hv\n · intro h v\n rw [← evalC_iff, eval_body ks c a b ha hb hc X (upd v a (v b)) v N\n (by simp [upd]) (by intro i hi hia; simp [upd, hia])]\n exact (evalC_iff _ _ _).mpr (h _)\n\n@[simp] theorem renameQ_flag (q : Nat × List Nat × C) (r : Rename) : (renameQ q r).1 = q.1 := by\n unfold renameQ; split <;> rfl\n\ntheorem quantifiedQ (q : Nat × List Nat × C) (r : Rename) (h : validQ q r = true)\n (X : Nat → Nat) (N : Nat → Nat → Nat) :\n (∀ k, holdsC (atKeys X (renameQ q r).2.1 k) N (renameQ q r).2.2) ↔\n (∀ k, holdsC (atKeys X q.2.1 k) N q.2.2) := by\n by_cases he : q.1 = r.flag\n · have hp : r.old ∈ q.2.1 ∧ r.fresh ∉ q.2.1 ∧ occC r.fresh q.2.2 = false := by\n simpa [validQ, he, Bool.and_eq_true, List.contains_iff_mem, and_assoc] using h\n simpa [renameQ, he] using quantified q.2.1 q.2.2 r.old r.fresh hp.1 hp.2.1 hp.2.2 X N\n · simp [renameQ, he]\n\ntheorem lookup_value (qs : List (Nat × List Nat × C)) (r : Rename)\n (h : qs.all (fun q => validQ q r) = true) (X : Nat → Nat) (N : Nat → Nat → Nat) (i : Nat) :\n (match lookup (fun q => q.1 == i) (qs.map (fun q => renameQ q r)) with\n | some q => if ∀ k, holdsC (atKeys X q.2.1 k) N q.2.2 then 1 else 0\n | none => X i) =\n (match lookup (fun q => q.1 == i) qs with\n | some q => if ∀ k, holdsC (atKeys X q.2.1 k) N q.2.2 then 1 else 0\n | none => X i) := by\n classical\n induction qs with\n | nil => rfl\n | cons q qs ih =>\n have hp : validQ q r = true ∧ qs.all (fun q => validQ q r) = true := by\n simpa only [List.all_cons, Bool.and_eq_true] using h\n by_cases hi : (q.1 == i) = true\n · simp only [List.map_cons, lookup, renameQ_flag, hi, ite_true]\n rw [quantifiedQ q r hp.1 X N]\n · simpa [List.map_cons, lookup, hi] using ih hp.2\n\ntheorem decideQ_rename (s : SMachine) (r : Rename) (h : valid s r = true)\n (X : Nat → Nat) (N : Nat → Nat → Nat) : decideQ (rename s r) X N = decideQ s X N := by\n classical\n funext i\n exact lookup_value s.qflags r h X N i\n\n/-- The complete semantic interface, independent of checker acceptance. -/\nstructure Equiv (s t : SMachine) : Prop where\n f : s.f = t.f\n carried : s.carried = t.carried\n every : s.every = t.every\n facts : s.facts = t.facts\n pfacts : s.pfacts = t.pfacts\n flags : ∀ X N, decideQ s X N = decideQ t X N\n\ntheorem Equiv.refl (s : SMachine) : Equiv s s := ⟨rfl, rfl, rfl, rfl, rfl, fun _ _ => rfl⟩\ntheorem Equiv.trans {s t u : SMachine} (h : Equiv s t) (g : Equiv t u) : Equiv s u :=\n ⟨h.f.trans g.f, h.carried.trans g.carried, h.every.trans g.every,\n h.facts.trans g.facts, h.pfacts.trans g.pfacts, fun X N => (h.flags X N).trans (g.flags X N)⟩\ntheorem rename_equiv (s : SMachine) (r : Rename) (h : valid s r = true) : Equiv (rename s r) s :=\n ⟨rfl, rfl, rfl, rfl, rfl, decideQ_rename s r h⟩\n\ntheorem renameAll_equiv (s : SMachine) (rs : List Rename) (h : validAll s rs = true) :\n Equiv (renameAll s rs) s := by\n induction rs generalizing s with\n | nil => exact Equiv.refl s\n | cons r rs ih =>\n have hp : valid s r = true ∧ validAll (rename s r) rs = true := by\n simpa only [validAll, Bool.and_eq_true] using h\n exact (ih (rename s r) hp.2).trans (rename_equiv s r hp.1)\n\ntheorem Equiv.withCarried {s t : SMachine} (h : Equiv s t) (M κ : Nat → Nat → Nat) :\n Kern.withCarried s M κ = Kern.withCarried t M κ := by\n funext mp key\n change (if s.carried.contains mp then κ mp else M mp) key =\n (if t.carried.contains mp then κ mp else M mp) key\n rw [h.carried]\n\ntheorem Equiv.view {s t : SMachine} (h : Equiv s t) (ρ ι : Nat → Nat) (M κ : Nat → Nat → Nat) :\n sView s ρ M ι κ = sView t ρ M ι κ := by\n simp only [sView, h.f, h.withCarried, h.flags]\n\ntheorem Equiv.next {s t : SMachine} (h : Equiv s t) (ρ ι : Nat → Nat) (M κ : Nat → Nat → Nat) :\n sNext s ρ M ι κ = sNext t ρ M ι κ := by\n simp only [sNext, h.view]\n have he : Kern.everyMaps s = Kern.everyMaps t := by\n funext D N mp key\n unfold Kern.everyMaps\n rw [h.every, h.f]\n rw [h.f, he]\n\ntheorem Equiv.sreach_imp {s t : SMachine} (h : Equiv s t) {ρ M} (hr : SReach s ρ M) : SReach t ρ M := by\n induction hr with\n | start ρ M hm hp hf hpf =>\n have hh := SReach.start (s := t) ρ M (by simpa only [h.f] using hm)\n (by simpa only [h.f] using hp) (by simpa only [h.facts] using hf)\n (by simpa only [SMachine.PFacts, h.pfacts] using hpf)\n simpa only [h.f] using hh\n | step ρ M ι κ hr ha ih =>\n have hh := SReach.step ρ M ι κ ih (by simpa only [h.view, h.f] using ha)\n simpa only [h.next] using hh\n\ntheorem Equiv.creach_imp {s t : SMachine} (h : Equiv s t) (ds : List CDecl) {ρ M}\n (hr : CReach s ds ρ M) : CReach t ds ρ M := by\n induction hr with\n | start ρ M hm hp hf hpf =>\n have hh := CReach.start (s := t) (ds := ds) ρ M (by simpa only [h.f] using hm)\n (by simpa only [h.f] using hp) (by simpa only [h.facts] using hf)\n (by simpa only [SMachine.PFacts, h.pfacts] using hpf)\n simpa only [h.f] using hh\n | step ρ M ι κ hr hg ha ih =>\n have hh := CReach.step ρ M ι κ ih (by simpa only [h.f, h.withCarried] using hg)\n (by simpa only [h.view, h.f] using ha)\n simpa only [h.next] using hh\n\ntheorem Equiv.symm {s t : SMachine} (h : Equiv s t) : Equiv t s :=\n ⟨h.f.symm, h.carried.symm, h.every.symm, h.facts.symm, h.pfacts.symm, fun X N => (h.flags X N).symm⟩\n\ntheorem Equiv.sreach {s t : SMachine} (h : Equiv s t) (ρ M) : SReach s ρ M ↔ SReach t ρ M :=\n ⟨h.sreach_imp, h.symm.sreach_imp⟩\n\ntheorem Equiv.creach {s t : SMachine} (h : Equiv s t) (ds : List CDecl) (ρ M) : CReach s ds ρ M ↔ CReach t ds ρ M :=\n ⟨h.creach_imp ds, h.symm.creach_imp ds⟩\n\n/-- Transport the existing count-machine checker soundness to the ORIGINAL machine. -/\ntheorem cmachine_sound (s : SMachine) (rs : List Rename) (ds : List CDecl) (ps : List CEntry)\n (hv : validAll s rs = true) (hc : checkCMachine (renameAll s rs) ds ps = true) :\n ∀ ρ M, CReach s ds ρ M → ∀ ce ∈ ps, ce.e.Holds ρ (withCnt ds ρ M) := by\n intro ρ M hr\n exact Kern.cmachine_sound (renameAll s rs) ds ps hc ρ M\n (((renameAll_equiv s rs hv).creach ds ρ M).mpr hr)\n\n/-- The same transport for the family check that carries each certificate's cuts. -/\ntheorem cmachineF_sound (s : SMachine) (rs : List Rename) (ds : List CDecl) (ps : List CEntryF)\n (hv : validAll s rs = true) (hc : checkCMachineF (renameAll s rs) ds ps = true) :\n ∀ ρ M, CReach s ds ρ M → ∀ ce ∈ ps, ce.e.Holds ρ (withCnt ds ρ M) := by\n intro ρ M hr\n exact Kern.cmachineF_sound (renameAll s rs) ds ps hc ρ M\n (((renameAll_equiv s rs hv).creach ds ρ M).mpr hr)\n\n/-- Transport the existing set-machine checker soundness to the ORIGINAL machine. -/\ntheorem smachine_sound (s : SMachine) (rs : List Rename) (ps : List SEntry)\n (hv : validAll s rs = true) (hc : checkSMachine (renameAll s rs) ps = true) :\n ∀ ρ M, SReach s ρ M → ∀ e ∈ ps, e.Holds ρ M := by\n intro ρ M hr\n exact Kern.smachine_sound (renameAll s rs) ps hc ρ M\n (((renameAll_equiv s rs hv).sreach ρ M).mpr hr)\n\nend Kern.QAlpha\n",
25
+ "RowAlpha.lean": "import QAlpha\n\nnamespace Kern.RowAlpha\nopen Classical\n\nstructure Rename where\n mp : Nat\n old : Nat\n fresh : Nat\n deriving DecidableEq, Repr\n\ndef renameRow (w : Nat × Nat × E) (r : Rename) : Nat × Nat × E :=\n if w.1 = r.mp then (w.1, r.fresh, substE [(r.old, .var r.fresh)] w.2.2) else w\n\ndef validRow (w : Nat × Nat × E) (r : Rename) : Bool :=\n if w.1 = r.mp then (w.2.1 == r.old) && !occE r.fresh w.2.2 else true\n\ndef rename (s : SMachine) (r : Rename) : SMachine :=\n { s with every := s.every.map (fun w => renameRow w r) }\n\ndef valid (s : SMachine) (r : Rename) : Bool := s.every.all (fun w => validRow w r)\n\ndef renameAll : SMachine → List Rename → SMachine\n | s, [] => s\n | s, r :: rs => renameAll (rename s r) rs\n\ndef validAll : SMachine → List Rename → Bool\n | _, [] => true\n | s, r :: rs => valid s r && validAll (rename s r) rs\n\n@[simp] theorem renameRow_mp (w : Nat × Nat × E) (r : Rename) : (renameRow w r).1 = w.1 := by\n unfold renameRow; split <;> rfl\n\ntheorem eval_row (e : E) (a b : Nat) (h : occE b e = false)\n (D : Nat → Nat) (N : Nat → Nat → Nat) (key : Nat) :\n evalE (upd D b key) N (substE [(a, .var b)] e) = evalE (upd D a key) N e := by\n rw [subst_evalE, applyS_single]\n apply congrE\n intro i hi\n have hib : i ≠ b := by intro he; subst i; simp [h] at hi\n by_cases hia : i = a\n · subst i; simp [upd, evalE]\n · simp [upd, evalE, hia, hib]\n\ntheorem row_value (w : Nat × Nat × E) (r : Rename) (h : validRow w r = true)\n (D : Nat → Nat) (N : Nat → Nat → Nat) (key : Nat) :\n evalE (upd D (renameRow w r).2.1 key) N (renameRow w r).2.2 =\n evalE (upd D w.2.1 key) N w.2.2 := by\n by_cases he : w.1 = r.mp\n · have hp : w.2.1 = r.old ∧ occE r.fresh w.2.2 = false := by\n simpa [validRow, he, Bool.and_eq_true] using h\n simpa [renameRow, he, hp.1] using eval_row w.2.2 r.old r.fresh hp.2 D N key\n · simp [renameRow, he]\n\ntheorem lookup_value (ws : List (Nat × Nat × E)) (r : Rename)\n (h : ws.all (fun w => validRow w r) = true) (D : Nat → Nat)\n (N : Nat → Nat → Nat) (mp key : Nat) (fallback : Nat) :\n (match lookup (fun w => w.1 == mp) (ws.map (fun w => renameRow w r)) with\n | some w => evalE (upd D w.2.1 key) N w.2.2\n | none => fallback) =\n (match lookup (fun w => w.1 == mp) ws with\n | some w => evalE (upd D w.2.1 key) N w.2.2\n | none => fallback) := by\n induction ws with\n | nil => rfl\n | cons w ws ih =>\n have hp : validRow w r = true ∧ ws.all (fun w => validRow w r) = true := by\n simpa only [List.all_cons, Bool.and_eq_true] using h\n by_cases hi : (w.1 == mp) = true\n · simpa only [List.map_cons, lookup, renameRow_mp, hi, ite_true] using row_value w r hp.1 D N key\n · simpa [List.map_cons, lookup, hi] using ih hp.2\n\ntheorem everyMaps_rename (s : SMachine) (r : Rename) (h : valid s r = true) :\n everyMaps (rename s r) = everyMaps s := by\n funext D N mp key\n exact lookup_value s.every r h D N mp key (writeMaps s.f.m.writes D N mp key)\n\nstructure Equiv (s t : SMachine) : Prop where\n f : s.f = t.f\n carried : s.carried = t.carried\n every : everyMaps s = everyMaps t\n facts : s.facts = t.facts\n pfacts : s.pfacts = t.pfacts\n flags : ∀ X N, decideQ s X N = decideQ t X N\n\ntheorem Equiv.refl (s : SMachine) : Equiv s s := ⟨rfl, rfl, rfl, rfl, rfl, fun _ _ => rfl⟩\ntheorem Equiv.trans {s t u : SMachine} (h : Equiv s t) (g : Equiv t u) : Equiv s u :=\n ⟨h.f.trans g.f, h.carried.trans g.carried, h.every.trans g.every,\n h.facts.trans g.facts, h.pfacts.trans g.pfacts, fun X N => (h.flags X N).trans (g.flags X N)⟩\ntheorem Equiv.symm {s t : SMachine} (h : Equiv s t) : Equiv t s :=\n ⟨h.f.symm, h.carried.symm, h.every.symm, h.facts.symm, h.pfacts.symm, fun X N => (h.flags X N).symm⟩\n\ntheorem rename_equiv (s : SMachine) (r : Rename) (h : valid s r = true) : Equiv (rename s r) s :=\n ⟨rfl, rfl, everyMaps_rename s r h, rfl, rfl, fun _ _ => rfl⟩\n\ntheorem renameAll_equiv (s : SMachine) (rs : List Rename) (h : validAll s rs = true) :\n Equiv (renameAll s rs) s := by\n induction rs generalizing s with\n | nil => exact Equiv.refl s\n | cons r rs ih =>\n have hp : valid s r = true ∧ validAll (rename s r) rs = true := by\n simpa only [validAll, Bool.and_eq_true] using h\n exact (ih (rename s r) hp.2).trans (rename_equiv s r hp.1)\n\ntheorem Equiv.withCarried {s t : SMachine} (h : Equiv s t) (M κ : Nat → Nat → Nat) :\n Kern.withCarried s M κ = Kern.withCarried t M κ := by\n funext mp key\n change (if s.carried.contains mp then κ mp else M mp) key =\n (if t.carried.contains mp then κ mp else M mp) key\n rw [h.carried]\n\ntheorem Equiv.view {s t : SMachine} (h : Equiv s t) (ρ ι : Nat → Nat) (M κ : Nat → Nat → Nat) :\n sView s ρ M ι κ = sView t ρ M ι κ := by\n simp only [sView, h.f, h.withCarried, h.flags]\n\ntheorem Equiv.next {s t : SMachine} (h : Equiv s t) (ρ ι : Nat → Nat) (M κ : Nat → Nat → Nat) :\n sNext s ρ M ι κ = sNext t ρ M ι κ := by\n simp only [sNext, h.view, h.f, h.every]\n\ntheorem Equiv.sreach_imp {s t : SMachine} (h : Equiv s t) {ρ M} (hr : SReach s ρ M) : SReach t ρ M := by\n induction hr with\n | start ρ M hm hp hf hpf =>\n have hh := SReach.start (s := t) ρ M (by simpa only [h.f] using hm)\n (by simpa only [h.f] using hp) (by simpa only [h.facts] using hf)\n (by simpa only [SMachine.PFacts, h.pfacts] using hpf)\n simpa only [h.f] using hh\n | step ρ M ι κ hr ha ih =>\n have hh := SReach.step ρ M ι κ ih (by simpa only [h.view, h.f] using ha)\n simpa only [h.next] using hh\n\ntheorem Equiv.creach_imp {s t : SMachine} (h : Equiv s t) (ds : List CDecl) {ρ M}\n (hr : CReach s ds ρ M) : CReach t ds ρ M := by\n induction hr with\n | start ρ M hm hp hf hpf =>\n have hh := CReach.start (s := t) (ds := ds) ρ M (by simpa only [h.f] using hm)\n (by simpa only [h.f] using hp) (by simpa only [h.facts] using hf)\n (by simpa only [SMachine.PFacts, h.pfacts] using hpf)\n simpa only [h.f] using hh\n | step ρ M ι κ hr hg ha ih =>\n have hh := CReach.step ρ M ι κ ih (by simpa only [h.f, h.withCarried] using hg)\n (by simpa only [h.view, h.f] using ha)\n simpa only [h.next] using hh\n\ntheorem Equiv.sreach {s t : SMachine} (h : Equiv s t) (ρ M) : SReach s ρ M ↔ SReach t ρ M :=\n ⟨h.sreach_imp, h.symm.sreach_imp⟩\ntheorem Equiv.creach {s t : SMachine} (h : Equiv s t) (ds : List CDecl) (ρ M) : CReach s ds ρ M ↔ CReach t ds ρ M :=\n ⟨h.creach_imp ds, h.symm.creach_imp ds⟩\n\nend Kern.RowAlpha\n",
26
+ "BoundGhost.lean": "import GhostMap\n\nnamespace Kern\n\n/-- Equal initial values, or a shared update at the key, suffice for equal results. -/\ntheorem updAll_congr_at {X X' : Nat → Nat} {i : Nat} (l : List (Nat × Nat))\n (h : X i = X' i ∨ i ∈ l.map (·.1)) : updAll X l i = updAll X' l i := by\n induction l generalizing X X' with\n | nil => simpa [updAll] using h\n | cons p ps ih =>\n apply ih\n simp only [List.map_cons, List.mem_cons] at h\n rcases h with h | h | h\n · left; simp only [upd]; split <;> simp_all\n · left; simp [upd, h]\n · exact Or.inr h\n\n/-- Shared updates make bound keys agree; other non-ghost keys already agreed. -/\ntheorem updAll_agree_bound {V : List Nat} {X X' : Nat → Nat} (h : Agree V X X')\n (l : List (Nat × Nat)) : Agree (V.filter fun v => !(l.map (·.1)).contains v) (updAll X l) (updAll X' l) := by\n intro i hi\n apply updAll_congr_at\n by_cases hk : i ∈ l.map (·.1)\n · exact Or.inr hk\n · left\n apply h i\n intro hv\n apply hi\n apply List.mem_filter.mpr\n exact ⟨hv, by simpa using hk⟩\n\ntheorem some_of_subst_bound_apart {V MS : List Nat} (σ : List (Nat × E)) (c : C)\n (hav : avoids (V.filter fun v => !(σ.map (·.1)).contains v) c = true)\n (ham : avoidsMaps MS c = true) {ρg ρ : Nat → Nat} {Mg M : Nat → Nat → Nat}\n (hag : Agree V ρg ρ) (hmag : ∀ mp, mp ∉ MS → Mg mp = M mp)\n (h : evalC ρg Mg (substC σ c) = true) :\n ∃ f : Nat → Nat, evalC (updAll ρ ((σ.map (·.1)).map fun i => (i, f i))) M c = true := by\n refine ⟨fun i => applyS σ ρg Mg i, ?_⟩\n have h1 := some_of_subst σ c ρg Mg h\n have hx := updAll_agree_bound hag ((σ.map (·.1)).map fun i => (i, applyS σ ρg Mg i))\n have hx' : Agree (V.filter fun v => !(σ.map (·.1)).contains v)\n (updAll ρg ((σ.map (·.1)).map fun i => (i, applyS σ ρg Mg i)))\n (updAll ρ ((σ.map (·.1)).map fun i => (i, applyS σ ρg Mg i))) := by\n simpa [List.map_map, Function.comp_def] using hx\n rw [congrC _ _ M _ (fun i hi => (hx' i (avoids_occ hav hi)).symm),\n congrMC _ M Mg _ (fun mp hmp => (hmag mp (avoidsMaps_occ ham hmp)).symm)]\n exact h1\n\ntheorem forall_some_of_ghostsubst_bound (g : SGhostedM) (hg : smghostOk g = true) (ps : List SEntry) (hl : checkSMachine g.full ps = true)\n (e : SEntry) (he : e ∈ ps) (σ : List (Nat × E)) (c : C) (hsub : e.law.holds = substC σ c)\n (hav : avoids (g.vars.filter fun v => !(σ.map (·.1)).contains v) c = true) (ham : avoidsMaps g.maps c = true) :\n ∀ ρ M, SReach g.orig ρ M → ExHolds c e.law.key (σ.map (·.1)) M e.keys2 ρ := by\n intro ρ M hr\n obtain ⟨ρg, Mg, hrg, hag, hmag⟩ := smghost_reach g hg hr\n have hall := smachine_sound g.full ps hl ρg Mg hrg e he\n simp only [SEntry.Holds] at hall\n -- (along the further keys, each at the same value on both sides)\n have go : ∀ (gs : List Nat) (ρg ρ : Nat → Nat), Agree g.vars ρg ρ → holdsOver e.law Mg gs ρg → ExHolds c e.law.key (σ.map (·.1)) M gs ρ := by\n intro gs\n induction gs with\n | nil =>\n intro ρg ρ hag h\n simp only [holdsOver, MLaw.Holds] at h\n cases hk : e.law.key with\n | none =>\n simp only [hk, hsub] at h\n simp only [ExHolds]\n exact some_of_subst_bound_apart σ c hav ham hag hmag h\n | some kv =>\n simp only [hk, hsub] at h\n simp only [ExHolds]\n intro v\n exact some_of_subst_bound_apart σ c hav ham (upd_agree hag kv v) hmag (h v)\n | cons k gs ih =>\n intro ρg ρ hag h w\n exact ih (upd ρg k w) (upd ρ k w) (upd_agree hag k w) (h w)\n exact go e.keys2 ρg ρ hag hall\n\nend Kern\n\n#print axioms Kern.updAll_congr_at\n#print axioms Kern.some_of_subst_bound_apart\n#print axioms Kern.forall_some_of_ghostsubst_bound\n",
27
+ "CountedSourceProjection.lean": "import CountMachine\nimport GhostMap\n\nnamespace Kern\n\n/-- Agreement of maps observable by the source. -/\ndef PublicMaps (fresh : List Nat) (M N : Nat → Nat → Nat) : Prop :=\n ∀ mp, mp ∉ fresh → M mp = N mp\n\n/-- The exact semantic obligation remaining for a source step: a producer request\n can be chosen which satisfies its counts, preserves the assumption, and has\n the same scalar successor and public map successor. No source assumption is\n weakened, and this does not assert any freshness property. -/\ndef CountedStepExtension (s : SMachine) (source producer : List CDecl)\n (fresh : List Nat) : Prop :=\n ∀ ρ M N ι κ, PublicMaps fresh N M →\n GHolds source (withInputs s.f.m.inputs ρ ι) (withCarried s M κ) →\n evalC (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 s.f.m.assume = true →\n ∃ κ', GHolds producer (withInputs s.f.m.inputs ρ ι) (withCarried s N κ') ∧\n evalC (sView s ρ N ι κ').1 (sView s ρ N ι κ').2 s.f.m.assume = true ∧\n (sNext s ρ N ι κ').1 = (sNext s ρ M ι κ).1 ∧\n PublicMaps fresh (sNext s ρ N ι κ').2 (sNext s ρ M ι κ).2\n\n/-- A simulation with an explicit step-extension premise; start is shared\n exactly, whereas subsequent map states need only agree publicly. -/\ntheorem counted_source_reach {s : SMachine} {source producer : List CDecl}\n {fresh : List Nat} (hstep : CountedStepExtension s source producer fresh) :\n ∀ {ρ M}, CReach s source ρ M →\n ∃ N, CReach s producer ρ N ∧ PublicMaps fresh N M := by\n intro ρ M hr\n induction hr with\n | start ρ M hM hp hf hpf =>\n exact ⟨M, CReach.start ρ M hM hp hf hpf, fun _ _ => rfl⟩\n | step ρ M ι κ hr hg ha ih =>\n obtain ⟨N, hn, hag⟩ := ih\n obtain ⟨κ', hg', ha', hs, hm⟩ := hstep ρ M N ι κ hag hg ha\n have hnext := CReach.step ρ N ι κ' hn hg' ha'\n rw [hs] at hnext\n exact ⟨_, hnext, hm⟩\n\n/-- Producer counts can always be constructed while keeping every non-count\n request map unchanged. This is the kernel's checked count construction. -/\ntheorem producer_request_counts (s : SMachine) (ds : List CDecl)\n (hd : cDistinct (cMaps ds) = true)\n (hc : ∀ d ∈ ds, d.mp ∈ s.carried)\n (hav : ∀ d ∈ ds, avoidsMapsE (cMaps ds) d.below = true ∧ avoidsMapsE (cMaps ds) d.body = true)\n (ρ : Nat → Nat) (M : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat) :\n ∃ κ', (∀ mp, mp ∉ cMaps ds → withCarried s M κ' mp = withCarried s M κ mp) ∧\n GHolds ds (withInputs s.f.m.inputs ρ ι) (withCarried s M κ') :=\n counts_exist s ds hd hc hav ρ M ι κ\n\n/-- Construct producer request counts without changing any public request map.\n Public producer declarations must already be source declarations; all extra\n maps are fresh, and freshness names only producer count maps. -/\ntheorem producer_request_public (s : SMachine) (source producer : List CDecl)\n (fresh : List Nat) (hd : cDistinct (cMaps producer) = true)\n (hc : ∀ d ∈ producer, d.mp ∈ s.carried)\n (hav : ∀ d ∈ producer, avoidsMapsE (cMaps producer) d.below = true ∧ avoidsMapsE (cMaps producer) d.body = true)\n (hkey : ∀ d ∈ producer, occE d.key d.below = false)\n (hsub : ∀ mp ∈ fresh, mp ∈ cMaps producer)\n (hpublic : ∀ d ∈ producer, d.mp ∉ fresh → d ∈ source)\n (ρ : Nat → Nat) (M N : Nat → Nat → Nat) (ι : Nat → Nat) (κ : Nat → Nat → Nat)\n (hag : PublicMaps fresh N M)\n (hs : GHolds source (withInputs s.f.m.inputs ρ ι) (withCarried s M κ)) :\n ∃ κ', GHolds producer (withInputs s.f.m.inputs ρ ι) (withCarried s N κ') ∧\n PublicMaps fresh (withCarried s N κ') (withCarried s M κ) := by\n obtain ⟨κ', hoff, hg⟩ := counts_exist s producer hd hc hav ρ N ι κ\n have hbase : ∀ mp, mp ∉ cMaps producer →\n withCarried s N κ' mp = withCarried s M κ mp := by\n intro mp hm\n rw [hoff mp hm]\n unfold withCarried\n split\n · rfl\n · exact hag mp (fun hf => hm (hsub mp hf))\n refine ⟨κ', hg, ?_⟩\n intro mp hm\n by_cases hp : mp ∈ cMaps producer\n · obtain ⟨d, hdp, heq⟩ := List.mem_map.mp hp\n subst mp\n funext x\n rw [hg d hdp x, hs d (hpublic d hdp hm) x]\n apply cntOf_congr d (hkey d hdp)\n · intro i _ _ _ _; rfl\n · intro m hor\n apply hbase m\n rcases hor with hb | hb\n · exact avoidsMapsE_occ (hav d hdp).1 hb\n · exact avoidsMapsE_occ (hav d hdp).2 hb\n · exact hbase mp hp\n\n/-- The two interpretations of public count maps agree, including original\n source counts, when added declarations are confined to fresh maps. -/\ntheorem withCnt_public (source producer : List CDecl) (fresh : List Nat)\n (hsd : cDistinct (cMaps source) = true)\n (hpd : cDistinct (cMaps producer) = true)\n (hsource : ∀ d ∈ source, d ∈ producer)\n (hpublic : ∀ d ∈ producer, d.mp ∉ fresh → d ∈ source)\n (hkey : ∀ d ∈ producer, occE d.key d.below = false)\n (hav : ∀ d ∈ producer, avoidsMapsE fresh d.below = true ∧ avoidsMapsE fresh d.body = true)\n (ρ : Nat → Nat) (M N : Nat → Nat → Nat) (hag : PublicMaps fresh N M) :\n PublicMaps fresh (withCnt producer ρ N) (withCnt source ρ M) := by\n intro mp hm\n by_cases hp : mp ∈ cMaps producer\n · obtain ⟨d, hdp, heq⟩ := List.mem_map.mp hp\n subst mp\n rw [withCnt_at hpd hdp, withCnt_at hsd (hpublic d hdp hm)]\n funext x\n apply cntOf_congr d (hkey d hdp)\n · intro i _ _ _ _; rfl\n · intro m hor\n apply hag m\n rcases hor with hb | hb\n · exact avoidsMapsE_occ (hav d hdp).1 hb\n · exact avoidsMapsE_occ (hav d hdp).2 hb\n · have hs : mp ∉ cMaps source := by\n intro hs\n obtain ⟨d, hd, heq⟩ := List.mem_map.mp hs\n apply hp\n exact List.mem_map.mpr ⟨d, hsource d hd, heq⟩\n rw [withCnt_other hp, withCnt_other hs]\n exact hag mp hm\n\n/-- Semantic noninterference of the machine with respect to fresh maps. This\n concerns only the machine, not count declarations or reachable states. -/\ndef MachinePublicStep (s : SMachine) (fresh : List Nat) : Prop :=\n ∀ ρ M N ι κ κ', PublicMaps fresh N M →\n PublicMaps fresh (withCarried s N κ') (withCarried s M κ) →\n evalC (sView s ρ N ι κ').1 (sView s ρ N ι κ').2 s.f.m.assume =\n evalC (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 s.f.m.assume ∧\n (sNext s ρ N ι κ').1 = (sNext s ρ M ι κ).1 ∧\n PublicMaps fresh (sNext s ρ N ι κ').2 (sNext s ρ M ι κ).2\n\n/-- Reduce step extension to count-declaration conditions and the machine's\n independently stated public-map noninterference. -/\ntheorem counted_step_of_public (s : SMachine) (source producer : List CDecl)\n (fresh : List Nat) (hd : cDistinct (cMaps producer) = true)\n (hc : ∀ d ∈ producer, d.mp ∈ s.carried)\n (hav : ∀ d ∈ producer, avoidsMapsE (cMaps producer) d.below = true ∧ avoidsMapsE (cMaps producer) d.body = true)\n (hkey : ∀ d ∈ producer, occE d.key d.below = false)\n (hsub : ∀ mp ∈ fresh, mp ∈ cMaps producer)\n (hpublic : ∀ d ∈ producer, d.mp ∉ fresh → d ∈ source)\n (hmachine : MachinePublicStep s fresh) : CountedStepExtension s source producer fresh := by\n intro ρ M N ι κ hag hg ha\n obtain ⟨κ', hc', hm⟩ := producer_request_public s source producer fresh hd hc hav hkey hsub hpublic ρ M N ι κ hag hg\n obtain ⟨he, hn, hw⟩ := hmachine ρ M N ι κ κ' hag hm\n exact ⟨κ', hc', he.trans ha, hn, hw⟩\n\n/-- When the interpreted maps agree publicly, a source law avoiding the fresh\n maps transfers without identifying the raw maps or the count declarations. -/\ntheorem source_law_transfer (e : SEntry) (fresh : List Nat)\n (havoid : avoidsMaps fresh e.law.holds = true) {ρ : Nat → Nat}\n {M N : Nat → Nat → Nat} (hag : PublicMaps fresh N M)\n (h : e.Holds ρ N) : e.Holds ρ M := by\n exact holdsOver_maps havoid (fun mp hm => (hag mp hm).symm) e.keys2 ρ h\n\nend Kern\n",
28
+ "CountedNoninterference.lean": "import CountedSourceProjection\n\nnamespace Kern\nopen Classical\n\n/-- Finite syntactic read footprint of a step. -/\ndef StepAvoids (s : SMachine) (fresh : List Nat) : Prop :=\n avoidsMaps fresh s.f.m.assume = true ∧\n (∀ p ∈ s.f.flags, avoidsMaps fresh p.2 = true) ∧\n (∀ q ∈ s.qflags, avoidsMaps fresh q.2.2 = true) ∧\n (∀ p ∈ s.f.m.step, avoidsMapsE fresh p.2 = true) ∧\n (∀ w ∈ s.f.m.writes, avoidsMapsE fresh w.2.1 = true ∧ avoidsMapsE fresh w.2.2 = true) ∧\n (∀ w ∈ s.every, avoidsMapsE fresh w.2.2 = true)\n\n /-- Executable finite check suitable for generated `by decide` certificates. -/\ndef stepAvoidsCheck (s : SMachine) (fresh : List Nat) : Bool :=\n avoidsMaps fresh s.f.m.assume &&\n s.f.flags.all (fun p => avoidsMaps fresh p.2) &&\n s.qflags.all (fun q => avoidsMaps fresh q.2.2) &&\n s.f.m.step.all (fun p => avoidsMapsE fresh p.2) &&\n s.f.m.writes.all (fun w => avoidsMapsE fresh w.2.1 && avoidsMapsE fresh w.2.2) &&\n s.every.all (fun w => avoidsMapsE fresh w.2.2)\n\ntheorem stepAvoids_of_check (s : SMachine) (fresh : List Nat)\n (h : stepAvoidsCheck s fresh = true) : StepAvoids s fresh := by\n simp only [stepAvoidsCheck, Bool.and_eq_true, List.all_eq_true] at h\n exact ⟨h.1.1.1.1.1, h.1.1.1.1.2, h.1.1.1.2, h.1.1.2, h.1.2, h.2⟩\n\n/-- Identical machine except for request-carried map names. Agreement of its\nrequest views suffices even when the carried lists differ on fresh names. -/\ntheorem step_avoids_two (s : SMachine) (fresh extra : List Nat)\n (h : StepAvoids s fresh) :\n ∀ ρ M N ι κ κ',\n PublicMaps fresh (withCarried {s with carried := s.carried ++ extra} N κ') (withCarried s M κ) →\n evalC (sView {s with carried := s.carried ++ extra} ρ N ι κ').1 (sView {s with carried := s.carried ++ extra} ρ N ι κ').2 s.f.m.assume =\n evalC (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 s.f.m.assume ∧\n (sNext {s with carried := s.carried ++ extra} ρ N ι κ').1 = (sNext s ρ M ι κ).1 ∧\n PublicMaps fresh (sNext {s with carried := s.carried ++ extra} ρ N ι κ').2 (sNext s ρ M ι κ).2 := by\n intro ρ M N ι κ κ' hN\n obtain ⟨ha, hf, hq, hs, hw, he⟩ := h\n let t : SMachine := {s with carried := s.carried ++ extra}\n let X := withInputs s.f.m.inputs ρ ι\n let A := withCarried t N κ'\n let B := withCarried s M κ\n have hQ : decideQ t X A = decideQ s X B := by\n funext v\n rw [decideQ_of, decideQ_of]\n change (match lookup (fun q => q.1 == v) s.qflags with\n | some q => if ∀ k, holdsC (atKeys X q.2.1 k) A q.2.2 then 1 else 0\n | none => X v) = _\n cases hl : lookup (fun q => q.1 == v) s.qflags with\n | some q =>\n exact ite_all_congr (fun _ _ _ => rfl) (fun mp hm => hN mp (avoidsMaps_occ (hq q (lookup_some hl).1) hm))\n | none => rfl\n have hD : decideFlags s.f.flags (decideQ t X A) A = decideFlags s.f.flags (decideQ s X B) B := by\n apply funext; intro i\n have hd := decide_apart (V := []) (MS := fresh) (fun p hp => by simpa [apartC, avoids] using hf p hp)\n (X := decideQ t X A) (X' := decideQ s X B) (N := A) (N' := B)\n (fun i _ => congrFun hQ i) hN\n exact hd i (by simp)\n have hc {c : C} (havoid : avoidsMaps fresh c = true) :\n evalC (decideFlags s.f.flags (decideQ t X A) A) A c =\n evalC (decideFlags s.f.flags (decideQ s X B) B) B c := by\n rw [hD]; exact congrMC _ _ _ c (fun mp hm => hN mp (avoidsMaps_occ havoid hm))\n have hx {e : E} (havoid : avoidsMapsE fresh e = true) :\n evalE (decideFlags s.f.flags (decideQ t X A) A) A e =\n evalE (decideFlags s.f.flags (decideQ s X B) B) B e := by\n rw [hD]; exact congrME _ _ _ e (fun mp hm => hN mp (avoidsMapsE_occ havoid hm))\n refine ⟨hc ha, ?_, ?_⟩\n · funext i\n simp only [sNext, sView, applyS]\n cases hst : assoc s.f.m.step i with\n | none => exact congrFun hD i\n | some e =>\n have hm : (i, e) ∈ s.f.m.step := by\n simp only [assoc, Option.map_eq_some_iff] at hst\n obtain ⟨q, hq', rfl⟩ := hst\n obtain ⟨hqm, hqv⟩ := lookup_some hq'\n simp only [beq_iff_eq] at hqv\n rw [← hqv]; exact hqm\n exact hx (hs (i,e) hm)\n · intro mp hmp\n funext key\n simp only [sNext, sView, everyMaps]\n change (match lookup (fun w => w.1 == mp) s.every with\n | some w => evalE (upd _ w.2.1 key) A w.2.2\n | none => writeMaps s.f.m.writes _ A mp key) = _\n cases hl : lookup (fun w => w.1 == mp) s.every with\n | some w =>\n rw [hD]\n exact congrME _ _ _ _ (fun m hm => hN m (avoidsMapsE_occ (he w (lookup_some hl).1) hm))\n | none =>\n simp only [writeMaps]\n cases hl2 : lookup (fun w => w.1 == mp) s.f.m.writes with\n | none => exact congrFun (hN mp hmp) key\n | some w =>\n obtain ⟨h1, h2⟩ := hw w (lookup_some hl2).1\n dsimp only\n have hn : A mp = B mp := hN mp hmp\n rw [hx h1, hx h2, hn]\n\n/-- The same-machine public-step property follows from finite syntax alone. -/\ntheorem step_avoids_public (s : SMachine) (fresh : List Nat)\n (h : StepAvoids s fresh) : MachinePublicStep s fresh := by\n intro ρ M N ι κ κ' _ hN\n have ht : ({s with carried := s.carried ++ []} : SMachine) = s := by cases s; simp\n have hh := step_avoids_two s fresh [] h\n rw [ht] at hh\n exact hh ρ M N ι κ κ' hN\n\n\nend Kern\n",
29
+ "CountedSourceBridge.lean": "import CountedNoninterference\n\nnamespace Kern\n\n/-- Extending carried names is idempotent when supplied the original request view. -/\ntheorem bapa_withCarried_from_view (s : SMachine) (extra : List Nat)\n (M κ : Nat → Nat → Nat) :\n withCarried {s with carried := s.carried ++ extra} M (withCarried s M κ) = withCarried s M κ := by\n funext mp\n simp only [withCarried, List.contains_append]\n cases hs : s.carried.contains mp <;> cases he : extra.contains mp <;> simp [hs, he]\n\n/-- A source run lifts to the same machine with additional carried count maps.\nOnly public-map agreement is asserted: fresh maps are not equated to arbitrary\nsource maps. Every premise below is about finite declarations or source syntax. -/\ntheorem bapa_counted_source_reach (s : SMachine) (source producer : List CDecl)\n (fresh extra : List Nat)\n (hd : cDistinct (cMaps producer) = true)\n (hc : ∀ d ∈ producer, d.mp ∈ s.carried ++ extra)\n (hav : ∀ d ∈ producer, avoidsMapsE (cMaps producer) d.below = true ∧ avoidsMapsE (cMaps producer) d.body = true)\n (hkey : ∀ d ∈ producer, occE d.key d.below = false)\n (hsub : ∀ mp ∈ fresh, mp ∈ cMaps producer)\n (hpublic : ∀ d ∈ producer, d.mp ∉ fresh → d ∈ source)\n (havoid : StepAvoids s fresh) :\n ∀ {ρ M}, CReach s source ρ M →\n ∃ N, CReach {s with carried := s.carried ++ extra} producer ρ N ∧ PublicMaps fresh N M := by\n let t : SMachine := {s with carried := s.carried ++ extra}\n intro ρ M hr\n induction hr with\n | start ρ M hM hp hf hpf =>\n exact ⟨M, CReach.start ρ M hM hp hf hpf, fun _ _ => rfl⟩\n | step ρ M ι κ hr hg ha ih =>\n obtain ⟨N, hn, hag⟩ := ih\n let κ0 := withCarried s M κ\n have hv0 : withCarried t M κ0 = withCarried s M κ := bapa_withCarried_from_view s extra M κ\n have hg0 : GHolds source (withInputs t.f.m.inputs ρ ι) (withCarried t M κ0) := by\n rw [hv0]\n exact hg\n obtain ⟨κ', hg', hv⟩ := producer_request_public t source producer fresh hd hc hav hkey hsub hpublic ρ M N ι κ0 hag hg0\n have hv' : PublicMaps fresh (withCarried t N κ') (withCarried s M κ) := by\n rw [hv0] at hv\n exact hv\n obtain ⟨ha', hs', hm'⟩ := step_avoids_two s fresh extra havoid ρ M N ι κ κ' hv'\n have hnext := CReach.step ρ N ι κ' hn hg' (ha'.trans ha)\n rw [hs'] at hnext\n exact ⟨_, hnext, hm'⟩\n\nprivate theorem bapa_avoidsMapsE_mono {small large : List Nat} {e : E}\n (hs : ∀ mp ∈ small, mp ∈ large) (h : avoidsMapsE large e = true) : avoidsMapsE small e = true := by\n simp only [avoidsMapsE, List.all_eq_true] at h ⊢\n intro mp hm\n exact h mp (hs mp hm)\n\n/-- The retained counted theorem transfers to the source count interpretation.\nThis theorem has no assumed operational simulation: it is derived above from\nfinite source noninterference and finite count-declaration premises. -/\ntheorem bapa_counted_source_law (s : SMachine) (source producer : List CDecl)\n (fresh extra : List Nat) (e : SEntry)\n (hsd : cDistinct (cMaps source) = true)\n (hd : cDistinct (cMaps producer) = true)\n (hc : ∀ d ∈ producer, d.mp ∈ s.carried ++ extra)\n (hav : ∀ d ∈ producer, avoidsMapsE (cMaps producer) d.below = true ∧ avoidsMapsE (cMaps producer) d.body = true)\n (hkey : ∀ d ∈ producer, occE d.key d.below = false)\n (hsub : ∀ mp ∈ fresh, mp ∈ cMaps producer)\n (hsource : ∀ d ∈ source, d ∈ producer)\n (hpublic : ∀ d ∈ producer, d.mp ∉ fresh → d ∈ source)\n (havoid : StepAvoids s fresh)\n (hlaw : avoidsMaps fresh e.law.holds = true)\n (hproof : ∀ ρ M, CReach {s with carried := s.carried ++ extra} producer ρ M → e.Holds ρ (withCnt producer ρ M)) :\n ∀ ρ M, CReach s source ρ M → e.Holds ρ (withCnt source ρ M) := by\n intro ρ M hr\n obtain ⟨N, hn, hag⟩ := bapa_counted_source_reach s source producer fresh extra hd hc hav hkey hsub hpublic havoid hr\n have hav' : ∀ d ∈ producer, avoidsMapsE fresh d.below = true ∧ avoidsMapsE fresh d.body = true := by\n intro d hm\n exact ⟨bapa_avoidsMapsE_mono hsub (hav d hm).1, bapa_avoidsMapsE_mono hsub (hav d hm).2⟩\n have hi := withCnt_public source producer fresh hsd hd hsource hpublic hkey hav' ρ M N hag\n exact source_law_transfer e fresh hlaw hi (hproof ρ N hn)\n\nend Kern\n\n#print axioms Kern.bapa_counted_source_reach\n#print axioms Kern.bapa_counted_source_law\n",
30
+ "SourceInclusion.lean": "import CountedSourceBridge\n\nnamespace Kern\n\n/-- One-way operational inclusion. None of these premises is a proof-search verdict. -/\nstructure SourceInclusion (s t : SMachine) : Prop where\n inputs : s.f.m.inputs = t.f.m.inputs\n carried : s.carried = t.carried\n initial : s.f.m.init = t.f.m.init\n startMaps : ∀ M, StartMaps s.f.m M → StartMaps t.f.m M\n pre : ∀ ρ M, evalC ρ M s.f.m.pre = true → evalC ρ M t.f.m.pre = true\n facts : ∀ ρ M, (∀ l ∈ s.facts, l.Holds ρ M) → ∀ l ∈ t.facts, l.Holds ρ M\n pfacts : ∀ ρ M, s.PFacts ρ M → t.PFacts ρ M\n admission : ∀ ρ M ι κ,\n evalC (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 s.f.m.assume = true →\n evalC (sView t ρ M ι κ).1 (sView t ρ M ι κ).2 t.f.m.assume = true\n next : ∀ ρ M ι κ,\n evalC (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 s.f.m.assume = true →\n sNext s ρ M ι κ = sNext t ρ M ι κ\n\ntheorem SourceInclusion.creach {s t : SMachine} (h : SourceInclusion s t) (ds : List CDecl) :\n ∀ {ρ M}, CReach s ds ρ M → CReach t ds ρ M := by\n intro ρ M hr\n induction hr with\n | start ρ M hm hp hf hpf =>\n rw [h.initial]\n exact .start ρ M (h.startMaps M hm) (h.pre ρ M hp) (h.facts ρ M hf) (h.pfacts ρ M hpf)\n | step ρ M ι κ hr hg ha ih =>\n have hc : withCarried s M κ = withCarried t M κ := by\n funext mp\n simp only [withCarried, h.carried]\n have hg' : GHolds ds (withInputs t.f.m.inputs ρ ι) (withCarried t M κ) := by\n rw [← h.inputs, ← hc]\n exact hg\n have out := CReach.step ρ M ι κ ih hg' (h.admission ρ M ι κ ha)\n rw [h.next ρ M ι κ ha]\n exact out\n\ntheorem SourceInclusion.sreach {s t : SMachine} (h : SourceInclusion s t) :\n ∀ {ρ M}, SReach s ρ M → SReach t ρ M := by\n intro ρ M hr\n induction hr with\n | start ρ M hm hp hf hpf =>\n rw [h.initial]\n exact .start ρ M (h.startMaps M hm) (h.pre ρ M hp) (h.facts ρ M hf) (h.pfacts ρ M hpf)\n | step ρ M ι κ hr ha ih =>\n have out := SReach.step ρ M ι κ ih (h.admission ρ M ι κ ha)\n rw [h.next ρ M ι κ ha]\n exact out\n\n/-- A checked implication between public entries, including all bound keys. -/\ndef SourceLawImplication (strong weak : SEntry) : Prop :=\n ∀ ρ M, strong.Holds ρ M → weak.Holds ρ M\n\ntheorem sourceLawImplication_of_pointwise (strong weak : SEntry)\n (hk : strong.law.key = weak.law.key) (hks : strong.keys2 = weak.keys2)\n (hp : ∀ ρ M, evalC ρ M strong.law.holds = true → evalC ρ M weak.law.holds = true) :\n SourceLawImplication strong weak := by\n have atom : ∀ ρ M, strong.law.Holds ρ M → weak.law.Holds ρ M := by\n intro ρ M ha\n unfold MLaw.Holds at ha ⊢\n rw [← hk]\n cases he : strong.law.key with\n | none => simp only [he] at ha ⊢; exact hp ρ M ha\n | some k => simp only [he] at ha ⊢; intro v; exact hp (upd ρ k v) M (ha v)\n intro ρ M hs\n unfold SEntry.Holds at hs ⊢\n rw [← hks]\n generalize strong.keys2 = ks at hs ⊢\n induction ks generalizing ρ with\n | nil => exact atom ρ M hs\n | cons k ks ih => intro v; exact ih (upd ρ k v) (hs v)\n\n/-- Compose operational inclusion and semantic law weakening. Count projection\n and alpha transport can be applied before/after this theorem independently. -/\ntheorem sourceLaw_via_inclusion {s t : SMachine} (ds : List CDecl)\n (h : SourceInclusion s t) (strong weak : SEntry)\n (hw : SourceLawImplication strong weak)\n (ht : ∀ ρ M, CReach t ds ρ M → strong.Holds ρ (withCnt ds ρ M)) :\n ∀ ρ M, CReach s ds ρ M → weak.Holds ρ (withCnt ds ρ M) := by\n intro ρ M hr\n exact hw ρ _ (ht ρ M (h.creach ds hr))\n\n/-- Uncounted counterpart, for composition with separately checked ghost/witness projection. -/\ntheorem sourceLaw_via_sinclusion {s t : SMachine}\n (h : SourceInclusion s t) (strong weak : SEntry)\n (hw : SourceLawImplication strong weak)\n (ht : ∀ ρ M, SReach t ρ M → strong.Holds ρ M) :\n ∀ ρ M, SReach s ρ M → weak.Holds ρ M := by\n intro ρ M hr\n exact hw ρ M (ht ρ M (h.sreach hr))\n\nend Kern\n#print axioms Kern.sourceLaw_via_sinclusion\n#print axioms Kern.SourceInclusion.creach\n#print axioms Kern.SourceInclusion.sreach\n#print axioms Kern.sourceLawImplication_of_pointwise\n#print axioms Kern.sourceLaw_via_inclusion\n",
31
+ "FiniteSimulation.lean": "import SourceInclusion\n\n/-! Finite (including zero-step) forward simulation. Counts remain part of each\nactual producer transition; no arbitrary relation is substituted for GHolds. -/\nnamespace Bapa.FiniteSimulation\nopen Kern\n\ninductive Steps {α : Type} (R : α → α → Prop) : α → α → Prop where\n | refl (x) : Steps R x x\n | next {x y z} : Steps R x y → R y z → Steps R x z\n\ninductive Reachable {α : Type} (I : α → Prop) (R : α → α → Prop) : α → Prop where\n | initial {x} : I x → Reachable I R x\n | next {x y} : Reachable I R x → R x y → Reachable I R y\n\ntheorem Steps.reachable {α : Type} {I : α → Prop} {R : α → α → Prop}\n {x y : α} (steps : Steps R x y) (hx : Reachable I R x) : Reachable I R y := by\n induction steps with\n | refl => exact hx\n | next _ edge ih => exact .next ih edge\n\ntheorem Steps.trans {α : Type} {R : α → α → Prop} {x y z : α}\n (xy : Steps R x y) (yz : Steps R y z) : Steps R x z := by\n induction yz with\n | refl => exact xy\n | next _ edge ih => exact .next ih edge\n\nstructure ForwardSimulation {α β : Type} (Is : α → Prop) (Rs : α → α → Prop)\n (It : β → Prop) (Rt : β → β → Prop) (rel : α → β → Prop) : Prop where\n initial : ∀ x, Is x → ∃ y, Reachable It Rt y ∧ rel x y\n matching : ∀ x x' y, Reachable Is Rs x → Reachable It Rt y → rel x y → Rs x x' →\n ∃ y', Steps Rt y y' ∧ rel x' y'\n\ntheorem ForwardSimulation.reaches {α β : Type} {Is : α → Prop} {Rs : α → α → Prop}\n {It : β → Prop} {Rt : β → β → Prop} {rel : α → β → Prop}\n (sim : ForwardSimulation Is Rs It Rt rel) {x} (hx : Reachable Is Rs x) :\n ∃ y, Reachable It Rt y ∧ rel x y := by\n induction hx with\n | initial hi => exact sim.initial _ hi\n | next hr edge ih =>\n obtain ⟨y, hy, hrel⟩ := ih\n obtain ⟨z, steps, hz⟩ := sim.matching _ _ _ hr hy hrel edge\n exact ⟨z, steps.reachable hy, hz⟩\n\ntheorem ForwardSimulation.transfer {α β : Type} {Is : α → Prop} {Rs : α → α → Prop}\n {It : β → Prop} {Rt : β → β → Prop} {rel : α → β → Prop}\n (sim : ForwardSimulation Is Rs It Rt rel) (P : β → Prop) (Q : α → Prop)\n (ht : ∀ y, Reachable It Rt y → P y) (imp : ∀ x y, rel x y → P y → Q x)\n {x} (hx : Reachable Is Rs x) : Q x := by\n obtain ⟨y, hy, hrel⟩ := sim.reaches hx\n exact imp x y hrel (ht y hy)\n\ntheorem ForwardSimulation.projected {α β : Type} {Is : α → Prop} {Rs : α → α → Prop}\n {It : β → Prop} {Rt : β → β → Prop} {rel : α → β → Prop}\n (sim : ForwardSimulation Is Rs It Rt rel) (project : β → α)\n (hproject : ∀ x y, rel x y → project y = x) (P : α → Prop)\n (ht : ∀ y, Reachable It Rt y → P (project y)) {x} (hx : Reachable Is Rs x) : P x := by\n obtain ⟨y, hy, hrel⟩ := sim.reaches hx\n rw [← hproject x y hrel]\n exact ht y hy\n\nabbrev KState := (Nat → Nat) × (Nat → Nat → Nat)\n\ndef Initial (s : SMachine) (x : KState) : Prop :=\n ∃ ρ M, StartMaps s.f.m M ∧ evalC ρ M s.f.m.pre = true ∧\n (∀ l ∈ s.facts, l.Holds ρ M) ∧ s.PFacts ρ M ∧ x = (applyS s.f.m.init ρ M, M)\n\ndef STransition (s : SMachine) (x y : KState) : Prop :=\n ∃ ι κ, evalC (sView s x.1 x.2 ι κ).1 (sView s x.1 x.2 ι κ).2 s.f.m.assume = true ∧\n y = sNext s x.1 x.2 ι κ\n\ndef CTransition (s : SMachine) (ds : List CDecl) (x y : KState) : Prop :=\n ∃ ι κ, GHolds ds (withInputs s.f.m.inputs x.1 ι) (withCarried s x.2 κ) ∧\n evalC (sView s x.1 x.2 ι κ).1 (sView s x.1 x.2 ι κ).2 s.f.m.assume = true ∧\n y = sNext s x.1 x.2 ι κ\n\nabbrev SSteps (s : SMachine) := Steps (STransition s)\nabbrev CSteps (s : SMachine) (ds : List CDecl) := Steps (CTransition s ds)\n\ntheorem sreach_into {s : SMachine} {ρ M} (h : SReach s ρ M) :\n Reachable (Initial s) (STransition s) (ρ,M) := by\n induction h with\n | start ρ M hm hp hf hpf => exact .initial ⟨ρ,M,hm,hp,hf,hpf,rfl⟩\n | step ρ M ι κ _ ha ih => exact .next ih ⟨ι,κ,ha,rfl⟩\n\ntheorem sreach_out {s : SMachine} {x} (h : Reachable (Initial s) (STransition s) x) :\n SReach s x.1 x.2 := by\n induction h with\n | initial hi =>\n obtain ⟨ρ,M,hm,hp,hf,hpf,rfl⟩ := hi\n exact .start ρ M hm hp hf hpf\n | next _ edge ih =>\n obtain ⟨ι,κ,ha,rfl⟩ := edge\n exact .step _ _ ι κ ih ha\n\ntheorem creach_into {s : SMachine} {ds : List CDecl} {ρ M} (h : CReach s ds ρ M) :\n Reachable (Initial s) (CTransition s ds) (ρ,M) := by\n induction h with\n | start ρ M hm hp hf hpf => exact .initial ⟨ρ,M,hm,hp,hf,hpf,rfl⟩\n | step ρ M ι κ _ hg ha ih => exact .next ih ⟨ι,κ,hg,ha,rfl⟩\n\ntheorem creach_out {s : SMachine} {ds : List CDecl} {x}\n (h : Reachable (Initial s) (CTransition s ds) x) : CReach s ds x.1 x.2 := by\n induction h with\n | initial hi =>\n obtain ⟨ρ,M,hm,hp,hf,hpf,rfl⟩ := hi\n exact .start ρ M hm hp hf hpf\n | next _ edge ih =>\n obtain ⟨ι,κ,hg,ha,rfl⟩ := edge\n exact .step _ _ ι κ ih hg ha\n\nabbrev SSimulation (s t : SMachine) (rel : KState → KState → Prop) :=\n ForwardSimulation (Initial s) (STransition s) (Initial t) (STransition t) rel\nabbrev CSimulation (s : SMachine) (ds : List CDecl) (t : SMachine) (dt : List CDecl)\n (rel : KState → KState → Prop) :=\n ForwardSimulation (Initial s) (CTransition s ds) (Initial t) (CTransition t dt) rel\n\ntheorem sprojected_reach {s t : SMachine} {rel : KState → KState → Prop}\n (sim : SSimulation s t rel) {ρ M} (h : SReach s ρ M) :\n ∃ y, SReach t y.1 y.2 ∧ rel (ρ,M) y := by\n obtain ⟨y, hy, hr⟩ := sim.reaches (sreach_into h)\n exact ⟨y,sreach_out hy,hr⟩\n\ntheorem cprojected_reach {s t : SMachine} {ds dt : List CDecl} {rel : KState → KState → Prop}\n (sim : CSimulation s ds t dt rel) {ρ M} (h : CReach s ds ρ M) :\n ∃ y, CReach t dt y.1 y.2 ∧ rel (ρ,M) y := by\n obtain ⟨y, hy, hr⟩ := sim.reaches (creach_into h)\n exact ⟨y,creach_out hy,hr⟩\n\n/-- The relation can require an idle phase boundary as well as projection\nagreement. Intermediate states need satisfy neither of those requirements. -/\ntheorem cprojected_law {s t : SMachine} {ds dt : List CDecl} {rel : KState → KState → Prop}\n (sim : CSimulation s ds t dt rel) (project : KState → KState)\n (hp : ∀ x y, rel x y → project y = x) (P : KState → Prop)\n (ht : ∀ ρ M, CReach t dt ρ M → P (project (ρ,M))) {ρ M} (h : CReach s ds ρ M) :\n P (ρ,M) := by\n obtain ⟨y, hy, hr⟩ := cprojected_reach sim h\n rw [← hp _ _ hr]\n exact ht y.1 y.2 hy\n\ntheorem sprojected_law {s t : SMachine} {rel : KState → KState → Prop}\n (sim : SSimulation s t rel) (project : KState → KState)\n (hp : ∀ x y, rel x y → project y = x) (P : KState → Prop)\n (ht : ∀ ρ M, SReach t ρ M → P (project (ρ,M))) {ρ M} (h : SReach s ρ M) :\n P (ρ,M) := by\n obtain ⟨y, hy, hr⟩ := sprojected_reach sim h\n rw [← hp _ _ hr]\n exact ht y.1 y.2 hy\n\n/-- Compose the new multi-step leg after the checked same-step inclusion. -/\ntheorem cafter_inclusion {s u t : SMachine} {ds dt : List CDecl} {rel : KState → KState → Prop}\n (inc : SourceInclusion s u) (sim : CSimulation u ds t dt rel)\n {ρ M} (h : CReach s ds ρ M) : ∃ y, CReach t dt y.1 y.2 ∧ rel (ρ,M) y :=\n cprojected_reach sim (inc.creach ds h)\n\ntheorem safter_inclusion {s u t : SMachine} {rel : KState → KState → Prop}\n (inc : SourceInclusion s u) (sim : SSimulation u t rel)\n {ρ M} (h : SReach s ρ M) : ∃ y, SReach t y.1 y.2 ∧ rel (ρ,M) y :=\n sprojected_reach sim (inc.sreach h)\n\n/-- Observable projections may omit source input temporaries as well as target\nscan registers. Only the public store projection must agree at boundaries. -/\ntheorem cobservable_law {Ω : Type} {s t : SMachine} {ds dt : List CDecl}\n {rel : KState → KState → Prop} (sim : CSimulation s ds t dt rel)\n (sourceView targetView : KState → Ω)\n (hp : ∀ x y, rel x y → targetView y = sourceView x) (P : Ω → Prop)\n (ht : ∀ ρ M, CReach t dt ρ M → P (targetView (ρ,M))) {ρ M} (h : CReach s ds ρ M) :\n P (sourceView (ρ,M)) := by\n obtain ⟨y, hy, hr⟩ := cprojected_reach sim h\n rw [← hp _ _ hr]\n exact ht y.1 y.2 hy\n\n#print axioms cobservable_law\n#print axioms ForwardSimulation.reaches\n#print axioms ForwardSimulation.projected\n#print axioms cprojected_reach\n#print axioms sprojected_reach\n#print axioms cprojected_law\n#print axioms sprojected_law\n#print axioms cafter_inclusion\n#print axioms safter_inclusion\nend Bapa.FiniteSimulation\n",
32
+ "CertificateBoundErasure.lean": "import CountMachine\n\n/-! Search-free rewriting of retained certificates. This is a candidate\ntransformation, not a theorem that arbitrary bound erasure preserves validity.\nArithmetic leaf rows, count-instance coefficients and arithmetic proof steps\nare kept. Splits for erased bound atoms are pruned in the corresponding\ndirection; all other split choices remain. The existing complete trusted\nchecker MUST accept the resulting candidate before any theorem is claimed. -/\nnamespace Bapa.CertificateBoundErasure\nopen Kern\n\nmutual\n def expr (bound : Nat) : E → E\n | .var i => .var i\n | .const n => .const n\n | .add a b => .add (expr bound a) (expr bound b)\n | .sub a b => .sub (expr bound a) (expr bound b)\n | .mul n a => .mul n (expr bound a)\n | .min a b => .min (expr bound a) (expr bound b)\n | .max a b => .max (expr bound a) (expr bound b)\n | .prod a b => .prod (expr bound a) (expr bound b)\n | .ite p a b => .ite (condition bound p) (expr bound a) (expr bound b)\n | .get m k => .get m (expr bound k)\n | .tup a b => .tup (expr bound a) (expr bound b)\n | .proj i a => .proj i (expr bound a)\n def condition (bound : Nat) : C → C\n | .lt a (.const n) => if n = bound then trueC else .lt (expr bound a) (.const n)\n | .le a (.const n) => if n = bound then trueC else .le (expr bound a) (.const n)\n | .lt a b => .lt (expr bound a) (expr bound b)\n | .le a b => .le (expr bound a) (expr bound b)\n | .eq a b => .eq (expr bound a) (expr bound b)\n | .and a b => .and (condition bound a) (condition bound b)\n | .or a b => .or (condition bound a) (condition bound b)\n | .not a => .not (condition bound a)\nend\n\ndef variableDefinition (bound : Nat) : VDef → VDef\n | .term e => .term (expr bound e)\n | d => d\n\ndef erasedSplit (bound : Nat) (r : Cert.Row) : Option Bool :=\n match r.coefs with\n | [(_, a)] =>\n if a = 1 ∧ (r.const = 1 - (bound : Int) ∨ r.const = -(bound : Int)) then some true\n else if a = -1 ∧ (r.const = (bound : Int) ∨ r.const = (bound : Int) + 1) then some false\n else none\n | _ => none\n\n/-- Deterministic syntactic pruning, NOT an assertion that the erased atom\n holds in every target model. The post-translation checker is mandatory. -/\ndef pruneBoundSplits (bound : Nat) : Tree → Tree\n | .split r yes no =>\n match erasedSplit bound r with\n | some true => pruneBoundSplits bound yes\n | some false => pruneBoundSplits bound no\n | none => .split r (pruneBoundSplits bound yes) (pruneBoundSplits bound no)\n | t => t\n\ndef certificate (bound : Nat) (k : Kern.Cert) : Kern.Cert :=\n (k.1.map (variableDefinition bound), k.2.1.map (condition bound), pruneBoundSplits bound k.2.2)\n\ndef law (bound : Nat) (l : MLaw) : MLaw := {l with holds := condition bound l.holds}\n\ndef scalarMachine (bound : Nat) (m : MMachine) : MMachine :=\n {m with\n init := m.init.map fun p => (p.1, expr bound p.2)\n step := m.step.map fun p => (p.1, expr bound p.2)\n writes := m.writes.map fun p => (p.1, expr bound p.2.1, expr bound p.2.2)\n pre := condition bound m.pre\n assume := condition bound m.assume}\n\ndef machine (bound : Nat) (s : SMachine) : SMachine :=\n {s with\n f := {s.f with\n m := scalarMachine bound s.f.m\n flags := s.f.flags.map fun p => (p.1, condition bound p.2)}\n every := s.every.map fun p => (p.1, p.2.1, expr bound p.2.2)\n qflags := s.qflags.map fun p => (p.1, p.2.1, condition bound p.2.2)\n facts := s.facts.map (law bound)\n pfacts := s.pfacts.map fun p => (law bound p.1, p.2)}\n\ndef pairInstances (bound : Nat) (ps : List (Nat × E × List E)) : List (Nat × E × List E) :=\n ps.map fun p => (p.1, expr bound p.2.1, p.2.2.map (expr bound))\n\ndef entry (bound : Nat) (e : SEntry) : SEntry :=\n {e with\n law := law bound e.law\n insts := e.insts.map fun p => (p.1, expr bound p.2)\n qinsts := e.qinsts.map fun p => (p.1, p.2.map (expr bound))\n finsts := e.finsts.map fun p => (p.1, expr bound p.2)\n pinsts := pairInstances bound e.pinsts\n pfinsts := pairInstances bound e.pfinsts\n start := certificate bound e.start\n step := certificate bound e.step}\n\ndef countDeclaration (bound : Nat) (d : CDecl) : CDecl :=\n {d with below := expr bound d.below, body := expr bound d.body}\n\ndef countedCertificate (bound : Nat) (k : CCert) : CCert :=\n {k with\n hyps := k.hyps.map (condition bound)\n reads := k.reads.map fun p => (p.1, p.2.1, expr bound p.2.2)\n insts := k.insts.map fun i => {i with below := expr bound i.below}\n tab := k.tab.map (variableDefinition bound)\n tree := pruneBoundSplits bound k.tree\n lemmas := k.lemmas.map fun l => {l with tree := pruneBoundSplits bound l.tree}\n picks := k.picks.map fun p => (p.1, p.2.map (expr bound))}\n\ndef countedEntry (bound : Nat) (e : CEntry) : CEntry :=\n {e := entry bound e.e, start := countedCertificate bound e.start,\n step := countedCertificate bound e.step}\n\ntheorem tree_is_pruned (bound : Nat) (k : CCert) :\n (countedCertificate bound k).tree = pruneBoundSplits bound k.tree := rfl\n\ntheorem leaf_rows_unchanged (bound : Nat) (rows : List (Cert.Row × Src))\n (steps : List Cert.Step) (eqs prods : List (Nat × Nat)) :\n pruneBoundSplits bound (.leafAt rows steps eqs prods) = .leafAt rows steps eqs prods := rfl\n\ntheorem instance_coefficients_unchanged (bound : Nat) (k : CCert) :\n (countedCertificate bound k).insts.map (fun i => (i.terms, i.unit)) =\n k.insts.map (fun i => (i.terms, i.unit)) := by\n simp [countedCertificate, List.map_map]\n\n/-- A translated family is valid only after its complete existing checker\n succeeds, including all count semantics and freshness side conditions. -/\ntheorem checked_counted_transport (bound : Nat) (s : SMachine) (ds : List CDecl)\n (ps : List CEntry)\n (h : checkCMachine (machine bound s) (ds.map (countDeclaration bound))\n (ps.map (countedEntry bound)) = true) :\n ∀ ρ M, CReach (machine bound s) (ds.map (countDeclaration bound)) ρ M →\n ∀ e ∈ ps.map (countedEntry bound),\n e.e.Holds ρ (withCnt (ds.map (countDeclaration bound)) ρ M) :=\n cmachine_sound _ _ _ h\n\n#print axioms tree_is_pruned\n#print axioms leaf_rows_unchanged\n#print axioms instance_coefficients_unchanged\n#print axioms checked_counted_transport\nend Bapa.CertificateBoundErasure\n",
33
+ "CertificateBoundSubstitution.lean": "import CertificateBoundErasure\n\n/-! Search-free bound substitution, not erasure. A fresh, fixed parameter is\ninserted as column0. All old column references shift by one. The retained tree\nand arithmetic steps remain, with recognized literal bound rows translated from\nx<bound to x<size. Only a complete post-translation check can accept the result. -/\nnamespace Bapa.CertificateBoundSubstitution\nopen Kern\n\nmutual\n def expr (bound size : Nat) : E → E\n | .var i => .var i\n | .const n => .const n\n | .add a b => .add (expr bound size a) (expr bound size b)\n | .sub a b => .sub (expr bound size a) (expr bound size b)\n | .mul n a => .mul n (expr bound size a)\n | .min a b => .min (expr bound size a) (expr bound size b)\n | .max a b => .max (expr bound size a) (expr bound size b)\n | .prod a b => .prod (expr bound size a) (expr bound size b)\n | .ite p a b => .ite (condition bound size p) (expr bound size a) (expr bound size b)\n | .get m k => .get m (expr bound size k)\n | .tup a b => .tup (expr bound size a) (expr bound size b)\n | .proj i a => .proj i (expr bound size a)\n def condition (bound size : Nat) : C → C\n | .lt a (.const n) => .lt (expr bound size a) (if n = bound then .var size else .const n)\n | .le a (.const n) => .le (expr bound size a) (if n = bound then .var size else .const n)\n | .lt a b => .lt (expr bound size a) (expr bound size b)\n | .le a b => .le (expr bound size a) (expr bound size b)\n | .eq a b => .eq (expr bound size a) (expr bound size b)\n | .and a b => .and (condition bound size a) (condition bound size b)\n | .or a b => .or (condition bound size a) (condition bound size b)\n | .not a => .not (condition bound size a)\nend\n\ndef shiftRow (r : Cert.Row) : Cert.Row :=\n ⟨r.coefs.map (fun (i,c) => (i+1,c)),r.const⟩\n\n/-- Replace only the four literal, one-column bound/complement patterns. -/\ndef boundRow (bound : Nat) (r : Cert.Row) : Cert.Row :=\n let shifted := shiftRow r\n match r.coefs with\n | [(_,a)] =>\n if a == 1 && r.const == 1 - (bound : Int) then ⟨(0,-1)::shifted.coefs,1⟩\n else if a == 1 && r.const == -(bound : Int) then ⟨(0,-1)::shifted.coefs,0⟩\n else if a == (-1) && r.const == (bound : Int) then ⟨(0,1)::shifted.coefs,0⟩\n else if a == (-1) && r.const == (bound : Int)+1 then ⟨(0,1)::shifted.coefs,1⟩\n else shifted\n | _ => shifted\n\ndef source : Src → Src\n | .nat i => .nat (i+1)\n | .term i => .term (i+1)\n | s => s\n\ndef proofStep (bound : Nat) : Cert.Step → Cert.Step\n | .cut i g q c => let r := boundRow bound ⟨q,c⟩; .cut i g r.coefs r.const\n | s => s\n\ndef eqPairs (pairs : List (Nat × Nat)) : List (Nat × Nat) :=\n pairs.map (fun (i,j) => (i+1,j+1))\n\ndef tree (bound : Nat) : Tree → Tree\n | .split r a b => .split (boundRow bound r) (tree bound a) (tree bound b)\n | .leaf rs ss eqs prods =>\n .leaf (rs.map (boundRow bound)) (ss.map (proofStep bound)) (eqPairs eqs) prods\n | .leafAt rs ss eqs prods =>\n .leafAt (rs.map (fun (r,s) => (boundRow bound r,source s)))\n (ss.map (proofStep bound)) (eqPairs eqs) prods\n | .leafSq rs sqs ss eqs prods =>\n .leafSq (rs.map (fun (r,s) => (boundRow bound r,source s)))\n (sqs.map shiftRow) (ss.map (proofStep bound)) (eqPairs eqs) prods\n\ndef variableDefinition (bound size : Nat) : VDef → VDef\n | .var i => .var i\n | .cell m key => .cell m (shiftRow key)\n | .cellT m keys => .cellT m (keys.map shiftRow)\n | .mono fs => .mono (fs.map (·+1))\n | .term e => .term (expr bound size e)\n\ndef certificate (bound size : Nat) (k : Kern.Cert) : Kern.Cert :=\n (.var size :: k.1.map (variableDefinition bound size),\n k.2.1.map (condition bound size),tree bound k.2.2)\n\ndef law (bound size : Nat) (l : MLaw) : MLaw :=\n {l with holds := condition bound size l.holds}\n\ndef scalarMachine (bound size : Nat) (m : MMachine) : MMachine :=\n {m with\n init := m.init.map (fun p => (p.1,expr bound size p.2))\n step := m.step.map (fun p => (p.1,expr bound size p.2))\n writes := m.writes.map (fun p => (p.1,expr bound size p.2.1,expr bound size p.2.2))\n pre := condition bound size m.pre\n assume := condition bound size m.assume}\n\ndef pairInstances (bound size : Nat) (ps : List (Nat × E × List E)) : List (Nat × E × List E) :=\n ps.map (fun p => (p.1,expr bound size p.2.1,p.2.2.map (expr bound size)))\n\ndef machine (bound size : Nat) (s : SMachine) : SMachine :=\n {s with\n f := {s.f with\n m := scalarMachine bound size s.f.m\n flags := s.f.flags.map (fun p => (p.1,condition bound size p.2))}\n every := s.every.map (fun p => (p.1,p.2.1,expr bound size p.2.2))\n qflags := s.qflags.map (fun p => (p.1,p.2.1,condition bound size p.2.2))\n facts := s.facts.map (law bound size)\n pfacts := s.pfacts.map (fun p => (law bound size p.1,p.2))}\n\ndef entry (bound size : Nat) (e : SEntry) : SEntry :=\n {e with\n law := law bound size e.law\n insts := e.insts.map (fun p => (p.1,expr bound size p.2))\n qinsts := e.qinsts.map (fun p => (p.1,p.2.map (expr bound size)))\n finsts := e.finsts.map (fun p => (p.1,expr bound size p.2))\n pinsts := pairInstances bound size e.pinsts\n pfinsts := pairInstances bound size e.pfinsts\n start := certificate bound size e.start\n step := certificate bound size e.step}\n\ntheorem size_column (bound size : Nat) (k : Kern.Cert) :\n (certificate bound size k).1.head? = some (.var size) := rfl\n\ntheorem strict_bound_pattern :\n (boundRow 64 (sp [(2,1)] (-63))).coefs = [(0,-1),(3,1)] ∧\n (boundRow 64 (sp [(2,1)] (-63))).const = 1 := by decide +kernel\n\ntheorem complement_pattern :\n (boundRow 64 (sp [(48,-1)] 64)).coefs = [(0,1),(49,-1)] ∧\n (boundRow 64 (sp [(48,-1)] 64)).const = 0 := by decide +kernel\n\ntheorem checked_transport (bound size : Nat) (s : SMachine) (ps : List SEntry)\n (h : checkSMachine (machine bound size s) (ps.map (entry bound size)) = true) :\n ∀ ρ M, SReach (machine bound size s) ρ M → ∀ e ∈ ps.map (entry bound size), e.Holds ρ M :=\n smachine_sound _ _ h\n\n#print axioms size_column\n#print axioms strict_bound_pattern\n#print axioms complement_pattern\n#print axioms checked_transport\nend Bapa.CertificateBoundSubstitution\n\n/-! Per-sort variant. Typings are untrusted annotations: missing/ambiguous\nannotations refuse emission, and every translated certificate must recheck.\nA typing is local to one entry, because bound names can have different roles\nin different laws. Parameter numbers denote fresh fixed environment variables.\nThe legacy common-size API above is deliberately unchanged. -/\nnamespace Bapa.CertificateBoundSubstitution.Typed\nopen Kern\n\nstructure Typing where\n sizes : List Nat\n variables : List (Nat × Nat)\n values : List (Nat × Nat)\n\ndef lookupSize (xs : List (Nat × Nat)) (i : Nat) : Option Nat :=\n (xs.find? (fun p => p.1 == i)).map (·.2)\n\ndef exprSize (p : Typing) : E → Option Nat\n | .var i => lookupSize p.variables i\n | .get m _ => lookupSize p.values m\n | .ite _ a b => match a, b with\n | .const _, _ => exprSize p b\n | _, .const _ => exprSize p a\n | _, _ => let x := exprSize p a; if x == exprSize p b then x else none\n | .add a (.const _) | .sub a (.const _) => exprSize p a\n | _ => none\n\ndef sizeOf (p : Typing) (e : E) : Option Nat := do\n let n ← exprSize p e\n if p.sizes.contains n then some n else none\n\nmutual\n def expr (bound : Nat) (p : Typing) : E → Option E\n | .var i => some (.var i)\n | .const n => some (.const n)\n | .add a b => do return .add (← expr bound p a) (← expr bound p b)\n | .sub a b => do return .sub (← expr bound p a) (← expr bound p b)\n | .mul n a => do return .mul n (← expr bound p a)\n | .min a b => do return .min (← expr bound p a) (← expr bound p b)\n | .max a b => do return .max (← expr bound p a) (← expr bound p b)\n | .prod a b => do return .prod (← expr bound p a) (← expr bound p b)\n | .ite c a b => do return .ite (← condition bound p c) (← expr bound p a) (← expr bound p b)\n | .get m k => do return .get m (← expr bound p k)\n | .tup a b => do return .tup (← expr bound p a) (← expr bound p b)\n | .proj i a => do return .proj i (← expr bound p a)\n def condition (bound : Nat) (p : Typing) : C → Option C\n | .lt a (.const n) => do\n let a' ← expr bound p a\n if n == bound then return .lt a' (.var (← sizeOf p a)) else return .lt a' (.const n)\n | .le a (.const n) => do\n let a' ← expr bound p a\n if n == bound then return .le a' (.var (← sizeOf p a)) else return .le a' (.const n)\n | .lt a b => do return .lt (← expr bound p a) (← expr bound p b)\n | .le a b => do return .le (← expr bound p a) (← expr bound p b)\n | .eq a b => do return .eq (← expr bound p a) (← expr bound p b)\n | .and a b => do return .and (← condition bound p a) (← condition bound p b)\n | .or a b => do return .or (← condition bound p a) (← condition bound p b)\n | .not a => do return .not (← condition bound p a)\nend\n\ndef shiftRow (n : Nat) (r : Cert.Row) : Cert.Row :=\n ⟨r.coefs.map (fun (i,c) => (i+n,c)),r.const⟩\n\ndef columnSize (p : Typing) (tab : List VDef) (i : Nat) : Option Nat := do\n let v ← tab[i]?\n let n ← match v with\n | .var x => lookupSize p.variables x\n | .cell m _ | .cellT m _ => lookupSize p.values m\n | .term e => exprSize p e\n | .mono _ => none\n if p.sizes.contains n then some (p.sizes.idxOf n) else none\n\n/-- Only the four old bound/complement row patterns change besides the uniform\ncolumn shift. A recognized bound on an untyped column is an explicit refusal. -/\ndef boundRow (bound : Nat) (p : Typing) (tab : List VDef) (r : Cert.Row) : Option Cert.Row := do\n let shifted := shiftRow p.sizes.length r\n match r.coefs with\n | [(i,a)] =>\n if a == 1 && r.const == 1 - (bound : Int) then\n return ⟨((← columnSize p tab i),-1)::shifted.coefs,1⟩\n else if a == 1 && r.const == -(bound : Int) then\n return ⟨((← columnSize p tab i),-1)::shifted.coefs,0⟩\n else if a == (-1) && r.const == (bound : Int) then\n return ⟨((← columnSize p tab i),1)::shifted.coefs,0⟩\n else if a == (-1) && r.const == (bound : Int)+1 then\n return ⟨((← columnSize p tab i),1)::shifted.coefs,1⟩\n else return shifted\n | _ => do return shifted\n\ndef source (n : Nat) : Src → Src\n | .nat i => .nat (i+n)\n | .term i => .term (i+n)\n | s => s\n\ndef proofStep (bound : Nat) (p : Typing) (tab : List VDef) : Cert.Step → Option Cert.Step\n | .cut i g q c => do\n let r ← boundRow bound p tab ⟨q,c⟩\n return .cut i g r.coefs r.const\n | s => some s\n\ndef eqPairs (n : Nat) (pairs : List (Nat × Nat)) : List (Nat × Nat) :=\n pairs.map (fun (i,j) => (i+n,j+n))\n\ndef tree (bound : Nat) (p : Typing) (tab : List VDef) : Tree → Option Tree\n | .split r a b => do\n let r' ← boundRow bound p tab r\n let a' ← tree bound p tab a\n let b' ← tree bound p tab b\n return .split r' a' b'\n | .leaf rs ss eqs prods => do\n let rs' ← rs.mapM (boundRow bound p tab)\n let ss' ← ss.mapM (proofStep bound p tab)\n return .leaf rs' ss' (eqPairs p.sizes.length eqs) prods\n | .leafAt rs ss eqs prods => do\n let rs' ← rs.mapM fun (r,s) => do return (← boundRow bound p tab r,source p.sizes.length s)\n let ss' ← ss.mapM (proofStep bound p tab)\n return .leafAt rs' ss' (eqPairs p.sizes.length eqs) prods\n | .leafSq rs sqs ss eqs prods => do\n let rs' ← rs.mapM fun (r,s) => do return (← boundRow bound p tab r,source p.sizes.length s)\n let ss' ← ss.mapM (proofStep bound p tab)\n return .leafSq rs' (sqs.map (shiftRow p.sizes.length)) ss' (eqPairs p.sizes.length eqs) prods\n\ndef variableDefinition (bound : Nat) (p : Typing) : VDef → Option VDef\n | .var i => some (.var i)\n | .cell m k => some (.cell m (shiftRow p.sizes.length k))\n | .cellT m ks => some (.cellT m (ks.map (shiftRow p.sizes.length)))\n | .mono fs => some (.mono (fs.map (·+p.sizes.length)))\n | .term e => do return .term (← expr bound p e)\n\ndef certificate (bound : Nat) (p : Typing) (k : Kern.Cert) : Option Kern.Cert := do\n let tab ← k.1.mapM (variableDefinition bound p)\n let hyps ← k.2.1.mapM (condition bound p)\n let t ← tree bound p k.1 k.2.2\n return (p.sizes.map VDef.var ++ tab,hyps,t)\n\ndef law (bound : Nat) (p : Typing) (l : MLaw) : Option MLaw := do\n return {l with holds := ← condition bound p l.holds}\n\ndef scalarMachine (bound : Nat) (p : Typing) (m : MMachine) : Option MMachine := do\n return {m with\n init := ← m.init.mapM (fun (v,e) => do return (v,← expr bound p e))\n step := ← m.step.mapM (fun (v,e) => do return (v,← expr bound p e))\n writes := ← m.writes.mapM (fun (v,k,e) => do return (v,← expr bound p k,← expr bound p e))\n pre := ← condition bound p m.pre\n assume := ← condition bound p m.assume}\n\ndef pairInstances (bound : Nat) (p : Typing) (ps : List (Nat × E × List E)) : Option (List (Nat × E × List E)) :=\n ps.mapM fun (i,e,es) => do return (i,← expr bound p e,← es.mapM (expr bound p))\n\ndef machine (bound : Nat) (p : Typing) (s : SMachine) : Option SMachine := do\n let m ← scalarMachine bound p s.f.m\n let flags ← s.f.flags.mapM (fun (v,c) => do return (v,← condition bound p c))\n return {s with\n f := {s.f with m := m, flags := flags}\n every := ← s.every.mapM (fun (v,k,e) => do return (v,k,← expr bound p e))\n qflags := ← s.qflags.mapM (fun (v,ks,c) => do return (v,ks,← condition bound p c))\n facts := ← s.facts.mapM (law bound p)\n pfacts := ← s.pfacts.mapM (fun (l,ks) => do return (← law bound p l,ks))}\n\ndef entry (bound : Nat) (p : Typing) (e : SEntry) : Option SEntry := do\n return {e with\n law := ← law bound p e.law\n insts := ← e.insts.mapM (fun (i,x) => do return (i,← expr bound p x))\n qinsts := ← e.qinsts.mapM (fun (i,xs) => do return (i,← xs.mapM (expr bound p)))\n finsts := ← e.finsts.mapM (fun (i,x) => do return (i,← expr bound p x))\n pinsts := ← pairInstances bound p e.pinsts\n pfinsts := ← pairInstances bound p e.pfinsts\n start := ← certificate bound p e.start\n step := ← certificate bound p e.step}\n\n/-- Drop only an optional named INIT-hypothesis cache. `checkIn` then checks the\nsame tree against the full goal reconstructed from the typed machine and law.\nThis does not delete a conjunct of that goal or add any size assumption. -/\ndef withoutInitialCache (e : SEntry) : SEntry :=\n {e with start := (e.start.1, [], e.start.2.2)}\n\ndef entryWithoutInitialCache (bound : Nat) (p : Typing) (e : SEntry) : Option SEntry :=\n entry bound p (withoutInitialCache e)\n\ntheorem initial_cache_tree_unchanged (e : SEntry) :\n (withoutInitialCache e).start.2.2 = e.start.2.2 := rfl\n\n/-- Drop only the optional STEP-hypothesis cache. The ordinary checker must\nvalidate the unchanged tree against the complete reconstructed STEP goal. -/\ndef withoutStepCache (e : SEntry) : SEntry :=\n {e with step := (e.step.1, [], e.step.2.2)}\n\ntheorem step_cache_tree_unchanged (e : SEntry) :\n (withoutStepCache e).step.2.2 = e.step.2.2 := rfl\n\ndef treeShape : Tree → List Nat\n | .split _ a b => 0 :: (treeShape a ++ treeShape b)\n | .leaf _ _ _ _ => [1]\n | .leafAt _ _ _ _ => [2]\n | .leafSq _ _ _ _ _ => [3]\n\n/-- There is no trust in annotations or transport success: acceptance still\nrequires the complete original kernel checker on the translated machine. -/\ntheorem checked_transport (s : SMachine) (ps : List SEntry)\n (h : checkSMachine s ps = true) :\n ∀ ρ M, SReach s ρ M → ∀ e ∈ ps, e.Holds ρ M := smachine_sound _ _ h\n\n#print axioms checked_transport\nend Bapa.CertificateBoundSubstitution.Typed\n",
34
+ "RadixKeySyntax.lean": "import Kernel\n\n/-! The key/binder layer of radix-to-tuple certificate translation.\nThis does NOT yet translate tables, law instances or arithmetic trees and must\nnot be used to claim a re-keyed family. Unknown whole-address variables fail\nclosed; their typed component binders must be supplied by the caller. -/\nnamespace Bapa.RadixKeySyntax\nopen Kern\n\nstructure RawAddress where\n variableId : Nat\n arity : Nat\n components : List E\n\ninductive Error where\n | zeroRadix\n | needBinderExpansion (variableId arity : Nat)\n | malformedBinder (variableId expected actual : Nat)\n | unsupportedKey (arity : Nat)\n deriving Repr, BEq\n\ndef tuple : List E → E\n | [] => .const 0\n | [a] => a\n | a :: rest => .tup a (tuple rest)\n\ndef tupleParts : E → List E\n | .tup a b => a :: tupleParts b\n | e => [e]\n\ndef literalParts (radix : Nat) : Nat → Nat → List E\n | 0, _ => []\n | 1, n => [.const n]\n | arity + 2, n => literalParts radix (arity + 1) (n / radix) ++ [.const (n % radix)]\n\n/-- Read a known Horner-form packed address. The flattened arity-three form\nemitted by the retained 0.49 certificates is supported explicitly too. -/\ndef keyParts (radix : Nat) (bindings : List RawAddress) : Nat → E → Except Error (List E)\n | 0, _ => .error (.unsupportedKey 0)\n | 1, e => .ok [e]\n | arity + 2, e =>\n if radix = 0 then .error .zeroRadix else\n match e with\n | .var v =>\n match bindings.find? (fun b => b.variableId == v && b.arity == arity + 2) with\n | none => .error (.needBinderExpansion v (arity + 2))\n | some b => if b.components.length = arity + 2 then .ok b.components\n else .error (.malformedBinder v (arity + 2) b.components.length)\n | .const n => .ok (literalParts radix (arity + 2) n)\n | .tup _ _ =>\n let ps := tupleParts e\n if ps.length = arity + 2 then .ok ps else .error (.unsupportedKey (arity + 2))\n | .add (.add (.mul r2 a) (.mul r b)) c =>\n if arity = 1 && r2 == radix * radix && r == radix then .ok [a,b,c]\n else .error (.unsupportedKey (arity + 2))\n | .add (.mul r addressHead) last =>\n if r == radix then do\n let ps ← keyParts radix bindings (arity + 1) addressHead\n return ps ++ [last]\n else .error (.unsupportedKey (arity + 2))\n | _ => .error (.unsupportedKey (arity + 2))\n\ndef rekey (radix arity : Nat) (bindings : List RawAddress) (e : E) : Except Error E :=\n (keyParts radix bindings arity e).map tuple\n\n/-- A raw address universal is exactly a universal over both fresh tuple\ncomponents. No finite radix or component bound is assumed. -/\ntheorem expand_pair_binder (P : Nat → Prop) :\n (∀ key, P key) ↔ ∀ a b, P (cpair a b) := by\n constructor\n · intro h a b; exact h _\n · intro h key\n have hk := h (cun key).1 (cun key).2\n simpa only [cpair_cun] using hk\n\ntheorem expand_triple_binder (P : Nat → Prop) :\n (∀ key, P key) ↔ ∀ a b c, P (cpair a (cpair b c)) := by\n constructor\n · intro h a b c; exact h _\n · intro h key\n have hk := h (cun key).1 (cun (cun key).2).1 (cun (cun key).2).2\n simpa only [cpair_cun] using hk\n\ntheorem pair_equality (a b c d : Nat) :\n cpair a b = cpair c d ↔ a = c ∧ b = d := by\n constructor\n · intro h\n have hk := congrArg cun h\n simpa only [cun_cpair, Prod.mk.injEq] using hk\n · rintro ⟨rfl,rfl⟩; rfl\n\ntheorem triple_equality (a b c d e f : Nat) :\n cpair a (cpair b c) = cpair d (cpair e f) ↔ a = d ∧ b = e ∧ c = f := by\n rw [pair_equality, pair_equality]\n\ntheorem old_radix_collision : 64 * 0 + 64 = 64 * 1 + 0 := by decide +kernel\n\ntheorem tuple_collision_refused : cpair 0 64 ≠ cpair 1 0 := by\n intro h\n have h' := (pair_equality 0 64 1 0).mp h\n exact Nat.zero_ne_one h'.1\n\ndef expected (r : Except Error E) (e : E) : Bool :=\n match r with | .ok x => beqE x e | .error _ => false\n\ndef testResults : List Bool :=\n [expected (rekey 64 2 [] (.add (.mul 64 (.var 1)) (.var 2))) (.tup (.var 1) (.var 2)),\n expected (rekey 64 3 [] (.add (.add (.mul 4096 (.var 1)) (.mul 64 (.var 2))) (.var 3)))\n (.tup (.var 1) (.tup (.var 2) (.var 3))),\n expected (rekey 64 3 [] (.add (.mul 64 (.add (.mul 64 (.var 1)) (.var 2))) (.var 3)))\n (.tup (.var 1) (.tup (.var 2) (.var 3))),\n expected (rekey 64 2 [⟨18,2,[.var 18,.var 101]⟩] (.var 18)) (.tup (.var 18) (.var 101)),\n match rekey 64 2 [] (.var 18) with | .error (.needBinderExpansion 18 2) => true | _ => false,\n match rekey 64 2 [⟨18,2,[.var 18]⟩] (.var 18) with | .error (.malformedBinder 18 2 1) => true | _ => false,\n expected (rekey 64 2 [] (.const 64)) (.tup (.const 1) (.const 0))]\n\ntheorem parser_controls : testResults = List.replicate 7 true := by decide +kernel\n\n#print axioms expand_pair_binder\n#print axioms expand_triple_binder\n#print axioms pair_equality\n#print axioms triple_equality\n#print axioms old_radix_collision\n#print axioms tuple_collision_refused\n#print axioms parser_controls\nend Bapa.RadixKeySyntax\n",
35
+ "RadixBinderExpansion.lean": "import RadixKeySyntax\nimport Sets\n\n/-! A fail-closed, typed binder/instance phase for certificate re-keying.\nThis phase changes candidate syntax only. It does not claim any certificate is\nvalid: table columns and arithmetic split/leaf rows still have to be translated\nand the complete family checker must accept the result. -/\nnamespace Bapa.RadixBinderExpansion\nopen Kern\nopen RadixKeySyntax\n\nstructure Uses where\n outside : Bool := false\n arities : List Nat := []\n\ndef Uses.join (a b : Uses) : Uses :=\n ⟨a.outside || b.outside, a.arities ++ b.arities⟩\n\ndef mapArity (layouts : List (Nat × Nat)) (mp : Nat) : Option Nat :=\n (layouts.find? (fun p => p.1 == mp)).map (·.2)\n\nmutual\n def inspectE (layouts : List (Nat × Nat)) (v : Nat) : E → Uses\n | .var i => ⟨i == v, []⟩\n | .const _ => {}\n | .get mp (.var i) =>\n if i != v then {} else\n match mapArity layouts mp with\n | some arity => ⟨false,[arity]⟩\n | none => ⟨true,[]⟩\n | .get _ key => inspectE layouts v key\n | .add a b | .sub a b | .min a b | .max a b | .prod a b | .tup a b =>\n (inspectE layouts v a).join (inspectE layouts v b)\n | .mul _ a | .proj _ a => inspectE layouts v a\n | .ite p a b => (inspectC layouts v p).join\n ((inspectE layouts v a).join (inspectE layouts v b))\n def inspectC (layouts : List (Nat × Nat)) (v : Nat) : C → Uses\n | .lt a b | .le a b | .eq a b => (inspectE layouts v a).join (inspectE layouts v b)\n | .and a b | .or a b => (inspectC layouts v a).join (inspectC layouts v b)\n | .not a => inspectC layouts v a\nend\n\nstructure Expanded where\n candidate : SEntry\n lawAddress : RawAddress\n skolemAddress : RawAddress\n\n/-- Expand a primary universal only if it occurs exclusively as a whole key\nof maps sharing an explicit arity. Reusing it as arithmetic, a tuple component,\na different-arity address, or a key of an untyped map is rejected. -/\ndef expandCandidate (layouts : List (Nat × Nat)) (fresh : List Nat)\n (e : SEntry) : Option Expanded := do\n let v ← e.law.key\n let uses := inspectC layouts v e.law.holds\n let arity ← uses.arities.head?\n if uses.outside || arity < 2 || !(uses.arities.all (· == arity)) ||\n fresh.length + 1 != arity || !(decide fresh.Nodup) ||\n !(fresh.all (fun f => f != v && f != e.sk && !e.keys2.contains f && !occC f e.law.holds)) then\n none\n else\n let parts := E.var v :: fresh.map E.var\n let law' := {e.law with holds := substC [(v,tuple parts)] e.law.holds}\n some ⟨{e with law := law', keys2 := e.keys2 ++ fresh},\n ⟨v,arity,parts⟩, ⟨e.sk,arity,E.var e.sk :: fresh.map E.var⟩⟩\n\n/-- A profile records only those referenced laws whose first binder expanded.\nExisting extra arguments are preserved after the new address components. -/\ndef translatePairInstance (radix : Nat) (profiles : List (Nat × Nat))\n (bindings : List RawAddress) (p : Nat × E × List E) :\n Except Error (Nat × E × List E) := do\n match profiles.find? (fun q => q.1 == p.1) with\n | none => return p\n | some profile =>\n let parts ← keyParts radix bindings profile.2 p.2.1\n match parts with\n | [] => throw (.unsupportedKey profile.2)\n | a :: rest => return (p.1,a,rest ++ p.2.2)\n\ndef translateInstances (radix : Nat) (profiles : List (Nat × Nat))\n (bindings : List RawAddress) : List (Nat × E) →\n Except Error (List (Nat × E) × List (Nat × E × List E))\n | [] => .ok ([],[])\n | p :: rest => do\n let (single,multiple) ← translateInstances radix profiles bindings rest\n if (profiles.find? (fun q => q.1 == p.1)).isSome then\n let translated ← translatePairInstance radix profiles bindings (p.1,p.2,[])\n return (single,translated :: multiple)\n else return (p :: single,multiple)\n\n/-- Untyped or mixed-role binders never silently become tuple addresses. -/\ntheorem mixed_role_refused (layouts : List (Nat × Nat)) (fresh : List Nat)\n (e : SEntry) (v : Nat) (hv : e.law.key = some v)\n (outside : (inspectC layouts v e.law.holds).outside = true) :\n expandCandidate layouts fresh e = none := by\n simp only [expandCandidate, hv, Option.bind_some]\n cases h : (inspectC layouts v e.law.holds).arities.head? with\n | none => simp [h]\n | some n => simp [h, outside]\n\n#print axioms mixed_role_refused\nend Bapa.RadixBinderExpansion\n",
36
+ "RadixCertificateTable.lean": "import RadixKeySyntax\n\n/-! The table/column phase of retained certificate re-keying. Every old column\nkeeps its relative position, after an explicit shift of fresh component\nvariables. Thus rows, monomials, cell-equality pairs and source hints have one\nuniform column map. A typed packed cell becomes a tuple cell. This constructs\ncandidate syntax only: it is NOT a validity-preservation claim. The complete\nkernel must recheck it, and a source-to-target bridge remains a separate duty. -/\nnamespace Bapa.RadixCertificateTable\nopen Kern\nopen RadixKeySyntax\n\ninductive Error where\n | key (reason : RadixKeySyntax.Error)\n | nonNaturalKeyRow\n | missingComponentColumn (variableId : Nat)\n | malformedTupleCell (map expected actual : Nat)\n deriving Repr, BEq\n\n/-- New variables go before every old definition, never after a dependent cell. -/\ndef freshVariables (tab : List VDef) (bindings : List RawAddress) : List Nat :=\n (bindings.flatMap (fun b => b.components.filterMap fun e =>\n match e with | .var v => some v | _ => none)).foldl (fun acc v =>\n if (findIdx (isVar v) tab).isSome || acc.contains v then acc else acc ++ [v]) []\n\ndef row (shift : Nat) (r : Cert.Row) : Cert.Row :=\n ⟨r.coefs.map (fun (i,c) => (i+shift,c)),r.const⟩\n\ndef pairs (shift : Nat) (ps : List (Nat × Nat)) : List (Nat × Nat) :=\n ps.map (fun (i,j) => (i+shift,j+shift))\n\ndef source (shift : Nat) : Src → Src\n | .nat i => .nat (i+shift)\n | .term i => .term (i+shift)\n | s => s\n\n/-- Arithmetic-step references name rows, not columns. Only an explicit cut\nrow contains columns; its source-row index and multiplier stay unchanged. -/\ndef proofStep (shift : Nat) : Cert.Step → Cert.Step\n | .cut i g q c => let r := row shift ⟨q,c⟩; .cut i g r.coefs r.const\n | s => s\n\n/-- A completely mechanical column relocation, with no pruning or leaf repair. -/\ndef relocateTree (shift : Nat) : Tree → Tree\n | .split r a b => .split (row shift r) (relocateTree shift a) (relocateTree shift b)\n | .leaf rs ss eqs prods =>\n .leaf (rs.map (row shift)) (ss.map (proofStep shift)) (pairs shift eqs) prods\n | .leafAt rs ss eqs prods =>\n .leafAt (rs.map (fun (r,s) => (row shift r,source shift s)))\n (ss.map (proofStep shift)) (pairs shift eqs) prods\n | .leafSq rs sqs ss eqs prods =>\n .leafSq (rs.map (fun (r,s) => (row shift r,source shift s)))\n (sqs.map (row shift)) (ss.map (proofStep shift)) (pairs shift eqs) prods\n\n/-- Formal polynomial place of one positive coefficient, capped at arity-1.\nThis is not an injectivity assertion about the old finite-radix encoding. -/\ndef coefficientPlace (radix : Nat) : Nat → Nat → Nat × Nat\n | 0, n => (0,n)\n | fuel+1, n =>\n if radix > 1 && n > 0 && n % radix == 0 then\n let (p,k) := coefficientPlace radix fuel (n / radix)\n (p+1,k)\n else (0,n)\n\ndef componentRow (radix arity component shift : Nat) (r : Cert.Row) : Cert.Row :=\n let cs := r.coefs.filterMap fun (j,c) =>\n let (place,k) := coefficientPlace radix (arity-1) c.natAbs\n if place + component + 1 == arity then some (j+shift,(k : Int)) else none\n let constant := ((literalParts radix arity r.const.natAbs)[component]?.getD (.const 0))\n let n := match constant with | .const n => n | _ => 0\n ⟨cs,n⟩\n\ndef components (radix arity : Nat) (bindings : List RawAddress)\n (oldTab newVars : List VDef) (r : Cert.Row) : Except Error (List Cert.Row) := do\n let shift := newVars.length\n if radix < 2 || arity < 2 then throw (.key (.unsupportedKey arity))\n -- A raw address must have an explicitly typed binder expansion. Never treat\n -- an unknown scalar variable as an already-decoded final component.\n match r.coefs with\n | [(j,1)] =>\n if r.const == 0 then\n match oldTab[j]? with\n | some (.var v) =>\n let b ← match bindings.find? (fun b => b.variableId == v && b.arity == arity) with\n | some b => pure b\n | none => throw (.key (.needBinderExpansion v arity))\n if b.components.length != arity then\n throw (.key (.malformedBinder v arity b.components.length))\n let basis := newVars ++ oldTab\n b.components.mapM fun e =>\n match linear basis [] e with\n | some r => pure r\n | none => throw (.missingComponentColumn v)\n | _ => throw (.key (.unsupportedKey arity))\n else decompose shift\n | _ => decompose shift\nwhere\n decompose shift :=\n if r.const < 0 || r.coefs.any (fun p => p.2 < 0) then .error .nonNaturalKeyRow\n else .ok ((List.range arity).map (fun i => componentRow radix arity i shift r))\n\n/-- The caller supplies the same typed expression translator used for the\nmachine and law. Unknown maps remain unary; an already-tuple cell must have its\nstated arity. Any later mismatch with a goal is rejected by the kernel. -/\ndef table (radix : Nat) (layouts : List (Nat × Nat)) (bindings : List RawAddress)\n (translate : E → Except Error E) (tab : List VDef) : Except Error (List VDef) := do\n let vars := (freshVariables tab bindings).map VDef.var\n let shift := vars.length\n let old ← tab.mapM fun d => do\n match d with\n | .var v => pure (.var v)\n | .mono js => pure (.mono (js.map (·+shift)))\n | .term e => return .term (← translate e)\n | .cell m key =>\n match (layouts.find? (fun p => p.1 == m)).map (·.2) with\n | none => pure (.cell m (row shift key))\n | some arity => return .cellT m (← components radix arity bindings tab vars key)\n | .cellT m keys =>\n match (layouts.find? (fun p => p.1 == m)).map (·.2) with\n | some arity =>\n if keys.length != arity then throw (.malformedTupleCell m arity keys.length)\n else pure (.cellT m (keys.map (row shift)))\n | none => pure (.cellT m (keys.map (row shift)))\n return vars ++ old\n\n/-- Relocation does not conflate distinct cell columns. -/\ntheorem column_map_injective (shift i j : Nat) : i+shift = j+shift ↔ i=j := by omega\n\ntheorem moved_bound_row :\n (row 3 (sp [(2,1)] (-63))).coefs = [(5,1)] ∧\n (row 3 (sp [(2,1)] (-63))).const = -63 := by decide +kernel\n\ndef expectedComponents (result : Except Error (List Cert.Row))\n (expected : List (List (Nat × Int) × Int)) : Bool :=\n match result with\n | .ok rs => rs.map (fun r => (r.coefs,r.const)) == expected\n | .error _ => false\n\ntheorem packed_pair_components : expectedComponents\n (components 64 2 [] [.var 0,.var 1] [] (sp [(0,64),(1,1)] 0))\n [([(0,1)],0), ([(1,1)],0)] = true := by decide +kernel\n\ntheorem packed_triple_components : expectedComponents\n (components 64 3 [] [.var 0,.var 1,.var 2] [] (sp [(0,4096),(1,64),(2,1)] 0))\n [([(0,1)],0), ([(1,1)],0), ([(2,1)],0)] = true := by decide +kernel\n\ndef rawAddressRefused : Bool :=\n match components 64 2 [] [.var 18] [] (sp [(0,1)] 0) with\n | .error (.key (.needBinderExpansion 18 2)) => true\n | _ => false\n\ntheorem unknown_raw_address_refused : rawAddressRefused = true := by decide +kernel\n\ntheorem raw_address_components : expectedComponents\n (components 64 2 [⟨18,2,[.var 18,.var 100]⟩] [.var 18] [.var 100]\n (sp [(0,1)] 0)) [([(1,1)],0), ([(0,1)],0)] = true := by decide +kernel\n\n#print axioms column_map_injective\n#print axioms moved_bound_row\n#print axioms packed_pair_components\n#print axioms packed_triple_components\n#print axioms unknown_raw_address_refused\n#print axioms raw_address_components\nend Bapa.RadixCertificateTable\n",
37
+ "RadixTupleSyntax.lean": "import RadixBinderExpansion\n\n/-! Typed machine/law/instance syntax for packed-key certificate candidates.\nOnly map keys with declared layouts are re-keyed. A whole-address binder used\nin an equality has to have an explicit RawAddress binding; unrelated arithmetic\nis not rewritten. A map's `every` binder remains one raw tuple-encoded natural,\nwith projections used in its body. All resulting goals and tables must still be\naccepted by the complete kernel. No source-bridge claim is made here. -/\nnamespace Bapa.RadixTupleSyntax\nopen Kern\nopen RadixKeySyntax\n\nstructure Config where\n radix : Nat := 64\n layouts : List (Nat × Nat)\n bindings : List RawAddress := []\n sizeVariable : Option Nat := none\n\n/-- Bind a whole tuple address without adding free component parameters to a\nmachine. After a tuple key is substituted, these projections are linearizable. -/\ndef projectionParts : Nat → E → List E\n | 0, _ => []\n | 1, e => [e]\n | n+2, e => .proj 0 e :: projectionParts (n+1) (.proj 1 e)\n\ndef rawArity (cfg : Config) : E → Option Nat\n | .var v => (cfg.bindings.find? (fun b => b.variableId == v)).map (·.arity)\n | _ => none\n\ndef key (cfg : Config) (mp : Nat) (e : E) : Except Error E :=\n match RadixBinderExpansion.mapArity cfg.layouts mp with\n | none => .ok e\n | some arity => rekey cfg.radix arity cfg.bindings e\n\ndef equality (cfg : Config) (a b a' b' : E) : Except Error C := do\n match rawArity cfg a, rawArity cfg b with\n | none, none => do return .eq a' b'\n | some arity, none | none, some arity =>\n return .eq (← rekey cfg.radix arity cfg.bindings a')\n (← rekey cfg.radix arity cfg.bindings b')\n | some arity, some other =>\n if arity != other then throw (.unsupportedKey other)\n return .eq (← rekey cfg.radix arity cfg.bindings a')\n (← rekey cfg.radix arity cfg.bindings b')\n\nmutual\n def expr (cfg : Config) : E → Except Error E\n | .var i => .ok (.var i)\n | .const n => .ok (.const n)\n | .add a b => do return .add (← expr cfg a) (← expr cfg b)\n | .sub a b => do return .sub (← expr cfg a) (← expr cfg b)\n | .mul n a => do return .mul n (← expr cfg a)\n | .min a b => do return .min (← expr cfg a) (← expr cfg b)\n | .max a b => do return .max (← expr cfg a) (← expr cfg b)\n | .prod a b => do return .prod (← expr cfg a) (← expr cfg b)\n | .ite p a b => do return .ite (← condition cfg p) (← expr cfg a) (← expr cfg b)\n | .get mp k => do return .get mp (← key cfg mp (← expr cfg k))\n | .tup a b => do return .tup (← expr cfg a) (← expr cfg b)\n | .proj i a => do return .proj i (← expr cfg a)\n def condition (cfg : Config) : C → Except Error C\n | .lt a (.const n) => do\n if n == cfg.radix then\n match cfg.sizeVariable with\n | none => do return trueC\n | some v => do return .lt (← expr cfg a) (.var v)\n return .lt (← expr cfg a) (.const n)\n | .le a (.const n) => do\n if n == cfg.radix then\n match cfg.sizeVariable with\n | none => do return trueC\n | some v => do return .le (← expr cfg a) (.var v)\n return .le (← expr cfg a) (.const n)\n | .lt a b => do return .lt (← expr cfg a) (← expr cfg b)\n | .le a b => do return .le (← expr cfg a) (← expr cfg b)\n | .eq a b => do equality cfg a b (← expr cfg a) (← expr cfg b)\n | .and a b => do return .and (← condition cfg a) (← condition cfg b)\n | .or a b => do return .or (← condition cfg a) (← condition cfg b)\n | .not a => do return .not (← condition cfg a)\nend\n\ndef law (cfg : Config) (l : MLaw) : Except Error MLaw := do\n return {l with holds := ← condition cfg l.holds}\n\ndef scalarMachine (cfg : Config) (m : MMachine) : Except Error MMachine := do\n return {m with\n init := ← m.init.mapM (fun p => do return (p.1,← expr cfg p.2))\n step := ← m.step.mapM (fun p => do return (p.1,← expr cfg p.2))\n writes := ← m.writes.mapM (fun p => do\n let k ← key cfg p.1 (← expr cfg p.2.1)\n return (p.1,k,← expr cfg p.2.2))\n pre := ← condition cfg m.pre\n assume := ← condition cfg m.assume}\n\ndef machine (cfg : Config) (s : SMachine) : Except Error SMachine := do\n return {s with\n f := {s.f with\n m := ← scalarMachine cfg s.f.m\n flags := ← s.f.flags.mapM (fun p => do return (p.1,← condition cfg p.2))}\n every := ← s.every.mapM (fun p => do return (p.1,p.2.1,← expr cfg p.2.2))\n qflags := ← s.qflags.mapM (fun p => do return (p.1,p.2.1,← condition cfg p.2.2))\n facts := ← s.facts.mapM (law cfg)\n pfacts := ← s.pfacts.mapM (fun p => do return (← law cfg p.1,p.2))}\n\n/-- Expand references to an expanded primary binder into the kernel's existing\nmulti-binder instance format. Profiles of laws and of facts are separate. -/\ndef instances (cfg : Config) (profiles : List (Nat × Nat))\n (single : List (Nat × E)) (multiple : List (Nat × E × List E)) :\n Except Error (List (Nat × E) × List (Nat × E × List E)) := do\n let (kept,expanded) ← RadixBinderExpansion.translateInstances cfg.radix profiles cfg.bindings single\n let original ← multiple.mapM (RadixBinderExpansion.translatePairInstance cfg.radix profiles cfg.bindings)\n let one ← kept.mapM (fun p => do return (p.1,← expr cfg p.2))\n let many ← (expanded ++ original).mapM (fun p => do\n return (p.1,← expr cfg p.2.1,← p.2.2.mapM (expr cfg)))\n return (one,many)\n\n/-- This phase intentionally leaves certificate tables and trees untouched.\nThe complete translator must replace them before calling checkSMachine. -/\ndef entrySyntax (cfg : Config) (lawProfiles factProfiles : List (Nat × Nat))\n (e : SEntry) : Except Error SEntry := do\n let (insts,pinsts) ← instances cfg lawProfiles e.insts e.pinsts\n let (finsts,pfinsts) ← instances cfg factProfiles e.finsts e.pfinsts\n return {e with\n law := ← law cfg e.law\n insts := insts\n pinsts := pinsts\n finsts := finsts\n pfinsts := pfinsts\n qinsts := ← e.qinsts.mapM (fun p => do return (p.1,← p.2.mapM (expr cfg)))}\n\ndef expectedC (r : Except Error C) (c : C) : Bool :=\n match r with | .ok c' => beqC c' c | .error _ => false\n\ndef pairConfig : Config := ⟨64,[(0,2)],[],none⟩\ndef rawConfig : Config := ⟨64,[(0,2)],[⟨18,2,[.var 18,.var 100]⟩],none⟩\n\ntheorem pair_read : expected\n (expr pairConfig (.get 0 (.add (.mul 64 (.var 1)) (.var 2))))\n (.get 0 (.tup (.var 1) (.var 2))) = true := by decide +kernel\n\ntheorem raw_read : expected (expr rawConfig (.get 0 (.var 18)))\n (.get 0 (.tup (.var 18) (.var 100))) = true := by decide +kernel\n\ntheorem raw_comparison : expectedC\n (condition rawConfig (.eq (.var 18) (.add (.mul 64 (.var 1)) (.var 2))))\n (.eq (.tup (.var 18) (.var 100)) (.tup (.var 1) (.var 2))) = true := by decide +kernel\n\ntheorem unrelated_comparison : expectedC\n (condition pairConfig (.eq (.var 3) (.const 1)))\n (.eq (.var 3) (.const 1)) = true := by decide +kernel\n\ntheorem erased_bound : expectedC\n (condition pairConfig (.lt (.var 1) (.const 64))) trueC = true := by decide +kernel\n\ntheorem replaced_bound : expectedC\n (condition {pairConfig with sizeVariable := some 200} (.lt (.var 1) (.const 64)))\n (.lt (.var 1) (.var 200)) = true := by decide +kernel\n\ntheorem projection_arity : (projectionParts 3 (.var 40)).length = 3 := rfl\n\n#print axioms pair_read\n#print axioms raw_read\n#print axioms raw_comparison\n#print axioms unrelated_comparison\n#print axioms erased_bound\n#print axioms replaced_bound\n#print axioms projection_arity\nend Bapa.RadixTupleSyntax\n",
38
+ "RadixEqualityTree.lean": "import RadixCertificateTable\nimport CertificateBoundErasure\n\n/-! Replace recognized two-sided packed-address equality tests by component\ncomparisons. This is a deterministic certificate candidate transformation,\nNOT an assertion that integer ordering of packed keys survives unbounded\nre-keying. Every resulting branch and arithmetic leaf is rechecked by Kern.\nNo new premise, arithmetic search, or invariant is introduced. -/\nnamespace Bapa.RadixEqualityTree\nopen Kern\n\nstructure Plan where\n old : Cert.Row\n components : List Cert.Row\n\n/-- Obtain tuple equality plans only from matching old/new cell columns. -/\ndef plans (shift : Nat) (oldTab newTab : List VDef) : List Plan :=\n (List.range oldTab.length).flatMap fun i =>\n (List.range oldTab.length).filterMap fun j =>\n match oldTab[i]?, oldTab[j]?, newTab[i+shift]?, newTab[j+shift]? with\n | some (VDef.cell m a), some (VDef.cell n b), some (VDef.cellT m' as_), some (VDef.cellT n' bs) =>\n if m == n && m == m' && n == n' && as_.length == bs.length &&\n as_.length > 1 && !(same a b) then\n some ⟨lsub a b,(as_.zip bs).map (fun (x,y) => lsub x y)⟩\n else none\n | _, _, _, _ => none\n\n/-- A context changes exactly scalar multiples of one old comparison's\ncoefficient vector. Its constant offset is preserved. This merely proposes\nleaf rows; the new leaf checker still has to find every proposed premise. -/\ndef rewriteOne (p : Plan) (replacement r : Cert.Row) : Option Cert.Row := do\n let (j,c) ← p.old.coefs.find? (fun q => q.2 != 0)\n let a := ((r.coefs.find? (fun q => q.1 == j)).map (·.2)).getD 0\n if a % c != 0 then none else\n let factor := a / c\n if Cert.allZero (lsub r (lscale factor p.old)).coefs then\n some (ladd (lscale factor replacement) (lconst (r.const-factor*p.old.const)))\n else none\n\ndef row (shift : Nat) (contexts : List (Plan × Cert.Row)) (r : Cert.Row) : Cert.Row :=\n match contexts.findSome? (fun (p,replacement) => rewriteOne p replacement r) with\n | some r' => r'\n | none => RadixCertificateTable.row shift r\n\ndef step (shift : Nat) (contexts : List (Plan × Cert.Row)) : Cert.Step → Cert.Step\n | .cut i g q c => let r := row shift contexts ⟨q,c⟩; .cut i g r.coefs r.const\n | s => s\n\n/-- Componentwise equality is the conjunction of both non-strict comparisons\nfor each component. All negative/positive branches remain present. -/\ndef componentCases (equal : Tree) (negative positive : Cert.Row → Tree) : List Cert.Row → Tree\n | [] => equal\n | r :: rs => .split r\n (.split (lscale (-1) r) (componentCases equal negative positive rs) (negative r))\n (positive r)\n\ndef tree (shift : Nat) (bound : Option Nat) (ps : List Plan)\n (contexts : List (Plan × Cert.Row)) : Tree → Tree\n | .split r yes no =>\n match bound.bind (fun n => CertificateBoundErasure.erasedSplit n r) with\n | some true => tree shift bound ps contexts yes\n | some false => tree shift bound ps contexts no\n | none =>\n match hyes : yes, ps.find? (fun p => same p.old r) with\n | .split opposite equal negative, some plan =>\n if same opposite (lscale (-1) r) then\n componentCases\n (tree shift bound ps ((plan,lconst 0)::contexts) equal)\n (fun component => tree shift bound ps ((plan,component)::contexts) negative)\n (fun component => tree shift bound ps ((plan,component)::contexts) no)\n plan.components\n else .split (row shift contexts r)\n (tree shift bound ps contexts yes) (tree shift bound ps contexts no)\n | _, _ => .split (row shift contexts r)\n (tree shift bound ps contexts yes) (tree shift bound ps contexts no)\n | .leaf rs ss eqs prods =>\n .leaf (rs.map (row shift contexts)) (ss.map (step shift contexts))\n (RadixCertificateTable.pairs shift eqs) prods\n | .leafAt rs ss eqs prods =>\n .leafAt (rs.map (fun (r,s) => (row shift contexts r,RadixCertificateTable.source shift s)))\n (ss.map (step shift contexts)) (RadixCertificateTable.pairs shift eqs) prods\n | .leafSq rs sqs ss eqs prods =>\n .leafSq (rs.map (fun (r,s) => (row shift contexts r,RadixCertificateTable.source shift s)))\n (sqs.map (row shift contexts)) (ss.map (step shift contexts))\n (RadixCertificateTable.pairs shift eqs) prods\ntermination_by t => sizeOf t\ndecreasing_by all_goals simp_all <;> omega\n\n/-- Only the complete trusted checker can turn candidate syntax into a law. -/\ntheorem checked_family (s : SMachine) (ps : List SEntry)\n (h : checkSMachine s ps = true) :\n ∀ ρ M, SReach s ρ M → ∀ e ∈ ps, e.Holds ρ M := smachine_sound _ _ h\n\n#print axioms checked_family\nend Bapa.RadixEqualityTree\n",
39
+ "CertificateBooleanCleanup.lean": "import CertificateBoundErasure\n\n/-! A deterministic Boolean cleanup after bound erasure. No SAT/SMT solver,\ninvariant enumeration, arithmetic proof search, or invented assumption is used.\nA rejected leaf is replaced ONLY when the target kernel's own leafRows already\ncontains a positive constant row. The complete checker must still accept the\nresulting tree, including all equal-cell side conditions. -/\nnamespace Bapa.CertificateBooleanCleanup\nopen Kern\n\ndef closeLeaf (tab : List VDef) (hyps : List C) (path : Path)\n (eqs : List (Nat × Nat)) (original : Tree) : Tree :=\n if checkT tab hyps path original then original else\n match (leafRows tab path hyps eqs).find? (fun r => Cert.allZero r.coefs && decide (0 < r.const)) with\n | none => original\n | some r => .leafAt [(r,.any)] [.input 0] eqs []\n\ndef tree (tab : List VDef) (hyps : List C) : Path → Tree → Tree\n | path, .split row yes no => .split row\n (tree tab hyps ((row,true)::path) yes) (tree tab hyps ((row,false)::path) no)\n | path, t@(.leaf _ _ eqs _) => closeLeaf tab hyps path eqs t\n | path, t@(.leafAt _ _ eqs _) => closeLeaf tab hyps path eqs t\n | path, t@(.leafSq _ _ _ eqs _) => closeLeaf tab hyps path eqs t\n\ndef certificate (goal : List C) (k : Kern.Cert) : Kern.Cert :=\n let hyps := if k.2.1.isEmpty then goal else k.2.1\n (k.1,k.2.1,tree k.1 hyps [] k.2.2)\n\ndef entry (s : SMachine) (ps : List SEntry) (e : SEntry) : SEntry :=\n {e with\n start := certificate (sStartGoal s e) e.start\n step := certificate (sStepGoal s ps e) e.step}\n\ntheorem named_hypotheses_unchanged (goal : List C) (k : Kern.Cert) :\n (certificate goal k).2.1 = k.2.1 := rfl\n\ntheorem table_unchanged (goal : List C) (k : Kern.Cert) :\n (certificate goal k).1 = k.1 := rfl\n\n#print axioms named_hypotheses_unchanged\n#print axioms table_unchanged\nend Bapa.CertificateBooleanCleanup\n",
40
+ "RadixCertificateTransport.lean": "import RadixTupleSyntax\nimport RadixEqualityTree\nimport CertificateBooleanCleanup\n\n/-! General, fail-closed composition of the typed key, binder, table and tree\nphases. The result is a candidate. Only a complete checkSMachine result gives a\nfamily theorem; there is no unconditional claim that fixed-radix certificates\nsurvive re-keying. The original source bridge is a separate obligation. -/\nnamespace Bapa.RadixCertificateTransport\nopen Kern\n\ninductive Error where\n | binder (index : Nat)\n | syntax (reason : RadixKeySyntax.Error)\n | table (reason : RadixCertificateTable.Error)\n | obligation (index : Nat) (phase reason : String)\n deriving Repr\n\nstructure Prepared where\n entry : SEntry\n profile : Option (Nat × Nat) := none\n bindings : List RadixKeySyntax.RawAddress := []\n\ndef prepare (layouts : List (Nat × Nat)) (freshBase index : Nat) (e : SEntry) : Except Error Prepared := do\n match e.law.key with\n | none => return ⟨e,none,[]⟩\n | some v =>\n let uses := RadixBinderExpansion.inspectC layouts v e.law.holds\n match uses.arities.head? with\n | none => return ⟨e,none,[]⟩\n | some arity =>\n let fresh := (List.range (arity-1)).map (fun i => freshBase + index*16+i)\n match RadixBinderExpansion.expandCandidate layouts fresh e with\n | none => throw (.binder index)\n | some p => return ⟨p.candidate,some (index,arity),[p.lawAddress,p.skolemAddress]⟩\n\ndef liftSyntax {α : Type} : Except RadixKeySyntax.Error α → Except Error α\n | .ok x => .ok x\n | .error e => .error (.syntax e)\n\ndef liftTable {α : Type} : Except RadixCertificateTable.Error α → Except Error α\n | .ok x => .ok x\n | .error e => .error (.table e)\n\ndef atObligation {α : Type} (index : Nat) (phase : String) : Except Error α → Except Error α\n | .ok x => .ok x\n | .error e => .error (.obligation index phase (reprStr e))\n\ndef translatedTableExpr (cfg : RadixTupleSyntax.Config) (e : E) :\n Except RadixCertificateTable.Error E :=\n match RadixTupleSyntax.expr cfg e with\n | .ok e => .ok e\n | .error e => .error (.key e)\n\n/-- Keep the actual target goal, not an invented replacement hypothesis list.\nAn empty named list tells checkIn to use its own complete generated goal. -/\ndef certificate (cfg : RadixTupleSyntax.Config) (cleanup : Bool) (goal : List C)\n (k : Kern.Cert) : Except Error Kern.Cert := do\n let tab ← liftTable (RadixCertificateTable.table cfg.radix cfg.layouts cfg.bindings\n (translatedTableExpr cfg) k.1)\n let shift := (RadixCertificateTable.freshVariables k.1 cfg.bindings).length\n let plans := RadixEqualityTree.plans shift k.1 tab\n let bound := if cfg.sizeVariable.isNone then some cfg.radix else none\n let candidate : Kern.Cert :=\n (tab,[],RadixEqualityTree.tree shift bound plans [] k.2.2)\n return if cleanup then CertificateBooleanCleanup.certificate goal candidate else candidate\n\n/-- Whole-address every binders remain bound variables, represented in the\nbody by explicit projection components; they do not become free parameters. -/\ndef everyBindings (layouts : List (Nat × Nat)) (s : SMachine) : List RadixKeySyntax.RawAddress :=\n s.every.filterMap fun p =>\n (RadixBinderExpansion.mapArity layouts p.1).map fun arity =>\n ⟨p.2.1,arity,RadixTupleSyntax.projectionParts arity (.var p.2.1)⟩\n\ndef translate (layouts : List (Nat × Nat)) (freshBase : Nat) (cleanup : Bool)\n (s : SMachine) (ps : List SEntry) : Except Error (SMachine × List SEntry) := do\n let prepared ← ps.zipIdx.mapM (fun (e,i) => prepare layouts freshBase i e)\n let profiles := prepared.filterMap (·.profile)\n let bindings := prepared.flatMap (·.bindings) ++ everyBindings layouts s\n let cfg : RadixTupleSyntax.Config := ⟨64,layouts,bindings,none⟩\n let machine ← liftSyntax (RadixTupleSyntax.machine cfg s)\n let entries ← prepared.zipIdx.mapM (fun (p,i) =>\n atObligation i \"syntax\" (liftSyntax (RadixTupleSyntax.entrySyntax cfg profiles [] p.entry)))\n let proof ← entries.zipIdx.mapM fun (e,i) => do\n let start ← atObligation i \"init\" (certificate cfg cleanup (sStartGoal machine e) e.start)\n let step ← atObligation i \"step\" (certificate cfg cleanup (sStepGoal machine entries e) e.step)\n return {e with start := start, step := step}\n return (machine,proof)\n\n/-- The same complete trusted gate is mandatory after every translation. -/\ntheorem checked (layouts : List (Nat × Nat)) (freshBase : Nat) (cleanup : Bool)\n (s : SMachine) (ps : List SEntry) (s' : SMachine) (ps' : List SEntry)\n (_translated : translate layouts freshBase cleanup s ps = .ok (s',ps'))\n (h : checkSMachine s' ps' = true) :\n ∀ ρ M, SReach s' ρ M → ∀ e ∈ ps', e.Holds ρ M := smachine_sound _ _ h\n\n#print axioms checked\nend Bapa.RadixCertificateTransport\n",
41
+ "FamilyParts.lean": "import CountMachine\n/-! One entry's check in pieces (research module, generated proofs' library; not part of the trusted files).\nEvery definition below is a restatement of a part of the existing check, and every theorem concludes the ORIGINAL\n`cEntryCheckF` / `checkMCF` / `checkGoalFrames` / `checkTFrames` from the pieces. Only that direction is used. -/\nopen Kern Cert\nnamespace FamilyParts\n\n/-- The subtree at an address, with the path extended by exactly the split conditions passed on the way. The walk\nstops at the first leaf: an address longer than the branch names that leaf with its own path. -/\ndef subAt : Path → Tree → List Bool → Path × Tree\n | p, .split l y _, true :: bs => subAt ((l, true) :: p) y bs\n | p, .split l _ n, false :: bs => subAt ((l, false) :: p) n bs\n | p, t, _ => (p, t)\n\ndef checkAt (tab : List VDef) (hyps : List C) (lemmas : List CutLemma) (frames : List FrameCut) (monos : List MonoCut) (lins : List LinCut)\n (p : Path) (t : Tree) (a : List Bool) : Bool :=\n checkTFrames tab hyps lemmas frames monos lins (subAt p t a).1 (subAt p t a).2\n\ntheorem checkAt_nil (tab : List VDef) (hyps : List C) (lemmas : List CutLemma) (frames : List FrameCut) (monos : List MonoCut) (lins : List LinCut)\n (p : Path) (t : Tree) (h : checkAt tab hyps lemmas frames monos lins p t [] = true) :\n checkTFrames tab hyps lemmas frames monos lins p t = true := by\n cases t <;> simpa [checkAt, subAt] using h\n\n/-- Both children of an address give the address. At a leaf either child is the leaf itself. -/\ntheorem checkAt_split (tab : List VDef) (hyps : List C) (lemmas : List CutLemma) (frames : List FrameCut) (monos : List MonoCut) (lins : List LinCut) :\n ∀ (a : List Bool) (p : Path) (t : Tree),\n checkAt tab hyps lemmas frames monos lins p t (a ++ [true]) = true →\n checkAt tab hyps lemmas frames monos lins p t (a ++ [false]) = true →\n checkAt tab hyps lemmas frames monos lins p t a = true := by\n intro a\n induction a with\n | nil =>\n intro p t h1 h0\n cases t with\n | split l y n =>\n simp only [checkAt, subAt, List.nil_append] at h1 h0 ⊢\n cases y <;> cases n <;> simp_all [checkTFrames, subAt]\n | leaf rows steps eqs prods => simpa [checkAt, subAt] using h1\n | leafAt rows steps eqs prods => simpa [checkAt, subAt] using h1\n | leafSq rows sqs steps eqs prods => simpa [checkAt, subAt] using h1\n | cons b a ih =>\n intro p t h1 h0\n cases t with\n | split l y n =>\n cases b with\n | true => exact ih ((l, true) :: p) y (by simpa [checkAt, subAt] using h1) (by simpa [checkAt, subAt] using h0)\n | false => exact ih ((l, false) :: p) n (by simpa [checkAt, subAt] using h1) (by simpa [checkAt, subAt] using h0)\n | leaf rows steps eqs prods => simpa [checkAt, subAt] using h1\n | leafAt rows steps eqs prods => simpa [checkAt, subAt] using h1\n | leafSq rows sqs steps eqs prods => simpa [checkAt, subAt] using h1\n\n/-- The list after j chunks of c. -/\ndef dropN (c : Nat) : Nat → List α → List α\n | 0, l => l\n | j + 1, l => (dropN c j l).drop c\n\n/-- A list's check from its first c elements and the rest: every element is in one of the two. -/\ntheorem all_split (p : α → Bool) (c : Nat) (l : List α) (h1 : (l.take c).all p = true) (h2 : (l.drop c).all p = true) : l.all p = true := by\n have h : (l.take c ++ l.drop c).all p = true := by rw [List.all_append, h1, h2]; rfl\n rwa [List.take_append_drop] at h\n\n/-- The step goal the original check builds, handed to a condition q; false when the original has no goal. -/\ndef mcfWith (ds : List CDecl) (k : CCert) (q : Goal → List Count → Bool) : Bool :=\n match toCounts ds k.reads with\n | some cs => match countHyps cs k.insts with\n | some hs => q ⟨k.tab, (k.hyps ++ k.reads.map (readHyp ds) ++ pickHyps ds k.reads k.picks) ++ hs⟩ cs\n | none => false\n | none => false\n\n/-- The original check's conditions outside the goal. -/\ndef mcfPre (hyps : List C) (ds : List CDecl) (k : CCert) : Bool :=\n namedIn hyps k.hyps hyps && ds.all (fun d => d.j != d.key && d.lo != d.key) && readsOk k.hyps ds k.reads\n && k.reads.all (fun r => k.insts.all (fun i => i.wit != r.1 && !occE i.wit r.2.2))\n && mcfWith ds k (fun _ cs => countedOkW cs k.insts)\n\n/-- The goal check's conditions outside the frames and the tree. -/\ndef goalPre (lemmas : List CutLemma) (monos : List MonoCut) (lins : List LinCut) (g : Goal) (cs : List Count) : Bool :=\n wfTab 0 g.tab && lemmas.all (checkLemma g.tab g.hyps) && monos.all (monoOk cs) && lins.all (linOk cs)\n\ntheorem goal_of_parts (g : Goal) (cs : List Count) (t : Tree) (lemmas : List CutLemma) (frames : List FrameCut) (monos : List MonoCut) (lins : List LinCut)\n (h0 : goalPre lemmas monos lins g cs = true) (hf : frames.all (frameOk g.tab cs) = true)\n (ht : checkAt g.tab g.hyps lemmas frames monos lins [] t [] = true) :\n checkGoalFrames g cs t lemmas frames monos lins = true := by\n have ht' := checkAt_nil _ _ _ _ _ _ _ _ ht\n simp only [goalPre, Bool.and_eq_true] at h0\n simp only [checkGoalFrames, Bool.and_eq_true]\n exact ⟨⟨⟨⟨⟨h0.1.1.1, h0.1.1.2⟩, hf⟩, h0.1.2⟩, h0.2⟩, ht'⟩\n\ntheorem mcfWith_map1 (ds : List CDecl) (k : CCert) (q r : Goal → List Count → Bool)\n (h : ∀ g cs, q g cs = true → r g cs = true) (hq : mcfWith ds k q = true) : mcfWith ds k r = true := by\n unfold mcfWith at hq ⊢\n cases h1 : toCounts ds k.reads with\n | none => rw [h1] at hq; cases hq\n | some cs =>\n rw [h1] at hq; simp only at hq ⊢\n cases h2 : countHyps cs k.insts with\n | none => rw [h2] at hq; cases hq\n | some hs => rw [h2] at hq; exact h _ _ hq\n\ntheorem mcfWith_map2 (ds : List CDecl) (k : CCert) (q1 q2 r : Goal → List Count → Bool)\n (h : ∀ g cs, q1 g cs = true → q2 g cs = true → r g cs = true) (h1 : mcfWith ds k q1 = true) (h2 : mcfWith ds k q2 = true) : mcfWith ds k r = true := by\n unfold mcfWith at h1 h2 ⊢\n cases e1 : toCounts ds k.reads with\n | none => rw [e1] at h1; cases h1\n | some cs =>\n rw [e1] at h1 h2; simp only at h1 h2 ⊢\n cases e2 : countHyps cs k.insts with\n | none => rw [e2] at h1; cases h1\n | some hs => rw [e2] at h1 h2; exact h _ _ h1 h2\n\ntheorem mcfWith_map3 (ds : List CDecl) (k : CCert) (q1 q2 q3 r : Goal → List Count → Bool)\n (h : ∀ g cs, q1 g cs = true → q2 g cs = true → q3 g cs = true → r g cs = true)\n (h1 : mcfWith ds k q1 = true) (h2 : mcfWith ds k q2 = true) (h3 : mcfWith ds k q3 = true) : mcfWith ds k r = true := by\n unfold mcfWith at h1 h2 h3 ⊢\n cases e1 : toCounts ds k.reads with\n | none => rw [e1] at h1; cases h1\n | some cs =>\n rw [e1] at h1 h2 h3; simp only at h1 h2 h3 ⊢\n cases e2 : countHyps cs k.insts with\n | none => rw [e2] at h1; cases h1\n | some hs => rw [e2] at h1 h2 h3; exact h _ _ h1 h2 h3\n\n/-- The original `checkMCF` from the conditions outside the goal and the goal check. -/\ntheorem checkMCF_of_parts (hyps : List C) (ds : List CDecl) (k : CCert) (frames : List FrameCut) (monos : List MonoCut) (lins : List LinCut)\n (hpre : mcfPre hyps ds k = true)\n (hgoal : mcfWith ds k (fun g cs => checkGoalFrames g cs k.tree k.lemmas frames monos lins) = true) :\n checkMCF hyps ds k frames monos lins = true := by\n unfold mcfPre at hpre\n unfold mcfWith at hpre hgoal\n unfold checkMCF checkCountedWF\n cases e1 : toCounts ds k.reads with\n | none => rw [e1] at hgoal; cases hgoal\n | some cs =>\n rw [e1] at hpre hgoal; simp only at hpre hgoal ⊢\n cases e2 : countHyps cs k.insts with\n | none => rw [e2] at hgoal; cases hgoal\n | some hs =>\n rw [e2] at hpre hgoal; simp only [Bool.and_eq_true] at hpre hgoal ⊢\n exact ⟨hpre.1, hpre.2, hgoal⟩\n\n/-- The entry's conditions other than the step goal. -/\ndef entryRest (s : SMachine) (ds : List CDecl) (es : List SEntry) (ce : CEntryF) : Bool :=\n cEntryOk s ds es ce.e && witsOk s es ce.start && witsOk s es ce.step\n && checkMCF (cStartGoal s ds ce.e) (cStartDecls s ds) ce.start ce.startAux.frames ce.startAux.monos ce.startAux.lins\n\n/-- The original `cEntryCheckF` from its pieces. -/\ntheorem entry_of_parts (s : SMachine) (ds : List CDecl) (es : List SEntry) (ce : CEntryF)\n (hrest : entryRest s ds es ce = true)\n (hstep : checkMCF (cStepGoal s ds es ce.e) (cStepDecls s ds) ce.step ce.stepAux.frames ce.stepAux.monos ce.stepAux.lins = true) :\n cEntryCheckF s ds es ce = true := by\n unfold entryRest at hrest\n unfold cEntryCheckF\n rw [hrest, hstep]; rfl\n\n-- Both primary obligations may be partitioned; no monolithic INIT is hidden in entryRest.\ndef entryPre (s : SMachine) (ds : List CDecl) (es : List SEntry) (ce : CEntryF) : Bool :=\n cEntryOk s ds es ce.e && witsOk s es ce.start && witsOk s es ce.step\n\ntheorem entry_of_both (s : SMachine) (ds : List CDecl) (es : List SEntry) (ce : CEntryF)\n (hp : entryPre s ds es ce = true)\n (hstart : checkMCF (cStartGoal s ds ce.e) (cStartDecls s ds) ce.start ce.startAux.frames ce.startAux.monos ce.startAux.lins = true)\n (hstep : checkMCF (cStepGoal s ds es ce.e) (cStepDecls s ds) ce.step ce.stepAux.frames ce.stepAux.monos ce.stepAux.lins = true) :\n cEntryCheckF s ds es ce = true := by\n unfold entryPre at hp\n unfold cEntryCheckF\n rw [hp, hstart, hstep]\n rfl\n\nend FamilyParts\n#print axioms FamilyParts.entry_of_both\n#print axioms FamilyParts.checkAt_nil\n#print axioms FamilyParts.checkAt_split\n#print axioms FamilyParts.all_split\n#print axioms FamilyParts.goal_of_parts\n#print axioms FamilyParts.mcfWith_map1\n#print axioms FamilyParts.mcfWith_map2\n#print axioms FamilyParts.mcfWith_map3\n#print axioms FamilyParts.checkMCF_of_parts\n#print axioms FamilyParts.entry_of_parts\n",
42
+ "StructuralWeakening.lean": "import SourceInclusion\nimport CertificateBoundErasure\n\n/-! Finite syntax certificates, not a decision procedure for semantic implication.\nThe generator proposes constructor trees; Lean checks every atom by definitional\nidentity. Neither arithmetic validity nor arbitrary propositional validity is\ninferred. Quantifier keys are checked separately by SourceLawImplication. -/\nnamespace Bapa.StructuralWeakening\nopen Kern\n\ninductive Subsumes : C → C → Prop where\n | refl (p : C) : Subsumes p p\n | top (p : C) : Subsumes p trueC\n | bot (p : C) : Subsumes (.lt (.const 0) (.const 0)) p\n | neg {p q} : Subsumes q p → Subsumes (.not p) (.not q)\n | orLeft {p q r} : Subsumes p q → Subsumes p (.or q r)\n | orRight {p q r} : Subsumes p r → Subsumes p (.or q r)\n | orElim {p q r} : Subsumes p r → Subsumes q r → Subsumes (.or p q) r\n | andLeft {p q r} : Subsumes p r → Subsumes (.and p q) r\n | andRight {p q r} : Subsumes q r → Subsumes (.and p q) r\n | andIntro {p q r} : Subsumes p q → Subsumes p r → Subsumes p (.and q r)\n\ntheorem sound {p q : C} (h : Subsumes p q) (ρ M) :\n evalC ρ M p = true → evalC ρ M q = true := by\n induction h with\n | refl => exact id\n | top => intro _; rfl\n | bot => intro h; simp [evalC, evalE] at h\n | @neg p q _ ih =>\n intro hn\n change (!evalC ρ M q) = true\n cases hq : evalC ρ M q with\n | false => rfl\n | true =>\n have hp := ih hq\n change (!evalC ρ M p) = true at hn\n rw [hp] at hn\n cases hn\n | orLeft _ ih => intro h; simp only [evalC, Bool.or_eq_true]; exact Or.inl (ih h)\n | orRight _ ih => intro h; simp only [evalC, Bool.or_eq_true]; exact Or.inr (ih h)\n | orElim _ _ ih₁ ih₂ =>\n intro h\n simp only [evalC, Bool.or_eq_true] at h\n exact h.elim ih₁ ih₂\n | andLeft _ ih =>\n intro h\n simp only [evalC, Bool.and_eq_true] at h\n exact ih h.1\n | andRight _ ih =>\n intro h\n simp only [evalC, Bool.and_eq_true] at h\n exact ih h.2\n | andIntro _ _ ih₁ ih₂ =>\n intro h\n simp only [evalC, Bool.and_eq_true]\n exact ⟨ih₁ h, ih₂ h⟩\n\ntheorem law {strong weak : SEntry}\n (hk : strong.law.key = weak.law.key) (hks : strong.keys2 = weak.keys2)\n (h : Subsumes strong.law.holds weak.law.holds) : SourceLawImplication strong weak :=\n sourceLawImplication_of_pointwise strong weak hk hks (sound h)\n\n/-- Extend the supplied candidate transform to cut-carrying entries. The cut\nlists are retained verbatim, never silently dropped. The complete F checker\nmust accept them against the transformed goals before soundness is available. -/\ndef countedEntryF (bound : Nat) (e : CEntryF) : CEntryF :=\n { e with\n e := CertificateBoundErasure.entry bound e.e\n start := CertificateBoundErasure.countedCertificate bound e.start\n step := CertificateBoundErasure.countedCertificate bound e.step }\n\n#print axioms sound\n#print axioms law\nend Bapa.StructuralWeakening\n",
43
+ "TypedSource.lean": "import SourceInclusion\nimport BoundGhost\n\nnamespace Kern.TypedSource\n/-- The public existential conclusion follows from a semantic law of the\n ghost extension. The certificate may have been checked on a larger machine\n reached by SourceInclusion; no checker premise for the smaller one is needed. -/\ntheorem ex_of_holds (g : SGhostedM) (hg : smghostOk g = true)\n (e : SEntry) (σ : List (Nat × E)) (c : C)\n (hsub : e.law.holds = substC σ c)\n (hav : avoids (g.vars.filter fun v => !(σ.map (·.1)).contains v) c = true)\n (ham : avoidsMaps g.maps c = true)\n (hall : ∀ ρ M, SReach g.full ρ M → e.Holds ρ M) :\n ∀ ρ M, SReach g.orig ρ M → ExHolds c e.law.key (σ.map (·.1)) M e.keys2 ρ := by\n intro ρ M hr\n obtain ⟨ρg, Mg, hrg, hag, hmag⟩ := smghost_reach g hg hr\n have h := hall ρg Mg hrg\n simp only [SEntry.Holds] at h\n have go : ∀ (gs : List Nat) (ρg ρ : Nat → Nat), Agree g.vars ρg ρ →\n holdsOver e.law Mg gs ρg → ExHolds c e.law.key (σ.map (·.1)) M gs ρ := by\n intro gs\n induction gs with\n | nil =>\n intro ρg ρ hag h\n simp only [holdsOver, MLaw.Holds] at h\n cases hk : e.law.key with\n | none =>\n simp only [hk, hsub] at h\n simp only [ExHolds]\n exact some_of_subst_bound_apart σ c hav ham hag hmag h\n | some kv =>\n simp only [hk, hsub] at h\n simp only [ExHolds]\n intro v\n exact some_of_subst_bound_apart σ c hav ham (upd_agree hag kv v) hmag (h v)\n | cons k gs ih =>\n intro ρg ρ hag h w\n exact ih (upd ρg k w) (upd ρ k w) (upd_agree hag k w) (h w)\n exact go e.keys2 ρg ρ hag h\nend Kern.TypedSource\n#print axioms Kern.TypedSource.ex_of_holds\n",
44
+ "InvariantSimulation.lean": "import FiniteSimulation\n\n/-! Invariant-restricted, one-step simulation. The invariant comes from the\nchecked target family, not from an extra premise on source executions. -/\nnamespace Bapa.InvariantSimulation\nopen Kern Bapa.FiniteSimulation\n\n/-- Local correspondence is required only where a checked target invariant\nholds. In contrast to `SourceInclusion`, this makes no all-state claim. -/\nstructure RestrictedInclusion (s t : SMachine) (Inv : KState → Prop) : Prop where\n initial : ∀ x, Initial s x → Initial t x\n admission : ∀ ρ M ι κ, Inv (ρ,M) →\n evalC (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 s.f.m.assume = true →\n evalC (sView t ρ M ι κ).1 (sView t ρ M ι κ).2 t.f.m.assume = true\n next : ∀ ρ M ι κ, Inv (ρ,M) →\n evalC (sView s ρ M ι κ).1 (sView s ρ M ι κ).2 s.f.m.assume = true →\n sNext s ρ M ι κ = sNext t ρ M ι κ\n\n/-- Boundary states coincide and satisfy the target's checked invariant. -/\ndef Relation (Inv : KState → Prop) (x y : KState) : Prop := x = y ∧ Inv y\n\n/-- The family invariant is a theorem about target reachability. It is never\ninserted into the source assumption or the source theorem's hypotheses. -/\ntheorem RestrictedInclusion.simulation {s t : SMachine} {Inv : KState → Prop}\n (hinc : RestrictedInclusion s t Inv)\n (checked : ∀ ρ M, SReach t ρ M → Inv (ρ,M)) :\n SSimulation s t (Relation Inv) where\n initial := by\n intro x hx\n have ht : Reachable (Initial t) (STransition t) x := .initial (hinc.initial x hx)\n exact ⟨x, ht, rfl, checked x.1 x.2 (sreach_out ht)⟩\n matching := by\n intro x x' y _ hy hrel hedge\n rcases hrel with ⟨heq, hinv⟩\n subst y\n rcases hedge with ⟨ι, κ, ha, rfl⟩\n have hta := hinc.admission x.1 x.2 ι κ hinv ha\n have hn := hinc.next x.1 x.2 ι κ hinv ha\n have edge : STransition t x (sNext t x.1 x.2 ι κ) := ⟨ι, κ, hta, rfl⟩\n have reach := Reachable.next hy edge\n refine ⟨sNext t x.1 x.2 ι κ, .next (.refl x) edge, hn, ?_⟩\n exact checked _ _ (sreach_out reach)\n\ntheorem RestrictedInclusion.sreach {s t : SMachine} {Inv : KState → Prop}\n (hinc : RestrictedInclusion s t Inv)\n (checked : ∀ ρ M, SReach t ρ M → Inv (ρ,M)) {ρ M}\n (hr : SReach s ρ M) : SReach t ρ M := by\n obtain ⟨y, hy, hrel⟩ := sprojected_reach (hinc.simulation checked) hr\n rcases hrel with ⟨rfl, _⟩\n exact hy\n\n/-- Transfer the exact source conclusion; only the target proof supplies the\ninvariant. No bounded-key premise or strengthened source assumption occurs. -/\ntheorem RestrictedInclusion.law {s t : SMachine} {Inv : KState → Prop}\n (hinc : RestrictedInclusion s t Inv)\n (checked : ∀ ρ M, SReach t ρ M → Inv (ρ,M))\n (P : (Nat → Nat) → (Nat → Nat → Nat) → Prop)\n (target : ∀ ρ M, SReach t ρ M → P ρ M) :\n ∀ ρ M, SReach s ρ M → P ρ M :=\n fun ρ M hr => target ρ M (hinc.sreach checked hr)\n\n/-- A Boolean map bound is sufficient for threshold and Boolean-normalized\nreads to coincide. This elementary implication is false without the bound. -/\ntheorem threshold_eq_one {n : Nat} (h : n ≤ 1) : (1 ≤ n ↔ n = 1) := by omega\n\ntheorem boolean_stutter {n : Nat} (h : n ≤ 1) : (if n = 1 then 1 else 0) = n := by\n split <;> omega\n\n#print axioms RestrictedInclusion.simulation\n#print axioms RestrictedInclusion.sreach\n#print axioms RestrictedInclusion.law\n#print axioms threshold_eq_one\n#print axioms boolean_stutter\nend Bapa.InvariantSimulation\n",
45
+ "SemanticSums.lean": "import Sums\n\n/-! Exact global sums from semantic finite-change covers. A cover is proved\nfrom update syntax and the already checked family; it is not an assumption\nadded to a source transition. This interface avoids requiring historical cover\ncertificate trees that an otherwise complete family capsule did not retain. -/\nnamespace Bapa.SemanticSums\nopen Kern\n\n/-- Only addresses explicitly present in a finite syntactic cover may change\nan integrand. Quantification is over every natural address, not a finite test. -/\ndef Preserves (h : SumMachine) (ps : List SEntry) : Prop :=\n ∀ ρ M, (∀ e ∈ ps, e.Holds ρ M) → ∀ ι κ,\n evalC (sView h.plain ρ M ι κ).1 (sView h.plain ρ M ι κ).2 h.s.f.m.assume = true →\n ∀ d ∈ h.sums, ∀ key,\n key ∉ d.cs.map (evalE (sView h.plain ρ M ι κ).1 (sView h.plain ρ M ι κ).2) →\n gAt d.g (sNext h.plain ρ M ι κ).2 key = gAt d.g M key\n\nvariable (h : SumMachine)\ntheorem sum_step (hok : sumOk h = true) (cover : Preserves h ps) {ρ M}\n (hsum : ∀ d ∈ h.sums, IsSum (gAt d.g M) (ρ d.v))\n (hlaws : ∀ e ∈ ps, e.Holds ρ M) (ι : Nat → Nat) (κ : Nat → Nat → Nat)\n (ha : evalC (sView h.plain ρ M ι κ).1 (sView h.plain ρ M ι κ).2 h.s.f.m.assume = true) :\n ∀ d ∈ h.sums, IsSum (gAt d.g (sNext h.plain ρ M ι κ).2) ((sNext h.plain ρ M ι κ).1 d.v) := by\n obtain ⟨hdist, hall⟩ := sumOk_parts hok\n intro d hd\n obtain ⟨hg, _, _, hcar, _, _, _, _, hv, _⟩ := sumOk1_parts (hall d hd)\n let V := (sView h.plain ρ M ι κ).1\n let N := withCarried h.s M κ\n let M' := (sNext h.plain ρ M ι κ).2\n let cs' := d.cs.map (evalE V N)\n have hold : evalE V N (dTermE (gHere d) d.cs) = dsum (gAt d.g M) cs' := by\n rw [dTermE_eval V N d.cs (gHere d) (gAt d.g N) (fun t => gHere_eval d hg V N t), gAt_carried h d hcar]\n have hnew : evalE V N (dTermE (gAfter h.s d) d.cs) = dsum (gAt d.g M') cs' :=\n dTermE_eval V N d.cs (gAfter h.s d) (gAt d.g M') (fun t => gAfter_eval h d hg V N t)\n have hval : (sNext h.plain ρ M ι κ).1 d.v = ρ d.v + dsum (gAt d.g M') cs' - dsum (gAt d.g M) cs' := by\n show applyS (h.s.f.m.step ++ h.sums.map (fun d => (d.v, sumNext h.s d))) V N d.v = _\n simp only [applyS]\n rw [assoc_after (fun hm => hv (by simp [hm])), assoc_sums (sumNext h.s) hdist hd]\n simp only [sumNext, evalE, hold, hnew]\n have hview : V d.v = ρ d.v := view_v h hv ρ M ι κ\n rw [hview]\n rw [hval]\n exact isSum_change cs' (hsum d hd) (cover ρ M hlaws ι κ ha d hd)\n\ntheorem sum_start (hok : sumOk h = true) (ρ : Nat → Nat) (M : Nat → Nat → Nat) (hM : StartMaps h.plain.f.m M) :\n ∀ d ∈ h.sums, IsSum (gAt d.g M) (applyS h.plain.f.m.init ρ M d.v) := by\n obtain ⟨hdist, hall⟩ := sumOk_parts hok\n intro d hd\n obtain ⟨_, hm, h0, _, _, _, _, _, hv, _⟩ := sumOk1_parts (hall d hd)\n have hval : applyS h.plain.f.m.init ρ M d.v = 0 := by\n show applyS (h.s.f.m.init ++ h.sums.map (fun d => (d.v, E.const 0))) ρ M d.v = 0\n simp only [applyS]\n rw [assoc_after (fun hm' => hv (by simp [hm'])), assoc_sums (fun _ => E.const 0) hdist hd]\n rfl\n rw [hval]\n refine isSum_zero (fun key => ?_)\n rw [gAt]\n refine Eq.trans (congrME _ _ _ d.g (fun mp hmp => ?_)) h0\n funext _\n obtain ⟨p, hp, hpe⟩ := List.mem_map.mp (hm mp (mapsE_occ mp d.g hmp))\n cases hl : lookup (fun p => p.1 == mp) h.s.f.m.maps0 with\n | none => exact absurd (lookup_none_all hl p hp) (by simp [hpe])\n | some p0 =>\n obtain ⟨hp0, hp0e⟩ := lookup_some hl\n simp only [beq_iff_eq] at hp0e\n simp only [startVal, hl, Option.map_some, Option.getD_some]\n rw [← hp0e]; exact hM p0 hp0 key\n\n\ntheorem sum_facts (hok : sumOk h = true) (hs : sOk h.plain = true) {ρ : Nat → Nat} {M : Nat → Nat → Nat}\n (hsum : ∀ d ∈ h.sums, IsSum (gAt d.g M) (ρ d.v)) (ι : Nat → Nat) (κ : Nat → Nat → Nat) :\n evalC (sView h.plain ρ M ι κ).1 (sView h.plain ρ M ι κ).2 (sumsC h.sums) = true := by\n obtain ⟨_, hall⟩ := sumOk_parts hok\n obtain ⟨_, hqd, _, _, hdx, _, _⟩ := sOk_parts h.plain hs\n let N := withCarried h.s M κ\n let Wi := withInputs h.s.f.m.inputs ρ ι\n have one : ∀ d ∈ h.sums, evalC (sView h.plain ρ M ι κ).1 N (.and (sumFact d) (.eq (.var d.q) (.const 1))) = true := by\n intro d hd\n obtain ⟨hg, _, _, hcar, _, _, _, _, hv, hvk⟩ := sumOk1_parts (hall d hd)\n have hvi : d.v ∉ h.s.f.m.inputs := fun hm => hv (by simp [hm])\n simp only [evalC, Bool.and_eq_true, decide_eq_true_eq]\n refine ⟨?_, ?_⟩\n · show decide (evalE _ N (dTermE (gHere d) d.cs) ≤ (sView h.plain ρ M ι κ).1 d.v) = true\n apply decide_eq_true\n rw [dTermE_eval _ N d.cs (gHere d) (gAt d.g N) (fun t => gHere_eval d hg _ N t), gAt_carried h d hcar, view_v h hv ρ M ι κ]\n exact dsum_le (hsum d hd) _\n · have hqv : d.q ∈ h.plain.qVars := List.mem_map_of_mem (q_mem h hd)\n have hqf : d.q ∉ flagVars h.s.f.flags := fun hm =>\n (distinct_append hdx).2.2 d.q (by simp only [SMachine.extVars, List.mem_append]; exact Or.inl (Or.inr hqv)) hm\n show decideFlags h.s.f.flags (decideQ h.plain Wi N) N d.q = 1\n rw [decide_other hqf, decideQ_of, lookup_unique hqd (q_mem h hd)]\n simp only\n rw [if_pos]\n intro key\n rw [← evalC_iff]\n show decide (evalE _ N (dTermE (gHere d) (.var d.k :: d.cs.map (inlineE h.s.f.flags))) ≤ atKeys Wi [d.k] key d.v) = true\n apply decide_eq_true\n rw [dTermE_eval _ N _ (gHere d) (gAt d.g N) (fun t => gHere_eval d hg _ N t), gAt_carried h d hcar,\n atKeys_out (show d.v ∉ [d.k] by simpa using hvk)]\n show _ ≤ withInputs h.s.f.m.inputs ρ ι d.v\n rw [withInputs_other hvi]\n exact dsum_le (hsum d hd) _\n have all : ∀ ds : List SumDecl, (∀ d ∈ ds, d ∈ h.sums) → evalC (sView h.plain ρ M ι κ).1 N (sumsC ds) = true := by\n intro ds\n induction ds with\n | nil => intro _; rfl\n | cons d ds ih =>\n intro hm\n have h1 := one d (hm d List.mem_cons_self)\n have h2 := ih (fun d' hd' => hm d' (List.mem_cons_of_mem _ hd'))\n show (evalC _ N (.and (sumFact d) (.eq (.var d.q) (.const 1))) && evalC _ N (sumsC ds)) = true\n rw [h1, h2]; rfl\n exact all h.sums (fun _ hd => hd)\n\n/-- The plain machine allows exactly the requests the rule's own assumption allows, wherever the sums are exact. -/\ntheorem sum_assume (hok : sumOk h = true) (hs : sOk h.plain = true) {ρ : Nat → Nat} {M : Nat → Nat → Nat}\n (hsum : ∀ d ∈ h.sums, IsSum (gAt d.g M) (ρ d.v)) (ι : Nat → Nat) (κ : Nat → Nat → Nat) :\n evalC (sView h.plain ρ M ι κ).1 (sView h.plain ρ M ι κ).2 h.plain.f.m.assume\n = evalC (sView h.plain ρ M ι κ).1 (sView h.plain ρ M ι κ).2 h.s.f.m.assume := by\n show (evalC _ _ h.s.f.m.assume && evalC _ _ (sumsC h.sums)) = _\n rw [sum_facts h hok hs hsum ι κ, Bool.and_true]\n\n\ntheorem sum_cells (hl : checkSMachine h.plain ps = true) (hok : sumOk h = true)\n (cover : Preserves h ps) :\n ∀ ρ M, SReach h.plain ρ M →\n (∀ d ∈ h.sums, IsSum (gAt d.g M) (ρ d.v)) ∧ ∀ e ∈ ps, e.Holds ρ M := by\n intro ρ M hr\n induction hr with\n | start ρ M hm hp hf hpf =>\n exact ⟨sum_start h hok ρ M hm, smachine_sound h.plain ps hl _ _ (.start ρ M hm hp hf hpf)⟩\n | step ρ M ι κ hr ha ih =>\n have ha0 : evalC (sView h.plain ρ M ι κ).1 (sView h.plain ρ M ι κ).2 h.s.f.m.assume = true := by\n have hboth : evalC (sView h.plain ρ M ι κ).1 (sView h.plain ρ M ι κ).2\n (.and h.s.f.m.assume (sumsC h.sums)) = true := ha\n simp only [evalC, Bool.and_eq_true] at hboth\n exact hboth.1\n exact ⟨sum_step h hok cover ih.1 ih.2 ι κ ha0,\n smachine_sound h.plain ps hl _ _ (.step ρ M ι κ hr ha)⟩\n\ntheorem sum_holds (hl : checkSMachine h.plain ps = true) (hok : sumOk h = true)\n (cover : Preserves h ps) :\n ∀ ρ M, SReach h.plain ρ M → ∀ d ∈ h.sums, IsSum (gAt d.g M) (ρ d.v) :=\n fun ρ M hr => (sum_cells h hl hok cover ρ M hr).1\n\ntheorem sum_allowed (hl : checkSMachine h.plain ps = true) (hok : sumOk h = true)\n (cover : Preserves h ps) :\n ∀ ρ M, SReach h.plain ρ M → ∀ ι κ,\n evalC (sView h.plain ρ M ι κ).1 (sView h.plain ρ M ι κ).2 h.plain.f.m.assume =\n evalC (sView h.plain ρ M ι κ).1 (sView h.plain ρ M ι κ).2 h.s.f.m.assume :=\n fun ρ M hr ι κ => sum_assume h hok (sOk_of hl) (sum_holds h hl hok cover ρ M hr) ι κ\n\nsection project\nvariable (hg : sghostOk h.ghosts = true)\ninclude hg\ntheorem sum_project (hl : checkSMachine h.plain ps = true) (hok : sumOk h = true)\n (cover : Preserves h ps) :\n ∀ {ρ M}, SReach h.s ρ M → ∃ ρg, SReach h.plain ρg M ∧ Agree h.ghosts.vars ρg ρ := by\n intro ρ M hr\n induction hr with\n | start ρ M hM h0 hfa hpf =>\n refine ⟨applyS h.plain.f.m.init ρ M, SReach.start ρ M hM h0 hfa hpf, fun i hi => ?_⟩\n have hvi : i ∉ h.sums.map (fun d => d.v) := fun hm => by\n obtain ⟨d, hd, rfl⟩ := List.mem_map.mp hm; exact hi (ghosts_vars h hd).1\n show applyS (h.s.f.m.init ++ h.sums.map (fun d => (d.v, E.const 0))) ρ M i = applyS h.s.f.m.init ρ M i\n exact applyS_append_other (by simpa using hvi) ρ M\n | step ρ M ι κ _ ha ih =>\n obtain ⟨ρg, hrg, hag⟩ := ih\n obtain ⟨hA, hS, hW⟩ := sum_ghost_step h hg hag M ι κ\n refine ⟨_, ?_, hS⟩\n rw [← hW]\n refine SReach.step ρg M ι κ hrg ?_\n rw [sum_allowed h hl hok cover ρg M hrg ι κ, hA]; exact ha\n\n/-- The laws of the plain machine that read no sum's name hold in every state the rule reaches. -/\ntheorem sum_project_laws (ps : List SEntry) (hl : checkSMachine h.plain ps = true) (hok : sumOk h = true)\n (cover : Preserves h ps) :\n ∀ ρ M, SReach h.s ρ M → ∀ e ∈ ps, avoids h.ghosts.vars e.law.holds = true → e.Holds ρ M := by\n intro ρ M hr e he hav\n obtain ⟨ρg, hrg, hag⟩ := sum_project h hg hl hok cover hr\n exact sentry_transfer (V := h.ghosts.vars) (MS := []) hav (by simp [avoidsMaps]) (fun i hi => (hag i hi).symm) (fun _ _ => rfl)\n (smachine_sound h.plain ps hl ρg M hrg e he)\n\n\nend project\n#print axioms sum_cells\n#print axioms sum_project_laws\nend Bapa.SemanticSums\n",
46
+ "RadixSumTransport.lean": "import RadixCertificateTransport\nimport Sums\n\n/-! Shape-parameterized radix candidate generation with opaque SUM addresses.\nNo source names, fixed basis, fixed radix, law indices or SUM identifiers occur.\nThis module constructs data only. Complete family and source checking are\nseparate mandatory obligations; a failed conversion never returns an old family.\n-/\nnamespace Bapa.RadixSumTransport\nopen Kern\nopen RadixKeySyntax\n\nstructure Plan where\n radix : Nat\n layouts : List (Nat × Nat)\n freshBase : Nat\n /-- Quantified SUM flags whose single argument denotes an opaque address. -/\n sumFlags : List (Nat × Nat)\n\nabbrev Error := RadixCertificateTransport.Error\n\ndef layout (p : Plan) (mp : Nat) : Option Nat :=\n RadixBinderExpansion.mapArity p.layouts mp\n\ndef config (p : Plan) (bs : List RawAddress := []) : RadixTupleSyntax.Config :=\n ⟨p.radix,p.layouts,bs,none⟩\n\n/-- Unbound scalar addresses are already raw SUM addresses, not components. -/\ndef address (p : Plan) (arity : Nat) (bs : List RawAddress) (e : E) : Except RadixKeySyntax.Error E :=\n match e with\n | .var v => if bs.any (fun b => b.variableId == v) then rekey p.radix arity bs e else .ok e\n | _ => rekey p.radix arity bs e\n\nmutual\n def expr (p : Plan) (bs : List RawAddress) : E → Except RadixKeySyntax.Error E\n | .var v => .ok (.var v)\n | .const n => .ok (.const n)\n | .get m k => do\n let k' ← match layout p m with\n | some arity => address p arity bs k\n | none => expr p bs k\n return .get m k'\n | .add a b => do return .add (← expr p bs a) (← expr p bs b)\n | .sub a b => do return .sub (← expr p bs a) (← expr p bs b)\n | .mul n a => do return .mul n (← expr p bs a)\n | .min a b => do return .min (← expr p bs a) (← expr p bs b)\n | .max a b => do return .max (← expr p bs a) (← expr p bs b)\n | .prod a b => do return .prod (← expr p bs a) (← expr p bs b)\n | .ite c a b => do return .ite (← cond p bs c) (← expr p bs a) (← expr p bs b)\n | .tup a b => do return .tup (← expr p bs a) (← expr p bs b)\n | .proj n a => do return .proj n (← expr p bs a)\n def cond (p : Plan) (bs : List RawAddress) : C → Except RadixKeySyntax.Error C\n | .lt a b => do return .lt (← expr p bs a) (← expr p bs b)\n | .le a b => do return .le (← expr p bs a) (← expr p bs b)\n | .eq a b => do\n let ca := RadixTupleSyntax.rawArity (config p bs) a\n let cb := RadixTupleSyntax.rawArity (config p bs) b\n match ca, cb with\n | none, none => return .eq (← expr p bs a) (← expr p bs b)\n | some n, none | none, some n => return .eq (← address p n bs a) (← address p n bs b)\n | some n, some m =>\n if n != m then throw (.unsupportedKey m)\n return .eq (← address p n bs a) (← address p n bs b)\n | .and a b => do return .and (← cond p bs a) (← cond p bs b)\n | .or a b => do return .or (← cond p bs a) (← cond p bs b)\n | .not a => do return .not (← cond p bs a)\nend\n\ndef isOpaque (bs : List RawAddress) (tab : List VDef) (r : Cert.Row) : Bool :=\n match r.coefs with\n | [(j,1)] => r.const == 0 && (match tab[j]? with\n | some (.var v) => !(bs.any (fun b => b.variableId == v))\n | _ => false)\n | _ => false\n\ndef table (p : Plan) (bs : List RawAddress) (old : List VDef) : Except RadixCertificateTable.Error (List VDef) := do\n let fresh := (RadixCertificateTable.freshVariables old bs).map VDef.var\n let shift := fresh.length\n let moved ← old.mapM fun d => do\n match d with\n | .var v => pure (.var v)\n | .mono js => pure (.mono (js.map (·+shift)))\n | .term e => match expr p bs (CertificateBoundErasure.expr p.radix e) with\n | .ok e' => pure (.term e')\n | .error error => throw (.key error)\n | .cell m k => match layout p m with\n | none => pure (.cell m (RadixCertificateTable.row shift k))\n | some n => if isOpaque bs old k then pure (.cell m (RadixCertificateTable.row shift k)) else\n return .cellT m (← RadixCertificateTable.components p.radix n bs old fresh k)\n | .cellT m ks => pure (.cellT m (ks.map (RadixCertificateTable.row shift)))\n return fresh ++ moved\n\ndef certificate (p : Plan) (bs : List RawAddress) (goal : List C) (k : Kern.Cert) : Except Error Kern.Cert := do\n let tab ← RadixCertificateTransport.liftTable (table p bs k.1)\n let shift := tab.length-k.1.length\n let plans := RadixEqualityTree.plans shift k.1 tab\n return CertificateBooleanCleanup.certificate goal\n (tab,[],RadixEqualityTree.tree shift (some p.radix) plans [] k.2.2)\n\ndef instanceParts (p : Plan) (n : Nat) (bs : List RawAddress) (e : E) : Except RadixKeySyntax.Error (List E) :=\n match e with\n | .var v => if bs.any (fun b => b.variableId == v) then keyParts p.radix bs n e\n else .ok (RadixTupleSyntax.projectionParts n e)\n | _ => keyParts p.radix bs n e\n\ndef entry (p : Plan) (profiles : List (Nat × Nat)) (bs : List RawAddress) (e : SEntry) : Except RadixKeySyntax.Error SEntry := do\n let mut one := []\n let mut many := []\n for (i,k) in e.insts do\n match RadixBinderExpansion.mapArity profiles i with\n | some n => match ← instanceParts p n bs k with\n | a :: rest => many := many ++ [(i,a,rest)]\n | [] => throw (.unsupportedKey n)\n | none => one := one ++ [(i,← expr p bs k)]\n for (i,k,ks) in e.pinsts do\n match RadixBinderExpansion.mapArity profiles i with\n | some n => match ← instanceParts p n bs k with\n | a :: rest => many := many ++ [(i,a,rest ++ (← ks.mapM (expr p bs)))]\n | [] => throw (.unsupportedKey n)\n | none => many := many ++ [(i,← expr p bs k,← ks.mapM (expr p bs))]\n return {e with\n law := {e.law with holds := ← cond p bs (CertificateBoundErasure.condition p.radix e.law.holds)}\n insts := one, pinsts := many\n qinsts := ← e.qinsts.mapM (fun (i,ks) => do\n match RadixBinderExpansion.mapArity p.sumFlags i with\n | none => return (i,← ks.mapM (expr p bs))\n | some n => match ks with\n | [k] => return (i,[← address p n bs k])\n | _ => throw (.unsupportedKey n))\n finsts := ← e.finsts.mapM (fun (i,k) => do return (i,← expr p bs k))\n pfinsts := ← e.pfinsts.mapM (fun (i,k,ks) => do return (i,← expr p bs k,← ks.mapM (expr p bs)))}\n\n/-- Covers use the integrand's map layout; whole-address integrands remain\nunchanged. A mixed-arity integrand is unsupported, never guessed. -/\ndef sumArity (p : Plan) (g : E) : Except Error (Option Nat) := do\n let arities := (mapsE g).filterMap (layout p)\n match arities with\n | [] => return none\n | n :: ns => if ns.all (· == n) then return some n else throw (.syntax (.unsupportedKey n))\n\ndef target (p : Plan) (old : SumMachine) : Except Error SumMachine := do\n let base ← RadixCertificateTransport.liftSyntax (RadixTupleSyntax.machine (config p) old.s)\n let sums ← old.sums.mapM fun d => do\n let n ← sumArity p d.g\n let cs ← d.cs.mapM fun k => RadixCertificateTransport.liftSyntax\n (match n with | some n => rekey p.radix n [] k | none => expr p [] k)\n return {d with cs := cs}\n return ⟨base,sums⟩\n\n/-- Fresh indices use an arity-dependent prefix sum, not a fixed stride. -/\ndef prepare (p : Plan) (ps : List SEntry) : Except Error (List RadixCertificateTransport.Prepared) := do\n let mut fresh := p.freshBase\n let mut result := []\n for (e,i) in ps.zipIdx do\n let next ← RadixCertificateTransport.prepare p.layouts fresh 0 e\n let width := match next.profile with | some (_,n) => n-1 | none => 0\n result := result ++ [{next with profile := next.profile.map (fun (_,n) => (i,n))}]\n fresh := fresh + width\n return result\n\ndef translate (p : Plan) (old : SumMachine) (ps : List SEntry) : Except Error (SumMachine × List SEntry) := do\n let t ← target p old\n let prepared ← prepare p ps\n let bs := prepared.flatMap (·.bindings)\n let profiles := prepared.filterMap (·.profile)\n let es ← prepared.mapM (fun x => RadixCertificateTransport.liftSyntax (entry p profiles bs x.entry))\n let proof ← es.mapM fun e => do\n let start ← certificate p bs (sStartGoal t.plain e) e.start\n let step ← certificate p bs (sStepGoal t.plain es e) e.step\n return {e with start := start, step := step}\n return (t,proof)\n\n/-- Candidate success is not a validity-preservation axiom. -/\ntheorem checked (t : SumMachine) (ps : List SEntry) (h : checkSMachine t.plain ps = true) :\n ∀ ρ M, SReach t.plain ρ M → ∀ e ∈ ps, e.Holds ρ M := smachine_sound _ _ h\n#print axioms checked\nend Bapa.RadixSumTransport\n",
25
47
  };