python2rust 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. python2rust/__init__.py +8 -0
  2. python2rust/__main__.py +5 -0
  3. python2rust/_core.py +44 -0
  4. python2rust/agent/__init__.py +0 -0
  5. python2rust/agent/agents.py +333 -0
  6. python2rust/agent/apply.py +516 -0
  7. python2rust/agent/finish.py +295 -0
  8. python2rust/agent/fixers.py +229 -0
  9. python2rust/agent/loop.py +441 -0
  10. python2rust/agent/patches.py +1165 -0
  11. python2rust/agent/port.py +579 -0
  12. python2rust/agent/prompts/judge_v2.md +96 -0
  13. python2rust/agent/review.py +34 -0
  14. python2rust/agent/rustlex.py +232 -0
  15. python2rust/cli/__init__.py +0 -0
  16. python2rust/cli/doctor.py +62 -0
  17. python2rust/cli/inputs.py +105 -0
  18. python2rust/cli/main.py +1162 -0
  19. python2rust/cli/ops.py +642 -0
  20. python2rust/cli/workflow.py +178 -0
  21. python2rust/core/__init__.py +38 -0
  22. python2rust/core/config.py +263 -0
  23. python2rust/core/constructs.py +124 -0
  24. python2rust/core/diagnostics.py +280 -0
  25. python2rust/core/emit/__init__.py +5 -0
  26. python2rust/core/emit/crates.py +51 -0
  27. python2rust/core/emit/render.py +561 -0
  28. python2rust/core/emit/schema.py +168 -0
  29. python2rust/core/emit/translate.py +304 -0
  30. python2rust/core/frontend/__init__.py +1 -0
  31. python2rust/core/frontend/module.py +896 -0
  32. python2rust/core/frontend/names.py +129 -0
  33. python2rust/core/frontend/project.py +277 -0
  34. python2rust/core/frontend/project_imports.py +173 -0
  35. python2rust/core/frontend/symbols.py +132 -0
  36. python2rust/core/frontend/walrus.py +59 -0
  37. python2rust/core/ir/__init__.py +1 -0
  38. python2rust/core/ir/nodes.py +675 -0
  39. python2rust/core/ir/rtypes.py +122 -0
  40. python2rust/core/ir/types.py +326 -0
  41. python2rust/core/lower/__init__.py +1 -0
  42. python2rust/core/lower/calls.py +1125 -0
  43. python2rust/core/lower/context.py +223 -0
  44. python2rust/core/lower/exceptions.py +317 -0
  45. python2rust/core/lower/exprs.py +845 -0
  46. python2rust/core/lower/fstrings.py +141 -0
  47. python2rust/core/lower/funcs.py +276 -0
  48. python2rust/core/lower/lowerer.py +366 -0
  49. python2rust/core/lower/modelcalls.py +195 -0
  50. python2rust/core/lower/models.py +645 -0
  51. python2rust/core/lower/stmts.py +722 -0
  52. python2rust/core/lower/testing.py +601 -0
  53. python2rust/core/lower/validation.py +253 -0
  54. python2rust/core/passes/__init__.py +1 -0
  55. python2rust/core/passes/aliasing.py +311 -0
  56. python2rust/core/passes/analysis.py +207 -0
  57. python2rust/core/passes/devirt.py +329 -0
  58. python2rust/core/passes/ownership.py +259 -0
  59. python2rust/core/passes/raises.py +275 -0
  60. python2rust/core/rt_lib.rs +2071 -0
  61. python2rust/data/README.md +81 -0
  62. python2rust/data/py2many_builtins.toml +4744 -0
  63. python2rust/errors.py +28 -0
  64. python2rust/py.typed +0 -0
  65. python2rust/report/__init__.py +0 -0
  66. python2rust/report/constructs.py +31 -0
  67. python2rust/report/contract.py +688 -0
  68. python2rust/report/corpus.py +323 -0
  69. python2rust/report/explain.py +168 -0
  70. python2rust/report/schemas.py +914 -0
  71. python2rust/server/__init__.py +0 -0
  72. python2rust/server/mcp_server.py +289 -0
  73. python2rust/server/mcp_workflow.py +100 -0
  74. python2rust/skill/SKILL.md +214 -0
  75. python2rust/verify/__init__.py +0 -0
  76. python2rust/verify/check.py +1135 -0
  77. python2rust/verify/equiv/__init__.py +1264 -0
  78. python2rust/verify/equiv/compare.py +455 -0
  79. python2rust/verify/equiv/harness.py +505 -0
  80. python2rust/verify/equiv/judge.py +358 -0
  81. python2rust/verify/equiv/procs.py +255 -0
  82. python2rust/verify/equiv/runner.py +248 -0
  83. python2rust/verify/equiv/types.py +543 -0
  84. python2rust/verify/keystore.py +76 -0
  85. python2rust/verify/ladder.py +396 -0
  86. python2rust/verify/sandbox.py +370 -0
  87. python2rust/verify/testrun.py +280 -0
  88. python2rust/workflow/__init__.py +0 -0
  89. python2rust/workflow/brief.py +312 -0
  90. python2rust/workflow/interview.py +366 -0
  91. python2rust/workflow/layout.py +103 -0
  92. python2rust/workflow/planner.py +409 -0
  93. python2rust/workflow/project.py +134 -0
  94. python2rust/workflow/schemas.py +265 -0
  95. python2rust/workflow/state.py +392 -0
  96. python2rust/workflow/staticscan.py +209 -0
  97. python2rust-0.1.0.dist-info/METADATA +395 -0
  98. python2rust-0.1.0.dist-info/RECORD +102 -0
  99. python2rust-0.1.0.dist-info/WHEEL +4 -0
  100. python2rust-0.1.0.dist-info/entry_points.txt +4 -0
  101. python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
  102. python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
