pycforge 0.15.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. pycforge/__init__.py +8 -0
  2. pycforge/__main__.py +2 -0
  3. pycforge/_version.py +1 -0
  4. pycforge/converter/__init__.py +0 -0
  5. pycforge/converter/analysis/__init__.py +5 -0
  6. pycforge/converter/analysis/functions.py +723 -0
  7. pycforge/converter/analysis/model.py +158 -0
  8. pycforge/converter/analysis/planning.py +464 -0
  9. pycforge/converter/analysis/stage.py +1976 -0
  10. pycforge/converter/analysis/symbols.py +237 -0
  11. pycforge/converter/analysis/validation.py +2166 -0
  12. pycforge/converter/c_output/__init__.py +2 -0
  13. pycforge/converter/c_output/conformance.py +297 -0
  14. pycforge/converter/c_output/renderer.py +220 -0
  15. pycforge/converter/conditional_regions/__init__.py +71 -0
  16. pycforge/converter/conditional_regions/analysis.py +481 -0
  17. pycforge/converter/conditional_regions/lowering.py +579 -0
  18. pycforge/converter/conditional_regions/model.py +243 -0
  19. pycforge/converter/conditional_regions/validation.py +690 -0
  20. pycforge/converter/containers/__init__.py +19 -0
  21. pycforge/converter/containers/analysis.py +542 -0
  22. pycforge/converter/containers/lowering.py +290 -0
  23. pycforge/converter/containers/model.py +146 -0
  24. pycforge/converter/contracts/__init__.py +0 -0
  25. pycforge/converter/contracts/configuration.py +178 -0
  26. pycforge/converter/contracts/identifiers.py +68 -0
  27. pycforge/converter/contracts/versions.py +71 -0
  28. pycforge/converter/core/__init__.py +0 -0
  29. pycforge/converter/core/artifact_io.py +87 -0
  30. pycforge/converter/core/cancellation.py +7 -0
  31. pycforge/converter/core/canonicalization.py +254 -0
  32. pycforge/converter/core/context.py +13 -0
  33. pycforge/converter/core/diagnostics.py +95 -0
  34. pycforge/converter/core/enums.py +23 -0
  35. pycforge/converter/core/fingerprint.py +22 -0
  36. pycforge/converter/core/pipeline.py +8 -0
  37. pycforge/converter/core/progress.py +25 -0
  38. pycforge/converter/core/request.py +50 -0
  39. pycforge/converter/core/resource_policy.py +31 -0
  40. pycforge/converter/core/result.py +23 -0
  41. pycforge/converter/core/serialization.py +36 -0
  42. pycforge/converter/core/stage.py +10 -0
  43. pycforge/converter/core/stage_artifact.py +80 -0
  44. pycforge/converter/core/stage_outcome.py +15 -0
  45. pycforge/converter/decision_trace/__init__.py +0 -0
  46. pycforge/converter/decision_trace/recorder.py +52 -0
  47. pycforge/converter/facade.py +459 -0
  48. pycforge/converter/frontend/__init__.py +4 -0
  49. pycforge/converter/frontend/normalizer.py +59 -0
  50. pycforge/converter/frontend/parser.py +20 -0
  51. pycforge/converter/frontend/source_document.py +93 -0
  52. pycforge/converter/frontend/stages.py +518 -0
  53. pycforge/converter/frontend/validation.py +76 -0
  54. pycforge/converter/io/__init__.py +0 -0
  55. pycforge/converter/io/atomic_writer.py +33 -0
  56. pycforge/converter/ir/__init__.py +1 -0
  57. pycforge/converter/ir/c_ir/__init__.py +4 -0
  58. pycforge/converter/ir/c_ir/builder.py +26 -0
  59. pycforge/converter/ir/c_ir/model.py +318 -0
  60. pycforge/converter/ir/c_ir/serialization.py +88 -0
  61. pycforge/converter/ir/c_ir/validation.py +834 -0
  62. pycforge/converter/ir/python_ir/__init__.py +17 -0
  63. pycforge/converter/ir/python_ir/nodes.py +86 -0
  64. pycforge/converter/keyword_calls/__init__.py +68 -0
  65. pycforge/converter/keyword_calls/analysis.py +458 -0
  66. pycforge/converter/keyword_calls/lowering.py +271 -0
  67. pycforge/converter/keyword_calls/model.py +304 -0
  68. pycforge/converter/keyword_calls/validation.py +802 -0
  69. pycforge/converter/keyword_only_calls/__init__.py +68 -0
  70. pycforge/converter/keyword_only_calls/analysis.py +640 -0
  71. pycforge/converter/keyword_only_calls/lowering.py +376 -0
  72. pycforge/converter/keyword_only_calls/model.py +328 -0
  73. pycforge/converter/keyword_only_calls/validation.py +1357 -0
  74. pycforge/converter/lowering.py +1000 -0
  75. pycforge/converter/modules/__init__.py +13 -0
  76. pycforge/converter/modules/analysis.py +1250 -0
  77. pycforge/converter/modules/lowering.py +200 -0
  78. pycforge/converter/modules/model.py +73 -0
  79. pycforge/converter/modules/stage.py +192 -0
  80. pycforge/converter/numeric_semantics/__init__.py +23 -0
  81. pycforge/converter/numeric_semantics/analysis.py +420 -0
  82. pycforge/converter/numeric_semantics/lowering.py +153 -0
  83. pycforge/converter/numeric_semantics/model.py +123 -0
  84. pycforge/converter/records/__init__.py +34 -0
  85. pycforge/converter/records/analysis.py +1394 -0
  86. pycforge/converter/records/lowering.py +393 -0
  87. pycforge/converter/records/model.py +319 -0
  88. pycforge/converter/rules/__init__.py +3 -0
  89. pycforge/converter/support_templates/__init__.py +49 -0
  90. pycforge/converter/support_templates/assembly.py +106 -0
  91. pycforge/converter/support_templates/factories.py +348 -0
  92. pycforge/converter/support_templates/model.py +159 -0
  93. pycforge/converter/support_templates/registry.py +388 -0
  94. pycforge/converter/telemetry/__init__.py +0 -0
  95. pycforge/converter/telemetry/sink.py +39 -0
  96. pycforge/ide/__init__.py +19 -0
  97. pycforge/ide/__main__.py +5 -0
  98. pycforge/ide/_worker_event_codec.py +276 -0
  99. pycforge/ide/_worker_protocol_json.py +197 -0
  100. pycforge/ide/_worker_protocol_types.py +90 -0
  101. pycforge/ide/_worker_request_codec.py +200 -0
  102. pycforge/ide/_worker_request_data.py +260 -0
  103. pycforge/ide/_worker_result_data.py +343 -0
  104. pycforge/ide/action_contract.py +469 -0
  105. pycforge/ide/action_validation.py +229 -0
  106. pycforge/ide/command_palette.py +223 -0
  107. pycforge/ide/controller.py +904 -0
  108. pycforge/ide/controller_conversion.py +546 -0
  109. pycforge/ide/controller_io.py +205 -0
  110. pycforge/ide/editor.py +951 -0
  111. pycforge/ide/editor_commands_qt.py +274 -0
  112. pycforge/ide/editor_lexical.py +43 -0
  113. pycforge/ide/editor_sidebars.py +236 -0
  114. pycforge/ide/editor_syntax.py +243 -0
  115. pycforge/ide/find_replace.py +535 -0
  116. pycforge/ide/icons.py +91 -0
  117. pycforge/ide/io_service.py +196 -0
  118. pycforge/ide/model.py +164 -0
  119. pycforge/ide/panels.py +903 -0
  120. pycforge/ide/positions.py +220 -0
  121. pycforge/ide/process_worker.py +130 -0
  122. pycforge/ide/qt.py +230 -0
  123. pycforge/ide/qt_actions.py +418 -0
  124. pycforge/ide/qt_close.py +169 -0
  125. pycforge/ide/qt_command_palette.py +297 -0
  126. pycforge/ide/qt_contract.py +220 -0
  127. pycforge/ide/qt_documents.py +590 -0
  128. pycforge/ide/qt_editor_buffers.py +113 -0
  129. pycforge/ide/qt_editor_surfaces.py +112 -0
  130. pycforge/ide/qt_menus.py +324 -0
  131. pycforge/ide/qt_projection.py +500 -0
  132. pycforge/ide/qt_shell.py +348 -0
  133. pycforge/ide/qt_shell_interactions.py +320 -0
  134. pycforge/ide/qt_state.py +393 -0
  135. pycforge/ide/qt_workspace_features.py +398 -0
  136. pycforge/ide/qt_workspace_navigation.py +208 -0
  137. pycforge/ide/qt_workspace_observers.py +173 -0
  138. pycforge/ide/qt_workspace_panels.py +545 -0
  139. pycforge/ide/qt_workspace_widgets.py +228 -0
  140. pycforge/ide/resources/icons/about.svg +1 -0
  141. pycforge/ide/resources/icons/add-document.svg +1 -0
  142. pycforge/ide/resources/icons/brand-mark.svg +1 -0
  143. pycforge/ide/resources/icons/bundle-search.svg +1 -0
  144. pycforge/ide/resources/icons/cancel.svg +1 -0
  145. pycforge/ide/resources/icons/check.svg +1 -0
  146. pycforge/ide/resources/icons/chevron-right.svg +1 -0
  147. pycforge/ide/resources/icons/close.svg +1 -0
  148. pycforge/ide/resources/icons/collapse-all.svg +1 -0
  149. pycforge/ide/resources/icons/command-palette.svg +1 -0
  150. pycforge/ide/resources/icons/convert.svg +1 -0
  151. pycforge/ide/resources/icons/copy.svg +1 -0
  152. pycforge/ide/resources/icons/cut.svg +1 -0
  153. pycforge/ide/resources/icons/decision-trace.svg +1 -0
  154. pycforge/ide/resources/icons/details.svg +1 -0
  155. pycforge/ide/resources/icons/diagnostics.svg +1 -0
  156. pycforge/ide/resources/icons/duplicate-line.svg +1 -0
  157. pycforge/ide/resources/icons/exit.svg +1 -0
  158. pycforge/ide/resources/icons/expand-all.svg +1 -0
  159. pycforge/ide/resources/icons/export.svg +1 -0
  160. pycforge/ide/resources/icons/find.svg +1 -0
  161. pycforge/ide/resources/icons/go-to-line.svg +1 -0
  162. pycforge/ide/resources/icons/go-to-output.svg +1 -0
  163. pycforge/ide/resources/icons/go-to-source.svg +1 -0
  164. pycforge/ide/resources/icons/history.svg +1 -0
  165. pycforge/ide/resources/icons/indent.svg +1 -0
  166. pycforge/ide/resources/icons/link-c.svg +1 -0
  167. pycforge/ide/resources/icons/mappings.svg +1 -0
  168. pycforge/ide/resources/icons/module.svg +1 -0
  169. pycforge/ide/resources/icons/move-down.svg +1 -0
  170. pycforge/ide/resources/icons/move-line-down.svg +1 -0
  171. pycforge/ide/resources/icons/move-line-up.svg +1 -0
  172. pycforge/ide/resources/icons/move-up.svg +1 -0
  173. pycforge/ide/resources/icons/next.svg +1 -0
  174. pycforge/ide/resources/icons/open.svg +1 -0
  175. pycforge/ide/resources/icons/outdent.svg +1 -0
  176. pycforge/ide/resources/icons/outline.svg +1 -0
  177. pycforge/ide/resources/icons/paste.svg +1 -0
  178. pycforge/ide/resources/icons/previous.svg +1 -0
  179. pycforge/ide/resources/icons/primary-module.svg +1 -0
  180. pycforge/ide/resources/icons/redo.svg +1 -0
  181. pycforge/ide/resources/icons/remove-document.svg +1 -0
  182. pycforge/ide/resources/icons/replace.svg +1 -0
  183. pycforge/ide/resources/icons/save-as.svg +1 -0
  184. pycforge/ide/resources/icons/save.svg +1 -0
  185. pycforge/ide/resources/icons/select-all.svg +1 -0
  186. pycforge/ide/resources/icons/settings.svg +1 -0
  187. pycforge/ide/resources/icons/show-c.svg +1 -0
  188. pycforge/ide/resources/icons/split-view.svg +1 -0
  189. pycforge/ide/resources/icons/summary.svg +1 -0
  190. pycforge/ide/resources/icons/telemetry.svg +1 -0
  191. pycforge/ide/resources/icons/toggle-comment.svg +1 -0
  192. pycforge/ide/resources/icons/toggle-fold.svg +1 -0
  193. pycforge/ide/resources/icons/undo.svg +1 -0
  194. pycforge/ide/resources/icons/whitespace.svg +1 -0
  195. pycforge/ide/revisions.py +400 -0
  196. pycforge/ide/search_service.py +280 -0
  197. pycforge/ide/session_history.py +150 -0
  198. pycforge/ide/source_editing.py +417 -0
  199. pycforge/ide/source_structure.py +558 -0
  200. pycforge/ide/source_structure_async.py +191 -0
  201. pycforge/ide/supervisor.py +503 -0
  202. pycforge/ide/theme.py +119 -0
  203. pycforge/ide/theme_stylesheet.py +598 -0
  204. pycforge/ide/theme_workspace_stylesheet.py +155 -0
  205. pycforge/ide/visual_tokens.py +142 -0
  206. pycforge/ide/worker_protocol.py +80 -0
  207. pycforge/ide/workspace_search.py +462 -0
  208. pycforge/ide/workspace_session.py +256 -0
  209. pycforge/laboratory/__init__.py +6 -0
  210. pycforge/laboratory/audits.py +2244 -0
  211. pycforge/laboratory/checkpoint_e.py +2685 -0
  212. pycforge/laboratory/cli.py +119 -0
  213. pycforge/laboratory/exit_codes.py +11 -0
  214. pycforge/laboratory/keyword_audit.py +661 -0
  215. pycforge/laboratory/keyword_only_audit.py +481 -0
  216. pycforge-0.15.2.dist-info/METADATA +209 -0
  217. pycforge-0.15.2.dist-info/RECORD +221 -0
  218. pycforge-0.15.2.dist-info/WHEEL +5 -0
  219. pycforge-0.15.2.dist-info/entry_points.txt +5 -0
  220. pycforge-0.15.2.dist-info/licenses/LICENSE +674 -0
  221. pycforge-0.15.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,690 @@
