use std::fmt::Write;
use serde_json::{Map, Value};
use super::schema::{
Absent, Contract, Primitive, PropertyType, Shape, Type, enum_value, pascal_case, properties,
shape, tag_property, tag_value,
};
const NAMESPACE: &str = "Allot.Tray.Core.Contract";
const HEADER: &str = "\
// <auto-generated>
// Generated from the Rust types behind contract/*.schema.json by
// shared/src/contract/csharp.rs. Do not edit; rerun
// `ALLOT_UPDATE_CONTRACT=1 cargo test -p allot-shared contract` instead.
// </auto-generated>
#nullable enable
using System.Collections.Generic;
using System.Text.Json.Serialization;
";
const STRICT_ENUM_CONVERTER: &str = "
/// <summary>
/// Decodes an enum from its serde name only, never from a number.
/// </summary>
public sealed class StrictEnumConverter<TEnum> : JsonStringEnumConverter<TEnum>
where TEnum : struct, System.Enum
{
/// <summary>
/// Creates the converter with integer values turned off.
/// </summary>
public StrictEnumConverter()
: base(namingPolicy: null, allowIntegerValues: false)
{
}
}
";
fn render(property_type: &PropertyType) -> String {
let name = match &property_type.ty {
Type::Primitive(primitive) => primitive_name(*primitive).to_owned(),
Type::Named(name) => (*name).to_owned(),
Type::Array(item) => format!("IReadOnlyList<{}>", render(item)),
};
if property_type.nullable {
format!("{name}?")
} else {
name
}
}
fn primitive_name(primitive: Primitive) -> &'static str {
match primitive {
Primitive::Bool => "bool",
Primitive::String => "string",
Primitive::Int64 => "long",
Primitive::UInt64 => "ulong",
Primitive::UInt32 => "uint",
Primitive::Float => "float",
Primitive::Double => "double",
}
}
pub(super) fn emit(roots: &[&Value]) -> String {
let contract = Contract::new(roots);
let mut out = format!("{HEADER}namespace {NAMESPACE};\n");
for (name, schema) in contract.types() {
emit_definition(&mut out, &contract.definitions, name, schema);
}
out.push_str(STRICT_ENUM_CONVERTER);
emit_context(&mut out, &contract.root_names());
out
}
fn emit_definition(out: &mut String, definitions: &Map<String, Value>, name: &str, schema: &Value) {
match shape(schema) {
Shape::Enum(variants) => emit_enum(out, name, schema, variants),
Shape::Union(variants) => emit_tagged_union(out, definitions, name, schema, variants),
Shape::Record => {
out.push('\n');
write_doc(out, "", schema);
writeln!(out, "public sealed record {name}").unwrap();
emit_properties(out, definitions, name, schema, None, "");
}
Shape::Inline => {}
}
}
fn emit_enum(out: &mut String, name: &str, schema: &Value, variants: &[Value]) {
out.push('\n');
write_doc(out, "", schema);
writeln!(out, "[JsonConverter(typeof(StrictEnumConverter<{name}>))]").unwrap();
writeln!(out, "public enum {name}\n{{").unwrap();
for (index, variant) in variants.iter().enumerate() {
let value = enum_value(variant);
if index > 0 {
out.push('\n');
}
write_doc(out, " ", variant);
writeln!(out, " [JsonStringEnumMemberName(\"{value}\")]").unwrap();
writeln!(out, " {},", pascal_case(value)).unwrap();
}
out.push_str("}\n");
}
fn emit_tagged_union(
out: &mut String,
definitions: &Map<String, Value>,
name: &str,
schema: &Value,
variants: &[Value],
) {
let tag = tag_property(name, variants);
let tag_values: Vec<&str> = variants
.iter()
.map(|variant| tag_value(variant, tag))
.collect();
out.push('\n');
write_doc(out, "", schema);
writeln!(
out,
"[JsonPolymorphic(TypeDiscriminatorPropertyName = \"{tag}\")]"
)
.unwrap();
for value in &tag_values {
let variant = pascal_case(value);
writeln!(
out,
"[JsonDerivedType(typeof({name}.{variant}), \"{value}\")]"
)
.unwrap();
}
writeln!(out, "public abstract record {name}\n{{").unwrap();
for (index, (variant, value)) in variants.iter().zip(&tag_values).enumerate() {
let variant_name = pascal_case(value);
if index > 0 {
out.push('\n');
}
write_doc(out, " ", variant);
writeln!(out, " public sealed record {variant_name} : {name}").unwrap();
emit_properties(out, definitions, &variant_name, variant, Some(tag), " ");
}
out.push_str("}\n");
}
fn emit_properties(
out: &mut String,
definitions: &Map<String, Value>,
record: &str,
schema: &Value,
skip: Option<&str>,
indent: &str,
) {
writeln!(out, "{indent}{{").unwrap();
for (index, property) in properties(definitions, record, schema, skip)
.iter()
.enumerate()
{
let member = member_name(record, property.json_name);
let cs_type = render(&property.ty);
let (accessors, initializer) = match property.absent {
Absent::Fail | Absent::Null => ("get; init;", String::new()),
Absent::EmptyString => ("get; set;", " = \"\";".to_owned()),
Absent::Variant(value) => {
("get; set;", format!(" = {cs_type}.{};", pascal_case(value)))
}
Absent::False => ("get; set;", " = false;".to_owned()),
Absent::EmptyArray => ("get; set;", " = [];".to_owned()),
};
let keyword = if property.is_required() {
"required "
} else {
""
};
if index > 0 {
out.push('\n');
}
let inner = format!("{indent} ");
write_doc(out, &inner, property.schema);
writeln!(
out,
"{inner}public {keyword}{cs_type} {member} {{ {accessors} }}{initializer}"
)
.unwrap();
}
writeln!(out, "{indent}}}").unwrap();
}
fn member_name(record: &str, json_name: &str) -> String {
let words_only = json_name
.split('_')
.all(|word| !word.is_empty() && word.bytes().all(|byte| byte.is_ascii_lowercase()));
assert!(
words_only,
"{record}.{json_name}: only lowercase words joined by `_` round-trip through \
SnakeCaseLower"
);
let member = pascal_case(json_name);
assert!(
member != record,
"{record}.{json_name}: a C# member cannot share its record's name"
);
member
}
fn emit_context(out: &mut String, root_names: &[&str]) {
out.push_str(
"
/// <summary>
/// System.Text.Json metadata for the contract types, with the options their serde shapes need.
/// </summary>
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.SnakeCaseLower,
AllowOutOfOrderMetadataProperties = true,
RespectNullableAnnotations = true)]
",
);
for name in root_names {
writeln!(out, "[JsonSerializable(typeof({name}))]").unwrap();
}
out.push_str(
"public sealed partial class ContractJsonContext : JsonSerializerContext
{
}
",
);
}
fn write_doc(out: &mut String, indent: &str, schema: &Value) {
let Some(description) = schema["description"].as_str() else {
return;
};
writeln!(out, "{indent}/// <summary>").unwrap();
for line in xml_doc(description).lines() {
if line.is_empty() {
writeln!(out, "{indent}///").unwrap();
} else {
writeln!(out, "{indent}/// {line}").unwrap();
}
}
writeln!(out, "{indent}/// </summary>").unwrap();
}
fn xml_doc(markdown: &str) -> String {
let escaped = markdown
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace("[`", "`")
.replace("`]", "`");
let mut doc = String::with_capacity(escaped.len());
for (index, part) in escaped.split('`').enumerate() {
if index % 2 == 1 {
let code = if part == "None" { "null" } else { part };
write!(doc, "<c>{code}</c>").unwrap();
} else {
doc.push_str(part);
}
}
doc
}