// #nullable enable using System.Collections.Generic; using System.Linq; using CarpaNet.Models; using CarpaNet.Utilities; namespace CarpaNet.Generation; /// /// Generates JSON serialization context (IJsonTypeInfoResolver) using JsonMetadataServices. /// public static class JsonContextGenerator { /// /// Generates a CreateTypeInfo factory method and its properties method for an object or record type. /// /// Source builder. /// Fully qualified C# type name (e.g., "AppBsky.Actor.DefsProfileViewBasic"). /// Sanitized name for use in method identifiers (no dots). /// Lexicon definition for the type. /// Current NSID context. /// Type registry. /// Generator options. /// Whether this is a record type with $type discriminator. /// Set to track already-generated types. public static void GenerateJsonTypeInfo( SourceBuilder sb, string qualifiedTypeName, string methodSuffix, LexiconDefinition def, string currentNsid, TypeRegistry registry, GeneratorOptions options, bool isRecord = false, HashSet? generatedTypes = null, HashSet? collectedPropertyTypes = null, List<(string FullTypeName, string MethodSuffix)>? nestedTypeDispatch = null, HashSet? concreteTypes = null) { generatedTypes ??= new HashSet(); if (!generatedTypes.Add(methodSuffix)) { return; } // Track this as a concrete type for serialization method generation concreteTypes?.Add(qualifiedTypeName); // Track this type for dispatch nestedTypeDispatch?.Add((qualifiedTypeName, methodSuffix)); var properties = def.Properties ?? new Dictionary(); var requiredProps = new HashSet(def.Required ?? Enumerable.Empty()); // Generate nested type infos for inline objects/unions in properties foreach (var prop in properties) { GenerateNestedTypeInfosForProperty(sb, qualifiedTypeName, methodSuffix, prop.Key, prop.Value, currentNsid, registry, options, generatedTypes, collectedPropertyTypes, nestedTypeDispatch, concreteTypes); } // Generate the Create method using JsonMetadataServices.CreateObjectInfo (AOT-compatible, no RequiresDynamicCode) sb.AppendLine($"private static global::System.Text.Json.Serialization.Metadata.JsonTypeInfo Create_{methodSuffix}_TypeInfo(global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace(); sb.AppendLine($"var objectInfo = new global::System.Text.Json.Serialization.Metadata.JsonObjectInfoValues()"); sb.OpenBrace(); // Use GetUninitializedObject to bypass 'required' member checks on generated types sb.AppendLine($"ObjectCreator = static () => (global::{qualifiedTypeName})global::System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(global::{qualifiedTypeName})),"); sb.AppendLine($"PropertyMetadataInitializer = _ => Create_{methodSuffix}_Properties(options),"); sb.CloseBrace(withSemicolon: true); sb.AppendLine($"var info = global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateObjectInfo(options, objectInfo);"); sb.AppendLine("return info;"); sb.CloseBrace(); sb.AppendLine(); // Generate the properties method sb.AppendLine($"private static global::System.Text.Json.Serialization.Metadata.JsonPropertyInfo[] Create_{methodSuffix}_Properties(global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace(); var propList = properties.ToList(); // For records, include the $type property if (isRecord) { collectedPropertyTypes?.Add("string"); sb.AppendLine($"var prop__dtype = global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreatePropertyInfo(options, new global::System.Text.Json.Serialization.Metadata.JsonPropertyInfoValues()"); sb.OpenBrace(); sb.AppendLine("IsProperty = true,"); sb.AppendLine("IsPublic = true,"); sb.AppendLine($"DeclaringType = typeof(global::{qualifiedTypeName}),"); sb.AppendLine("PropertyName = \"Type\","); sb.AppendLine("JsonPropertyName = \"$type\","); sb.AppendLine($"Getter = obj => ((global::{qualifiedTypeName})obj).Type,"); sb.AppendLine("IsExtensionData = false,"); sb.CloseBrace(withSemicolon: false); sb.AppendLine(");"); sb.AppendLine(); } // Extract the short class name and namespace for property type resolution var shortClassName = qualifiedTypeName.Contains(".") ? qualifiedTypeName.Substring(qualifiedTypeName.LastIndexOf('.') + 1) : qualifiedTypeName; var typeNamespace = qualifiedTypeName.Contains(".") ? qualifiedTypeName.Substring(0, qualifiedTypeName.LastIndexOf('.')) : ""; for (int i = 0; i < propList.Count; i++) { var prop = propList[i]; var propName = NsidHelper.ToPascalCase(prop.Key); var jsonName = prop.Key; var propType = GetPropertyCSharpType(prop.Value, currentNsid, registry, shortClassName, prop.Key, typeNamespace); var isRequired = requiredProps.Contains(prop.Key) || prop.Value.IsRequired; var isNullable = IsNullableProperty(prop.Value, def, prop.Key); // Check if propName conflicts with className var cleanClassName = NsidHelper.StripEscapePrefix(shortClassName); if (propName.Equals(cleanClassName, System.StringComparison.OrdinalIgnoreCase)) { propName = propName + "Value"; } // Records auto-generate a "Type" property for the $type discriminator, // so rename any lexicon property that would also become "Type" if (isRecord && propName == "Type") { propName = "TypeValue"; } propName = NsidHelper.EscapeIdentifier(propName); // Resolve property type to fully qualified form var fullPropType = ResolveToGlobalType(propType); if (isNullable && !fullPropType.EndsWith("?") && !IsReferenceType(propType)) { fullPropType = fullPropType + "?"; } // Collect this property type for built-in type info generation (strip @ escape prefix) if (collectedPropertyTypes != null) { var collectedType = propType.Replace("@", ""); if (isNullable && !IsReferenceType(propType)) { collectedType = collectedType + "?"; } collectedPropertyTypes.Add(collectedType); } var varName = $"prop_{SanitizeVarName(prop.Key)}"; sb.AppendLine($"var {varName} = global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreatePropertyInfo<{fullPropType}>(options, new global::System.Text.Json.Serialization.Metadata.JsonPropertyInfoValues<{fullPropType}>()"); sb.OpenBrace(); sb.AppendLine("IsProperty = true,"); sb.AppendLine("IsPublic = true,"); sb.AppendLine($"DeclaringType = typeof(global::{qualifiedTypeName}),"); sb.AppendLine($"PropertyName = \"{propName}\","); sb.AppendLine($"JsonPropertyName = \"{jsonName}\","); sb.AppendLine($"Getter = obj => ((global::{qualifiedTypeName})obj).{propName},"); if (isRequired && !isNullable) { sb.AppendLine($"Setter = (obj, val) => ((global::{qualifiedTypeName})obj).{propName} = val!,"); } else { sb.AppendLine($"Setter = (obj, val) => ((global::{qualifiedTypeName})obj).{propName} = val,"); } sb.AppendLine("IsExtensionData = false,"); sb.CloseBrace(withSemicolon: false); sb.AppendLine(");"); sb.AppendLine(); } // Build the return array sb.AppendIndent(); sb.Append("return new global::System.Text.Json.Serialization.Metadata.JsonPropertyInfo[] { "); if (isRecord) { sb.Append("prop__dtype, "); } for (int i = 0; i < propList.Count; i++) { var varName = $"prop_{SanitizeVarName(propList[i].Key)}"; sb.Append(varName); if (i < propList.Count - 1) { sb.Append(", "); } } sb.Append(" };\n"); sb.CloseBrace(); sb.AppendLine(); } /// /// Generates a CreateTypeInfo factory method for a union interface with polymorphism options. /// For open unions (isClosed=false), generates a custom JsonConverter that gracefully /// returns null for unknown $type discriminator values instead of throwing. /// public static void GenerateJsonUnionTypeInfo( SourceBuilder sb, string qualifiedTypeName, string methodSuffix, List refs, string currentNsid, TypeRegistry registry, GeneratorOptions options, bool isClosed = false, HashSet? generatedTypes = null, List<(string FullTypeName, string MethodSuffix)>? nestedTypeDispatch = null) { generatedTypes ??= new HashSet(); if (!generatedTypes.Add(methodSuffix)) { return; } // Track this type for dispatch nestedTypeDispatch?.Add((qualifiedTypeName, methodSuffix)); if (isClosed) { // Closed unions: use JsonPolymorphismOptions (unknown types will throw) sb.AppendLine($"private static global::System.Text.Json.Serialization.Metadata.JsonTypeInfo Create_{methodSuffix}_TypeInfo(global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace(); sb.AppendLine($"var info = global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateObjectInfo(options, new global::System.Text.Json.Serialization.Metadata.JsonObjectInfoValues());"); sb.AppendLine($"var polyOptions = new global::System.Text.Json.Serialization.Metadata.JsonPolymorphismOptions();"); sb.AppendLine("polyOptions.TypeDiscriminatorPropertyName = \"$type\";"); foreach (var refString in refs) { var typeName = registry.ResolveToCSharpType(refString, currentNsid); var discriminator = GetTypeDiscriminator(refString, currentNsid, registry); sb.AppendLine($"polyOptions.DerivedTypes.Add(new global::System.Text.Json.Serialization.Metadata.JsonDerivedType(typeof(global::{typeName}), \"{discriminator}\"));"); } sb.AppendLine("info.PolymorphismOptions = polyOptions;"); sb.AppendLine("return info;"); sb.CloseBrace(); sb.AppendLine(); } else { // Open unions: generate a custom converter that returns null for unknown $type values GenerateOpenUnionConverter(sb, qualifiedTypeName, methodSuffix, refs, currentNsid, registry); sb.AppendLine($"private static global::System.Text.Json.Serialization.Metadata.JsonTypeInfo Create_{methodSuffix}_TypeInfo(global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace(); sb.AppendLine($"return global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateValueInfo(options, new Converter_{methodSuffix}());"); sb.CloseBrace(); sb.AppendLine(); } } /// /// Generates a JsonConverter class for an open union interface that gracefully handles unknown $type values. /// private static void GenerateOpenUnionConverter( SourceBuilder sb, string qualifiedTypeName, string methodSuffix, List refs, string currentNsid, TypeRegistry registry) { sb.AppendLine($"private sealed class Converter_{methodSuffix} : global::System.Text.Json.Serialization.JsonConverter"); sb.OpenBrace(); // Read method sb.AppendLine($"public override global::{qualifiedTypeName}? Read(ref global::System.Text.Json.Utf8JsonReader reader, global::System.Type typeToConvert, global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace(); sb.AppendLine("var element = global::System.Text.Json.JsonElement.ParseValue(ref reader);"); sb.AppendLine("if (!element.TryGetProperty(\"$type\", out var typeProp))"); sb.AppendLine(" return null;"); sb.AppendLine("var typeStr = typeProp.GetString();"); sb.AppendLine("return typeStr switch"); sb.OpenBrace(); foreach (var refString in refs) { var typeName = registry.ResolveToCSharpType(refString, currentNsid); var discriminator = GetTypeDiscriminator(refString, currentNsid, registry); sb.AppendLine($"\"{discriminator}\" => (global::{qualifiedTypeName}?)global::System.Text.Json.JsonSerializer.Deserialize(element, options.GetTypeInfo(typeof(global::{typeName}))),"); } sb.AppendLine("_ => null,"); sb.CloseBrace(withSemicolon: true); sb.CloseBrace(); sb.AppendLine(); // Write method sb.AppendLine($"public override void Write(global::System.Text.Json.Utf8JsonWriter writer, global::{qualifiedTypeName} value, global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace(); sb.AppendLine("global::System.Text.Json.JsonSerializer.Serialize(writer, value, options.GetTypeInfo(value.GetType()));"); sb.CloseBrace(); sb.CloseBrace(); sb.AppendLine(); } /// /// Generates nested type infos for a property (handles inline objects, unions, etc.) /// private static void GenerateNestedTypeInfosForProperty( SourceBuilder sb, string parentQualifiedTypeName, string parentMethodSuffix, string propertyName, LexiconDefinition prop, string currentNsid, TypeRegistry registry, GeneratorOptions options, HashSet generatedTypes, HashSet? collectedPropertyTypes = null, List<(string FullTypeName, string MethodSuffix)>? nestedTypeDispatch = null, HashSet? concreteTypes = null) { // Handle inline objects if (prop.Type == "object" && prop.Properties != null && prop.Properties.Count > 0) { var pascalProp = NsidHelper.ToPascalCase(propertyName); var nestedQualified = $"{parentQualifiedTypeName}{pascalProp}"; var nestedSuffix = $"{parentMethodSuffix}_{pascalProp}"; GenerateJsonTypeInfo(sb, nestedQualified, nestedSuffix, prop, currentNsid, registry, options, generatedTypes: generatedTypes, collectedPropertyTypes: collectedPropertyTypes, nestedTypeDispatch: nestedTypeDispatch, concreteTypes: concreteTypes); } // Handle unions (skip open unions with no refs - those use JsonElement directly) if (prop.Type == "union" && prop.Refs != null && !(prop.Closed != true && prop.Refs.Count == 0)) { var pascalProp = NsidHelper.ToPascalCase(propertyName); // Extract short parent class name for interface naming var shortParent = parentQualifiedTypeName.Contains(".") ? parentQualifiedTypeName.Substring(parentQualifiedTypeName.LastIndexOf('.') + 1) : parentQualifiedTypeName; var ns = parentQualifiedTypeName.Contains(".") ? parentQualifiedTypeName.Substring(0, parentQualifiedTypeName.LastIndexOf('.')) : ""; var interfaceShort = $"I{shortParent}{pascalProp}"; var interfaceQualified = string.IsNullOrEmpty(ns) ? interfaceShort : $"{ns}.{interfaceShort}"; var interfaceSuffix = $"{parentMethodSuffix}_I{pascalProp}"; GenerateJsonUnionTypeInfo(sb, interfaceQualified, interfaceSuffix, prop.Refs, currentNsid, registry, options, isClosed: prop.Closed == true, generatedTypes: generatedTypes, nestedTypeDispatch: nestedTypeDispatch); } // Handle arrays if (prop.Type == "array" && prop.Items != null) { if (prop.Items.Type == "object" && prop.Items.Properties != null && prop.Items.Properties.Count > 0) { var pascalProp = NsidHelper.ToPascalCase(propertyName); var nestedQualified = $"{parentQualifiedTypeName}{pascalProp}Item"; var nestedSuffix = $"{parentMethodSuffix}_{pascalProp}Item"; GenerateJsonTypeInfo(sb, nestedQualified, nestedSuffix, prop.Items, currentNsid, registry, options, generatedTypes: generatedTypes, collectedPropertyTypes: collectedPropertyTypes, nestedTypeDispatch: nestedTypeDispatch, concreteTypes: concreteTypes); } if (prop.Items.Type == "union" && prop.Items.Refs != null && !(prop.Items.Closed != true && prop.Items.Refs.Count == 0)) { var pascalProp = NsidHelper.ToPascalCase(propertyName); var shortParent = parentQualifiedTypeName.Contains(".") ? parentQualifiedTypeName.Substring(parentQualifiedTypeName.LastIndexOf('.') + 1) : parentQualifiedTypeName; var ns = parentQualifiedTypeName.Contains(".") ? parentQualifiedTypeName.Substring(0, parentQualifiedTypeName.LastIndexOf('.')) : ""; // Union arrays use the same interface name as direct union properties (no Item suffix) var cleanParent = NsidHelper.StripEscapePrefix(shortParent); var cleanProp = NsidHelper.StripEscapePrefix(pascalProp); var interfaceShort = $"I{cleanParent}{cleanProp}"; var interfaceQualified = string.IsNullOrEmpty(ns) ? interfaceShort : $"{ns}.{interfaceShort}"; var interfaceSuffix = $"{parentMethodSuffix}_I{cleanProp}"; GenerateJsonUnionTypeInfo(sb, interfaceQualified, interfaceSuffix, prop.Items.Refs, currentNsid, registry, options, isClosed: prop.Items.Closed == true, generatedTypes: generatedTypes, nestedTypeDispatch: nestedTypeDispatch); } } } private static string GetPropertyCSharpType( LexiconDefinition prop, string currentNsid, TypeRegistry registry, string? parentClassName = null, string? propertyName = null, string? parentNamespace = null) { if (!string.IsNullOrEmpty(prop.Ref)) { var resolved = registry.ResolveToCSharpType(prop.Ref, currentNsid); return QualifyUnionNames(resolved, prop.Ref!, currentNsid, registry); } var nsPrefix = !string.IsNullOrEmpty(parentNamespace) ? $"{parentNamespace}." : ""; return prop.Type switch { "string" => prop.Format switch { "datetime" => "System.DateTimeOffset", "uri" => "string", "at-uri" => "CarpaNet.ATUri", "did" => "CarpaNet.ATDid", "handle" => "CarpaNet.ATHandle", "at-identifier" => "CarpaNet.ATIdentifier", "cid" => "string", "language" => "string", "nsid" => "string", "record-key" => "string", "tid" => "string", _ => "string" }, "integer" => "long", "boolean" => "bool", "bytes" => "byte[]", "cid-link" => "CarpaNet.ATCid", "blob" => "CarpaNet.ATBlob", "unknown" => "System.Text.Json.JsonElement", "token" => "string", "array" => GetArrayType(prop, currentNsid, registry, parentClassName, propertyName, parentNamespace), "object" when prop.Properties != null && prop.Properties.Count > 0 && parentClassName != null && propertyName != null => $"{nsPrefix}{parentClassName}{NsidHelper.ToPascalCase(propertyName)}", "union" when prop.Closed != true && (prop.Refs == null || prop.Refs.Count == 0) => "System.Text.Json.JsonElement", "union" when prop.Refs != null && parentClassName != null && propertyName != null => $"{nsPrefix}I{NsidHelper.StripEscapePrefix(parentClassName)}{NsidHelper.StripEscapePrefix(NsidHelper.ToPascalCase(propertyName))}", _ => "object" }; } private static string GetArrayType( LexiconDefinition prop, string currentNsid, TypeRegistry registry, string? parentClassName = null, string? propertyName = null, string? parentNamespace = null) { if (prop.Items == null) { return "System.Collections.Generic.List"; } var items = prop.Items; var nsPrefix = !string.IsNullOrEmpty(parentNamespace) ? $"{parentNamespace}." : ""; if (items.Type == "object" && items.Properties != null && items.Properties.Count > 0 && parentClassName != null && propertyName != null) { var nestedClassName = $"{nsPrefix}{parentClassName}{NsidHelper.ToPascalCase(propertyName)}Item"; return $"System.Collections.Generic.List<{nestedClassName}>"; } if (items.Type == "union" && items.Refs != null && parentClassName != null && propertyName != null && !(items.Closed != true && items.Refs.Count == 0)) { // Union arrays use the same interface name as direct union properties (no Item suffix) var cleanParent = NsidHelper.StripEscapePrefix(parentClassName); var cleanProp = NsidHelper.StripEscapePrefix(NsidHelper.ToPascalCase(propertyName)); var interfaceName = $"{nsPrefix}I{cleanParent}{cleanProp}"; return $"System.Collections.Generic.List<{interfaceName}>"; } var elementType = GetPropertyCSharpType(items, currentNsid, registry, parentClassName, propertyName != null ? $"{propertyName}Item" : null, parentNamespace); return $"System.Collections.Generic.List<{elementType}>"; } private static string GetTypeDiscriminator(string refString, string currentNsid, TypeRegistry registry) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = registry.Lookup(fullRef); if (typeInfo != null) { return typeInfo.FullRef; } return fullRef; } /// /// Ensures union interface names are fully qualified. /// TypeRegistry.ResolveToCSharpType returns short names for unions (e.g., "IDefsPreferences"), /// but we need fully qualified names (e.g., "AppBsky.Actor.IDefsPreferences") since /// the JSON context lives in a different namespace. /// This also handles cases where the union is embedded in List<T>. /// private static string QualifyUnionNames(string resolved, string refString, string currentNsid, TypeRegistry registry) { // Handle List - qualify the inner type if (resolved.StartsWith("System.Collections.Generic.List<") && resolved.EndsWith(">")) { var inner = resolved.Substring("System.Collections.Generic.List<".Length, resolved.Length - "System.Collections.Generic.List<".Length - 1); var qualifiedInner = QualifyUnionNames(inner, refString, currentNsid, registry); return $"System.Collections.Generic.List<{qualifiedInner}>"; } // Check if this is a bare interface name that needs qualification if (resolved.StartsWith("I") && resolved.Length > 1 && char.IsUpper(resolved[1]) && !resolved.Contains(".")) { var fullRef = refString.StartsWith("#") ? $"{currentNsid}{refString}" : refString; var typeInfo = registry.Lookup(fullRef); if (typeInfo != null) { // Get namespace from FullCSharpTypeName var fullName = typeInfo.FullCSharpTypeName; var lastDot = fullName.LastIndexOf('.'); if (lastDot >= 0) { var ns = fullName.Substring(0, lastDot); return $"{ns}.{resolved}"; } } } return resolved; } private static string ResolveLocalRef(string refString, string currentNsid) { if (refString.StartsWith("#")) { return $"{currentNsid}{refString}"; } return refString; } private static bool IsNullableProperty(LexiconDefinition prop, LexiconDefinition parent, string propName) { var required = parent.Required ?? new List(); var nullable = parent.Nullable ?? new List(); var isRequired = required.Contains(propName) || prop.IsRequired; // A property can be both required (must be present) and nullable (value can be null) if (nullable.Contains(propName)) { return true; } // ObjectGenerator strips nullability for required properties (TrimEnd('?')), // so we must match: required properties are NEVER nullable in the generated class. if (isRequired) { return false; } return true; } private static bool IsReferenceType(string typeName) { return typeName switch { "string" => true, "byte[]" => true, "object" => true, "long" or "int" or "bool" or "double" or "float" or "short" or "byte" or "decimal" => false, "System.DateTimeOffset" => false, // Value type "System.Text.Json.JsonElement" => false, // Value type _ when typeName.StartsWith("System.Collections.Generic.List<") => true, "CarpaNet.ATBlob" => true, // ATBlob is a class _ when typeName.StartsWith("CarpaNet.AT") => false, // Remaining AT* types are structs _ when typeName.StartsWith("I") && typeName.Length > 1 && char.IsUpper(typeName[1]) => true, // Interface types _ when typeName.Contains(".") => true, // Assume class types are reference types _ => false }; } /// /// Converts a C# type name to a global:: qualified form. /// Primitives like "string", "bool", "long" remain as-is. /// private static string ResolveToGlobalType(string typeName) { // Handle List specially if (typeName.StartsWith("System.Collections.Generic.List<") && typeName.EndsWith(">")) { var inner = typeName.Substring("System.Collections.Generic.List<".Length, typeName.Length - "System.Collections.Generic.List<".Length - 1); return $"global::System.Collections.Generic.List<{ResolveToGlobalType(inner)}>"; } return typeName switch { "string" => "string", "bool" => "bool", "long" => "long", "int" => "int", "byte[]" => "byte[]", "object" => "object", _ when typeName.Contains(".") => $"global::{typeName}", _ => typeName }; } /// /// Converts a fully-qualified type name to a safe C# identifier suffix. /// Replaces dots with underscores. /// public static string ToMethodSuffix(string qualifiedTypeName) { return qualifiedTypeName.Replace(".", "_").Replace("@", ""); } private static string SanitizeVarName(string name) { var result = new System.Text.StringBuilder(); foreach (var c in name) { if (char.IsLetterOrDigit(c) || c == '_') { result.Append(c); } else { result.Append('_'); } } if (result.Length > 0 && char.IsDigit(result[0])) { result.Insert(0, '_'); } return result.ToString(); } // --- Built-in type info generation for AOT support --- // Map of primitive type names to their JsonMetadataServices converter property names private static readonly Dictionary KnownConverters = new Dictionary { ["string"] = "StringConverter", ["long"] = "Int64Converter", ["bool"] = "BooleanConverter", ["int"] = "Int32Converter", ["byte[]"] = "ByteArrayConverter", ["System.DateTimeOffset"] = "DateTimeOffsetConverter", ["System.Text.Json.JsonElement"] = "JsonElementConverter", }; // Runtime types that have public JsonConverter classes private static readonly Dictionary RuntimeConverterTypes = new Dictionary { ["CarpaNet.ATDid"] = "CarpaNet.ATDidJsonConverter", ["CarpaNet.ATHandle"] = "CarpaNet.ATHandleJsonConverter", ["CarpaNet.ATUri"] = "CarpaNet.ATUriJsonConverter", ["CarpaNet.ATIdentifier"] = "CarpaNet.ATIdentifierJsonConverter", ["CarpaNet.ATCid"] = "CarpaNet.ATCidJsonConverter", ["CarpaNet.ATBlob"] = "CarpaNet.ATBlobJsonConverter", }; /// /// Generates JsonTypeInfo factory methods for all non-object property types /// (primitives, runtime types, nullable versions, and List<T> collections). /// Returns dispatch lines for insertion into GetTypeInfo. /// public static List GenerateBuiltInTypeInfos( SourceBuilder sb, HashSet propertyTypes, HashSet generatedObjectTypeNames) { var dispatchLines = new List(); var generated = new HashSet(); // Sort so base types come before nullable versions foreach (var propType in propertyTypes.OrderBy(t => t.EndsWith("?") ? 1 : 0).ThenBy(t => t.StartsWith("System.Collections.Generic.List<") ? 1 : 0)) { if (!generated.Add(propType)) { continue; } // Handle List if (propType.StartsWith("System.Collections.Generic.List<") && propType.EndsWith(">")) { var elementType = propType.Substring("System.Collections.Generic.List<".Length, propType.Length - "System.Collections.Generic.List<".Length - 1); // Ensure element type has a factory if it's a built-in type if (!generatedObjectTypeNames.Contains(elementType) && generated.Add(elementType)) { GenerateValueTypeFactory(sb, elementType, dispatchLines); } GenerateListTypeFactory(sb, propType, elementType, dispatchLines); continue; } // Handle nullable types var isNullable = propType.EndsWith("?"); var baseType = isNullable ? propType.Substring(0, propType.Length - 1) : propType; // Skip types that are generated objects/unions if (generatedObjectTypeNames.Contains(baseType)) { continue; } if (isNullable) { // Ensure base type factory exists if (generated.Add(baseType)) { GenerateValueTypeFactory(sb, baseType, dispatchLines); } GenerateNullableTypeFactory(sb, baseType, dispatchLines); } else { GenerateValueTypeFactory(sb, baseType, dispatchLines); } } return dispatchLines; } private static void GenerateValueTypeFactory( SourceBuilder sb, string typeName, List dispatchLines) { var globalType = ResolveToGlobalType(typeName); var safeName = ToBuiltInSuffix(typeName); var typeofExpr = globalType; // for typeof() sb.AppendLine($"private static global::System.Text.Json.Serialization.Metadata.JsonTypeInfo<{globalType}> Create_BuiltIn_{safeName}_TypeInfo(global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace(); if (KnownConverters.TryGetValue(typeName, out var converterName)) { sb.AppendLine($"return global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateValueInfo<{globalType}>(options, global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.{converterName});"); } else if (RuntimeConverterTypes.TryGetValue(typeName, out var converterType)) { sb.AppendLine($"return global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateValueInfo<{globalType}>(options, new global::{converterType}());"); } else { // Fallback for any other types - use GetConverter (may not work if type is resolved by this resolver) sb.AppendLine($"return global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateValueInfo<{globalType}>(options, (global::System.Text.Json.Serialization.JsonConverter<{globalType}>)options.GetConverter(typeof({globalType})));"); } sb.CloseBrace(); sb.AppendLine(); dispatchLines.Add($"if (type == typeof({typeofExpr})) return Create_BuiltIn_{safeName}_TypeInfo(options);"); } private static void GenerateNullableTypeFactory( SourceBuilder sb, string baseTypeName, List dispatchLines) { var globalBase = ResolveToGlobalType(baseTypeName); var safeName = ToBuiltInSuffix(baseTypeName); var baseSafeName = safeName; sb.AppendLine($"private static global::System.Text.Json.Serialization.Metadata.JsonTypeInfo<{globalBase}?> Create_BuiltIn_Nullable{safeName}_TypeInfo(global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace(); // Create the underlying type info to get the nullable converter sb.AppendLine($"var underlyingInfo = Create_BuiltIn_{baseSafeName}_TypeInfo(options);"); sb.AppendLine($"var converter = global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.GetNullableConverter<{globalBase}>(underlyingInfo);"); sb.AppendLine($"return global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateValueInfo<{globalBase}?>(options, converter);"); sb.CloseBrace(); sb.AppendLine(); dispatchLines.Add($"if (type == typeof({globalBase}?)) return Create_BuiltIn_Nullable{safeName}_TypeInfo(options);"); } private static void GenerateListTypeFactory( SourceBuilder sb, string fullListType, string elementType, List dispatchLines) { var globalElement = ResolveToGlobalType(elementType); var globalList = $"global::System.Collections.Generic.List<{globalElement}>"; var safeName = "List_" + ToBuiltInSuffix(elementType); sb.AppendLine($"private static global::System.Text.Json.Serialization.Metadata.JsonTypeInfo<{globalList}> Create_BuiltIn_{safeName}_TypeInfo(global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace(); sb.AppendLine($"return global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateListInfo<{globalList}, {globalElement}>(options, new global::System.Text.Json.Serialization.Metadata.JsonCollectionInfoValues<{globalList}>()"); sb.OpenBrace(); sb.AppendLine($"ObjectCreator = static () => new {globalList}(),"); sb.CloseBrace(withSemicolon: false); sb.AppendLine(");"); sb.CloseBrace(); sb.AppendLine(); dispatchLines.Add($"if (type == typeof({globalList})) return Create_BuiltIn_{safeName}_TypeInfo(options);"); } internal static string ToBuiltInSuffix(string typeName) { return typeName switch { "string" => "String", "long" => "Int64", "bool" => "Boolean", "int" => "Int32", "byte[]" => "ByteArray", "object" => "Object", _ => typeName.Replace(".", "_").Replace("@", "").Replace("<", "_").Replace(">", "_") }; } }