1
+ """Independent validation for published conditional-region facts.
2
+
3
+ This module intentionally does not import the producer or lowerer. It rebuilds
4
+ the exact eligible-region set from Python IR and cumulative fact tables, then
5
+ checks the serialized facts and RulePlans for exact equality.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Mapping
11
+
12
+ from pycforge.converter.ir.python_ir import python_ir_reference_ids
13
+
14
+ from .model import (
15
+ CONDITIONAL_REGION_KEY_DOMAIN,
16
+ CONDITIONAL_REGION_LOWERING_SHAPE,
17
+ CONDITIONAL_REGION_OBLIGATIONS,
18
+ CONDITIONAL_REGION_PROVENANCE_EVIDENCE,
19
+ CONDITIONAL_REGION_TABLE_DEPENDENCIES,
20
+ CONDITIONAL_REGION_TABLE_ID,
21
+ ConditionalRegionKind,
22
+ ConditionalRegionValidationCanceled,
23
+ conditional_region_id,
24
+ )
25
+
26
+
27
+ _SCALARS = {"integer-like", "floating-like", "boolean-like", "string-like"}
28
+ _COMPARABLE = {"integer-like", "floating-like", "boolean-like"}
29
+ _COMPARE_OPS = {"Eq", "NotEq", "Lt", "LtE", "Gt", "GtE"}
30
+
31
+
32
+ def _check_cancellation(cancellation: Any) -> None:
33
+ if cancellation is not None and bool(
34
+ getattr(cancellation, "is_canceled", False)
35
+ ):
36
+ raise ConditionalRegionValidationCanceled
37
+
38
+
39
+ class _ValidationPrerequisiteClosure:
40
+ """Independent persistent prerequisite rope for linear reconstruction."""
41
+
42
+ __slots__ = ("parts", "node_id", "nonempty")
43
+
44
+ def __init__(
45
+ self,
46
+ parts: tuple["_ValidationPrerequisiteClosure", ...] = (),
47
+ node_id: str | None = None,
48
+ ) -> None:
49
+ self.parts = tuple(part for part in parts if part.nonempty)
50
+ self.node_id = node_id
51
+ self.nonempty = bool(self.parts) or node_id is not None
52
+
53
+ def materialize(self, cancellation: Any) -> tuple[str, ...]:
54
+ if not self.nonempty:
55
+ return ()
56
+ result: list[str] = []
57
+ seen_node_ids: set[str] = set()
58
+ seen_closures: set[int] = set()
59
+ stack: list[_ValidationPrerequisiteClosure | str] = [self]
60
+ while stack:
61
+ _check_cancellation(cancellation)
62
+ item = stack.pop()
63
+ if isinstance(item, str):
64
+ if item not in seen_node_ids:
65
+ seen_node_ids.add(item)
66
+ result.append(item)
67
+ continue
68
+ identity = id(item)
69
+ if identity in seen_closures:
70
+ continue
71
+ seen_closures.add(identity)
72
+ if item.node_id is not None:
73
+ stack.append(item.node_id)
74
+ stack.extend(reversed(item.parts))
75
+ return tuple(result)
76
+
77
+
78
+ _EMPTY_VALIDATION_PREREQUISITES = _ValidationPrerequisiteClosure()
79
+
80
+
81
+ def _validation_closure(
82
+ parts: tuple[_ValidationPrerequisiteClosure, ...] = (),
83
+ node_id: str | None = None,
84
+ ) -> _ValidationPrerequisiteClosure:
85
+ if node_id is None and not any(part.nonempty for part in parts):
86
+ return _EMPTY_VALIDATION_PREREQUISITES
87
+ return _ValidationPrerequisiteClosure(parts, node_id)
88
+
89
+
90
+ def validate_conditional_region_facts(
91
+ payload: dict[str, Any],
92
+ tables: list[dict[str, Any]] | tuple[dict[str, Any], ...] | None = None,
93
+ *,
94
+ expected_fact_schema: str | None = None,
95
+ require_table: bool = True,
96
+ cancellation: Any = None,
97
+ ) -> tuple[bool, str]:
98
+ """Validate the exact conditional-region table and its RulePlans.
99
+
100
+ The complete independent reconstruction is implemented below this public
101
+ boundary; the signature intentionally accepts a caller-supplied table list
102
+ so the cumulative validator need not reshape its payload.
103
+ """
104
+
105
+ return _validate(
106
+ payload,
107
+ tuple(tables if tables is not None else payload.get("fact_tables", ())),
108
+ expected_fact_schema=expected_fact_schema,
109
+ require_table=require_table,
110
+ cancellation=cancellation,
111
+ )
112
+
113
+
114
+ def _validate(
115
+ payload: dict[str, Any],
116
+ tables: tuple[dict[str, Any], ...],
117
+ *,
118
+ expected_fact_schema: str | None,
119
+ require_table: bool,
120
+ cancellation: Any,
121
+ ) -> tuple[bool, str]:
122
+ _check_cancellation(cancellation)
123
+ table = next(
124
+ (item for item in tables if item.get("table_id") == CONDITIONAL_REGION_TABLE_ID),
125
+ None,
126
+ )
127
+ if table is None:
128
+ return (False, "conditional-region fact table is absent") if require_table else (True, "")
129
+ if (
130
+ (expected_fact_schema is not None and table.get("schema_version") != expected_fact_schema)
131
+ or not isinstance(table.get("schema_version"), str)
132
+ or not table.get("schema_version")
133
+ or table.get("producer_stage") != "analysis.plan"
134
+ or table.get("key_domain") != CONDITIONAL_REGION_KEY_DOMAIN
135
+ or table.get("completeness") != "complete"
136
+ or tuple(table.get("invalidation_dependencies", ()))
137
+ != CONDITIONAL_REGION_TABLE_DEPENDENCIES
138
+ ):
139
+ return False, "conditional-region fact schema is invalid"
140
+
141
+ module = payload.get("python_ir")
142
+ if not isinstance(module, dict) or not isinstance(module.get("nodes"), list):
143
+ return False, "conditional-region validation lacks Python IR"
144
+ table_map: dict[Any, dict[str, Any]] = {}
145
+ for candidate in tables:
146
+ _check_cancellation(cancellation)
147
+ if isinstance(candidate, dict):
148
+ table_map[candidate.get("table_id")] = candidate
149
+ required = {
150
+ "value-category-facts",
151
+ "call-target-facts",
152
+ "container-access-facts",
153
+ "record-access-facts",
154
+ "numeric-operation-facts",
155
+ "module-function-facts",
156
+ "module-source-facts",
157
+ }
158
+ if not required.issubset(table_map):
159
+ return False, "conditional-region proof dependencies are absent"
160
+
161
+ def values(table_id: str) -> tuple[dict[str, Any], ...]:
162
+ result: list[dict[str, Any]] = []
163
+ for record in table_map[table_id].get("records", ()):
164
+ _check_cancellation(cancellation)
165
+ if isinstance(record, dict) and isinstance(record.get("value"), dict):
166
+ result.append(record["value"])
167
+ return tuple(result)
168
+
169
+ categories: dict[Any, Any] = {}
170
+ for record in table_map["value-category-facts"].get("records", ()):
171
+ _check_cancellation(cancellation)
172
+ if isinstance(record, dict):
173
+ categories[record.get("key")] = record.get("value")
174
+ supported_calls: set[Any] = set()
175
+ for item in values("call-target-facts"):
176
+ if (
177
+ item.get("supported") is True
178
+ and item.get("resolution") == "understood-source-function"
179
+ ):
180
+ supported_calls.add(item.get("call_node_id"))
181
+ numeric_operations: set[Any] = set()
182
+ for item in values("numeric-operation-facts"):
183
+ numeric_operations.add(item.get("binop_node_id"))
184
+ container_accesses: set[Any] = set()
185
+ for item in values("container-access-facts"):
186
+ if item.get("supported") is True:
187
+ container_accesses.add(item.get("subscript_node_id"))
188
+ record_accesses: set[Any] = set()
189
+ for item in values("record-access-facts"):
190
+ record_accesses.add(item.get("access_node_id"))
191
+ module_sources: dict[Any, dict[str, Any]] = {}
192
+ for item in values("module-source-facts"):
193
+ module_sources[item.get("module_id")] = item
194
+ function_records: dict[str, dict[str, Any]] = {}
195
+ for item in values("module-function-facts"):
196
+ _check_cancellation(cancellation)
197
+ source = module_sources.get(item.get("module_id"), {})
198
+ function_records[str(item.get("function_node_id"))] = {
199
+ **item,
200
+ "logical_name": source.get("logical_name"),
201
+ }
202
+
203
+ reconstruction = _IndependentReconstruction(
204
+ module,
205
+ categories=categories,
206
+ function_records=function_records,
207
+ supported_calls=frozenset(item for item in supported_calls if isinstance(item, str)),
208
+ numeric_operations=frozenset(item for item in numeric_operations if isinstance(item, str)),
209
+ container_accesses=frozenset(item for item in container_accesses if isinstance(item, str)),
210
+ record_accesses=frozenset(item for item in record_accesses if isinstance(item, str)),
211
+ target_contract=str(payload.get("target_contract", "")),
212
+ cancellation=cancellation,
213
+ )
214
+ try:
215
+ expected = reconstruction.expected_regions()
216
+ except ValueError as exc:
217
+ return False, str(exc)
218
+
219
+ records = table.get("records")
220
+ if not isinstance(records, list):
221
+ return False, "conditional-region records are malformed"
222
+ keys: list[Any] = []
223
+ for record in records:
224
+ _check_cancellation(cancellation)
225
+ if isinstance(record, dict):
226
+ keys.append(record.get("key"))
227
+ if len(keys) != len(records) or keys != sorted(keys) or len(keys) != len(set(keys)):
228
+ return False, "conditional-region keys are not unique and sorted"
229
+ found: dict[str, dict[str, Any]] = {}
230
+ provenance: dict[str, dict[str, Any]] = {}
231
+ for record in records:
232
+ _check_cancellation(cancellation)
233
+ key, value = record.get("key"), record.get("value")
234
+ if not isinstance(key, str) or not isinstance(value, dict):
235
+ return False, "conditional-region record identity is malformed"
236
+ if value.get("region_node_id") != key:
237
+ return False, "conditional-region record key disagrees with its value"
238
+ found[key] = value
239
+ provenance[key] = record.get("provenance")
240
+ if set(found) != set(expected):
241
+ return False, "conditional-region facts do not exactly cover eligible regions"
242
+ for node_id, value in expected.items():
243
+ _check_cancellation(cancellation)
244
+ if found[node_id] != value:
245
+ return False, "conditional-region fact disagrees with independent reconstruction"
246
+ proof = provenance.get(node_id)
247
+ if not isinstance(proof, dict) or proof.get(
248
+ "source_node_ids"
249
+ ) != _provenance_ids(value, cancellation):
250
+ return False, "conditional-region provenance nodes are incomplete"
251
+ if proof.get("evidence") != list(CONDITIONAL_REGION_PROVENANCE_EVIDENCE):
252
+ return False, "conditional-region provenance evidence is invalid"
253
+
254
+ valid, reason = _validate_plans(payload, expected, cancellation)
255
+ if not valid:
256
+ return valid, reason
257
+ return True, ""
258
+
259
+
260
+ def _provenance_ids(fact: dict[str, Any], cancellation: Any) -> list[str]:
261
+ result: list[str] = []
262
+ seen: set[str] = set()
263
+ values = (
264
+ fact["region_node_id"],
265
+ fact["function_node_id"],
266
+ *fact["operator_node_ids"],
267
+ *fact["operand_node_ids"],
268
+ *fact["prerequisite_node_ids"],
269
+ )
270
+ for value in values:
271
+ _check_cancellation(cancellation)
272
+ if value not in seen:
273
+ seen.add(value)
274
+ result.append(value)
275
+ return result
276
+
277
+
278
+ class _IndependentReconstruction:
279
+ def __init__(
280
+ self,
281
+ module: dict[str, Any],
282
+ *,
283
+ categories: Mapping[str, Any],
284
+ function_records: Mapping[str, Mapping[str, Any]],
285
+ supported_calls: frozenset[str],
286
+ numeric_operations: frozenset[str],
287
+ container_accesses: frozenset[str],
288
+ record_accesses: frozenset[str],
289
+ target_contract: str,
290
+ cancellation: Any,
291
+ ) -> None:
292
+ self.module = module
293
+ self.cancellation = cancellation
294
+ self.nodes: dict[str, dict[str, Any]] = {}
295
+ self.order: dict[str, int] = {}
296
+ for ordinal, node in enumerate(module["nodes"]):
297
+ _check_cancellation(self.cancellation)
298
+ self.nodes[node["node_id"]] = node
299
+ self.order[node["node_id"]] = ordinal
300
+ self.categories = categories
301
+ self.function_records = function_records
302
+ self.supported_calls = supported_calls
303
+ self.numeric_operations = numeric_operations
304
+ self.container_accesses = container_accesses
305
+ self.record_accesses = record_accesses
306
+ self.target_contract = target_contract
307
+ self.children: dict[str, tuple[str, ...]] = {}
308
+ for node_id, node in self.nodes.items():
309
+ _check_cancellation(self.cancellation)
310
+ self.children[node_id] = self._children(node)
311
+ self.owner_by_node = self._owners()
312
+ self.approved: dict[str, bool] = {}
313
+ self.prerequisites: dict[str, _ValidationPrerequisiteClosure] = {}
314
+
315
+ def _children(self, node: dict[str, Any]) -> tuple[str, ...]:
316
+ return tuple(
317
+ child
318
+ for field, value in node.get("fields", {}).items()
319
+ for child in python_ir_reference_ids(node["kind"], field, value, self.nodes)
320
+ )
321
+
322
+ def _owners(self) -> dict[str, str]:
323
+ owners: dict[str, str] = {}
324
+ for function_id in sorted(self.function_records):
325
+ _check_cancellation(self.cancellation)
326
+ if function_id not in self.nodes:
327
+ continue
328
+ stack = [function_id]
329
+ while stack:
330
+ _check_cancellation(self.cancellation)
331
+ current = stack.pop()
332
+ if current in owners:
333
+ continue
334
+ owners[current] = function_id
335
+ for child in reversed(self.children[current]):
336
+ if child != current and self.nodes[child]["kind"] not in {
337
+ "FunctionDef",
338
+ "AsyncFunctionDef",
339
+ }:
340
+ stack.append(child)
341
+ return owners
342
+
343
+ def _postorder(self) -> tuple[str, ...]:
344
+ result: list[str] = []
345
+ state: dict[str, int] = {}
346
+ for start in sorted(self.nodes, key=self.order.__getitem__):
347
+ if state.get(start) == 2:
348
+ continue
349
+ stack = [(start, False)]
350
+ while stack:
351
+ _check_cancellation(self.cancellation)
352
+ node_id, expanded = stack.pop()
353
+ if expanded:
354
+ if state.get(node_id) != 2:
355
+ state[node_id] = 2
356
+ result.append(node_id)
357
+ continue
358
+ if state.get(node_id) == 2:
359
+ continue
360
+ if state.get(node_id) == 1:
361
+ raise ValueError("conditional-region Python IR is cyclic")
362
+ state[node_id] = 1
363
+ stack.append((node_id, True))
364
+ for child in reversed(self.children[node_id]):
365
+ if state.get(child) == 1:
366
+ raise ValueError("conditional-region Python IR is cyclic")
367
+ if state.get(child) != 2:
368
+ stack.append((child, False))
369
+ return tuple(result)
370
+
371
+ def expected_regions(self) -> dict[str, dict[str, Any]]:
372
+ for node_id in self._postorder():
373
+ node = self.nodes[node_id]
374
+ self.approved[node_id] = self._approved(node)
375
+ self.prerequisites[node_id] = self._prerequisites(node)
376
+ result: dict[str, dict[str, Any]] = {}
377
+ for node in self.module["nodes"]:
378
+ _check_cancellation(self.cancellation)
379
+ if not self.approved.get(node["node_id"]):
380
+ continue
381
+ fields = node["fields"]
382
+ if node["kind"] == "BoolOp":
383
+ values = tuple(fields.get("values", ()))
384
+ if any(
385
+ self.prerequisites.get(
386
+ item,
387
+ _EMPTY_VALIDATION_PREREQUISITES,
388
+ ).nonempty
389
+ for item in values
390
+ ):
391
+ result[node["node_id"]] = self._fact(
392
+ node, ConditionalRegionKind.BOOLEAN_SHORT_CIRCUIT
393
+ )
394
+ elif node["kind"] == "Compare" and len(tuple(fields.get("ops", ()))) > 1:
395
+ operands = (fields.get("left"), *tuple(fields.get("comparators", ())))
396
+ if any(
397
+ self.nodes[item]["kind"] not in {"Name", "Constant"}
398
+ or self.prerequisites.get(
399
+ item,
400
+ _EMPTY_VALIDATION_PREREQUISITES,
401
+ ).nonempty
402
+ for item in operands[2:]
403
+ ):
404
+ result[node["node_id"]] = self._fact(
405
+ node, ConditionalRegionKind.CHAINED_COMPARISON
406
+ )
407
+ return result
408
+
409
+ def _approved(self, node: dict[str, Any]) -> bool:
410
+ kind, fields, node_id = node["kind"], node["fields"], node["node_id"]
411
+ category = self.categories.get(node_id, "unknown")
412
+ if kind in {"Name", "Constant"}:
413
+ return category in _SCALARS
414
+ if kind == "Attribute":
415
+ return node_id in self.record_accesses and category in _SCALARS
416
+ if kind == "Subscript":
417
+ return node_id in self.container_accesses and category in _SCALARS
418
+ if kind == "Call":
419
+ return (
420
+ node_id in self.supported_calls
421
+ and category in _SCALARS
422
+ and all(self.approved.get(item, False) for item in fields.get("args", ()))
423
+ )
424
+ if kind == "UnaryOp":
425
+ operand = fields.get("operand")
426
+ operator = self.nodes.get(fields.get("op"), {}).get("kind")
427
+ operand_category = self.categories.get(operand)
428
+ if not self.approved.get(operand, False):
429
+ return False
430
+ if operator == "Not":
431
+ return category == "boolean-like" and operand_category in _COMPARABLE
432
+ return operator in {"UAdd", "USub"} and category in {
433
+ "integer-like",
434
+ "floating-like",
435
+ }
436
+ if kind == "BinOp":
437
+ left, right = fields.get("left"), fields.get("right")
438
+ operator = self.nodes.get(fields.get("op"), {}).get("kind")
439
+ if not self.approved.get(left, False) or not self.approved.get(right, False):
440
+ return False
441
+ if operator in {"FloorDiv", "Mod"}:
442
+ return node_id in self.numeric_operations
443
+ if operator == "Div":
444
+ return category == "floating-like"
445
+ return operator in {"Add", "Sub", "Mult"} and category in {
446
+ "integer-like",
447
+ "floating-like",
448
+ }
449
+ if kind == "BoolOp":
450
+ values = tuple(fields.get("values", ()))
451
+ operator = self.nodes.get(fields.get("op"), {}).get("kind")
452
+ return (
453
+ operator in {"And", "Or"}
454
+ and len(values) >= 2
455
+ and category == "boolean-like"
456
+ and all(
457
+ self.categories.get(item) == "boolean-like"
458
+ and self.approved.get(item, False)
459
+ for item in values
460
+ )
461
+ )
462
+ if kind == "Compare":
463
+ operands = (fields.get("left"), *tuple(fields.get("comparators", ())))
464
+ operators = tuple(fields.get("ops", ()))
465
+ operand_categories = tuple(self.categories.get(item) for item in operands)
466
+ return (
467
+ bool(operators)
468
+ and len(operands) == len(operators) + 1
469
+ and all(self.approved.get(item, False) for item in operands)
470
+ and all(self.nodes.get(item, {}).get("kind") in _COMPARE_OPS for item in operators)
471
+ and operand_categories[0] in _COMPARABLE
472
+ and all(item == operand_categories[0] for item in operand_categories)
473
+ and category == "boolean-like"
474
+ )
475
+ return False
476
+
477
+ def _prerequisites(
478
+ self,
479
+ node: dict[str, Any],
480
+ ) -> _ValidationPrerequisiteClosure:
481
+ if not self.approved.get(node["node_id"], False):
482
+ return _EMPTY_VALIDATION_PREREQUISITES
483
+ kind, fields, node_id = node["kind"], node["fields"], node["node_id"]
484
+
485
+ def merge(ids: tuple[str, ...]) -> _ValidationPrerequisiteClosure:
486
+ return _validation_closure(
487
+ tuple(
488
+ self.prerequisites.get(
489
+ child,
490
+ _EMPTY_VALIDATION_PREREQUISITES,
491
+ )
492
+ for child in ids
493
+ )
494
+ )
495
+
496
+ if kind == "Call":
497
+ return _validation_closure(
498
+ (merge(tuple(fields.get("args", ()))),),
499
+ node_id,
500
+ )
501
+ if kind == "UnaryOp":
502
+ return self.prerequisites.get(
503
+ fields.get("operand"),
504
+ _EMPTY_VALIDATION_PREREQUISITES,
505
+ )
506
+ if kind == "BinOp":
507
+ inherited = merge((fields["left"], fields["right"]))
508
+ return (
509
+ _validation_closure((inherited,), node_id)
510
+ if node_id in self.numeric_operations
511
+ else inherited
512
+ )
513
+ if kind == "BoolOp":
514
+ inherited = merge(tuple(fields.get("values", ())))
515
+ return (
516
+ _validation_closure((inherited,), node_id)
517
+ if inherited.nonempty
518
+ else _EMPTY_VALIDATION_PREREQUISITES
519
+ )
520
+ if kind == "Compare":
521
+ operands = (fields["left"], *tuple(fields.get("comparators", ())))
522
+ inherited = merge(operands)
523
+ return (
524
+ _validation_closure((inherited,), node_id)
525
+ if len(tuple(fields.get("ops", ()))) > 1
526
+ else inherited
527
+ )
528
+ return _EMPTY_VALIDATION_PREREQUISITES
529
+
530
+ def _fact(self, node: dict[str, Any], kind: ConditionalRegionKind) -> dict[str, Any]:
531
+ fields = node["fields"]
532
+ if kind is ConditionalRegionKind.BOOLEAN_SHORT_CIRCUIT:
533
+ operands = tuple(fields["values"])
534
+ operators = (fields["op"],)
535
+ prefix = 1
536
+ guard = (
537
+ "when-result-true"
538
+ if self.nodes[operators[0]]["kind"] == "And"
539
+ else "when-result-false"
540
+ )
541
+ else:
542
+ operands = (fields["left"], *tuple(fields.get("comparators", ())))
543
+ operators = tuple(fields["ops"])
544
+ prefix = 2
545
+ guard = "when-result-true"
546
+ owner_id = self.owner_by_node.get(node["node_id"])
547
+ owner = self.function_records.get(owner_id or "")
548
+ if not isinstance(owner, Mapping):
549
+ raise ValueError("conditional-region function ownership is absent")
550
+ source = {
551
+ "module_id": owner.get("module_id"),
552
+ "document_id": owner.get("document_id"),
553
+ "logical_name": owner.get("logical_name"),
554
+ }
555
+ if not all(isinstance(value, str) and value for value in source.values()):
556
+ raise ValueError("conditional-region source ownership is invalid")
557
+ placements = []
558
+ for ordinal, operand in enumerate(operands):
559
+ _check_cancellation(self.cancellation)
560
+ unconditional = ordinal < prefix
561
+ prerequisite_node_ids = self.prerequisites.get(
562
+ operand,
563
+ _EMPTY_VALIDATION_PREREQUISITES,
564
+ ).materialize(self.cancellation)
565
+ placements.append(
566
+ {
567
+ "operand_node_id": operand,
568
+ "ordinal": ordinal,
569
+ "category": self.categories[operand],
570
+ "evaluation_mode": "unconditional" if unconditional else "guarded",
571
+ "guard_polarity": "none" if unconditional else guard,
572
+ "guard_after_operand_ordinal": None if unconditional else ordinal - 1,
573
+ "requires_statement_prelude": bool(prerequisite_node_ids),
574
+ "prerequisite_node_ids": list(prerequisite_node_ids),
575
+ "legacy_direct_safe": self.nodes[operand]["kind"] in {"Name", "Constant"},
576
+ }
577
+ )
578
+ prerequisite_values: list[str] = []
579
+ prerequisite_seen: set[str] = set()
580
+ for placement in placements:
581
+ for prerequisite in placement["prerequisite_node_ids"]:
582
+ _check_cancellation(self.cancellation)
583
+ if prerequisite not in prerequisite_seen:
584
+ prerequisite_seen.add(prerequisite)
585
+ prerequisite_values.append(prerequisite)
586
+ prerequisites = tuple(prerequisite_values)
587
+ return {
588
+ "region_id": conditional_region_id(node["node_id"], kind),
589
+ "region_node_id": node["node_id"],
590
+ "region_kind": kind.value,
591
+ "function_node_id": owner_id,
592
+ **source,
593
+ "operator_node_ids": list(operators),
594
+ "operator_kinds": [self.nodes[item]["kind"] for item in operators],
595
+ "operand_node_ids": list(operands),
596
+ "operand_categories": [self.categories[item] for item in operands],
597
+ "unconditional_prefix_count": prefix,
598
+ "placements": placements,
599
+ "guarded_operand_node_ids": list(operands[prefix:]),
600
+ "prerequisite_node_ids": list(prerequisites),
601
+ "result_category": "boolean-like",
602
+ "result_c_type": "bool",
603
+ "evaluation_order": list(operands),
604
+ "operands_evaluated_once": True,
605
+ "lowering_shape": CONDITIONAL_REGION_LOWERING_SHAPE,
606
+ "allocation_model": "none",
607
+ "cleanup_model": "none",
608
+ "runtime_failure_channel": "unchanged",
609
+ "target_contract": self.target_contract,
610
+ }
611
+
612
+
613
+ def _validate_plans(
614
+ payload: dict[str, Any],
615
+ expected: dict[str, dict[str, Any]],
616
+ cancellation: Any,
617
+ ) -> tuple[bool, str]:
618
+ _check_cancellation(cancellation)
619
+ conditional_rule_ids = {
620
+ "phase14.conditional.boolean_region",
621
+ "phase14.conditional.comparison_region",
622
+ }
623
+ conditional_plans: list[dict[str, Any]] = []
624
+ plans_by_source: dict[Any, list[dict[str, Any]]] = {}
625
+ for item in payload.get("rule_plans", ()):
626
+ _check_cancellation(cancellation)
627
+ if isinstance(item, dict) and item.get("rule_id") in conditional_rule_ids:
628
+ conditional_plans.append(item)
629
+ plans_by_source.setdefault(item.get("source_node_id"), []).append(item)
630
+ if {item.get("source_node_id") for item in conditional_plans} != set(expected):
631
+ return False, "conditional-region RulePlans do not exactly cover facts"
632
+ support: dict[Any, dict[str, Any]] = {}
633
+ for item in payload.get("support_decisions", ()):
634
+ _check_cancellation(cancellation)
635
+ if isinstance(item, dict):
636
+ support[item.get("node_id")] = item
637
+ for node_id, fact in expected.items():
638
+ _check_cancellation(cancellation)
639
+ matches = plans_by_source.get(node_id, ())
640
+ if len(matches) != 1:
641
+ return False, "conditional region lacks exactly one RulePlan"
642
+ plan = matches[0]
643
+ rule_id = (
644
+ "phase14.conditional.boolean_region"
645
+ if fact["region_kind"] == "boolean-short-circuit"
646
+ else "phase14.conditional.comparison_region"
647
+ )
648
+ rule_facts = {
649
+ "value-category:boolean-like",
650
+ f"conditional-region:{node_id}",
651
+ f"conditional-region-kind:{fact['region_kind']}",
652
+ f"conditional-unconditional-prefix:{fact['unconditional_prefix_count']}",
653
+ f"conditional-guarded-operand-count:{len(fact['guarded_operand_node_ids'])}",
654
+ f"conditional-lowering-shape:{fact['lowering_shape']}",
655
+ f"conditional-target:{fact['target_contract']}",
656
+ }
657
+ explanation = [
658
+ "selected",
659
+ rule_id,
660
+ "for",
661
+ "BoolOp" if fact["region_kind"] == "boolean-short-circuit" else "Compare",
662
+ "conditional-region",
663
+ fact["region_kind"],
664
+ "unconditional-prefix",
665
+ str(fact["unconditional_prefix_count"]),
666
+ "guarded-operands",
667
+ str(len(fact["guarded_operand_node_ids"])),
668
+ "lowered-as",
669
+ fact["lowering_shape"],
670
+ ]
671
+ decision = support.get(node_id)
672
+ if (
673
+ plan.get("rule_id") != rule_id
674
+ or plan.get("rule_version") != "0.14.1"
675
+ or plan.get("support_state") != "SupportedDirect"
676
+ or plan.get("helper_requirements") != []
677
+ or set(plan.get("facts_used", ())) != rule_facts
678
+ or plan.get("semantic_obligations") != list(CONDITIONAL_REGION_OBLIGATIONS)
679
+ or plan.get("resolved_obligations") != list(CONDITIONAL_REGION_OBLIGATIONS)
680
+ or plan.get("unresolved_obligations") != []
681
+ or plan.get("explanation_tokens") != explanation
682
+ or not isinstance(decision, dict)
683
+ or decision.get("state") != "SupportedDirect"
684
+ or decision.get("rule_plan_id") != plan.get("plan_id")
685
+ ):
686
+ return False, "conditional-region RulePlan does not close its exact proof"
687
+ return True, ""
688
+
689
+
690
+ __all__ = ["validate_conditional_region_facts"]