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,1357 @@
1
+ """Independent reconstruction of required keyword-only binding evidence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Mapping
6
+
7
+ from .model import (
8
+ CUMULATIVE_KEYWORD_ONLY_TARGET_DIAGNOSTIC_CODE,
9
+ CUMULATIVE_KEYWORD_ONLY_TARGET_REASON,
10
+ KEYWORD_ONLY_CALL_FACT_SCHEMA,
11
+ KEYWORD_ONLY_CALL_KEY_DOMAIN,
12
+ KEYWORD_ONLY_CALL_LOWERING_SHAPE,
13
+ KEYWORD_ONLY_CALL_OBLIGATIONS,
14
+ KEYWORD_ONLY_CALL_PROVENANCE_EVIDENCE,
15
+ KEYWORD_ONLY_CALL_RULE_ID,
16
+ KEYWORD_ONLY_CALL_RULE_VERSION,
17
+ KEYWORD_ONLY_CALL_TABLE_DEPENDENCIES,
18
+ KEYWORD_ONLY_CALL_TABLE_ID,
19
+ KeywordOnlyCallValidationCanceled,
20
+ keyword_only_call_binding_id,
21
+ )
22
+
23
+
24
+ class _MalformedKeywordOnlyEvidence(ValueError):
25
+ pass
26
+
27
+
28
+ _ANNOTATION_CONTRACTS = {
29
+ "int": (
30
+ "integer-like",
31
+ "int64_t",
32
+ "by-value",
33
+ "not-applicable",
34
+ "callee-activation",
35
+ ),
36
+ "float": (
37
+ "floating-like",
38
+ "double",
39
+ "by-value",
40
+ "not-applicable",
41
+ "callee-activation",
42
+ ),
43
+ "bool": (
44
+ "boolean-like",
45
+ "bool",
46
+ "by-value",
47
+ "not-applicable",
48
+ "callee-activation",
49
+ ),
50
+ "str": (
51
+ "string-like",
52
+ "const char *",
53
+ "borrowed-pointer",
54
+ "borrowed",
55
+ "caller-managed-valid-for-call",
56
+ ),
57
+ }
58
+
59
+
60
+ def _sequence(value: Any) -> bool:
61
+ return isinstance(value, (list, tuple))
62
+
63
+
64
+ def _category(value: Any) -> str:
65
+ return value.value if hasattr(value, "value") else str(value or "unknown")
66
+
67
+
68
+ def _check(cancellation: Any) -> None:
69
+ if cancellation is not None and bool(
70
+ getattr(cancellation, "is_canceled", False)
71
+ ):
72
+ raise KeywordOnlyCallValidationCanceled
73
+
74
+
75
+ def _record_values(
76
+ table: Mapping[str, Any],
77
+ cancellation: Any,
78
+ ) -> tuple[dict[str, Any], ...]:
79
+ records = table.get("records")
80
+ if not isinstance(records, list):
81
+ raise _MalformedKeywordOnlyEvidence("keyword-only dependency records are malformed")
82
+ result: list[dict[str, Any]] = []
83
+ for record in records:
84
+ _check(cancellation)
85
+ value = record.get("value") if isinstance(record, dict) else None
86
+ if not isinstance(value, dict):
87
+ raise _MalformedKeywordOnlyEvidence(
88
+ "keyword-only dependency contains a malformed record"
89
+ )
90
+ result.append(value)
91
+ return tuple(result)
92
+
93
+
94
+ class _IndependentKeywordOnlyReconstruction:
95
+ """Producer-independent implementation of the bounded binding algorithm."""
96
+
97
+ def __init__(
98
+ self,
99
+ *,
100
+ node_values: list[dict[str, Any]],
101
+ nodes: Mapping[str, dict[str, Any]],
102
+ node_order: Mapping[str, int],
103
+ occurrence_bindings: Mapping[str, str],
104
+ binding_by_declaration: Mapping[str, str],
105
+ declaration_by_binding: Mapping[str, str],
106
+ signatures: Mapping[str, dict[str, Any]],
107
+ categories: Mapping[str, str],
108
+ ignored_call_node_ids: frozenset[str],
109
+ cancellation: Any,
110
+ ) -> None:
111
+ self.node_values = node_values
112
+ self.nodes = nodes
113
+ self.node_order = node_order
114
+ self.occurrence_bindings = occurrence_bindings
115
+ self.binding_by_declaration = binding_by_declaration
116
+ self.declaration_by_binding = declaration_by_binding
117
+ self.signatures = signatures
118
+ self.categories = categories
119
+ self.ignored = ignored_call_node_ids
120
+ self.cancellation = cancellation
121
+ self.call_target_contracts: dict[str, dict[str, Any]] = {}
122
+
123
+ def expected(self) -> dict[str, dict[str, Any]]:
124
+ result: dict[str, dict[str, Any]] = {}
125
+ for call in self.node_values:
126
+ _check(self.cancellation)
127
+ if call.get("kind") != "Call" or call.get("node_id") in self.ignored:
128
+ continue
129
+ fields = call.get("fields")
130
+ if (
131
+ not isinstance(fields, dict)
132
+ or not _sequence(fields.get("args"))
133
+ or not _sequence(fields.get("keywords"))
134
+ ):
135
+ raise _MalformedKeywordOnlyEvidence(
136
+ "keyword-only Python IR call fields are malformed"
137
+ )
138
+ callee_id = fields.get("func")
139
+ callee = self.nodes.get(callee_id)
140
+ binding_id = self.occurrence_bindings.get(callee_id)
141
+ signature = self.signatures.get(binding_id)
142
+ if (
143
+ not isinstance(callee, dict)
144
+ or callee.get("kind") != "Name"
145
+ or not isinstance(signature, dict)
146
+ or signature.get("eligible") is not True
147
+ ):
148
+ continue
149
+ shape = self._signature_shape(signature)
150
+ if shape is None:
151
+ continue
152
+ result[call["node_id"]] = self._fact(
153
+ call,
154
+ signature,
155
+ str(binding_id),
156
+ shape,
157
+ )
158
+ return result
159
+
160
+ def _signature_shape(
161
+ self,
162
+ signature: dict[str, Any],
163
+ ) -> tuple[
164
+ dict[str, Any],
165
+ tuple[str, ...],
166
+ tuple[str, ...],
167
+ tuple[str, ...],
168
+ ] | None:
169
+ target = self.nodes.get(signature.get("function_node_id"))
170
+ target_fields = target.get("fields") if isinstance(target, dict) else None
171
+ arguments = (
172
+ self.nodes.get(target_fields.get("args"))
173
+ if isinstance(target_fields, dict)
174
+ else None
175
+ )
176
+ fields = arguments.get("fields") if isinstance(arguments, dict) else None
177
+ if not isinstance(fields, dict):
178
+ raise _MalformedKeywordOnlyEvidence(
179
+ "keyword-only signature Python IR is malformed"
180
+ )
181
+ for name in (
182
+ "posonlyargs",
183
+ "args",
184
+ "kwonlyargs",
185
+ "kw_defaults",
186
+ "defaults",
187
+ ):
188
+ if not _sequence(fields.get(name)):
189
+ raise _MalformedKeywordOnlyEvidence(
190
+ "keyword-only signature sequences are malformed"
191
+ )
192
+ posonly = tuple(fields["posonlyargs"])
193
+ positional = tuple(fields["args"])
194
+ keyword_only = tuple(fields["kwonlyargs"])
195
+ if not keyword_only:
196
+ return None
197
+ if (
198
+ len(fields["kw_defaults"]) != len(keyword_only)
199
+ or any(item is not None for item in fields["kw_defaults"])
200
+ or fields["defaults"]
201
+ or fields.get("vararg")
202
+ or fields.get("kwarg")
203
+ ):
204
+ return None
205
+ return fields, posonly, positional, keyword_only
206
+
207
+ def _fact(
208
+ self,
209
+ call: dict[str, Any],
210
+ signature: dict[str, Any],
211
+ target_binding_id: str,
212
+ shape: tuple[
213
+ dict[str, Any],
214
+ tuple[str, ...],
215
+ tuple[str, ...],
216
+ tuple[str, ...],
217
+ ],
218
+ ) -> dict[str, Any]:
219
+ fields = call["fields"]
220
+ call_id = call["node_id"]
221
+ _, posonly, positional, keyword_only = shape
222
+ formal_ids = posonly + positional + keyword_only
223
+ parameters_value = signature.get("parameters")
224
+ if not _sequence(parameters_value) or any(
225
+ not isinstance(item, dict) for item in parameters_value
226
+ ):
227
+ raise _MalformedKeywordOnlyEvidence(
228
+ "keyword-only signature facts are malformed"
229
+ )
230
+ parameters = tuple(parameters_value)
231
+ target_id = signature.get("function_node_id")
232
+ target = self.nodes.get(target_id)
233
+ target_fields = target.get("fields") if isinstance(target, dict) else None
234
+ if (
235
+ not isinstance(target_id, str)
236
+ or not isinstance(target, dict)
237
+ or target.get("kind") != "FunctionDef"
238
+ or not isinstance(target_fields, dict)
239
+ or self.binding_by_declaration.get(target_id) != target_binding_id
240
+ ):
241
+ raise _MalformedKeywordOnlyEvidence(
242
+ "keyword-only target signature identity is malformed"
243
+ )
244
+ target_name = target_fields.get("name")
245
+ if not isinstance(target_name, str) or not target_name:
246
+ raise _MalformedKeywordOnlyEvidence(
247
+ "keyword-only target function name is malformed"
248
+ )
249
+ return_contract = self._annotation_contract(target_fields.get("returns"))
250
+ return_annotation_id = target_fields.get("returns")
251
+ return_spelling = self.nodes[return_annotation_id]["fields"]["id"]
252
+ expected_signature = {
253
+ "function_node_id": target_id,
254
+ "binding_id": target_binding_id,
255
+ "source_name": target_name,
256
+ "return_category": return_contract[0],
257
+ "return_c_type": return_contract[1],
258
+ "return_annotation_node_id": return_annotation_id,
259
+ "return_annotation_spelling": return_spelling,
260
+ "return_passing": return_contract[2],
261
+ "return_ownership": return_contract[3],
262
+ "return_lifetime": return_contract[4],
263
+ "prototype_required": True,
264
+ "eligible": True,
265
+ "rejection_reason": None,
266
+ }
267
+ if any(
268
+ signature.get(name) != value
269
+ for name, value in expected_signature.items()
270
+ ):
271
+ raise _MalformedKeywordOnlyEvidence(
272
+ "keyword-only signature facts disagree with Python IR annotations"
273
+ )
274
+ if len(parameters) != len(formal_ids):
275
+ raise _MalformedKeywordOnlyEvidence(
276
+ "keyword-only signature parameter coverage is malformed"
277
+ )
278
+ parameter_names: list[str] = []
279
+ parameter_categories: list[str] = []
280
+ ownership_boundary: list[str] = []
281
+ annotation_evidence: list[str] = []
282
+ for ordinal, (parameter_id, parameter_fact) in enumerate(
283
+ zip(formal_ids, parameters)
284
+ ):
285
+ _check(self.cancellation)
286
+ parameter = self.nodes.get(parameter_id)
287
+ parameter_fields = (
288
+ parameter.get("fields") if isinstance(parameter, dict) else None
289
+ )
290
+ if (
291
+ not isinstance(parameter_id, str)
292
+ or not isinstance(parameter, dict)
293
+ or parameter.get("kind") != "arg"
294
+ or not isinstance(parameter_fields, dict)
295
+ ):
296
+ raise _MalformedKeywordOnlyEvidence(
297
+ "keyword-only formal Python IR is malformed"
298
+ )
299
+ parameter_name = parameter_fields.get("arg")
300
+ annotation_id = parameter_fields.get("annotation")
301
+ if not isinstance(parameter_name, str) or not parameter_name:
302
+ raise _MalformedKeywordOnlyEvidence(
303
+ "keyword-only formal name is malformed"
304
+ )
305
+ contract = self._annotation_contract(annotation_id)
306
+ spelling = self.nodes[annotation_id]["fields"]["id"]
307
+ expected_parameter = {
308
+ "parameter_node_id": parameter_id,
309
+ "binding_id": self.binding_by_declaration.get(parameter_id),
310
+ "source_name": parameter_name,
311
+ "ordinal": ordinal,
312
+ "category": contract[0],
313
+ "c_type": contract[1],
314
+ "annotation_node_id": annotation_id,
315
+ "annotation_spelling": spelling,
316
+ "passing": contract[2],
317
+ "ownership": contract[3],
318
+ "lifetime": contract[4],
319
+ }
320
+ if (
321
+ not isinstance(expected_parameter["binding_id"], str)
322
+ or any(
323
+ parameter_fact.get(name) != value
324
+ for name, value in expected_parameter.items()
325
+ )
326
+ ):
327
+ raise _MalformedKeywordOnlyEvidence(
328
+ "keyword-only parameter facts disagree with Python IR annotations"
329
+ )
330
+ parameter_names.append(parameter_name)
331
+ parameter_categories.append(contract[0])
332
+ ownership_boundary.append(":".join(contract[2:]))
333
+ annotation_evidence.append(annotation_id)
334
+ parameter_node_ids = formal_ids
335
+ parameter_names_tuple = tuple(parameter_names)
336
+ parameter_categories_tuple = tuple(parameter_categories)
337
+ parameter_kinds = (
338
+ ("positional-only",) * len(posonly)
339
+ + ("positional-or-keyword",) * len(positional)
340
+ + ("keyword-only",) * len(keyword_only)
341
+ )
342
+ if (
343
+ parameter_node_ids != formal_ids
344
+ or len(parameter_names_tuple) != len(set(parameter_names_tuple))
345
+ ):
346
+ raise _MalformedKeywordOnlyEvidence(
347
+ "keyword-only formal identities are malformed"
348
+ )
349
+ positional_ids = tuple(fields["args"])
350
+ keyword_ids = tuple(fields["keywords"])
351
+ if any(not isinstance(item, str) for item in (*positional_ids, *keyword_ids)):
352
+ raise _MalformedKeywordOnlyEvidence(
353
+ "keyword-only actual identities are malformed"
354
+ )
355
+ keyword_nodes: list[dict[str, Any]] = []
356
+ for keyword_id in keyword_ids:
357
+ keyword = self.nodes.get(keyword_id)
358
+ keyword_fields = keyword.get("fields") if isinstance(keyword, dict) else None
359
+ if (
360
+ not isinstance(keyword, dict)
361
+ or keyword.get("kind") != "keyword"
362
+ or not isinstance(keyword_fields, dict)
363
+ or not isinstance(keyword_fields.get("value"), str)
364
+ or keyword_fields["value"] not in self.nodes
365
+ ):
366
+ raise _MalformedKeywordOnlyEvidence(
367
+ "keyword-only keyword evidence is malformed"
368
+ )
369
+ keyword_nodes.append(keyword)
370
+ positional_entries = [
371
+ {
372
+ "kind": "positional",
373
+ "position": position,
374
+ "argument": argument_id,
375
+ "keyword": None,
376
+ "name": None,
377
+ "order_node_id": argument_id,
378
+ }
379
+ for position, argument_id in enumerate(positional_ids)
380
+ ]
381
+ if any(item["argument"] not in self.nodes for item in positional_entries):
382
+ raise _MalformedKeywordOnlyEvidence(
383
+ "keyword-only positional actual is absent"
384
+ )
385
+ keyword_entries = [
386
+ {
387
+ "kind": "keyword",
388
+ "position": position,
389
+ "argument": keyword["fields"]["value"],
390
+ "keyword": keyword["node_id"],
391
+ "name": keyword["fields"].get("arg"),
392
+ "order_node_id": keyword["node_id"],
393
+ }
394
+ for position, keyword in enumerate(keyword_nodes)
395
+ ]
396
+ entries = self._merge(positional_entries, keyword_entries)
397
+ for ordinal, entry in enumerate(entries):
398
+ entry["ordinal"] = ordinal
399
+ by_position = {
400
+ (item["kind"], item["position"]): item for item in entries
401
+ }
402
+
403
+ positional_capacity = len(posonly) + len(positional)
404
+ addressable = {
405
+ name: ordinal
406
+ for ordinal, name in enumerate(parameter_names_tuple)
407
+ if ordinal >= len(posonly)
408
+ }
409
+ all_names = {
410
+ name: ordinal for ordinal, name in enumerate(parameter_names_tuple)
411
+ }
412
+ parameter_arguments: list[str | None] = [None] * len(parameters)
413
+ parameter_sources: list[int | None] = [None] * len(parameters)
414
+ source_parameters: dict[tuple[str, int], int | None] = {}
415
+ unpacking: list[tuple[int, str]] = []
416
+ excess: list[tuple[int, str]] = []
417
+ problems: list[tuple[int, str, str]] = []
418
+ saw_starred = False
419
+ for position, argument_id in enumerate(positional_ids):
420
+ _check(self.cancellation)
421
+ entry = by_position[("positional", position)]
422
+ if self.nodes[argument_id].get("kind") == "Starred":
423
+ saw_starred = True
424
+ source_parameters[("positional", position)] = None
425
+ unpacking.append((entry["ordinal"], argument_id))
426
+ elif saw_starred:
427
+ source_parameters[("positional", position)] = None
428
+ elif position >= positional_capacity:
429
+ source_parameters[("positional", position)] = None
430
+ excess.append((entry["ordinal"], argument_id))
431
+ else:
432
+ source_parameters[("positional", position)] = position
433
+ parameter_arguments[position] = argument_id
434
+ parameter_sources[position] = entry["ordinal"]
435
+ for position, keyword in enumerate(keyword_nodes):
436
+ _check(self.cancellation)
437
+ entry = by_position[("keyword", position)]
438
+ keyword_id = keyword["node_id"]
439
+ name = keyword["fields"].get("arg")
440
+ if name is None:
441
+ source_parameters[("keyword", position)] = None
442
+ unpacking.append((entry["ordinal"], keyword_id))
443
+ continue
444
+ parameter_ordinal = addressable.get(name)
445
+ if parameter_ordinal is None:
446
+ source_parameters[("keyword", position)] = None
447
+ reason = (
448
+ f"Positional-only parameter cannot be bound by keyword: {name}"
449
+ if name in all_names
450
+ else f"Unknown keyword argument: {name}"
451
+ )
452
+ problems.append((entry["ordinal"], keyword_id, reason))
453
+ continue
454
+ source_parameters[("keyword", position)] = parameter_ordinal
455
+ if parameter_arguments[parameter_ordinal] is not None:
456
+ prior = parameter_sources[parameter_ordinal]
457
+ prior_entry = (
458
+ entries[prior]
459
+ if isinstance(prior, int) and 0 <= prior < len(entries)
460
+ else None
461
+ )
462
+ reason = (
463
+ f"Keyword argument duplicates a positionally bound parameter: {name}"
464
+ if prior_entry and prior_entry["kind"] == "positional"
465
+ else f"Duplicate keyword argument: {name}"
466
+ )
467
+ problems.append((entry["ordinal"], keyword_id, reason))
468
+ continue
469
+ parameter_arguments[parameter_ordinal] = keyword["fields"]["value"]
470
+ parameter_sources[parameter_ordinal] = entry["ordinal"]
471
+
472
+ argument_bindings: list[dict[str, Any]] = []
473
+ for entry in entries:
474
+ _check(self.cancellation)
475
+ parameter_ordinal = source_parameters.get(
476
+ (entry["kind"], entry["position"])
477
+ )
478
+ valid = (
479
+ isinstance(parameter_ordinal, int)
480
+ and 0 <= parameter_ordinal < len(parameters)
481
+ )
482
+ argument_id = entry["argument"]
483
+ argument_bindings.append(
484
+ {
485
+ "source_argument_node_id": argument_id,
486
+ "keyword_node_id": entry["keyword"],
487
+ "keyword_name": entry["name"],
488
+ "source_ordinal": entry["ordinal"],
489
+ "parameter_node_id": (
490
+ parameter_node_ids[parameter_ordinal] if valid else None
491
+ ),
492
+ "parameter_name": (
493
+ parameter_names_tuple[parameter_ordinal] if valid else None
494
+ ),
495
+ "parameter_kind": (
496
+ parameter_kinds[parameter_ordinal] if valid else None
497
+ ),
498
+ "parameter_ordinal": parameter_ordinal,
499
+ "category": self._actual_category(argument_id),
500
+ "expected_category": (
501
+ parameter_categories_tuple[parameter_ordinal]
502
+ if valid
503
+ else None
504
+ ),
505
+ }
506
+ )
507
+ missing = [
508
+ parameter_names_tuple[index]
509
+ for index, value in enumerate(parameter_arguments)
510
+ if value is None
511
+ ]
512
+ mismatches = [
513
+ item
514
+ for item in argument_bindings
515
+ if item["parameter_ordinal"] is not None
516
+ and item["expected_category"] is not None
517
+ and item["category"] != item["expected_category"]
518
+ and parameter_sources[item["parameter_ordinal"]]
519
+ == item["source_ordinal"]
520
+ ]
521
+ keyword_only_coverage = all(
522
+ parameter_arguments[index] is not None
523
+ for index in range(positional_capacity, len(parameters))
524
+ )
525
+ coverage = bool(
526
+ not unpacking
527
+ and not excess
528
+ and not problems
529
+ and not missing
530
+ and len(entries) == len(parameters)
531
+ )
532
+ code = reason = rejection = None
533
+ if unpacking:
534
+ _, rejection = min(unpacking, key=lambda item: item[0])
535
+ code, reason = "PYC2910", (
536
+ "Starred and unpacked arguments are unsupported by the exact "
537
+ "required keyword-only profile"
538
+ )
539
+ elif excess:
540
+ _, rejection = min(excess, key=lambda item: item[0])
541
+ code, reason = "PYC2904", (
542
+ "Positional argument count exceeds the positional portion of "
543
+ "the target signature"
544
+ )
545
+ elif problems:
546
+ _, rejection, reason = min(problems, key=lambda item: item[0])
547
+ code = "PYC2912"
548
+ elif missing:
549
+ rejection, code, reason = call_id, "PYC2904", (
550
+ "Every target parameter must be supplied exactly once; missing: "
551
+ + ", ".join(missing)
552
+ )
553
+ elif mismatches:
554
+ mismatch = mismatches[0]
555
+ rejection = (
556
+ mismatch["keyword_node_id"]
557
+ or mismatch["source_argument_node_id"]
558
+ )
559
+ code, reason = "PYC2905", (
560
+ "Argument representation does not match parameter "
561
+ f"{mismatch['parameter_name']}"
562
+ )
563
+ supported = code is None and coverage and keyword_only_coverage
564
+ if code is None and not supported:
565
+ rejection, code, reason = call_id, "PYC2904", (
566
+ "Arguments do not exactly cover the required keyword-only signature"
567
+ )
568
+ source_ids = [item["source_argument_node_id"] for item in argument_bindings]
569
+ source_categories = [item["category"] for item in argument_bindings]
570
+ self.call_target_contracts[call_id] = {
571
+ "call_node_id": call_id,
572
+ "callee_node_id": fields["func"],
573
+ "target_function_node_id": target_id,
574
+ "target_binding_id": target_binding_id,
575
+ "target_name": target_name,
576
+ "argument_node_ids": source_ids,
577
+ "argument_categories": source_categories,
578
+ "parameter_categories": list(parameter_categories_tuple),
579
+ "return_category": return_contract[0],
580
+ "evaluation_order": source_ids,
581
+ "arguments_evaluated_once": True,
582
+ "ownership_boundary": ownership_boundary,
583
+ "annotation_evidence": annotation_evidence + [return_annotation_id],
584
+ }
585
+ return {
586
+ "binding_id": keyword_only_call_binding_id(call_id, target_binding_id),
587
+ "call_node_id": call_id,
588
+ "callee_node_id": fields["func"],
589
+ "target_function_node_id": target_id,
590
+ "target_binding_id": target_binding_id,
591
+ "target_name": target_name,
592
+ "positional_only_parameter_count": len(posonly),
593
+ "positional_or_keyword_parameter_count": len(positional),
594
+ "keyword_only_parameter_count": len(keyword_only),
595
+ "parameter_node_ids": list(parameter_node_ids),
596
+ "parameter_names": list(parameter_names_tuple),
597
+ "parameter_kinds": list(parameter_kinds),
598
+ "parameter_categories": list(parameter_categories_tuple),
599
+ "required_keyword_only_parameter_node_ids": list(
600
+ parameter_node_ids[positional_capacity:]
601
+ ),
602
+ "required_keyword_only_parameter_names": list(
603
+ parameter_names_tuple[positional_capacity:]
604
+ ),
605
+ "required_keyword_only_parameter_categories": list(
606
+ parameter_categories_tuple[positional_capacity:]
607
+ ),
608
+ "positional_argument_node_ids": list(positional_ids),
609
+ "keyword_node_ids": list(keyword_ids),
610
+ "keyword_names": [
611
+ item.get("fields", {}).get("arg") for item in keyword_nodes
612
+ ],
613
+ "keyword_value_node_ids": [
614
+ item.get("fields", {}).get("value") for item in keyword_nodes
615
+ ],
616
+ "argument_bindings": argument_bindings,
617
+ "source_argument_node_ids": source_ids,
618
+ "source_argument_categories": source_categories,
619
+ "source_to_parameter_ordinals": [
620
+ item["parameter_ordinal"] for item in argument_bindings
621
+ ],
622
+ "parameter_argument_node_ids": parameter_arguments,
623
+ "parameter_to_source_ordinals": parameter_sources,
624
+ "evaluation_order": source_ids,
625
+ "arguments_evaluated_once": True,
626
+ "parameter_coverage_exact": coverage,
627
+ "keyword_only_coverage_exact": keyword_only_coverage,
628
+ "lowering_shape": KEYWORD_ONLY_CALL_LOWERING_SHAPE,
629
+ "allocation_model": "none",
630
+ "cleanup_model": "none",
631
+ "runtime_binding_failure": (
632
+ "proved-absent" if supported else "compile-time-rejected"
633
+ ),
634
+ "supported": supported,
635
+ "diagnostic_code": code,
636
+ "reason": reason,
637
+ "rejection_node_id": rejection,
638
+ }
639
+
640
+ def expected_call_target(self, fact: Mapping[str, Any]) -> dict[str, Any]:
641
+ contract = dict(self.call_target_contracts[fact["call_node_id"]])
642
+ contract.update(
643
+ {
644
+ "resolution": (
645
+ "understood-source-function"
646
+ if fact["supported"]
647
+ else "ineligible-source-function"
648
+ ),
649
+ "supported": fact["supported"],
650
+ "diagnostic_code": fact["diagnostic_code"],
651
+ "reason": fact["reason"],
652
+ }
653
+ )
654
+ return contract
655
+
656
+ def _annotation_contract(
657
+ self,
658
+ annotation_id: Any,
659
+ ) -> tuple[str, str, str, str, str]:
660
+ annotation = self.nodes.get(annotation_id)
661
+ fields = annotation.get("fields") if isinstance(annotation, dict) else None
662
+ spelling = fields.get("id") if isinstance(fields, dict) else None
663
+ contract = _ANNOTATION_CONTRACTS.get(spelling)
664
+ if (
665
+ not isinstance(annotation_id, str)
666
+ or not isinstance(annotation, dict)
667
+ or annotation.get("kind") != "Name"
668
+ or contract is None
669
+ ):
670
+ raise _MalformedKeywordOnlyEvidence(
671
+ "keyword-only annotation evidence is malformed"
672
+ )
673
+ return contract
674
+
675
+ def _actual_category(self, node_id: str) -> str:
676
+ independent = self._source_category(node_id, frozenset())
677
+ recorded = self.categories.get(node_id, "unknown")
678
+ if independent is not None and recorded != independent:
679
+ raise _MalformedKeywordOnlyEvidence(
680
+ "keyword-only actual category disagrees with Python IR annotations"
681
+ )
682
+ return independent if independent is not None else recorded
683
+
684
+ def _source_category(
685
+ self,
686
+ node_id: str,
687
+ active: frozenset[str],
688
+ ) -> str | None:
689
+ if node_id in active:
690
+ return None
691
+ node = self.nodes.get(node_id)
692
+ fields = node.get("fields") if isinstance(node, dict) else None
693
+ if not isinstance(node, dict) or not isinstance(fields, dict):
694
+ return None
695
+ kind = node.get("kind")
696
+ if kind == "Constant":
697
+ value = fields.get("value")
698
+ if isinstance(value, bool):
699
+ return "boolean-like"
700
+ if isinstance(value, int):
701
+ return "integer-like"
702
+ if isinstance(value, float) or (
703
+ _sequence(value)
704
+ and tuple(value[:2]) == ("unsupported-python-value", "float-nonfinite")
705
+ ):
706
+ return "floating-like"
707
+ if isinstance(value, str):
708
+ return "string-like"
709
+ return None
710
+ if kind == "Name":
711
+ binding_id = self.occurrence_bindings.get(node_id)
712
+ declaration_id = self.declaration_by_binding.get(binding_id)
713
+ declaration = self.nodes.get(declaration_id)
714
+ declaration_fields = (
715
+ declaration.get("fields")
716
+ if isinstance(declaration, dict)
717
+ else None
718
+ )
719
+ if (
720
+ isinstance(declaration, dict)
721
+ and declaration.get("kind") == "arg"
722
+ and isinstance(declaration_fields, dict)
723
+ ):
724
+ annotation_id = declaration_fields.get("annotation")
725
+ annotation = self.nodes.get(annotation_id)
726
+ annotation_fields = (
727
+ annotation.get("fields")
728
+ if isinstance(annotation, dict)
729
+ else None
730
+ )
731
+ spelling = (
732
+ annotation_fields.get("id")
733
+ if isinstance(annotation_fields, dict)
734
+ and annotation.get("kind") == "Name"
735
+ else None
736
+ )
737
+ contract = _ANNOTATION_CONTRACTS.get(spelling)
738
+ return contract[0] if contract is not None else None
739
+ return "callable-like" if (
740
+ isinstance(declaration, dict)
741
+ and declaration.get("kind") == "FunctionDef"
742
+ ) else None
743
+ next_active = active | {node_id}
744
+ if kind == "Call":
745
+ callee_binding = self.occurrence_bindings.get(fields.get("func"))
746
+ target_id = self.declaration_by_binding.get(callee_binding)
747
+ target = self.nodes.get(target_id)
748
+ target_fields = target.get("fields") if isinstance(target, dict) else None
749
+ if (
750
+ isinstance(target, dict)
751
+ and target.get("kind") == "FunctionDef"
752
+ and isinstance(target_fields, dict)
753
+ ):
754
+ annotation_id = target_fields.get("returns")
755
+ annotation = self.nodes.get(annotation_id)
756
+ annotation_fields = (
757
+ annotation.get("fields")
758
+ if isinstance(annotation, dict)
759
+ else None
760
+ )
761
+ spelling = (
762
+ annotation_fields.get("id")
763
+ if isinstance(annotation_fields, dict)
764
+ and annotation.get("kind") == "Name"
765
+ else None
766
+ )
767
+ contract = _ANNOTATION_CONTRACTS.get(spelling)
768
+ return contract[0] if contract is not None else None
769
+ return None
770
+ if kind == "UnaryOp":
771
+ operand = self._source_category(fields.get("operand"), next_active)
772
+ operator = self.nodes.get(fields.get("op"), {}).get("kind")
773
+ if operator == "Not" and operand in {
774
+ "integer-like",
775
+ "floating-like",
776
+ "boolean-like",
777
+ }:
778
+ return "boolean-like"
779
+ if operator in {"UAdd", "USub"} and operand in {
780
+ "integer-like",
781
+ "floating-like",
782
+ }:
783
+ return operand
784
+ return None
785
+ if kind == "BoolOp":
786
+ values = tuple(
787
+ self._source_category(item, next_active)
788
+ for item in fields.get("values", ())
789
+ )
790
+ return "boolean-like" if values and all(
791
+ item == "boolean-like" for item in values
792
+ ) else None
793
+ if kind == "Compare":
794
+ values = (
795
+ self._source_category(fields.get("left"), next_active),
796
+ *(
797
+ self._source_category(item, next_active)
798
+ for item in fields.get("comparators", ())
799
+ ),
800
+ )
801
+ return "boolean-like" if (
802
+ values
803
+ and None not in values
804
+ and len(set(values)) == 1
805
+ and values[0]
806
+ in {"integer-like", "floating-like", "boolean-like"}
807
+ ) else None
808
+ if kind == "BinOp":
809
+ left = self._source_category(fields.get("left"), next_active)
810
+ right = self._source_category(fields.get("right"), next_active)
811
+ operator = self.nodes.get(fields.get("op"), {}).get("kind")
812
+ if operator == "Div":
813
+ return (
814
+ "floating-like"
815
+ if left == right == "floating-like"
816
+ else None
817
+ )
818
+ if left == right and left in {
819
+ "integer-like",
820
+ "floating-like",
821
+ "string-like",
822
+ }:
823
+ return left
824
+ return None
825
+
826
+ def _merge(
827
+ self,
828
+ positional: list[dict[str, Any]],
829
+ keywords: list[dict[str, Any]],
830
+ ) -> list[dict[str, Any]]:
831
+ result: list[dict[str, Any]] = []
832
+ left = right = 0
833
+ while left < len(positional) and right < len(keywords):
834
+ _check(self.cancellation)
835
+ if self._source_key(
836
+ positional[left]["order_node_id"]
837
+ ) <= self._source_key(keywords[right]["order_node_id"]):
838
+ result.append(positional[left])
839
+ left += 1
840
+ else:
841
+ result.append(keywords[right])
842
+ right += 1
843
+ result.extend(positional[left:])
844
+ result.extend(keywords[right:])
845
+ return result
846
+
847
+ def _source_key(self, node_id: str) -> tuple[int, int]:
848
+ node = self.nodes.get(node_id, {})
849
+ provenance = node.get("provenance")
850
+ span = provenance.get("source_span") if isinstance(provenance, dict) else None
851
+ start = span.get("start") if isinstance(span, dict) else None
852
+ offset = start.get("offset") if isinstance(start, dict) else None
853
+ return (
854
+ offset if isinstance(offset, int) else 2**63 - 1,
855
+ self.node_order.get(node_id, 2**63 - 1),
856
+ )
857
+
858
+
859
+ def _provenance_ids(fact: dict[str, Any]) -> list[str]:
860
+ values = (
861
+ fact["call_node_id"],
862
+ fact["callee_node_id"],
863
+ fact["target_function_node_id"],
864
+ *fact["parameter_node_ids"],
865
+ *fact["positional_argument_node_ids"],
866
+ *fact["keyword_node_ids"],
867
+ *fact["keyword_value_node_ids"],
868
+ )
869
+ return list(dict.fromkeys(values))
870
+
871
+
872
+ def _validate_plans(
873
+ payload: Mapping[str, Any],
874
+ expected: Mapping[str, dict[str, Any]],
875
+ cumulatively_ineligible_target_function_node_ids: frozenset[str],
876
+ cancellation: Any,
877
+ ) -> tuple[bool, str]:
878
+ plans = payload.get("rule_plans")
879
+ if not isinstance(plans, list):
880
+ return False, "keyword-only RulePlans are malformed"
881
+ feature_plans: dict[str, dict[str, Any]] = {}
882
+ for plan in plans:
883
+ _check(cancellation)
884
+ if not isinstance(plan, dict):
885
+ return False, "keyword-only RulePlans are malformed"
886
+ if plan.get("rule_id") != KEYWORD_ONLY_CALL_RULE_ID:
887
+ continue
888
+ source_id = plan.get("source_node_id")
889
+ if not isinstance(source_id, str) or source_id in feature_plans:
890
+ return False, "keyword-only RulePlans have invalid coverage"
891
+ feature_plans[source_id] = plan
892
+ tables = payload.get("fact_tables")
893
+ if not isinstance(tables, list):
894
+ return False, "keyword-only RulePlan dependencies are malformed"
895
+ call_table = next(
896
+ (
897
+ item
898
+ for item in tables
899
+ if isinstance(item, dict)
900
+ and item.get("table_id") == "call-target-facts"
901
+ ),
902
+ None,
903
+ )
904
+ if not isinstance(call_table, dict):
905
+ return False, "keyword-only call-target facts are absent"
906
+ calls = {
907
+ item.get("call_node_id"): item
908
+ for item in _record_values(call_table, cancellation)
909
+ }
910
+ supported = {
911
+ call_id: fact
912
+ for call_id, fact in expected.items()
913
+ if fact["supported"] and calls.get(call_id, {}).get("supported") is True
914
+ }
915
+ if set(feature_plans) != set(supported):
916
+ return False, "keyword-only RulePlans do not exactly cover supported facts"
917
+ for call_id, fact in supported.items():
918
+ _check(cancellation)
919
+ plan = feature_plans[call_id]
920
+ feature_facts = {
921
+ f"keyword-only-call-binding:{fact['binding_id']}",
922
+ f"keyword-only-call:{call_id}",
923
+ f"keyword-only-call-target:{fact['target_binding_id']}",
924
+ f"keyword-only-parameter-count:{fact['keyword_only_parameter_count']}",
925
+ f"keyword-only-source-argument-count:{len(fact['source_argument_node_ids'])}",
926
+ f"keyword-only-call-lowering-shape:{fact['lowering_shape']}",
927
+ *(
928
+ f"argument-category:{category}"
929
+ for category in fact["source_argument_categories"]
930
+ ),
931
+ }
932
+ facts_used = plan.get("facts_used")
933
+ obligations = plan.get("semantic_obligations")
934
+ if (
935
+ plan.get("rule_version") != KEYWORD_ONLY_CALL_RULE_VERSION
936
+ or plan.get("support_state") != "SupportedDirect"
937
+ or plan.get("helper_requirements") != []
938
+ or plan.get("unresolved_obligations") != []
939
+ or not isinstance(facts_used, list)
940
+ or not feature_facts.issubset(set(facts_used))
941
+ or not isinstance(obligations, list)
942
+ or obligations[: len(KEYWORD_ONLY_CALL_OBLIGATIONS)]
943
+ != list(KEYWORD_ONLY_CALL_OBLIGATIONS)
944
+ or plan.get("resolved_obligations") != obligations
945
+ ):
946
+ return False, "keyword-only RulePlan does not close its exact proof"
947
+ explanation = plan.get("explanation_tokens")
948
+ if (
949
+ not isinstance(explanation, list)
950
+ or "required-keyword-only-call-binding" not in explanation
951
+ or fact["lowering_shape"] not in explanation
952
+ ):
953
+ return False, "keyword-only RulePlan explanation is incomplete"
954
+ return _validate_declaration_plans(
955
+ payload,
956
+ plans,
957
+ cumulatively_ineligible_target_function_node_ids,
958
+ cancellation,
959
+ )
960
+
961
+
962
+ def _validate_declaration_plans(
963
+ payload: Mapping[str, Any],
964
+ plans: list[dict[str, Any]],
965
+ cumulatively_ineligible_target_function_node_ids: frozenset[str],
966
+ cancellation: Any,
967
+ ) -> tuple[bool, str]:
968
+ """Require explicit plan evidence even when an eligible declaration is uncalled."""
969
+
970
+ module = payload.get("python_ir")
971
+ node_values = module.get("nodes") if isinstance(module, dict) else None
972
+ tables = payload.get("fact_tables")
973
+ if not isinstance(node_values, list) or not isinstance(tables, list):
974
+ return False, "keyword-only declaration evidence dependencies are malformed"
975
+ nodes = {
976
+ node.get("node_id"): node
977
+ for node in node_values
978
+ if isinstance(node, dict) and isinstance(node.get("node_id"), str)
979
+ }
980
+ signature_table = next(
981
+ (
982
+ table
983
+ for table in tables
984
+ if isinstance(table, dict)
985
+ and table.get("table_id") == "function-signature-facts"
986
+ ),
987
+ None,
988
+ )
989
+ if not isinstance(signature_table, dict):
990
+ return False, "keyword-only declaration signature facts are absent"
991
+ eligible_signatures = {
992
+ signature.get("function_node_id"): signature
993
+ for signature in _record_values(signature_table, cancellation)
994
+ if signature.get("eligible") is True
995
+ }
996
+ plans_by_source: dict[str, list[dict[str, Any]]] = {}
997
+ for plan in plans:
998
+ _check(cancellation)
999
+ source_id = plan.get("source_node_id")
1000
+ if isinstance(source_id, str):
1001
+ plans_by_source.setdefault(source_id, []).append(plan)
1002
+ for function_id, signature in eligible_signatures.items():
1003
+ _check(cancellation)
1004
+ if function_id in cumulatively_ineligible_target_function_node_ids:
1005
+ continue
1006
+ function = nodes.get(function_id)
1007
+ function_fields = (
1008
+ function.get("fields") if isinstance(function, dict) else None
1009
+ )
1010
+ arguments = (
1011
+ nodes.get(function_fields.get("args"))
1012
+ if isinstance(function_fields, dict)
1013
+ else None
1014
+ )
1015
+ fields = arguments.get("fields") if isinstance(arguments, dict) else None
1016
+ if not isinstance(fields, dict):
1017
+ return False, "keyword-only declaration Python IR is malformed"
1018
+ keyword_only_ids = fields.get("kwonlyargs")
1019
+ keyword_defaults = fields.get("kw_defaults")
1020
+ if (
1021
+ not _sequence(keyword_only_ids)
1022
+ or not keyword_only_ids
1023
+ or not _sequence(keyword_defaults)
1024
+ or tuple(keyword_defaults) != (None,) * len(keyword_only_ids)
1025
+ or fields.get("defaults")
1026
+ or fields.get("vararg")
1027
+ or fields.get("kwarg")
1028
+ ):
1029
+ continue
1030
+ keyword_only_names: list[str] = []
1031
+ for parameter_id in keyword_only_ids:
1032
+ _check(cancellation)
1033
+ parameter = nodes.get(parameter_id)
1034
+ name = (
1035
+ parameter.get("fields", {}).get("arg")
1036
+ if isinstance(parameter, dict)
1037
+ else None
1038
+ )
1039
+ if (
1040
+ not isinstance(parameter_id, str)
1041
+ or not isinstance(name, str)
1042
+ or not name
1043
+ ):
1044
+ return False, "keyword-only declaration parameter evidence is malformed"
1045
+ keyword_only_names.append(name)
1046
+ expected_parameter_ids = (
1047
+ tuple(fields.get("posonlyargs", ()))
1048
+ + tuple(fields.get("args", ()))
1049
+ + tuple(keyword_only_ids)
1050
+ )
1051
+ signature_parameters = signature.get("parameters")
1052
+ if _sequence(signature_parameters):
1053
+ for _ in signature_parameters:
1054
+ _check(cancellation)
1055
+ if (
1056
+ not _sequence(signature_parameters)
1057
+ or tuple(
1058
+ item.get("parameter_node_id")
1059
+ for item in signature_parameters
1060
+ if isinstance(item, dict)
1061
+ )
1062
+ != expected_parameter_ids
1063
+ or len(signature_parameters) != len(expected_parameter_ids)
1064
+ ):
1065
+ return False, "keyword-only declaration signature facts are incomplete"
1066
+ declaration_plans = plans_by_source.get(function_id, ())
1067
+ if len(declaration_plans) != 1:
1068
+ return False, "keyword-only declaration lacks exactly one RulePlan"
1069
+ plan = declaration_plans[0]
1070
+ required_facts = {
1071
+ f"keyword-only-signature:{function_id}",
1072
+ f"keyword-only-parameter-count:{len(keyword_only_ids)}",
1073
+ "keyword-only-c-interface:mode-erased-after-static-binding",
1074
+ *(
1075
+ f"keyword-only-parameter:{ordinal}:{parameter_id}:{name}"
1076
+ for ordinal, (parameter_id, name) in enumerate(
1077
+ zip(keyword_only_ids, keyword_only_names)
1078
+ )
1079
+ ),
1080
+ }
1081
+ declaration_obligations = [
1082
+ "required-keyword-only-parameters-exact",
1083
+ "keyword-only-parameter-kinds-preserved",
1084
+ "c-interface-mode-erasure-after-static-binding",
1085
+ "defaults-and-variadics-absent",
1086
+ ]
1087
+ declaration_explanation = [
1088
+ "required-keyword-only-signature",
1089
+ str(len(keyword_only_ids)),
1090
+ "c-interface-mode-erasure",
1091
+ "after-static-binding",
1092
+ ]
1093
+ facts_used = plan.get("facts_used")
1094
+ obligations = plan.get("semantic_obligations")
1095
+ explanation = plan.get("explanation_tokens")
1096
+ if (
1097
+ plan.get("support_state") != "SupportedDirect"
1098
+ or not isinstance(facts_used, list)
1099
+ or not required_facts.issubset(facts_used)
1100
+ or not isinstance(obligations, list)
1101
+ or obligations[-len(declaration_obligations) :]
1102
+ != declaration_obligations
1103
+ or plan.get("resolved_obligations") != obligations
1104
+ or plan.get("unresolved_obligations") != []
1105
+ or not isinstance(explanation, list)
1106
+ or explanation[-len(declaration_explanation) :]
1107
+ != declaration_explanation
1108
+ ):
1109
+ return False, "keyword-only declaration RulePlan evidence is incomplete"
1110
+ return True, ""
1111
+
1112
+
1113
+ def validate_keyword_only_call_binding_facts(
1114
+ payload: Mapping[str, Any],
1115
+ tables: list[dict[str, Any]] | tuple[dict[str, Any], ...] | None = None,
1116
+ *,
1117
+ expected_fact_schema: str = KEYWORD_ONLY_CALL_FACT_SCHEMA,
1118
+ require_table: bool = True,
1119
+ require_plans: bool = True,
1120
+ ignored_call_node_ids: frozenset[str] = frozenset(),
1121
+ cumulatively_ineligible_target_function_node_ids: frozenset[str] = frozenset(),
1122
+ cancellation: Any = None,
1123
+ ) -> tuple[bool, str]:
1124
+ """Fail closed on malformed or producer-inconsistent feature evidence."""
1125
+
1126
+ _check(cancellation)
1127
+ if not isinstance(payload, Mapping):
1128
+ return False, "keyword-only validation payload is malformed"
1129
+ if (
1130
+ not isinstance(ignored_call_node_ids, (set, frozenset))
1131
+ or any(not isinstance(item, str) for item in ignored_call_node_ids)
1132
+ or not isinstance(
1133
+ cumulatively_ineligible_target_function_node_ids,
1134
+ (set, frozenset),
1135
+ )
1136
+ or any(
1137
+ not isinstance(item, str)
1138
+ for item in cumulatively_ineligible_target_function_node_ids
1139
+ )
1140
+ ):
1141
+ return False, "keyword-only validation exclusions are malformed"
1142
+ try:
1143
+ raw_tables = tables if tables is not None else payload.get("fact_tables")
1144
+ if not _sequence(raw_tables) or any(
1145
+ not isinstance(item, dict) for item in raw_tables
1146
+ ):
1147
+ return False, "keyword-only fact tables are malformed"
1148
+ table_values = tuple(raw_tables)
1149
+ feature_table = next(
1150
+ (
1151
+ item
1152
+ for item in table_values
1153
+ if item.get("table_id") == KEYWORD_ONLY_CALL_TABLE_ID
1154
+ ),
1155
+ None,
1156
+ )
1157
+ if feature_table is None:
1158
+ return (
1159
+ (False, "keyword-only call binding fact table is absent")
1160
+ if require_table
1161
+ else (True, "")
1162
+ )
1163
+ if (
1164
+ feature_table.get("schema_version") != expected_fact_schema
1165
+ or feature_table.get("producer_stage") != "analysis.plan"
1166
+ or feature_table.get("key_domain") != KEYWORD_ONLY_CALL_KEY_DOMAIN
1167
+ or feature_table.get("completeness") != "complete"
1168
+ or tuple(feature_table.get("invalidation_dependencies", ()))
1169
+ != KEYWORD_ONLY_CALL_TABLE_DEPENDENCIES
1170
+ ):
1171
+ return False, "keyword-only call binding fact schema is invalid"
1172
+ table_map: dict[str, dict[str, Any]] = {}
1173
+ for item in table_values:
1174
+ table_id = item.get("table_id")
1175
+ if not isinstance(table_id, str) or table_id in table_map:
1176
+ return False, "keyword-only fact-table identities are malformed"
1177
+ table_map[table_id] = item
1178
+ required = {
1179
+ "binding-facts",
1180
+ "function-signature-facts",
1181
+ "value-category-facts",
1182
+ "call-target-facts",
1183
+ }
1184
+ if not required.issubset(table_map):
1185
+ return False, "keyword-only proof dependencies are absent"
1186
+ module = payload.get("python_ir")
1187
+ node_values = module.get("nodes") if isinstance(module, dict) else None
1188
+ if not isinstance(node_values, list):
1189
+ return False, "keyword-only validation lacks normalized Python IR"
1190
+ nodes: dict[str, dict[str, Any]] = {}
1191
+ node_order: dict[str, int] = {}
1192
+ for ordinal, node in enumerate(node_values):
1193
+ _check(cancellation)
1194
+ node_id = node.get("node_id") if isinstance(node, dict) else None
1195
+ if not isinstance(node_id, str) or node_id in nodes:
1196
+ return False, "keyword-only Python IR identities are invalid"
1197
+ nodes[node_id] = node
1198
+ node_order[node_id] = ordinal
1199
+ occurrence_bindings: dict[str, str] = {}
1200
+ binding_by_declaration: dict[str, str] = {}
1201
+ declaration_by_binding: dict[str, str] = {}
1202
+ for binding in _record_values(table_map["binding-facts"], cancellation):
1203
+ binding_id = binding.get("binding_id")
1204
+ declaration_id = binding.get("declaration_node_id")
1205
+ binding_kind = binding.get("binding_kind")
1206
+ occurrences = binding.get("occurrence_node_ids")
1207
+ if (
1208
+ not isinstance(binding_id, str)
1209
+ or not isinstance(declaration_id, str)
1210
+ or declaration_id not in nodes
1211
+ or binding_id in declaration_by_binding
1212
+ or not _sequence(occurrences)
1213
+ ):
1214
+ raise _MalformedKeywordOnlyEvidence(
1215
+ "keyword-only binding facts are malformed"
1216
+ )
1217
+ declaration_by_binding[binding_id] = declaration_id
1218
+ if binding_kind in {"function", "parameter"}:
1219
+ if declaration_id in binding_by_declaration:
1220
+ raise _MalformedKeywordOnlyEvidence(
1221
+ "keyword-only declaration binding conflicts"
1222
+ )
1223
+ binding_by_declaration[declaration_id] = binding_id
1224
+ for occurrence in occurrences:
1225
+ if not isinstance(occurrence, str):
1226
+ raise _MalformedKeywordOnlyEvidence(
1227
+ "keyword-only binding occurrence is malformed"
1228
+ )
1229
+ prior = occurrence_bindings.get(occurrence)
1230
+ if prior is not None and prior != binding_id:
1231
+ raise _MalformedKeywordOnlyEvidence(
1232
+ "keyword-only occurrence binding conflicts"
1233
+ )
1234
+ occurrence_bindings[occurrence] = binding_id
1235
+ signatures: dict[str, dict[str, Any]] = {}
1236
+ for signature in _record_values(
1237
+ table_map["function-signature-facts"],
1238
+ cancellation,
1239
+ ):
1240
+ binding_id = signature.get("binding_id")
1241
+ if not isinstance(binding_id, str) or binding_id in signatures:
1242
+ raise _MalformedKeywordOnlyEvidence(
1243
+ "keyword-only signatures are malformed"
1244
+ )
1245
+ signatures[binding_id] = signature
1246
+ categories: dict[str, str] = {}
1247
+ records = table_map["value-category-facts"].get("records")
1248
+ if not isinstance(records, list):
1249
+ raise _MalformedKeywordOnlyEvidence(
1250
+ "keyword-only categories are malformed"
1251
+ )
1252
+ for record in records:
1253
+ _check(cancellation)
1254
+ key = record.get("key") if isinstance(record, dict) else None
1255
+ if not isinstance(key, str) or key in categories:
1256
+ raise _MalformedKeywordOnlyEvidence(
1257
+ "keyword-only category record is malformed"
1258
+ )
1259
+ categories[key] = _category(record.get("value"))
1260
+ reconstruction = _IndependentKeywordOnlyReconstruction(
1261
+ node_values=node_values,
1262
+ nodes=nodes,
1263
+ node_order=node_order,
1264
+ occurrence_bindings=occurrence_bindings,
1265
+ binding_by_declaration=binding_by_declaration,
1266
+ declaration_by_binding=declaration_by_binding,
1267
+ signatures=signatures,
1268
+ categories=categories,
1269
+ ignored_call_node_ids=frozenset(ignored_call_node_ids),
1270
+ cancellation=cancellation,
1271
+ )
1272
+ expected = reconstruction.expected()
1273
+ for call_id, fact in tuple(expected.items()):
1274
+ _check(cancellation)
1275
+ if (
1276
+ fact["supported"]
1277
+ and fact["target_function_node_id"]
1278
+ in cumulatively_ineligible_target_function_node_ids
1279
+ ):
1280
+ expected[call_id] = {
1281
+ **fact,
1282
+ "runtime_binding_failure": "compile-time-rejected",
1283
+ "supported": False,
1284
+ "diagnostic_code": (
1285
+ CUMULATIVE_KEYWORD_ONLY_TARGET_DIAGNOSTIC_CODE
1286
+ ),
1287
+ "reason": CUMULATIVE_KEYWORD_ONLY_TARGET_REASON,
1288
+ "rejection_node_id": fact["target_function_node_id"],
1289
+ }
1290
+ records = feature_table.get("records")
1291
+ if not isinstance(records, list):
1292
+ return False, "keyword-only binding records are malformed"
1293
+ keys = [
1294
+ record.get("key") if isinstance(record, dict) else None
1295
+ for record in records
1296
+ ]
1297
+ if (
1298
+ any(not isinstance(key, str) for key in keys)
1299
+ or any(keys[index - 1] >= keys[index] for index in range(1, len(keys)))
1300
+ ):
1301
+ return False, "keyword-only binding keys are not unique and sorted"
1302
+ found: dict[str, dict[str, Any]] = {}
1303
+ provenance: dict[str, Any] = {}
1304
+ for record in records:
1305
+ key = record["key"]
1306
+ value = record.get("value")
1307
+ if not isinstance(value, dict) or value.get("call_node_id") != key:
1308
+ return False, "keyword-only binding record identity is malformed"
1309
+ found[key] = value
1310
+ provenance[key] = record.get("provenance")
1311
+ if set(found) != set(expected):
1312
+ return False, "keyword-only facts do not exactly cover candidates"
1313
+ call_targets: dict[str, dict[str, Any]] = {}
1314
+ for item in _record_values(table_map["call-target-facts"], cancellation):
1315
+ _check(cancellation)
1316
+ call_id = item.get("call_node_id")
1317
+ if not isinstance(call_id, str) or call_id in call_targets:
1318
+ raise _MalformedKeywordOnlyEvidence(
1319
+ "keyword-only call-target identities are malformed"
1320
+ )
1321
+ call_targets[call_id] = item
1322
+ for call_id, fact in expected.items():
1323
+ _check(cancellation)
1324
+ if found[call_id] != fact:
1325
+ return False, (
1326
+ "keyword-only fact disagrees with independent reconstruction"
1327
+ )
1328
+ proof = provenance.get(call_id)
1329
+ if (
1330
+ not isinstance(proof, dict)
1331
+ or proof.get("source_node_ids") != _provenance_ids(fact)
1332
+ or proof.get("evidence")
1333
+ != list(KEYWORD_ONLY_CALL_PROVENANCE_EVIDENCE)
1334
+ ):
1335
+ return False, "keyword-only fact provenance is incomplete"
1336
+ target = call_targets.get(call_id)
1337
+ if target != reconstruction.expected_call_target(fact):
1338
+ return False, (
1339
+ "keyword-only fact disagrees with call-target evidence"
1340
+ )
1341
+ if require_plans:
1342
+ valid, reason = _validate_plans(
1343
+ payload,
1344
+ expected,
1345
+ frozenset(cumulatively_ineligible_target_function_node_ids),
1346
+ cancellation,
1347
+ )
1348
+ if not valid:
1349
+ return valid, reason
1350
+ return True, ""
1351
+ except _MalformedKeywordOnlyEvidence as exc:
1352
+ return False, str(exc) or "keyword-only evidence is malformed"
1353
+ except (AttributeError, IndexError, KeyError, TypeError, ValueError):
1354
+ return False, "keyword-only evidence is malformed"
1355
+
1356
+
1357
+ __all__ = ["validate_keyword_only_call_binding_facts"]