allot-shared 0.5.0

Internal to Allot, no stable API: protocol, config, and path types
Documentation
//! Emits the C# records the tray app decodes `GET /ui/state` and the kill and remove responses
//! with, from the same JSON Schemas as `contract/*.schema.json`.

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;

";

// Integer values would let a renumbered Rust enum decode silently; names are the contract.
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)
    {
    }
}
";

/// The C# spelling of a property type, with `?` when the schema allows `null`.
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",
    }
}

/// Returns the C# source for `roots` (the `UiState` schema first) and every definition they
/// use, each type once.
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");
}

/// A serde internally tagged enum: one nested record per variant, told apart by the tag.
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");
}

/// Writes the `{ ... }` body of a record; `skip` is a tag property the converter consumes.
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, pinned) = member_name(record, property.json_name);
        let cs_type = render(&property.ty);
        // The source generator sets every init-only property in its object initializer, so an
        // absent member would overwrite the default with null; a setter is only called when
        // the member is present. A null default is what an absent member gets anyway.
        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);
        if pinned {
            writeln!(out, "{inner}[JsonPropertyName(\"{}\")]", property.json_name).unwrap();
        }
        writeln!(
            out,
            "{inner}public {keyword}{cs_type} {member} {{ {accessors} }}{initializer}"
        )
        .unwrap();
    }
    writeln!(out, "{indent}}}").unwrap();
}

/// PascalCase member name, and whether it needs its JSON name pinned. The context's snake_case
/// policy maps a name of lowercase words back to `json_name`; a word with digits, such as
/// `p90`, gets `[JsonPropertyName]` instead of relying on how the policy splits digits.
fn member_name(record: &str, json_name: &str) -> (String, bool) {
    let words_only = json_name.split('_').all(|word| {
        word.bytes()
            .next()
            .is_some_and(|byte| byte.is_ascii_lowercase())
            && word
                .bytes()
                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
    });
    assert!(
        words_only,
        "{record}.{json_name}: only lowercase words, digits after their first letter, joined \
         by `_` map to C# members"
    );
    let member = pascal_case(json_name);
    assert!(
        member != record,
        "{record}.{json_name}: a C# member cannot share its record's name"
    );
    let pinned = json_name.bytes().any(|byte| byte.is_ascii_digit());
    (member, pinned)
}

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
{
}
",
    );
}

/// Writes the schema's `description` as an XML doc summary.
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();
}

/// Escapes XML and turns rustdoc code spans, including `[`links`]`, into `<c>` elements, with
/// Rust's `None` shown as C#'s `null`.
fn xml_doc(markdown: &str) -> String {
    let escaped = markdown
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .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
}