Something went wrong. Try again.
.NET ATProtocol Library - Built for Source Gen
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869// <auto-generated />#nullable enable
using System;using System.Collections.Generic;using CarpaNet.Models;using CarpaNet.Utilities;
namespace CarpaNet.Generation;
/// <summary>/// Generates C# interfaces and attributes for Lexicon union types./// </summary>public static class UnionGenerator{ /// <summary> /// Generates a union interface with JsonPolymorphic attributes. /// For open unions, no polymorphic attributes are emitted since a custom JsonConverter /// in the generated JSON context handles unknown $type values gracefully. /// </summary> public static void GenerateUnionInterface( SourceBuilder sb, string interfaceName, LexiconDefinition def, string currentNsid, TypeRegistry registry) { var refs = def.Refs ?? new List<string>(); var isClosed = def.Closed == true;
sb.WriteSummary(def.Description);
if (isClosed) { // Closed unions: use JsonPolymorphic attributes (all types are known) sb.WriteAttribute("System.Text.Json.Serialization.JsonPolymorphic(TypeDiscriminatorPropertyName = \"$type\")");
foreach (var refString in refs) { var typeName = registry.ResolveToCSharpType(refString, currentNsid); var discriminator = GetTypeDiscriminator(refString, currentNsid); sb.WriteAttribute($"System.Text.Json.Serialization.JsonDerivedType(typeof({typeName}), \"{discriminator}\")"); } }
// Open unions: no polymorphic attributes - the generated JSON context // provides a custom JsonConverter that handles unknown $type values.
sb.AppendLine($"public interface {interfaceName}"); sb.OpenBrace(); sb.CloseBrace(); }
/// <summary> /// Gets the $type discriminator value for a ref. /// </summary> private static string GetTypeDiscriminator(string refString, string currentNsid) { // Local reference: nsid#name if (refString.StartsWith("#")) { return $"{currentNsid}{refString}"; }
// Global reference return refString; }}