@@ -0,0 +1,688 @@
1
+ """`contract`: diff the OpenAPI document of a Python (FastAPI) app with the Rust port's.
2
+
3
+ The oracle for web-service ports: `app.openapi()` on one side, the document generated by the Rust
4
+ crate (utoipa) on the other. Both are normalised first so that harmless differences between OpenAPI
5
+ 3.0 and 3.1 and between pydantic and utoipa do not show up:
6
+
7
+ * `nullable: true`, `type: [T, "null"]`, `anyOf/oneOf: [T, {type: null}]` and null in an enum all mean
8
+ "nullable T"; `const` is a one-value enum; `exclusiveMinimum: true` (3.0) is the number form (3.1)
9
+ * `$ref`s are followed, so component names do not matter; `allOf: [X]` is X
10
+ * `title`, `description`, `example(s)`, `summary` and tags are cosmetic and ignored
11
+ * FastAPI's default operationId (`<function><path>_<method>`) is reduced to the function name
12
+ * a Python-only 422 `HTTPValidationError` response is ignored unless `strict_422`
13
+
14
+ Every finding has a stable code `PY2RS-C###`, a severity, and a JSON pointer on both sides.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import gzip
20
+ import json
21
+ import re
22
+ import shlex
23
+ import subprocess
24
+ import tomllib
25
+ from collections import Counter
26
+ from dataclasses import dataclass, field
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ from python2rust.cli.ops import envelope
31
+ from python2rust.errors import EXIT_FINDINGS, EXIT_OK, RustSideError, UsageError
32
+
33
+ HTTP_METHODS = ("get", "put", "post", "delete", "options", "head", "patch", "trace")
34
+ CONSTRAINTS = (
35
+ "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength",
36
+ "pattern", "minItems", "maxItems", "multipleOf", "uniqueItems", "minProperties", "maxProperties",
37
+ ) # fmt: skip
38
+
39
+ # code -> (severity, one-line meaning). Append-only, like the diagnostic codes.
40
+ CODES: dict[str, tuple[str, str]] = {
41
+ "PY2RS-C001": ("error", "path exists in Python but not in Rust"),
42
+ "PY2RS-C002": ("warning", "path exists in Rust but not in Python"),
43
+ "PY2RS-C003": ("error", "method exists in Python but not in Rust"),
44
+ "PY2RS-C004": ("warning", "method exists in Rust but not in Python"),
45
+ "PY2RS-C010": ("warning", "operationId differs"),
46
+ "PY2RS-C011": ("warning", "deprecated flag differs"),
47
+ "PY2RS-C020": ("error", "parameter exists in Python but not in Rust"),
48
+ "PY2RS-C021": ("warning", "parameter exists in Rust but not in Python"),
49
+ "PY2RS-C022": ("error", "parameter `required` differs"),
50
+ "PY2RS-C030": ("error", "request body exists in Python but not in Rust"),
51
+ "PY2RS-C031": ("warning", "request body exists in Rust but not in Python"),
52
+ "PY2RS-C032": ("error", "request body `required` differs"),
53
+ "PY2RS-C033": ("error", "content types differ"),
54
+ "PY2RS-C040": ("error", "response status exists in Python but not in Rust"),
55
+ "PY2RS-C041": ("warning", "response status exists in Rust but not in Python"),
56
+ "PY2RS-C100": ("error", "schema type differs"),
57
+ "PY2RS-C101": ("error", "nullability differs"),
58
+ "PY2RS-C102": ("error", "format differs"),
59
+ "PY2RS-C103": ("error", "enum values differ"),
60
+ "PY2RS-C104": ("error", "property exists in Python but not in Rust"),
61
+ "PY2RS-C105": ("warning", "property exists in Rust but not in Python"),
62
+ "PY2RS-C106": ("error", "property `required` differs"),
63
+ "PY2RS-C107": ("error", "constraint differs (min/max/pattern/length/items/...)"),
64
+ "PY2RS-C108": ("warning", "schema default differs"),
65
+ "PY2RS-C109": ("error", "array `items` exist on one side only"),
66
+ "PY2RS-C110": ("warning", "additionalProperties differs"),
67
+ "PY2RS-C111": ("error", "oneOf/anyOf variants differ"),
68
+ }
69
+
70
+ NORMALISATION = [
71
+ "nullable / type arrays / anyOf-with-null / null enum member -> nullable flag",
72
+ "const -> single-value enum; exclusiveMinimum/Maximum booleans -> numbers",
73
+ "$ref followed (component names ignored); allOf with one member unwrapped",
74
+ "title, description, example(s), summary, tags ignored",
75
+ "FastAPI default operationId reduced to the function name",
76
+ "Python-only 422 HTTPValidationError response ignored (unless strict_422)",
77
+ ]
78
+
79
+
80
+ def ptr(*parts: object) -> str:
81
+ return "".join("/" + str(p).replace("~", "~0").replace("/", "~1") for p in parts)
82
+
83
+
84
+ @dataclass
85
+ class Node:
86
+ """A schema node with the JSON pointer it was reached through (after following $refs)."""
87
+
88
+ raw: Any
89
+ at: str
90
+
91
+
92
+ @dataclass
93
+ class View:
94
+ types: frozenset[str] = frozenset()
95
+ nullable: bool = False
96
+ fmt: str | None = None
97
+ enum: tuple[str, ...] | None = None
98
+ props: dict[str, Node] = field(default_factory=dict)
99
+ required: frozenset[str] = frozenset()
100
+ items: Node | None = None
101
+ addl: Any = None # None | bool | Node
102
+ constraints: dict[str, Any] = field(default_factory=dict)
103
+ default: Any = None
104
+ has_default: bool = False
105
+ variants: list[Node] | None = None
106
+ at: str = ""
107
+
108
+
109
+ class Doc:
110
+ def __init__(self, data: dict[str, Any]):
111
+ if not isinstance(data, dict) or "paths" not in data:
112
+ raise UsageError("not an OpenAPI document (no `paths`)")
113
+ self.data = data
114
+
115
+ def resolve(self, node: Node, depth: int = 0) -> Node:
116
+ raw = node.raw
117
+ if not isinstance(raw, dict) or depth > 50:
118
+ return node
119
+ ref = raw.get("$ref")
120
+ if isinstance(ref, str) and ref.startswith("#/"):
121
+ cur: Any = self.data
122
+ for part in ref[2:].split("/"):
123
+ part = part.replace("~1", "/").replace("~0", "~")
124
+ cur = cur.get(part) if isinstance(cur, dict) else None
125
+ if cur is not None:
126
+ return self.resolve(Node(cur, ref[1:]), depth + 1)
127
+ if isinstance(raw.get("allOf"), list) and len(raw["allOf"]) == 1 and len(raw) <= 3:
128
+ member = self.resolve(Node(raw["allOf"][0], node.at + "/allOf/0"), depth + 1)
129
+ siblings = {k: v for k, v in raw.items() if k != "allOf"}
130
+ if siblings and isinstance(member.raw, dict):
131
+ return Node({**member.raw, **siblings}, member.at)
132
+ return member
133
+ return node
134
+
135
+ def view(self, node: Node) -> View:
136
+ node = self.resolve(node)
137
+ raw = node.raw if isinstance(node.raw, dict) else {}
138
+ v = View(at=node.at)
139
+ nullable = bool(raw.get("nullable"))
140
+ for key in ("anyOf", "oneOf"):
141
+ members = raw.get(key)
142
+ if not isinstance(members, list):
143
+ continue
144
+ real = [(i, m) for i, m in enumerate(members) if not _is_null(m)]
145
+ nullable = nullable or len(real) != len(members)
146
+ if len(real) == 1:
147
+ i, m = real[0]
148
+ inner = self.view(Node(m, f"{node.at}/{key}/{i}"))
149
+ inner.nullable = inner.nullable or nullable
150
+ return inner
151
+ v.variants = [Node(m, f"{node.at}/{key}/{i}") for i, m in real]
152
+ if isinstance(raw.get("allOf"), list) and len(raw["allOf"]) > 1:
153
+ for i, m in enumerate(raw["allOf"]): # merge object members
154
+ part = self.view(Node(m, f"{node.at}/allOf/{i}"))
155
+ v.props.update(part.props)
156
+ v.required |= part.required
157
+ v.types |= part.types
158
+ t = raw.get("type")
159
+ types = set(t) if isinstance(t, list) else ({t} if isinstance(t, str) else set())
160
+ if "null" in types and len(types) > 1:
161
+ types.discard("null")
162
+ nullable = True
163
+ v.types |= frozenset(types)
164
+ props = raw.get("properties")
165
+ if isinstance(props, dict):
166
+ v.props.update(
167
+ {k: Node(s, f"{node.at}/properties/{ptr(k)[1:]}") for k, s in props.items()}
168
+ )
169
+ if isinstance(raw.get("required"), list):
170
+ v.required |= frozenset(raw["required"])
171
+ if not v.types:
172
+ v.types = frozenset({"object"} if v.props else {"array"} if "items" in raw else set())
173
+ if "items" in raw:
174
+ v.items = Node(raw["items"], node.at + "/items")
175
+ ap = raw.get("additionalProperties")
176
+ if isinstance(ap, dict):
177
+ v.addl = Node(ap, node.at + "/additionalProperties")
178
+ elif isinstance(ap, bool):
179
+ v.addl = ap
180
+ enum = raw.get("enum")
181
+ if "const" in raw:
182
+ enum = [raw["const"]]
183
+ if isinstance(enum, list):
184
+ if None in enum:
185
+ nullable = True
186
+ v.enum = tuple(sorted(json.dumps(e, sort_keys=True) for e in enum if e is not None))
187
+ v.fmt = raw.get("format")
188
+ for k in CONSTRAINTS:
189
+ if k in raw:
190
+ v.constraints[k] = raw[k]
191
+ for k, bound in (("exclusiveMinimum", "minimum"), ("exclusiveMaximum", "maximum")):
192
+ if v.constraints.get(k) is True and bound in v.constraints:
193
+ v.constraints[k] = v.constraints.pop(bound)
194
+ elif v.constraints.get(k) is False:
195
+ del v.constraints[k]
196
+ if "default" in raw:
197
+ v.has_default, v.default = True, raw["default"]
198
+ v.nullable = nullable
199
+ return v
200
+
201
+
202
+ def _is_null(schema: Any) -> bool:
203
+ return isinstance(schema, dict) and schema.get("type") == "null" and len(schema) <= 2
204
+
205
+
206
+ # --- diffing ------------------------------------------------------------------------------------
207
+
208
+
209
+ @dataclass
210
+ class Ctx:
211
+ py: Doc
212
+ rs: Doc
213
+ findings: list[dict[str, Any]] = field(default_factory=list)
214
+ seen: set[tuple[str, str]] = field(default_factory=set)
215
+ strict_422: bool = False
216
+
217
+ def add(self, code: str, op: str | None, message: str, py: str | None, rs: str | None) -> None:
218
+ sev, _ = CODES[code]
219
+ self.findings.append(
220
+ {
221
+ "code": code,
222
+ "severity": sev,
223
+ "operation": op,
224
+ "message": message,
225
+ "python": py,
226
+ "rust": rs,
227
+ }
228
+ )
229
+
230
+
231
+ def diff_schema(ctx: Ctx, a: Node, b: Node, op: str | None, where: str) -> None:
232
+ va, vb = ctx.py.view(a), ctx.rs.view(b)
233
+ key = (va.at, vb.at)
234
+ if key in ctx.seen: # recursive schemas
235
+ return
236
+ ctx.seen.add(key)
237
+ pa, pb = va.at or a.at, vb.at or b.at
238
+ if va.nullable != vb.nullable:
239
+ ctx.add(
240
+ "PY2RS-C101",
241
+ op,
242
+ f"{where}: nullable is {va.nullable} in Python, {vb.nullable} in Rust",
243
+ pa,
244
+ pb,
245
+ )
246
+ if va.types and vb.types and va.types != vb.types:
247
+ ctx.add(
248
+ "PY2RS-C100",
249
+ op,
250
+ f"{where}: type {sorted(va.types)} in Python, {sorted(vb.types)} in Rust",
251
+ pa,
252
+ pb,
253
+ )
254
+ if va.fmt != vb.fmt:
255
+ ctx.add(
256
+ "PY2RS-C102", op, f"{where}: format {va.fmt!r} in Python, {vb.fmt!r} in Rust", pa, pb
257
+ )
258
+ if va.enum != vb.enum:
259
+ ctx.add("PY2RS-C103", op, f"{where}: enum {va.enum} in Python, {vb.enum} in Rust", pa, pb)
260
+ for k in sorted(set(va.constraints) | set(vb.constraints)):
261
+ if va.constraints.get(k) != vb.constraints.get(k):
262
+ ctx.add(
263
+ "PY2RS-C107", op,
264
+ f"{where}: {k} is {va.constraints.get(k)!r} in Python, {vb.constraints.get(k)!r} in Rust",
265
+ pa, pb,
266
+ ) # fmt: skip
267
+ if (va.has_default or vb.has_default) and (va.default, va.has_default) != (
268
+ vb.default,
269
+ vb.has_default,
270
+ ):
271
+ ctx.add(
272
+ "PY2RS-C108",
273
+ op,
274
+ f"{where}: default {va.default!r} in Python, {vb.default!r} in Rust",
275
+ pa,
276
+ pb,
277
+ )
278
+ for name in sorted(set(va.props) | set(vb.props)):
279
+ here = f"{where}.{name}"
280
+ if name not in vb.props:
281
+ ctx.add("PY2RS-C104", op, f"{here}: property missing in Rust", va.props[name].at, pb)
282
+ elif name not in va.props:
283
+ ctx.add("PY2RS-C105", op, f"{here}: property only in Rust", pa, vb.props[name].at)
284
+ else:
285
+ if (name in va.required) != (name in vb.required):
286
+ ctx.add(
287
+ "PY2RS-C106", op,
288
+ f"{here}: required is {name in va.required} in Python, {name in vb.required} in Rust",
289
+ va.props[name].at, vb.props[name].at,
290
+ ) # fmt: skip
291
+ diff_schema(ctx, va.props[name], vb.props[name], op, here)
292
+ if va.items and vb.items:
293
+ diff_schema(ctx, va.items, vb.items, op, where + "[]")
294
+ elif bool(va.items) != bool(vb.items):
295
+ ctx.add(
296
+ "PY2RS-C109",
297
+ op,
298
+ f"{where}: `items` only on the {'Python' if va.items else 'Rust'} side",
299
+ pa,
300
+ pb,
301
+ )
302
+ _diff_additional(ctx, va, vb, op, where, pa, pb)
303
+ if va.variants is not None or vb.variants is not None:
304
+ _diff_variants(ctx, va, vb, op, where, pa, pb)
305
+
306
+
307
+ def _diff_additional(
308
+ ctx: Ctx, va: View, vb: View, op: str | None, where: str, pa: str, pb: str
309
+ ) -> None:
310
+ if "object" not in (va.types | vb.types):
311
+ return
312
+ x, y = (True if v.addl is None else v.addl for v in (va, vb))
313
+ if isinstance(x, Node) and isinstance(y, Node):
314
+ diff_schema(ctx, x, y, op, where + "{}")
315
+ elif isinstance(x, Node) != isinstance(y, Node) or (isinstance(x, bool) and x != y):
316
+ ctx.add("PY2RS-C110", op, f"{where}: additionalProperties differs", pa, pb)
317
+
318
+
319
+ def _diff_variants(
320
+ ctx: Ctx, va: View, vb: View, op: str | None, where: str, pa: str, pb: str
321
+ ) -> None:
322
+ xs, ys = va.variants or [], vb.variants or []
323
+ free = list(ys)
324
+ for x in xs:
325
+ for y in free:
326
+ probe = Ctx(ctx.py, ctx.rs, seen=set(ctx.seen))
327
+ diff_schema(probe, x, y, op, where)
328
+ if not probe.findings:
329
+ free.remove(y)
330
+ break
331
+ else:
332
+ ctx.add("PY2RS-C111", op, f"{where}: a Python variant has no equal in Rust", x.at, pb)
333
+ for y in free:
334
+ if len(xs) == len(ys) or not xs:
335
+ ctx.add("PY2RS-C111", op, f"{where}: a Rust variant has no equal in Python", pa, y.at)
336
+ if len(xs) != len(ys) and xs and ys:
337
+ ctx.add(
338
+ "PY2RS-C111", op, f"{where}: {len(xs)} variants in Python, {len(ys)} in Rust", pa, pb
339
+ )
340
+
341
+
342
+ def default_operation_id(path: str, method: str) -> str:
343
+ return re.sub(r"\W", "_", path) + "_" + method
344
+
345
+
346
+ def norm_operation_id(op_id: Any, path: str, method: str) -> Any:
347
+ suffix = default_operation_id(path, method)
348
+ if isinstance(op_id, str) and op_id.endswith(suffix) and len(op_id) > len(suffix):
349
+ return op_id[: -len(suffix)]
350
+ return op_id
351
+
352
+
353
+ def _params(
354
+ doc: Doc, op: dict[str, Any], path_item: dict[str, Any], at: str
355
+ ) -> dict[tuple[str, str], tuple[dict[str, Any], str]]:
356
+ out: dict[tuple[str, str], tuple[dict[str, Any], str]] = {}
357
+ for base, params in (
358
+ (at.rsplit("/", 1)[0], path_item.get("parameters", [])),
359
+ (at, op.get("parameters", [])),
360
+ ):
361
+ for i, p in enumerate(params if isinstance(params, list) else []):
362
+ node = doc.resolve(Node(p, f"{base}/parameters/{i}"))
363
+ if isinstance(node.raw, dict) and "name" in node.raw:
364
+ out[(node.raw["name"], node.raw.get("in", ""))] = (node.raw, node.at)
365
+ return out
366
+
367
+
368
+ def diff_operation(
369
+ ctx: Ctx,
370
+ path: str,
371
+ method: str,
372
+ pa_op: dict[str, Any],
373
+ rs_op: dict[str, Any],
374
+ pa_item: dict[str, Any],
375
+ rs_item: dict[str, Any],
376
+ ) -> None:
377
+ label = f"{method.upper()} {path}"
378
+ pa, pb = ptr("paths", path, method), ptr("paths", path, method)
379
+ ia, ib = (
380
+ norm_operation_id(pa_op.get("operationId"), path, method),
381
+ norm_operation_id(rs_op.get("operationId"), path, method),
382
+ )
383
+ if ia != ib:
384
+ ctx.add(
385
+ "PY2RS-C010",
386
+ label,
387
+ f"operationId {pa_op.get('operationId')!r} in Python, {rs_op.get('operationId')!r} in Rust",
388
+ pa + "/operationId",
389
+ pb + "/operationId",
390
+ )
391
+ if bool(pa_op.get("deprecated")) != bool(rs_op.get("deprecated")):
392
+ ctx.add(
393
+ "PY2RS-C011", label, "deprecated flag differs", pa + "/deprecated", pb + "/deprecated"
394
+ )
395
+ # parameters
396
+ xa, xb = _params(ctx.py, pa_op, pa_item, pa), _params(ctx.rs, rs_op, rs_item, pb)
397
+ for key in sorted(set(xa) | set(xb)):
398
+ name = f"parameter {key[0]} ({key[1]})"
399
+ if key not in xb:
400
+ ctx.add("PY2RS-C020", label, f"{name} missing in Rust", xa[key][1], pb)
401
+ elif key not in xa:
402
+ ctx.add("PY2RS-C021", label, f"{name} only in Rust", pa, xb[key][1])
403
+ else:
404
+ (ra, at_a), (rb, at_b) = xa[key], xb[key]
405
+ if bool(ra.get("required")) != bool(rb.get("required")):
406
+ ctx.add(
407
+ "PY2RS-C022",
408
+ label,
409
+ f"{name}: required is {bool(ra.get('required'))} in Python, {bool(rb.get('required'))} in Rust",
410
+ at_a + "/required",
411
+ at_b + "/required",
412
+ )
413
+ diff_schema(
414
+ ctx,
415
+ Node(ra.get("schema", {}), at_a + "/schema"),
416
+ Node(rb.get("schema", {}), at_b + "/schema"),
417
+ label,
418
+ name,
419
+ )
420
+ # request body
421
+ ba, bb = (
422
+ ctx.py.resolve(Node(pa_op.get("requestBody"), pa + "/requestBody")),
423
+ ctx.rs.resolve(Node(rs_op.get("requestBody"), pb + "/requestBody")),
424
+ )
425
+ if pa_op.get("requestBody") and not rs_op.get("requestBody"):
426
+ ctx.add("PY2RS-C030", label, "request body missing in Rust", ba.at, pb)
427
+ elif rs_op.get("requestBody") and not pa_op.get("requestBody"):
428
+ ctx.add("PY2RS-C031", label, "request body only in Rust", pa, bb.at)
429
+ elif pa_op.get("requestBody"):
430
+ if bool(ba.raw.get("required")) != bool(bb.raw.get("required")):
431
+ ctx.add("PY2RS-C032", label, "request body required differs", ba.at, bb.at)
432
+ _diff_content(ctx, label, "request body", ba, bb)
433
+ # responses
434
+ ra, rb = pa_op.get("responses", {}), rs_op.get("responses", {})
435
+ for status in sorted(set(ra) | set(rb)):
436
+ if (
437
+ status == "422"
438
+ and status not in rb
439
+ and not ctx.strict_422
440
+ and _is_validation_error(ctx.py, ra[status])
441
+ ):
442
+ continue
443
+ at_a, at_b = (
444
+ ptr("paths", path, method, "responses", status),
445
+ ptr("paths", path, method, "responses", status),
446
+ )
447
+ if status not in rb:
448
+ ctx.add(
449
+ "PY2RS-C040", label, f"response {status} missing in Rust", at_a, pb + "/responses"
450
+ )
451
+ elif status not in ra:
452
+ ctx.add("PY2RS-C041", label, f"response {status} only in Rust", pa + "/responses", at_b)
453
+ else:
454
+ _diff_content(
455
+ ctx,
456
+ label,
457
+ f"response {status}",
458
+ ctx.py.resolve(Node(ra[status], at_a)),
459
+ ctx.rs.resolve(Node(rb[status], at_b)),
460
+ )
461
+
462
+
463
+ def _is_validation_error(doc: Doc, response: Any) -> bool:
464
+ try:
465
+ schema = response["content"]["application/json"]["schema"]
466
+ except KeyError, TypeError:
467
+ return False
468
+ ref = schema.get("$ref", "") if isinstance(schema, dict) else ""
469
+ return ref.endswith("/HTTPValidationError")
470
+
471
+
472
+ def _diff_content(ctx: Ctx, label: str, where: str, a: Node, b: Node) -> None:
473
+ ca = a.raw.get("content") or {} if isinstance(a.raw, dict) else {}
474
+ cb = b.raw.get("content") or {} if isinstance(b.raw, dict) else {}
475
+ if set(ca) != set(cb):
476
+ ctx.add(
477
+ "PY2RS-C033",
478
+ label,
479
+ f"{where}: content types {sorted(ca)} in Python, {sorted(cb)} in Rust",
480
+ a.at + "/content",
481
+ b.at + "/content",
482
+ )
483
+ for ctype in sorted(set(ca) & set(cb)):
484
+ sa, sb = ca[ctype].get("schema"), cb[ctype].get("schema")
485
+ if sa is not None and sb is not None:
486
+ diff_schema(
487
+ ctx,
488
+ Node(sa, f"{a.at}/content/{ptr(ctype)[1:]}/schema"),
489
+ Node(sb, f"{b.at}/content/{ptr(ctype)[1:]}/schema"),
490
+ label,
491
+ where,
492
+ )
493
+
494
+
495
+ def operations(doc: Doc) -> dict[tuple[str, str], tuple[dict[str, Any], dict[str, Any]]]:
496
+ out = {}
497
+ for path, item in (doc.data.get("paths") or {}).items():
498
+ for method in HTTP_METHODS:
499
+ if isinstance(item, dict) and isinstance(item.get(method), dict):
500
+ out[(path, method)] = (item[method], item)
501
+ return out
502
+
503
+
504
+ def compare(
505
+ py: dict[str, Any],
506
+ rs: dict[str, Any],
507
+ *,
508
+ strict_422: bool = False,
509
+ ignore_operation_id: bool = False,
510
+ ) -> dict[str, Any]:
511
+ """Compare two OpenAPI documents; returns {findings, operations_compared, operations_identical}."""
512
+ ctx = Ctx(Doc(py), Doc(rs), strict_422=strict_422)
513
+ pa, pb = operations(ctx.py), operations(ctx.rs)
514
+ paths_a, paths_b = {p for p, _ in pa}, {p for p, _ in pb}
515
+ for path in sorted(paths_a - paths_b):
516
+ ctx.add("PY2RS-C001", None, f"path {path} missing in Rust", ptr("paths", path), None)
517
+ for path in sorted(paths_b - paths_a):
518
+ ctx.add("PY2RS-C002", None, f"path {path} only in Rust", None, ptr("paths", path))
519
+ both = sorted(paths_a & paths_b)
520
+ compared: set[str] = set()
521
+ for path in both:
522
+ for method in HTTP_METHODS:
523
+ a, b = pa.get((path, method)), pb.get((path, method))
524
+ label = f"{method.upper()} {path}"
525
+ if a and not b:
526
+ ctx.add(
527
+ "PY2RS-C003",
528
+ label,
529
+ f"{label} missing in Rust",
530
+ ptr("paths", path, method),
531
+ ptr("paths", path),
532
+ )
533
+ elif b and not a:
534
+ ctx.add(
535
+ "PY2RS-C004",
536
+ label,
537
+ f"{label} only in Rust",
538
+ ptr("paths", path),
539
+ ptr("paths", path, method),
540
+ )
541
+ elif a and b:
542
+ compared.add(label)
543
+ diff_operation(ctx, path, method, a[0], b[0], a[1], b[1])
544
+ if ignore_operation_id:
545
+ ctx.findings = [f for f in ctx.findings if f["code"] != "PY2RS-C010"]
546
+ bad = {f["operation"] for f in ctx.findings} & compared
547
+ ctx.findings.sort(
548
+ key=lambda f: (
549
+ f["operation"] or "",
550
+ f["code"],
551
+ f["python"] or "",
552
+ f["rust"] or "",
553
+ f["message"],
554
+ )
555
+ )
556
+ return {
557
+ "findings": ctx.findings,
558
+ "operations_compared": len(compared),
559
+ "operations_identical": len(compared) - len(bad),
560
+ }
561
+
562
+
563
+ # --- loading the two sides ----------------------------------------------------------------------
564
+
565
+
566
+ def load_json(path: str) -> dict[str, Any]:
567
+ p = Path(path)
568
+ try:
569
+ raw = gzip.decompress(p.read_bytes()) if p.suffix == ".gz" else p.read_bytes()
570
+ data = json.loads(raw)
571
+ except (OSError, ValueError) as exc:
572
+ raise UsageError(f"cannot read OpenAPI JSON {path}: {exc}") from exc
573
+ return data
574
+
575
+
576
+ def parse_json_output(text: str, what: str) -> dict[str, Any]:
577
+ start = text.find("{")
578
+ try:
579
+ data = json.loads(text[start:] if start >= 0 else text)
580
+ except ValueError as exc:
581
+ raise RustSideError(f"{what} did not print an OpenAPI JSON document: {exc}") from exc
582
+ if not isinstance(data, dict) or "paths" not in data:
583
+ raise RustSideError(f"{what} printed JSON, but not an OpenAPI document (no `paths`)")
584
+ return data
585
+
586
+
587
+ def rust_document(
588
+ source: str, *, command: str | None, bin_name: str | None, timeout: float
589
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
590
+ """The Rust side: a JSON file, or a crate directory (run its --print-openapi hook / `command`)."""
591
+ path = Path(source)
592
+ if path.is_file() and command is None:
593
+ return load_json(source), {"source": "file", "path": source}
594
+ if not path.exists():
595
+ raise UsageError(f"Rust side does not exist: {source}")
596
+ if command is not None:
597
+ argv = shlex.split(command)
598
+ how, cwd = "command", (path if path.is_dir() else None)
599
+ else:
600
+ manifest = path / "Cargo.toml"
601
+ if not manifest.is_file():
602
+ raise UsageError(f"{source} is not a JSON file or a crate (no Cargo.toml)")
603
+ name = bin_name or tomllib.loads(manifest.read_text(encoding="utf-8")).get(
604
+ "package", {}
605
+ ).get("name")
606
+ if not name:
607
+ raise UsageError("cannot tell the binary name; pass --bin NAME or --rust-openapi-cmd")
608
+ argv = ["cargo", "run", "--quiet", "--bin", name, "--", "--print-openapi"]
609
+ how, cwd = "crate", path
610
+ try:
611
+ proc = subprocess.run(argv, capture_output=True, text=True, cwd=cwd, timeout=timeout)
612
+ except FileNotFoundError as exc:
613
+ raise RustSideError(f"cannot run {argv[0]}: {exc}") from exc
614
+ except subprocess.TimeoutExpired:
615
+ raise RustSideError(f"{' '.join(argv)} timed out after {timeout:g}s") from None
616
+ if proc.returncode != 0:
617
+ tail = " ".join(proc.stderr.strip().splitlines()[-6:])
618
+ raise RustSideError(f"`{' '.join(argv)}` exited {proc.returncode}: {tail}")
619
+ return parse_json_output(proc.stdout, " ".join(argv)), {
620
+ "source": how,
621
+ "path": source,
622
+ "command": argv,
623
+ }
624
+
625
+
626
+ def side_info(doc: dict[str, Any], extra: dict[str, Any]) -> dict[str, Any]:
627
+ ops_ = operations(Doc(doc))
628
+ return {
629
+ **extra,
630
+ "openapi": doc.get("openapi"),
631
+ "paths": len(doc.get("paths", {})),
632
+ "operations": len(ops_),
633
+ }
634
+
635
+
636
+ def contract_doc(
637
+ python_path: str, rust_source: str, *, command: str | None = None, bin_name: str | None = None,
638
+ timeout: float = 600, strict_422: bool = False, ignore_operation_id: bool = False,
639
+ ) -> tuple[dict[str, Any], int]: # fmt: skip
640
+ py = load_json(python_path)
641
+ rs, rs_info = rust_document(rust_source, command=command, bin_name=bin_name, timeout=timeout)
642
+ result = compare(py, rs, strict_422=strict_422, ignore_operation_id=ignore_operation_id)
643
+ findings = result["findings"]
644
+ by_code = Counter(f["code"] for f in findings)
645
+ sev = Counter(f["severity"] for f in findings)
646
+ code = EXIT_OK if not findings else EXIT_FINDINGS
647
+ doc = envelope(
648
+ "contract",
649
+ ok=code == EXIT_OK,
650
+ python=side_info(py, {"source": "file", "path": python_path}),
651
+ rust=side_info(rs, rs_info),
652
+ normalisation=NORMALISATION,
653
+ summary={
654
+ "findings": len(findings),
655
+ "errors": sev["error"],
656
+ "warnings": sev["warning"],
657
+ "operations_compared": result["operations_compared"],
658
+ "operations_identical": result["operations_identical"],
659
+ "by_code": dict(sorted(by_code.items())),
660
+ },
661
+ findings=findings,
662
+ )
663
+ doc["markdown"] = contract_markdown(doc)
664
+ return doc, code
665
+
666
+
667
+ def contract_markdown(doc: dict[str, Any]) -> str:
668
+ s = doc["summary"]
669
+ verdict = (
670
+ "identical after normalisation" if not s["findings"] else f"{s['findings']} difference(s)"
671
+ )
672
+ lines = [
673
+ f"# OpenAPI contract: {verdict}",
674
+ "",
675
+ f"Python: {doc['python']['operations']} operations, Rust: {doc['rust']['operations']} operations; "
676
+ f"{s['operations_identical']} of {s['operations_compared']} shared operations identical.",
677
+ ]
678
+ if s["by_code"]:
679
+ lines += ["", "| code | severity | count | meaning |", "|---|---|---:|---|"]
680
+ lines += [f"| {c} | {CODES[c][0]} | {n} | {CODES[c][1]} |" for c, n in s["by_code"].items()]
681
+ lines += ["", "| operation | code | finding |", "|---|---|---|"]
682
+ lines += [
683
+ f"| {f['operation'] or '-'} | {f['code']} | {f['message']} |"
684
+ for f in doc["findings"][:100]
685
+ ]
686
+ if len(doc["findings"]) > 100:
687
+ lines.append(f"| ... | | {len(doc['findings']) - 100} more (see --json) |")
688
+ return "\n".join(lines) + "\n"