1173 lines
43 KiB
Rust
1173 lines
43 KiB
Rust
//! Pass 2 (Python): render the Python interface definition from the same
|
|
//! [`model::MessageModel`]s the Rust serde emitter consumes, so both languages
|
|
//! implement one JSON contract from one schema.
|
|
//!
|
|
//! The output is a single module over `typing` + `msgspec`. Each message maps
|
|
//! to the Python shape its JSON contract implies rather than to a 1:1 mirror
|
|
//! of the proto struct: plain objects and positional tuples are frozen
|
|
//! `msgspec.Struct`s; bare lists are `List[T]`; one-or-many carriers are
|
|
//! `Union[T, List[T]]`; transparent wrappers are `Optional[T]`; untagged
|
|
//! unions are a `Union` of their arms; tagged unions are a `Union` of their
|
|
//! payload Structs plus `Dict[str, Any]` for the passthrough arm. Every
|
|
//! message gets `decode_<Name>` / `encode_<Name>` functions over parsed JSON
|
|
//! values; Structs expose them as `from_json_value` / `to_json_value`.
|
|
//! Contract violations raise `JsonContractError` carrying serde's error texts,
|
|
//! so a 400 body reads the same from either server.
|
|
|
|
use std::collections::{HashMap, HashSet};
|
|
|
|
use crate::model::{
|
|
self, DefaultLit, FieldKind, FieldModel, MessageKind, MessageModel, ScalarTy, VariantModel,
|
|
};
|
|
use prost_reflect::DescriptorPool;
|
|
|
|
const HEADER: &str = "# Generated by sglang-api-codegen from proto/sglang -- DO NOT EDIT.
|
|
# The sglang.json.v1 options in the schema are the JSON contract; edit the
|
|
# .proto files and `cargo gen-api`.
|
|
\"\"\"Generated SGLang API types: the HTTP JSON interface of package {package}.
|
|
|
|
Frozen msgspec Structs for JSON objects and tuples, type aliases for the other
|
|
JSON shapes, and `decode_*` / `encode_*` codecs implementing the sglang.json.v1
|
|
options exactly as the Rust server does. Decode with
|
|
`X.from_json_value(json.loads(s))` and encode with `json.dumps(x.to_json_value())`.
|
|
\"\"\"
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
|
|
import msgspec
|
|
|
|
";
|
|
|
|
const PRELUDE: &str = r#"class JsonContractError(ValueError):
|
|
"""The JSON value violates the schema contract (an HTTP 400 in the server)."""
|
|
|
|
|
|
def _is_number(v: Any) -> bool:
|
|
return isinstance(v, (int, float)) and not isinstance(v, bool)
|
|
|
|
|
|
def _is_int(v: Any) -> bool:
|
|
return isinstance(v, int) and not isinstance(v, bool)
|
|
|
|
|
|
def _unexpected(v: Any) -> str:
|
|
"""serde's `Unexpected` display, so both languages report one text."""
|
|
if v is None:
|
|
return "null"
|
|
if isinstance(v, bool):
|
|
return f"boolean `{'true' if v else 'false'}`"
|
|
if isinstance(v, int):
|
|
return f"integer `{v}`"
|
|
if isinstance(v, float):
|
|
return f"floating point `{v}`"
|
|
if isinstance(v, str):
|
|
return f'string "{v}"'
|
|
if isinstance(v, list):
|
|
return "sequence"
|
|
if isinstance(v, dict):
|
|
return "map"
|
|
return type(v).__name__
|
|
|
|
|
|
def _invalid_type(v: Any, expected: str) -> JsonContractError:
|
|
return JsonContractError(f"invalid type: {_unexpected(v)}, expected {expected}")
|
|
|
|
|
|
def _expect_bool(v: Any, expected: str) -> bool:
|
|
if isinstance(v, bool):
|
|
return v
|
|
raise _invalid_type(v, expected=expected)
|
|
|
|
|
|
def _expect_int(v: Any, expected: str) -> int:
|
|
if _is_int(v):
|
|
return v
|
|
raise _invalid_type(v, expected=expected)
|
|
|
|
|
|
def _expect_uint(v: Any, expected: str) -> int:
|
|
if _is_int(v):
|
|
if v < 0:
|
|
raise JsonContractError(f"invalid value: integer `{v}`, expected {expected}")
|
|
return v
|
|
raise _invalid_type(v, expected=expected)
|
|
|
|
|
|
def _expect_float(v: Any, expected: str) -> float:
|
|
if _is_number(v):
|
|
return float(v)
|
|
raise _invalid_type(v, expected=expected)
|
|
|
|
|
|
def _expect_str(v: Any, expected: str) -> str:
|
|
if isinstance(v, str):
|
|
return v
|
|
raise _invalid_type(v, expected=expected)
|
|
|
|
|
|
def _expect_seq(v: Any, expected: str) -> List[Any]:
|
|
if isinstance(v, list):
|
|
return v
|
|
raise _invalid_type(v, expected=expected)
|
|
|
|
|
|
def _expect_map(v: Any, expected: str) -> Dict[str, Any]:
|
|
if isinstance(v, dict):
|
|
return v
|
|
raise _invalid_type(v, expected=expected)
|
|
|
|
|
|
def _unknown_field(key: str, fields: Tuple[str, ...]) -> JsonContractError:
|
|
"""serde's `unknown_field` text: the DENY policy's 400 body."""
|
|
if not fields:
|
|
return JsonContractError(f"unknown field `{key}`, there are no fields")
|
|
if len(fields) == 1:
|
|
return JsonContractError(f"unknown field `{key}`, expected `{fields[0]}`")
|
|
if len(fields) == 2:
|
|
return JsonContractError(
|
|
f"unknown field `{key}`, expected `{fields[0]}` or `{fields[1]}`"
|
|
)
|
|
listed = ", ".join(f"`{f}`" for f in fields)
|
|
return JsonContractError(f"unknown field `{key}`, expected one of {listed}")
|
|
|
|
|
|
"#;
|
|
|
|
/// The Python runtime shape a message name resolves to, for `isinstance`
|
|
/// dispatch in union codecs and for ordering alias definitions.
|
|
#[derive(Clone, Copy, PartialEq, Debug)]
|
|
enum Shape {
|
|
/// A msgspec Struct class (Struct, Tuple).
|
|
Class,
|
|
/// A `List[...]` alias (BareList).
|
|
List,
|
|
/// Any other alias (Transparent, OneOrMany, unions): no single runtime type.
|
|
Value,
|
|
}
|
|
|
|
struct Ctx<'a> {
|
|
package: &'a str,
|
|
shapes: HashMap<&'a str, Shape>,
|
|
models: HashMap<&'a str, &'a MessageModel>,
|
|
}
|
|
|
|
impl<'a> Ctx<'a> {
|
|
fn new(models: &'a [MessageModel], package: &'a str) -> Self {
|
|
let mut shapes = HashMap::new();
|
|
let mut by_name = HashMap::new();
|
|
for m in models {
|
|
let shape = match &m.kind {
|
|
MessageKind::Struct { .. } | MessageKind::Tuple { .. } => Shape::Class,
|
|
MessageKind::BareList { .. } => Shape::List,
|
|
_ => Shape::Value,
|
|
};
|
|
shapes.insert(m.rust_name.as_str(), shape);
|
|
by_name.insert(m.rust_name.as_str(), m);
|
|
}
|
|
Ctx {
|
|
package,
|
|
shapes,
|
|
models: by_name,
|
|
}
|
|
}
|
|
|
|
fn shape(&self, name: &str) -> Shape {
|
|
*self
|
|
.shapes
|
|
.get(name)
|
|
.unwrap_or_else(|| panic!("unknown message {name}"))
|
|
}
|
|
|
|
fn model(&self, name: &str) -> &MessageModel {
|
|
self.models
|
|
.get(name)
|
|
.unwrap_or_else(|| panic!("unknown message {name}"))
|
|
}
|
|
|
|
fn full_name(&self, name: &str) -> String {
|
|
format!("{}.{name}", self.package)
|
|
}
|
|
}
|
|
|
|
pub fn emit_python(descriptor_bytes: &[u8], package: &str) -> String {
|
|
let pool = DescriptorPool::decode(descriptor_bytes).expect("decode descriptor set");
|
|
let models = model::build_models(&pool, package);
|
|
let ctx = Ctx::new(&models, package);
|
|
|
|
let mut out = String::new();
|
|
out.push_str(&HEADER.replace("{package}", package));
|
|
out.push_str(PRELUDE);
|
|
|
|
out.push_str("# ---- Structs: JSON objects and positional tuples ----\n\n\n");
|
|
for m in &models {
|
|
match &m.kind {
|
|
MessageKind::Struct {
|
|
deny_unknown,
|
|
fields,
|
|
} => emit_struct_class(&mut out, &ctx, m, *deny_unknown, fields),
|
|
MessageKind::Tuple { fields } => emit_tuple_class(&mut out, &ctx, m, fields),
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
out.push_str("# ---- type aliases: JSON shapes without an object of their own ----\n\n");
|
|
emit_aliases(&mut out, &ctx, &models);
|
|
|
|
out.push_str("\n# ---- codecs: parsed JSON value <-> Python value ----\n\n\n");
|
|
for m in &models {
|
|
match &m.kind {
|
|
MessageKind::Skip => {}
|
|
MessageKind::Struct {
|
|
deny_unknown,
|
|
fields,
|
|
} => emit_struct_codec(&mut out, m, *deny_unknown, fields),
|
|
MessageKind::Tuple { fields } => emit_tuple_codec(&mut out, m, fields),
|
|
MessageKind::BareList { item } => emit_bare_list_codec(&mut out, m, item),
|
|
MessageKind::Transparent { field } => emit_transparent_codec(&mut out, m, field),
|
|
MessageKind::OneOrMany { one, many, .. } => {
|
|
emit_one_or_many_codec(&mut out, &ctx, m, one, many)
|
|
}
|
|
MessageKind::Untagged { variants, .. } => {
|
|
emit_untagged_codec(&mut out, &ctx, m, variants)
|
|
}
|
|
MessageKind::TaggedUnion {
|
|
tag,
|
|
variants,
|
|
passthrough,
|
|
..
|
|
} => emit_tagged_codec(&mut out, m, tag, variants, passthrough.as_ref()),
|
|
}
|
|
}
|
|
// One trailing newline: the end-of-file hook must not rewrite the output.
|
|
out.trim_end().to_string() + "\n"
|
|
}
|
|
|
|
// ---- naming and typing -------------------------------------------------
|
|
|
|
/// Python keyword escaping for attribute names (the JSON key is unaffected).
|
|
fn py_ident(name: &str) -> String {
|
|
const KEYWORDS: &[&str] = &[
|
|
"False", "None", "True", "and", "as", "assert", "async", "await", "break", "class",
|
|
"continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global",
|
|
"if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return",
|
|
"try", "while", "with", "yield",
|
|
];
|
|
if KEYWORDS.contains(&name) {
|
|
format!("{name}_")
|
|
} else {
|
|
name.to_string()
|
|
}
|
|
}
|
|
|
|
fn py_scalar(ty: &ScalarTy) -> &'static str {
|
|
match ty {
|
|
ScalarTy::F64 => "float",
|
|
ScalarTy::I32 | ScalarTy::I64 | ScalarTy::U32 | ScalarTy::U64 => "int",
|
|
ScalarTy::Bool => "bool",
|
|
ScalarTy::Str => "str",
|
|
}
|
|
}
|
|
|
|
fn py_lit(d: &DefaultLit) -> String {
|
|
match d {
|
|
DefaultLit::F64(v) => format!("{v:?}"),
|
|
DefaultLit::I64(v) => v.to_string(),
|
|
DefaultLit::Bool(v) => if *v { "True" } else { "False" }.to_string(),
|
|
DefaultLit::Str(v) => format!("{v:?}"),
|
|
}
|
|
}
|
|
|
|
fn type_default(ty: &ScalarTy) -> &'static str {
|
|
match ty {
|
|
ScalarTy::F64 => "0.0",
|
|
ScalarTy::I32 | ScalarTy::I64 | ScalarTy::U32 | ScalarTy::U64 => "0",
|
|
ScalarTy::Bool => "False",
|
|
ScalarTy::Str => "\"\"",
|
|
}
|
|
}
|
|
|
|
/// The element type of a field: what a list holds, what an Optional wraps.
|
|
fn inner_ty(kind: &FieldKind) -> String {
|
|
match kind {
|
|
FieldKind::Scalar { ty, .. }
|
|
| FieldKind::OptScalar { ty, .. }
|
|
| FieldKind::RepeatedScalar { ty } => py_scalar(ty).to_string(),
|
|
FieldKind::Message { rust_path, .. } | FieldKind::RepeatedMessage { rust_path } => {
|
|
rust_path.clone()
|
|
}
|
|
FieldKind::RepeatedRawJson | FieldKind::RawJson { .. } => "Any".to_string(),
|
|
FieldKind::Map { value } => format!("Dict[str, {}]", py_scalar(value)),
|
|
}
|
|
}
|
|
|
|
/// The Struct attribute annotation.
|
|
fn field_ty(kind: &FieldKind) -> String {
|
|
match kind {
|
|
FieldKind::Scalar { .. } => inner_ty(kind),
|
|
FieldKind::OptScalar { .. } | FieldKind::Message { .. } | FieldKind::RawJson { .. } => {
|
|
format!("Optional[{}]", inner_ty(kind))
|
|
}
|
|
FieldKind::RepeatedScalar { .. }
|
|
| FieldKind::RepeatedMessage { .. }
|
|
| FieldKind::RepeatedRawJson => format!("List[{}]", inner_ty(kind)),
|
|
FieldKind::Map { .. } => inner_ty(kind),
|
|
}
|
|
}
|
|
|
|
/// The Struct default: the value an ABSENT JSON key yields.
|
|
fn field_default(kind: &FieldKind) -> String {
|
|
match kind {
|
|
FieldKind::Scalar { ty, null_default } => null_default
|
|
.as_ref()
|
|
.map(py_lit)
|
|
.unwrap_or_else(|| type_default(ty).to_string()),
|
|
FieldKind::OptScalar {
|
|
null_is_none_default,
|
|
null_default,
|
|
..
|
|
} => null_is_none_default
|
|
.as_ref()
|
|
.or(null_default.as_ref())
|
|
.map(py_lit)
|
|
.unwrap_or_else(|| "None".to_string()),
|
|
FieldKind::Message { .. } | FieldKind::RawJson { .. } => "None".to_string(),
|
|
FieldKind::RepeatedScalar { .. }
|
|
| FieldKind::RepeatedMessage { .. }
|
|
| FieldKind::RepeatedRawJson => "[]".to_string(),
|
|
FieldKind::Map { .. } => "{}".to_string(),
|
|
}
|
|
}
|
|
|
|
// ---- scalar codecs -----------------------------------------------------
|
|
|
|
/// `_expect_*(var, "expected")` validating one scalar; `expected` defaults to
|
|
/// serde's own type name for that scalar.
|
|
fn expect_call(ty: &ScalarTy, var: &str, expected: Option<&str>) -> String {
|
|
let (func, default_expected) = match ty {
|
|
ScalarTy::F64 => ("_expect_float", "f64"),
|
|
ScalarTy::I32 => ("_expect_int", "i32"),
|
|
ScalarTy::I64 => ("_expect_int", "i64"),
|
|
ScalarTy::U32 => ("_expect_uint", "u32"),
|
|
ScalarTy::U64 => ("_expect_uint", "u64"),
|
|
ScalarTy::Bool => ("_expect_bool", "a boolean"),
|
|
ScalarTy::Str => ("_expect_str", "a string"),
|
|
};
|
|
format!(
|
|
"{func}({var}, expected={:?})",
|
|
expected.unwrap_or(default_expected)
|
|
)
|
|
}
|
|
|
|
/// Encoding a scalar: identity, except doubles are normalized to float so an
|
|
/// int-valued temperature serializes as `1.0` like the Rust side.
|
|
fn enc_scalar(ty: &ScalarTy, var: &str) -> String {
|
|
match ty {
|
|
ScalarTy::F64 => format!("float({var})"),
|
|
_ => var.to_string(),
|
|
}
|
|
}
|
|
|
|
/// The decode expression for one present key's value `x` (null handling per
|
|
/// the field's presence/default rules; absent keys never reach here).
|
|
fn de_expr(kind: &FieldKind, x: &str) -> String {
|
|
match kind {
|
|
FieldKind::Scalar { ty, null_default } => match null_default {
|
|
// null_resets_default: explicit null is the schema default.
|
|
Some(d) => format!(
|
|
"{} if {x} is None else {}",
|
|
py_lit(d),
|
|
expect_call(ty, x, None)
|
|
),
|
|
None => expect_call(ty, x, None),
|
|
},
|
|
FieldKind::OptScalar {
|
|
ty, null_default, ..
|
|
} => match null_default {
|
|
Some(d) => format!(
|
|
"{} if {x} is None else {}",
|
|
py_lit(d),
|
|
expect_call(ty, x, None)
|
|
),
|
|
None => format!("None if {x} is None else {}", expect_call(ty, x, None)),
|
|
},
|
|
FieldKind::Message { rust_path, .. } => {
|
|
format!("None if {x} is None else decode_{rust_path}({x})")
|
|
}
|
|
FieldKind::RepeatedScalar { ty } => format!(
|
|
"[] if {x} is None else [{} for e in _expect_seq({x}, expected=\"a sequence\")]",
|
|
expect_call(ty, "e", None)
|
|
),
|
|
FieldKind::RepeatedMessage { rust_path } => format!(
|
|
"[] if {x} is None else [decode_{rust_path}(e) for e in _expect_seq({x}, expected=\"a sequence\")]"
|
|
),
|
|
FieldKind::RepeatedRawJson => {
|
|
format!("[] if {x} is None else list(_expect_seq({x}, expected=\"a sequence\"))")
|
|
}
|
|
FieldKind::Map { value } => format!(
|
|
"{{}} if {x} is None else {{k: {} for k, e in _expect_map({x}, expected=\"a map\").items()}}",
|
|
expect_call(value, "e", None)
|
|
),
|
|
// raw_json: the value passes through verbatim.
|
|
FieldKind::RawJson { .. } => x.to_string(),
|
|
}
|
|
}
|
|
|
|
/// The encode expression for a non-None value `x` of this field.
|
|
fn enc_expr(kind: &FieldKind, x: &str) -> String {
|
|
match kind {
|
|
FieldKind::Scalar { ty, .. } | FieldKind::OptScalar { ty, .. } => enc_scalar(ty, x),
|
|
FieldKind::Message { rust_path, .. } => format!("encode_{rust_path}({x})"),
|
|
FieldKind::RepeatedScalar { ty } => match ty {
|
|
ScalarTy::F64 => format!("[float(e) for e in {x}]"),
|
|
_ => format!("list({x})"),
|
|
},
|
|
FieldKind::RepeatedMessage { rust_path } => {
|
|
format!("[encode_{rust_path}(e) for e in {x}]")
|
|
}
|
|
FieldKind::RepeatedRawJson => format!("list({x})"),
|
|
FieldKind::Map { value } => match value {
|
|
ScalarTy::F64 => format!("{{k: float(e) for k, e in {x}.items()}}"),
|
|
_ => format!("dict({x})"),
|
|
},
|
|
FieldKind::RawJson { .. } => x.to_string(),
|
|
}
|
|
}
|
|
|
|
/// Statements storing one field into the dict `d`, honoring its presence and
|
|
/// null rules. `always_emit_null` = tagged-union payload semantics.
|
|
fn ser_stmts(f: &FieldModel, receiver: &str, always_emit_null: bool, indent: &str) -> String {
|
|
let key = &f.json_name;
|
|
let get = format!("{receiver}{}", py_ident(&f.json_name));
|
|
let enc = enc_expr(&f.kind, &get);
|
|
let nullable = |emit_null: bool| -> String {
|
|
if emit_null || always_emit_null {
|
|
if enc == get {
|
|
format!("{indent}d[{key:?}] = {get}\n")
|
|
} else {
|
|
format!("{indent}d[{key:?}] = None if {get} is None else {enc}\n")
|
|
}
|
|
} else {
|
|
format!("{indent}if {get} is not None:\n{indent} d[{key:?}] = {enc}\n")
|
|
}
|
|
};
|
|
match &f.kind {
|
|
FieldKind::Scalar { .. } => format!("{indent}d[{key:?}] = {enc}\n"),
|
|
// null_is_none: None means "explicit null", distinct from absent
|
|
// (the default), so it must encode as null to round-trip.
|
|
FieldKind::OptScalar {
|
|
emit_null,
|
|
null_is_none_default,
|
|
..
|
|
} => nullable(*emit_null || null_is_none_default.is_some()),
|
|
FieldKind::Message { emit_null, .. } | FieldKind::RawJson { emit_null } => {
|
|
nullable(*emit_null)
|
|
}
|
|
FieldKind::RepeatedScalar { .. }
|
|
| FieldKind::RepeatedMessage { .. }
|
|
| FieldKind::RepeatedRawJson
|
|
| FieldKind::Map { .. } => {
|
|
format!("{indent}if {get}:\n{indent} d[{key:?}] = {enc}\n")
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---- Structs ---------------------------------------------------------
|
|
|
|
fn emit_methods(out: &mut String, name: &str, ret: &str) {
|
|
out.push_str(&format!(
|
|
r#" @classmethod
|
|
def from_json_value(cls, value: Any) -> "{name}":
|
|
"""Decode a parsed JSON value; raises JsonContractError on a contract violation."""
|
|
return decode_{name}(value)
|
|
|
|
def to_json_value(self) -> {ret}:
|
|
"""Encode to a JSON-ready value (json.dumps-compatible)."""
|
|
return encode_{name}(self)
|
|
|
|
|
|
"#
|
|
));
|
|
}
|
|
|
|
fn emit_struct_class(
|
|
out: &mut String,
|
|
ctx: &Ctx,
|
|
m: &MessageModel,
|
|
deny_unknown: bool,
|
|
fields: &[FieldModel],
|
|
) {
|
|
let name = &m.rust_name;
|
|
let policy = if deny_unknown { "rejected" } else { "ignored" };
|
|
out.push_str(&format!(
|
|
"class {name}(msgspec.Struct, kw_only=True, frozen=True):\n \"\"\"{}: JSON object (unknown keys {policy}).\"\"\"\n\n",
|
|
ctx.full_name(name)
|
|
));
|
|
for f in fields {
|
|
out.push_str(&format!(
|
|
" {}: {} = {}\n",
|
|
py_ident(&f.json_name),
|
|
field_ty(&f.kind),
|
|
field_default(&f.kind)
|
|
));
|
|
}
|
|
if !fields.is_empty() {
|
|
out.push('\n');
|
|
}
|
|
emit_methods(out, name, "Dict[str, Any]");
|
|
}
|
|
|
|
fn emit_tuple_class(out: &mut String, ctx: &Ctx, m: &MessageModel, fields: &[FieldModel]) {
|
|
let name = &m.rust_name;
|
|
let members: Vec<&str> = fields.iter().map(|f| f.json_name.as_str()).collect();
|
|
out.push_str(&format!(
|
|
"class {name}(msgspec.Struct, kw_only=True, frozen=True):\n \"\"\"{}: JSON positional array [{}].\"\"\"\n\n",
|
|
ctx.full_name(name),
|
|
members.join(", ")
|
|
));
|
|
for f in fields {
|
|
out.push_str(&format!(
|
|
" {}: {} = {}\n",
|
|
py_ident(&f.json_name),
|
|
field_ty(&f.kind),
|
|
field_default(&f.kind)
|
|
));
|
|
}
|
|
if !fields.is_empty() {
|
|
out.push('\n');
|
|
}
|
|
emit_methods(out, name, "List[Any]");
|
|
}
|
|
|
|
// ---- aliases -----------------------------------------------------------
|
|
|
|
/// The alias definition (Python type expression, JSON note, referenced
|
|
/// message names) for a non-Struct message.
|
|
fn alias_def(m: &MessageModel) -> Option<(String, &'static str, Vec<String>)> {
|
|
let refs = |kinds: &[&FieldKind]| -> Vec<String> {
|
|
kinds
|
|
.iter()
|
|
.filter_map(|k| match k {
|
|
FieldKind::Message { rust_path, .. } | FieldKind::RepeatedMessage { rust_path } => {
|
|
Some(rust_path.clone())
|
|
}
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
};
|
|
match &m.kind {
|
|
MessageKind::BareList { item } => Some((
|
|
format!("List[{}]", inner_ty(&item.kind)),
|
|
"JSON bare array",
|
|
refs(&[&item.kind]),
|
|
)),
|
|
MessageKind::Transparent { field } => Some((
|
|
format!("Optional[{}]", inner_ty(&field.kind)),
|
|
"JSON: the wrapped value itself, null when unset",
|
|
refs(&[&field.kind]),
|
|
)),
|
|
MessageKind::OneOrMany { one, many, .. } => Some((
|
|
format!("Union[{}, {}]", inner_ty(&one.kind), inner_ty(&many.kind)),
|
|
"JSON: one value or an array of values",
|
|
refs(&[&one.kind, &many.kind]),
|
|
)),
|
|
MessageKind::Untagged { variants, .. } => {
|
|
let arms: Vec<String> = variants.iter().map(|v| inner_ty(&v.kind)).collect();
|
|
let kinds: Vec<&FieldKind> = variants.iter().map(|v| &v.kind).collect();
|
|
Some((
|
|
format!("Union[{}]", arms.join(", ")),
|
|
"JSON: the value's shape picks the arm",
|
|
refs(&kinds),
|
|
))
|
|
}
|
|
MessageKind::TaggedUnion {
|
|
variants,
|
|
passthrough,
|
|
..
|
|
} => {
|
|
let mut arms: Vec<String> = variants.iter().map(|v| inner_ty(&v.kind)).collect();
|
|
let note = if passthrough.is_some() {
|
|
arms.push("Dict[str, Any]".to_string());
|
|
"JSON object tagged by its type key; unknown tags pass through as a dict"
|
|
} else {
|
|
"JSON object tagged by its type key"
|
|
};
|
|
let kinds: Vec<&FieldKind> = variants.iter().map(|v| &v.kind).collect();
|
|
Some((format!("Union[{}]", arms.join(", ")), note, refs(&kinds)))
|
|
}
|
|
MessageKind::Struct { .. } | MessageKind::Tuple { .. } | MessageKind::Skip => None,
|
|
}
|
|
}
|
|
|
|
/// Aliases are evaluated at import time, so each is emitted after the aliases
|
|
/// it references (Struct classes are already defined above them).
|
|
fn emit_aliases(out: &mut String, ctx: &Ctx, models: &[MessageModel]) {
|
|
let mut pending: Vec<&MessageModel> =
|
|
models.iter().filter(|m| alias_def(m).is_some()).collect();
|
|
let mut done: HashSet<String> = HashSet::new();
|
|
while !pending.is_empty() {
|
|
let before = pending.len();
|
|
let mut i = 0;
|
|
while i < pending.len() {
|
|
let m = pending[i];
|
|
let (ty, note, refs) = alias_def(m).expect("alias");
|
|
let ready = refs
|
|
.iter()
|
|
.all(|r| ctx.shape(r) == Shape::Class || done.contains(r));
|
|
if ready {
|
|
out.push_str(&format!(
|
|
"# {}: {note}.\n{} = {ty}\n\n",
|
|
ctx.full_name(&m.rust_name),
|
|
m.rust_name
|
|
));
|
|
done.insert(m.rust_name.clone());
|
|
pending.remove(i);
|
|
} else {
|
|
i += 1;
|
|
}
|
|
}
|
|
assert!(
|
|
pending.len() < before,
|
|
"type alias cycle among {:?}",
|
|
pending.iter().map(|m| &m.rust_name).collect::<Vec<_>>()
|
|
);
|
|
}
|
|
}
|
|
|
|
// ---- codecs ------------------------------------------------------------
|
|
|
|
fn emit_struct_codec(
|
|
out: &mut String,
|
|
m: &MessageModel,
|
|
deny_unknown: bool,
|
|
fields: &[FieldModel],
|
|
) {
|
|
let name = &m.rust_name;
|
|
if deny_unknown {
|
|
let names: Vec<String> = fields
|
|
.iter()
|
|
.map(|f| format!("{:?},", f.json_name))
|
|
.collect();
|
|
out.push_str(&format!("_FIELDS_{name} = ({})\n\n\n", names.join(" ")));
|
|
}
|
|
|
|
out.push_str(&format!(
|
|
"def decode_{name}(value: Any) -> {name}:\n m = _expect_map(value, expected=\"struct {name}\")\n"
|
|
));
|
|
if fields.is_empty() {
|
|
if deny_unknown {
|
|
out.push_str(" for key in m:\n raise _unknown_field(key, fields=())\n");
|
|
}
|
|
out.push_str(&format!(" return {name}()\n\n\n"));
|
|
} else {
|
|
out.push_str(" kw: Dict[str, Any] = {}\n for key, x in m.items():\n");
|
|
for (i, f) in fields.iter().enumerate() {
|
|
let kw = if i == 0 { "if" } else { "elif" };
|
|
out.push_str(&format!(
|
|
" {kw} key == {:?}:\n kw[{:?}] = {}\n",
|
|
f.json_name,
|
|
py_ident(&f.json_name),
|
|
de_expr(&f.kind, "x")
|
|
));
|
|
}
|
|
if deny_unknown {
|
|
out.push_str(&format!(
|
|
" else:\n raise _unknown_field(key, fields=_FIELDS_{name})\n"
|
|
));
|
|
}
|
|
out.push_str(&format!(" return {name}(**kw)\n\n\n"));
|
|
}
|
|
|
|
out.push_str(&format!(
|
|
"def encode_{name}(v: {name}) -> Dict[str, Any]:\n d: Dict[str, Any] = {{}}\n"
|
|
));
|
|
for f in fields {
|
|
out.push_str(&ser_stmts(f, "v.", false, " "));
|
|
}
|
|
out.push_str(" return d\n\n\n");
|
|
}
|
|
|
|
fn emit_tuple_codec(out: &mut String, m: &MessageModel, fields: &[FieldModel]) {
|
|
let name = &m.rust_name;
|
|
let len = fields.len();
|
|
let expected = format!("a {len}-element tuple");
|
|
out.push_str(&format!(
|
|
"def decode_{name}(value: Any) -> {name}:\n s = _expect_seq(value, expected={expected:?})\n if len(s) != {len}:\n raise JsonContractError(f\"invalid length {{len(s)}}, expected {expected}\")\n return {name}(\n"
|
|
));
|
|
for (i, f) in fields.iter().enumerate() {
|
|
let x = format!("s[{i}]");
|
|
let expr = match &f.kind {
|
|
FieldKind::Scalar { .. } | FieldKind::OptScalar { .. } => de_expr(&f.kind, &x),
|
|
other => panic!("{name}: tuple member kind {other:?} unsupported"),
|
|
};
|
|
out.push_str(&format!(" {}={expr},\n", py_ident(&f.json_name)));
|
|
}
|
|
out.push_str(" )\n\n\n");
|
|
|
|
out.push_str(&format!(
|
|
"def encode_{name}(v: {name}) -> List[Any]:\n return [\n"
|
|
));
|
|
for f in fields {
|
|
let get = format!("v.{}", py_ident(&f.json_name));
|
|
let expr = match &f.kind {
|
|
FieldKind::Scalar { .. } => enc_expr(&f.kind, &get),
|
|
FieldKind::OptScalar { .. } => {
|
|
let enc = enc_expr(&f.kind, &get);
|
|
if enc == get {
|
|
get
|
|
} else {
|
|
format!("None if {get} is None else {enc}")
|
|
}
|
|
}
|
|
other => panic!("{name}: tuple member kind {other:?} unsupported"),
|
|
};
|
|
out.push_str(&format!(" {expr},\n"));
|
|
}
|
|
out.push_str(" ]\n\n\n");
|
|
}
|
|
|
|
fn emit_bare_list_codec(out: &mut String, m: &MessageModel, item: &FieldModel) {
|
|
let name = &m.rust_name;
|
|
let elem = match &item.kind {
|
|
FieldKind::RepeatedScalar { ty } => expect_call(ty, "e", None),
|
|
FieldKind::RepeatedMessage { rust_path } => format!("decode_{rust_path}(e)"),
|
|
other => panic!("{name}: bare_list item must be repeated, got {other:?}"),
|
|
};
|
|
out.push_str(&format!(
|
|
"def decode_{name}(value: Any) -> {name}:\n return [{elem} for e in _expect_seq(value, expected=\"a sequence\")]\n\n\n"
|
|
));
|
|
out.push_str(&format!(
|
|
"def encode_{name}(v: {name}) -> List[Any]:\n return {}\n\n\n",
|
|
enc_expr(&item.kind, "v")
|
|
));
|
|
}
|
|
|
|
fn emit_transparent_codec(out: &mut String, m: &MessageModel, field: &FieldModel) {
|
|
let name = &m.rust_name;
|
|
let (de, en) = match &field.kind {
|
|
FieldKind::OptScalar { ty, .. } => (expect_call(ty, "value", None), enc_scalar(ty, "v")),
|
|
FieldKind::Message { rust_path, .. } => (
|
|
format!("decode_{rust_path}(value)"),
|
|
format!("encode_{rust_path}(v)"),
|
|
),
|
|
other => panic!(
|
|
"{name}: transparent field must be an optional scalar or a message, got {other:?}"
|
|
),
|
|
};
|
|
out.push_str(&format!(
|
|
"def decode_{name}(value: Any) -> {name}:\n return None if value is None else {de}\n\n\n"
|
|
));
|
|
out.push_str(&format!(
|
|
"def encode_{name}(v: {name}) -> Any:\n return None if v is None else {en}\n\n\n"
|
|
));
|
|
}
|
|
|
|
/// How the `one` arm of a one-or-many carrier is recognized and decoded.
|
|
enum OneArm {
|
|
Scalar(ScalarTy),
|
|
/// The `one` is itself a bare list of scalars (TokenIds, StringList): the
|
|
/// outer array is ambiguous, so dispatch on the first element's shape.
|
|
ListOfScalar(String, ScalarTy),
|
|
Class(String),
|
|
}
|
|
|
|
/// The Python test recognizing one element of a bare scalar list.
|
|
fn first_elem_check(ty: &ScalarTy) -> &'static str {
|
|
match ty {
|
|
ScalarTy::Str => "isinstance(value[0], str)",
|
|
ScalarTy::Bool => "isinstance(value[0], bool)",
|
|
_ => "_is_number(value[0])",
|
|
}
|
|
}
|
|
|
|
fn one_arm(ctx: &Ctx, name: &str, one: &VariantModel) -> OneArm {
|
|
match &one.kind {
|
|
FieldKind::Scalar { ty, .. } | FieldKind::OptScalar { ty, .. } => {
|
|
OneArm::Scalar(ty.clone())
|
|
}
|
|
FieldKind::Message { rust_path, .. } => match &ctx.model(rust_path).kind {
|
|
// A presence wrapper's JSON is its bare scalar.
|
|
MessageKind::Transparent {
|
|
field:
|
|
FieldModel {
|
|
kind: FieldKind::OptScalar { ty, .. },
|
|
..
|
|
},
|
|
} => OneArm::Scalar(ty.clone()),
|
|
MessageKind::BareList {
|
|
item:
|
|
FieldModel {
|
|
kind: FieldKind::RepeatedScalar { ty },
|
|
..
|
|
},
|
|
} => OneArm::ListOfScalar(rust_path.clone(), ty.clone()),
|
|
MessageKind::Struct { .. } => OneArm::Class(rust_path.clone()),
|
|
other => panic!("{name}: unsupported one arm {rust_path} ({other:?})"),
|
|
},
|
|
other => panic!("{name}: unsupported one arm {other:?}"),
|
|
}
|
|
}
|
|
|
|
fn emit_one_or_many_codec(
|
|
out: &mut String,
|
|
ctx: &Ctx,
|
|
m: &MessageModel,
|
|
one: &VariantModel,
|
|
many: &VariantModel,
|
|
) {
|
|
let name = &m.rust_name;
|
|
let many_p = match &many.kind {
|
|
FieldKind::Message { rust_path, .. } => rust_path.clone(),
|
|
other => panic!("{name}: many arm must be a list message, got {other:?}"),
|
|
};
|
|
let expected = format!("a value or an array of values for {name}");
|
|
let (de_body, en_body) = match one_arm(ctx, name, one) {
|
|
OneArm::ListOfScalar(one_p, ty) => (
|
|
format!(
|
|
" if isinstance(value, list):\n # [] and [scalar, ...] are one flat list; anything else is a batch.\n if not value or {check}:\n return decode_{one_p}(value)\n return decode_{many_p}(value)\n raise _invalid_type(value, expected={expected:?})\n",
|
|
check = first_elem_check(&ty)
|
|
),
|
|
format!(
|
|
" if v and isinstance(v[0], list):\n return encode_{many_p}(v)\n return encode_{one_p}(v)\n"
|
|
),
|
|
),
|
|
OneArm::Scalar(ty) => (
|
|
format!(
|
|
" if isinstance(value, list):\n return decode_{many_p}(value)\n return {}\n",
|
|
expect_call(&ty, "value", Some(&expected))
|
|
),
|
|
format!(
|
|
" if isinstance(v, list):\n return encode_{many_p}(v)\n return {}\n",
|
|
enc_scalar(&ty, "v")
|
|
),
|
|
),
|
|
OneArm::Class(one_p) => (
|
|
format!(
|
|
" if isinstance(value, list):\n return decode_{many_p}(value)\n return decode_{one_p}(_expect_map(value, expected={expected:?}))\n"
|
|
),
|
|
format!(
|
|
" if isinstance(v, list):\n return encode_{many_p}(v)\n return encode_{one_p}(v)\n"
|
|
),
|
|
),
|
|
};
|
|
out.push_str(&format!(
|
|
"def decode_{name}(value: Any) -> {name}:\n{de_body}\n\ndef encode_{name}(v: {name}) -> Any:\n{en_body}\n\n"
|
|
));
|
|
}
|
|
|
|
/// The Python runtime shapes a field or message's JSON can take.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
enum PyShape {
|
|
Str,
|
|
Int,
|
|
Float,
|
|
Bool,
|
|
Dict,
|
|
List,
|
|
NoneT,
|
|
}
|
|
|
|
fn py_scalar_shapes(ty: &ScalarTy) -> Vec<PyShape> {
|
|
match ty {
|
|
ScalarTy::Str => vec![PyShape::Str],
|
|
ScalarTy::I32 | ScalarTy::I64 | ScalarTy::U32 | ScalarTy::U64 => vec![PyShape::Int],
|
|
ScalarTy::F64 => vec![PyShape::Int, PyShape::Float],
|
|
ScalarTy::Bool => vec![PyShape::Bool],
|
|
}
|
|
}
|
|
|
|
/// `(JSON shapes, runtime class names)` of a kind: the shapes drive the decode
|
|
/// dispatch, the classes the encode dispatch (a decoded dict is a Struct).
|
|
fn py_shapes(ctx: &Ctx, kind: &FieldKind) -> (Vec<PyShape>, Vec<String>) {
|
|
match kind {
|
|
FieldKind::Scalar { ty, .. } | FieldKind::OptScalar { ty, .. } => {
|
|
(py_scalar_shapes(ty), vec![])
|
|
}
|
|
FieldKind::Message { rust_path, .. } => py_message_shapes(ctx, rust_path),
|
|
FieldKind::RepeatedScalar { .. }
|
|
| FieldKind::RepeatedMessage { .. }
|
|
| FieldKind::RepeatedRawJson => (vec![PyShape::List], vec![]),
|
|
FieldKind::Map { .. } => (vec![PyShape::Dict], vec![]),
|
|
FieldKind::RawJson { .. } => panic!("raw_json has no fixed shape"),
|
|
}
|
|
}
|
|
|
|
fn py_message_shapes(ctx: &Ctx, name: &str) -> (Vec<PyShape>, Vec<String>) {
|
|
let mut shapes: Vec<PyShape> = Vec::new();
|
|
let mut classes: Vec<String> = Vec::new();
|
|
let mut add = |(s, c): (Vec<PyShape>, Vec<String>)| {
|
|
for x in s {
|
|
if !shapes.contains(&x) {
|
|
shapes.push(x);
|
|
}
|
|
}
|
|
for x in c {
|
|
if !classes.contains(&x) {
|
|
classes.push(x);
|
|
}
|
|
}
|
|
};
|
|
match &ctx.model(name).kind {
|
|
MessageKind::Struct { .. } | MessageKind::TaggedUnion { .. } => {
|
|
add((vec![PyShape::Dict], vec![name.to_string()]))
|
|
}
|
|
MessageKind::Tuple { .. } | MessageKind::BareList { .. } => {
|
|
add((vec![PyShape::List], vec![]))
|
|
}
|
|
MessageKind::Transparent { field } => {
|
|
add(py_shapes(ctx, &field.kind));
|
|
add((vec![PyShape::NoneT], vec![]));
|
|
}
|
|
MessageKind::Untagged { variants, .. } => {
|
|
for v in variants {
|
|
add(py_shapes(ctx, &v.kind));
|
|
}
|
|
}
|
|
MessageKind::OneOrMany { one, .. } => {
|
|
add(py_shapes(ctx, &one.kind));
|
|
add((vec![PyShape::List], vec![]));
|
|
}
|
|
MessageKind::Skip => panic!("{name}: a gRPC-only message has no JSON shape"),
|
|
}
|
|
(shapes, classes)
|
|
}
|
|
|
|
/// Whether a bare-list message's elements are themselves arrays.
|
|
fn py_elements_are_lists(ctx: &Ctx, name: &str) -> bool {
|
|
match &ctx.model(name).kind {
|
|
MessageKind::BareList { item } => match &item.kind {
|
|
FieldKind::RepeatedMessage { rust_path } => {
|
|
py_message_shapes(ctx, rust_path).0.contains(&PyShape::List)
|
|
}
|
|
_ => false,
|
|
},
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
fn emit_untagged_codec(out: &mut String, ctx: &Ctx, m: &MessageModel, variants: &[VariantModel]) {
|
|
let name = &m.rust_name;
|
|
let mut de = format!("def decode_{name}(value: Any) -> {name}:\n");
|
|
let mut en = format!("def encode_{name}(v: {name}) -> Any:\n");
|
|
|
|
struct Arm<'a> {
|
|
v: &'a VariantModel,
|
|
shapes: Vec<PyShape>,
|
|
classes: Vec<String>,
|
|
}
|
|
let arms: Vec<Arm> = variants
|
|
.iter()
|
|
.map(|v| {
|
|
let (shapes, classes) = py_shapes(ctx, &v.kind);
|
|
Arm { v, shapes, classes }
|
|
})
|
|
.collect();
|
|
let decode_expr = |a: &Arm| match &a.v.kind {
|
|
FieldKind::Scalar { .. } | FieldKind::OptScalar { .. } => "value".to_string(),
|
|
FieldKind::Message { rust_path, .. } => format!("decode_{rust_path}(value)"),
|
|
other => panic!("{name}: untagged variant kind {other:?} unsupported"),
|
|
};
|
|
let encode_expr = |a: &Arm| match &a.v.kind {
|
|
FieldKind::Scalar { .. } | FieldKind::OptScalar { .. } => "v".to_string(),
|
|
FieldKind::Message { rust_path, .. } => format!("encode_{rust_path}(v)"),
|
|
_ => unreachable!(),
|
|
};
|
|
// Two list-shaped arms: the one whose elements are lists is the nested
|
|
// form, told apart by the first element (`[]` is the flat form).
|
|
let list_arms: Vec<&Arm> = arms
|
|
.iter()
|
|
.filter(|a| a.shapes.contains(&PyShape::List))
|
|
.collect();
|
|
let nested_arm: Option<String> = match list_arms.len() {
|
|
0 | 1 => None,
|
|
2 => {
|
|
let is_nested = |a: &Arm| match &a.v.kind {
|
|
FieldKind::Message { rust_path, .. } => py_elements_are_lists(ctx, rust_path),
|
|
_ => false,
|
|
};
|
|
match (is_nested(list_arms[0]), is_nested(list_arms[1])) {
|
|
(true, false) => Some(list_arms[0].v.json_name.clone()),
|
|
(false, true) => Some(list_arms[1].v.json_name.clone()),
|
|
_ => panic!("{name}: two list-shaped arms cannot be told apart"),
|
|
}
|
|
}
|
|
_ => panic!("{name}: more than two list-shaped untagged arms"),
|
|
};
|
|
|
|
// Decode: one test per shape, bool before int (a Python bool is an int).
|
|
for shape in [
|
|
PyShape::NoneT,
|
|
PyShape::Bool,
|
|
PyShape::Str,
|
|
PyShape::Int,
|
|
PyShape::Float,
|
|
PyShape::Dict,
|
|
PyShape::List,
|
|
] {
|
|
let claimants: Vec<&Arm> = arms.iter().filter(|a| a.shapes.contains(&shape)).collect();
|
|
if claimants.is_empty() {
|
|
continue;
|
|
}
|
|
if shape != PyShape::List && claimants.len() > 1 {
|
|
panic!(
|
|
"{name}: untagged arms {:?} all accept a JSON {shape:?}",
|
|
claimants.iter().map(|a| &a.v.json_name).collect::<Vec<_>>()
|
|
);
|
|
}
|
|
if shape == PyShape::List && claimants.len() == 2 {
|
|
let nested = nested_arm.as_deref().expect("nested arm");
|
|
let (n, f) = if claimants[0].v.json_name == nested {
|
|
(claimants[0], claimants[1])
|
|
} else {
|
|
(claimants[1], claimants[0])
|
|
};
|
|
de.push_str(&format!(
|
|
" if isinstance(value, list):\n if value and isinstance(value[0], list):\n return {}\n return {}\n",
|
|
decode_expr(n),
|
|
decode_expr(f)
|
|
));
|
|
continue;
|
|
}
|
|
let check = match shape {
|
|
PyShape::NoneT => "value is None",
|
|
PyShape::Bool => "isinstance(value, bool)",
|
|
PyShape::Str => "isinstance(value, str)",
|
|
PyShape::Int => "_is_int(value)",
|
|
PyShape::Float => "_is_number(value)",
|
|
PyShape::Dict => "isinstance(value, dict)",
|
|
PyShape::List => "isinstance(value, list)",
|
|
};
|
|
de.push_str(&format!(
|
|
" if {check}:\n return {}\n",
|
|
decode_expr(claimants[0])
|
|
));
|
|
}
|
|
de.push_str(&format!(
|
|
" raise _invalid_type(value, expected=\"one of the {name} shapes\")\n\n\n"
|
|
));
|
|
|
|
// Encode: the runtime value's type picks the arm (a decoded object is its
|
|
// Struct class); list arms by first element.
|
|
for a in &arms {
|
|
let mut types: Vec<String> = Vec::new();
|
|
for s in &a.shapes {
|
|
let t = match s {
|
|
PyShape::Str => "str",
|
|
PyShape::Bool => "bool",
|
|
PyShape::Int => "int",
|
|
PyShape::Float => "float",
|
|
PyShape::List => "list",
|
|
PyShape::Dict | PyShape::NoneT => continue,
|
|
};
|
|
if !types.iter().any(|x| x == t) {
|
|
types.push(t.to_string());
|
|
}
|
|
}
|
|
types.extend(a.classes.iter().cloned());
|
|
let mut check = if types.is_empty() {
|
|
"False".to_string()
|
|
} else {
|
|
format!("isinstance(v, ({},))", types.join(", "))
|
|
};
|
|
if a.shapes.contains(&PyShape::NoneT) {
|
|
check = format!("v is None or {check}");
|
|
}
|
|
if a.shapes.contains(&PyShape::List) && list_arms.len() == 2 {
|
|
let elem = if nested_arm.as_deref() == Some(a.v.json_name.as_str()) {
|
|
"(v and isinstance(v[0], list))"
|
|
} else {
|
|
"not (v and isinstance(v[0], list))"
|
|
};
|
|
check = format!("isinstance(v, list) and {elem}");
|
|
}
|
|
en.push_str(&format!(
|
|
" if {check}:\n return {}\n",
|
|
encode_expr(a)
|
|
));
|
|
}
|
|
en.push_str(" return v\n\n\n");
|
|
out.push_str(&de);
|
|
out.push_str(&en);
|
|
}
|
|
|
|
fn emit_tagged_codec(
|
|
out: &mut String,
|
|
m: &MessageModel,
|
|
tag: &str,
|
|
variants: &[VariantModel],
|
|
passthrough: Option<&VariantModel>,
|
|
) {
|
|
let name = &m.rust_name;
|
|
// Decode: a known tag builds its payload from the declared keys; a payload
|
|
// that fails to parse, or an unknown tag, falls back to the passthrough
|
|
// (or errors when the schema declares none).
|
|
let fallback = if passthrough.is_some() {
|
|
"return dict(raw)".to_string()
|
|
} else {
|
|
format!("raise JsonContractError(\"unknown {tag} for {name}\")")
|
|
};
|
|
let mut de = format!(
|
|
"def decode_{name}(value: Any) -> {name}:\n raw = _expect_map(value, expected=\"map\")\n tag = raw.get({tag:?})\n"
|
|
);
|
|
for (i, v) in variants.iter().enumerate() {
|
|
let payload = match &v.kind {
|
|
FieldKind::Message { rust_path, .. } => rust_path.clone(),
|
|
other => panic!("{name}: tagged variant must be message-typed, got {other:?}"),
|
|
};
|
|
let kw = if i == 0 { "if" } else { "elif" };
|
|
de.push_str(&format!(
|
|
" {kw} tag == {:?}:\n try:\n return {payload}(\n",
|
|
v.json_name
|
|
));
|
|
for f in &v.payload_fields {
|
|
let key = &f.json_name;
|
|
let read = match &f.kind {
|
|
FieldKind::OptScalar { ty, .. } => expect_call(ty, &format!("raw[{key:?}]"), None),
|
|
FieldKind::Message { rust_path, .. } => {
|
|
format!("decode_{rust_path}(raw[{key:?}])")
|
|
}
|
|
other => panic!("{name}: tagged payload field kind {other:?} unsupported"),
|
|
};
|
|
de.push_str(&format!(
|
|
" {}=None if raw.get({key:?}) is None else {read},\n",
|
|
py_ident(key)
|
|
));
|
|
}
|
|
let on_error = if passthrough.is_some() {
|
|
"return dict(raw)"
|
|
} else {
|
|
"raise"
|
|
};
|
|
de.push_str(&format!(
|
|
" )\n except JsonContractError:\n {on_error}\n"
|
|
));
|
|
}
|
|
de.push_str(&format!(" {fallback}\n\n\n"));
|
|
|
|
// Encode: {tag: variant name, ...payload fields with explicit nulls}.
|
|
let mut en = format!("def encode_{name}(v: {name}) -> Any:\n");
|
|
for v in variants {
|
|
let payload = match &v.kind {
|
|
FieldKind::Message { rust_path, .. } => rust_path.clone(),
|
|
other => panic!("{name}: tagged variant must be message-typed, got {other:?}"),
|
|
};
|
|
en.push_str(&format!(
|
|
" if isinstance(v, {payload}):\n d: Dict[str, Any] = {{{tag:?}: {:?}}}\n",
|
|
v.json_name
|
|
));
|
|
for f in &v.payload_fields {
|
|
en.push_str(&ser_stmts(f, "v.", true, " "));
|
|
}
|
|
en.push_str(" return d\n");
|
|
}
|
|
if passthrough.is_some() {
|
|
en.push_str(" if isinstance(v, dict):\n return dict(v)\n");
|
|
}
|
|
en.push_str(&format!(
|
|
" raise TypeError(f\"{name}: unsupported value {{type(v).__name__}}\")\n\n\n"
|
|
));
|
|
out.push_str(&de);
|
|
out.push_str(&en);
|
|
}
|