// #nullable enable using System; using System.Collections.Generic; using CarpaNet.Models; using CarpaNet.Utilities; namespace CarpaNet.Generation; /// /// Generates C# interfaces and attributes for Lexicon union types. /// public static class UnionGenerator { /// /// 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. /// public static void GenerateUnionInterface( SourceBuilder sb, string interfaceName, LexiconDefinition def, string currentNsid, TypeRegistry registry) { var refs = def.Refs ?? new List(); 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(); } /// /// Gets the $type discriminator value for a ref. /// private static string GetTypeDiscriminator(string refString, string currentNsid) { // Local reference: nsid#name if (refString.StartsWith("#")) { return $"{currentNsid}{refString}"; } // Global reference return refString; } }