Something went wrong. Try again.
.NET ATProtocol Library - Built for Source Gen
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816// <auto-generated />#nullable enable
using System.Collections.Generic;using System.Linq;using CarpaNet.Models;using CarpaNet.Utilities;
namespace CarpaNet.Generation;
/// <summary>/// Generates JSON serialization context (IJsonTypeInfoResolver) using JsonMetadataServices./// </summary>public static class JsonContextGenerator{ /// <summary> /// Generates a CreateTypeInfo factory method and its properties method for an object or record type. /// </summary> /// <param name="sb">Source builder.</param> /// <param name="qualifiedTypeName">Fully qualified C# type name (e.g., "AppBsky.Actor.DefsProfileViewBasic").</param> /// <param name="methodSuffix">Sanitized name for use in method identifiers (no dots).</param> /// <param name="def">Lexicon definition for the type.</param> /// <param name="currentNsid">Current NSID context.</param> /// <param name="registry">Type registry.</param> /// <param name="options">Generator options.</param> /// <param name="isRecord">Whether this is a record type with $type discriminator.</param> /// <param name="generatedTypes">Set to track already-generated types.</param> public static void GenerateJsonTypeInfo( SourceBuilder sb, string qualifiedTypeName, string methodSuffix, LexiconDefinition def, string currentNsid, TypeRegistry registry, GeneratorOptions options, bool isRecord = false, HashSet<string>? generatedTypes = null, HashSet<string>? collectedPropertyTypes = null, List<(string FullTypeName, string MethodSuffix)>? nestedTypeDispatch = null, HashSet<string>? concreteTypes = null) { generatedTypes ??= new HashSet<string>();
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<string, LexiconDefinition>(); var requiredProps = new HashSet<string>(def.Required ?? Enumerable.Empty<string>());
// 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<global::{qualifiedTypeName}> Create_{methodSuffix}_TypeInfo(global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace(); sb.AppendLine($"var objectInfo = new global::System.Text.Json.Serialization.Metadata.JsonObjectInfoValues<global::{qualifiedTypeName}>()"); 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<global::{qualifiedTypeName}>(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<string>(options, new global::System.Text.Json.Serialization.Metadata.JsonPropertyInfoValues<string>()"); 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(); }
/// <summary> /// 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. /// </summary> public static void GenerateJsonUnionTypeInfo( SourceBuilder sb, string qualifiedTypeName, string methodSuffix, List<string> refs, string currentNsid, TypeRegistry registry, GeneratorOptions options, bool isClosed = false, HashSet<string>? generatedTypes = null, List<(string FullTypeName, string MethodSuffix)>? nestedTypeDispatch = null) { generatedTypes ??= new HashSet<string>();
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<global::{qualifiedTypeName}> Create_{methodSuffix}_TypeInfo(global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace();
sb.AppendLine($"var info = global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateObjectInfo<global::{qualifiedTypeName}>(options, new global::System.Text.Json.Serialization.Metadata.JsonObjectInfoValues<global::{qualifiedTypeName}>());");
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<global::{qualifiedTypeName}> Create_{methodSuffix}_TypeInfo(global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace(); sb.AppendLine($"return global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateValueInfo<global::{qualifiedTypeName}>(options, new Converter_{methodSuffix}());"); sb.CloseBrace(); sb.AppendLine(); } }
/// <summary> /// Generates a JsonConverter class for an open union interface that gracefully handles unknown $type values. /// </summary> private static void GenerateOpenUnionConverter( SourceBuilder sb, string qualifiedTypeName, string methodSuffix, List<string> refs, string currentNsid, TypeRegistry registry) { sb.AppendLine($"private sealed class Converter_{methodSuffix} : global::System.Text.Json.Serialization.JsonConverter<global::{qualifiedTypeName}>"); 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(); }
/// <summary> /// Generates nested type infos for a property (handles inline objects, unions, etc.) /// </summary> private static void GenerateNestedTypeInfosForProperty( SourceBuilder sb, string parentQualifiedTypeName, string parentMethodSuffix, string propertyName, LexiconDefinition prop, string currentNsid, TypeRegistry registry, GeneratorOptions options, HashSet<string> generatedTypes, HashSet<string>? collectedPropertyTypes = null, List<(string FullTypeName, string MethodSuffix)>? nestedTypeDispatch = null, HashSet<string>? 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<object>"; }
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; }
/// <summary> /// 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>. /// </summary> private static string QualifyUnionNames(string resolved, string refString, string currentNsid, TypeRegistry registry) { // Handle List<T> - 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<string>(); var nullable = parent.Nullable ?? new List<string>(); 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 }; }
/// <summary> /// Converts a C# type name to a global:: qualified form. /// Primitives like "string", "bool", "long" remain as-is. /// </summary> private static string ResolveToGlobalType(string typeName) { // Handle List<T> 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 }; }
/// <summary> /// Converts a fully-qualified type name to a safe C# identifier suffix. /// Replaces dots with underscores. /// </summary> 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<string, string> KnownConverters = new Dictionary<string, string> { ["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<string, string> RuntimeConverterTypes = new Dictionary<string, string> { ["CarpaNet.ATDid"] = "CarpaNet.ATDidJsonConverter", ["CarpaNet.ATHandle"] = "CarpaNet.ATHandleJsonConverter", ["CarpaNet.ATUri"] = "CarpaNet.ATUriJsonConverter", ["CarpaNet.ATIdentifier"] = "CarpaNet.ATIdentifierJsonConverter", ["CarpaNet.ATCid"] = "CarpaNet.ATCidJsonConverter", ["CarpaNet.ATBlob"] = "CarpaNet.ATBlobJsonConverter", };
/// <summary> /// 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. /// </summary> public static List<string> GenerateBuiltInTypeInfos( SourceBuilder sb, HashSet<string> propertyTypes, HashSet<string> generatedObjectTypeNames) { var dispatchLines = new List<string>(); var generated = new HashSet<string>();
// 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<T> 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<string> 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<string> 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<string> 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(">", "_") }; }}