Something went wrong. Try again.
.NET ATProtocol Library - Built for Source Gen
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345// <auto-generated />#nullable enable
using System;using System.Collections.Generic;using System.Linq;using CarpaNet.Models;using CarpaNet.Utilities;
namespace CarpaNet.Generation;
/// <summary>/// Generates C# classes from Lexicon object definitions./// </summary>public static class ObjectGenerator{ /// <summary> /// Generates a C# class for a Lexicon object type. /// </summary> public static void GenerateClass( SourceBuilder sb, string className, LexiconDefinition def, string currentNsid, TypeRegistry registry, bool isRecord = false, string? recordType = null, string? typeId = null) { var requiredProps = def.Required ?? new List<string>(); var nullableProps = def.Nullable ?? new List<string>(); var properties = def.Properties ?? new Dictionary<string, LexiconDefinition>();
// First, generate inline union interfaces for union properties GenerateInlineUnionInterfaces(sb, className, properties, currentNsid, registry);
sb.WriteSummary(def.Description);
if (isRecord && !string.IsNullOrEmpty(recordType)) { sb.WriteAttribute($"CarpaNet.ATRecord(\"{recordType}\")"); }
sb.AppendLine($"public partial class {NsidHelper.EscapeIdentifier(className)}"); sb.OpenBrace();
// Add TypeId constant for all types that have a type identifier if (!string.IsNullOrEmpty(typeId)) { sb.AppendLine($"public const string TypeId = \"{typeId}\";"); sb.AppendLine(); }
// Add $type constant for records if (isRecord && !string.IsNullOrEmpty(recordType)) { sb.AppendLine($"public const string RecordType = \"{recordType}\";"); sb.AppendLine(); sb.WriteAttribute("System.Text.Json.Serialization.JsonPropertyName(\"$type\")"); sb.AppendLine("public string Type => RecordType;"); sb.AppendLine(); }
foreach (var prop in properties) { GenerateProperty(sb, className, prop.Key, prop.Value, currentNsid, registry, requiredProps, nullableProps, isRecord); }
sb.CloseBrace(); }
/// <summary> /// Generates inline union interfaces for properties with union types. /// </summary> private static void GenerateInlineUnionInterfaces( SourceBuilder sb, string className, Dictionary<string, LexiconDefinition> properties, string currentNsid, TypeRegistry registry) { foreach (var prop in properties) { if (prop.Value.Type == "union" && prop.Value.Refs != null && !(prop.Value.Closed != true && prop.Value.Refs.Count == 0)) { var interfaceName = GenerateUnionInterfaceName(className, prop.Key); UnionGenerator.GenerateUnionInterface(sb, interfaceName, prop.Value, currentNsid, registry); sb.AppendLine(); }
// Also handle arrays of unions if (prop.Value.Type == "array" && prop.Value.Items?.Type == "union" && prop.Value.Items.Refs != null && !(prop.Value.Items.Closed != true && prop.Value.Items.Refs.Count == 0)) { var interfaceName = GenerateUnionInterfaceName(className, prop.Key); UnionGenerator.GenerateUnionInterface(sb, interfaceName, prop.Value.Items, currentNsid, registry); sb.AppendLine(); } } }
/// <summary> /// Generates a C# property. /// </summary> public static void GenerateProperty( SourceBuilder sb, string className, string propertyName, LexiconDefinition def, string currentNsid, TypeRegistry registry, List<string> requiredProps, List<string> nullableProps, bool isRecord = false) { var isRequired = requiredProps.Contains(propertyName) || def.IsRequired; var isNullable = nullableProps.Contains(propertyName) || !isRequired; var csharpName = NsidHelper.ToPascalCase(propertyName);
// If property name matches class name, add a suffix to avoid C# error // Check before escaping to handle cases where both would be escaped identically var cleanClassName = NsidHelper.StripEscapePrefix(className); if (csharpName.Equals(cleanClassName, StringComparison.OrdinalIgnoreCase)) { csharpName = csharpName + "Value"; }
// Records auto-generate a "Type" property for the $type discriminator, // so rename any lexicon property that would also become "Type" if (isRecord && csharpName == "Type") { csharpName = "TypeValue"; }
csharpName = NsidHelper.EscapeIdentifier(csharpName);
sb.WriteSummary(def.Description);
// JSON property name attribute sb.WriteAttribute($"System.Text.Json.Serialization.JsonPropertyName(\"{propertyName}\")");
// Add validation attributes WriteValidationAttributes(sb, def);
// Get the C# type var typeName = GetPropertyType(def, currentNsid, registry, className, propertyName);
// Handle nullable if (isNullable && !typeName.EndsWith("?")) { typeName = MakeNullable(typeName); }
// Build property declaration var required = isRequired ? "required " : ""; var defaultValue = GetDefaultValue(def);
if (defaultValue != null && !isRequired) { sb.AppendLine($"public {typeName} {csharpName} {{ get; set; }} = {defaultValue};"); } else if (isRequired) { // Properties that are both required and nullable keep the nullable type var propTypeName = isNullable ? typeName : typeName.TrimEnd('?'); sb.AppendLine($"public {required}{propTypeName} {csharpName} {{ get; set; }}"); } else { sb.AppendLine($"public {typeName} {csharpName} {{ get; set; }}"); }
sb.AppendLine(); }
/// <summary> /// Writes validation attributes based on lexicon constraints. /// Uses AOT-safe custom attributes from CarpaNet.Validation. /// </summary> private static void WriteValidationAttributes(SourceBuilder sb, LexiconDefinition def) { // String length validation (for strings and bytes) if (def.Type == "string" || def.Type == "bytes") { if (def.MinLength.HasValue || def.MaxLength.HasValue) { var minLength = def.MinLength ?? 0; var maxLength = def.MaxLength ?? int.MaxValue; sb.WriteAttribute($"CarpaNet.Validation.ATStringLength({maxLength}, MinimumLength = {minLength})"); } else if (def.MaxGraphemes.HasValue) { // MaxGraphemes is a hint for grapheme clusters, use as approximate max length sb.WriteAttribute($"CarpaNet.Validation.ATMaxLength({def.MaxGraphemes.Value})"); } }
// Integer range validation if (def.Type == "integer") { if (def.Minimum.HasValue || def.Maximum.HasValue) { var minimum = def.Minimum ?? long.MinValue; var maximum = def.Maximum ?? long.MaxValue; sb.WriteAttribute($"CarpaNet.Validation.ATRange({minimum}, {maximum})"); } }
// Array length validation if (def.Type == "array") { if (def.MinLength.HasValue || def.MaxLength.HasValue) { if (def.MaxLength.HasValue) { sb.WriteAttribute($"CarpaNet.Validation.ATMaxLength({def.MaxLength.Value})"); } if (def.MinLength.HasValue) { sb.WriteAttribute($"CarpaNet.Validation.ATMinLength({def.MinLength.Value})"); } } } }
/// <summary> /// Gets the C# type for a property, handling unions and refs via the registry. /// </summary> private static string GetPropertyType( LexiconDefinition def, string currentNsid, TypeRegistry registry, string className, string propertyName) { return def.Type switch { "boolean" => "bool", "integer" => "long", "string" => MapStringType(def), "bytes" => "byte[]", "cid-link" => "CarpaNet.ATCid", "blob" => "CarpaNet.ATBlob", "unknown" => "System.Text.Json.JsonElement", "token" => "string", "ref" => registry.ResolveToCSharpType(def.Ref, currentNsid), "union" when def.Closed != true && (def.Refs == null || def.Refs.Count == 0) => "System.Text.Json.JsonElement", "union" => GenerateUnionInterfaceName(className, propertyName), "array" => GetArrayType(def, currentNsid, registry, className, propertyName), "object" => "object", // Inline objects - would need special handling _ => "object" }; }
/// <summary> /// Gets the C# type for an array. /// </summary> private static string GetArrayType( LexiconDefinition def, string currentNsid, TypeRegistry registry, string className, string propertyName) { if (def.Items == null) { return "System.Collections.Generic.List<object>"; }
var itemType = GetPropertyType(def.Items, currentNsid, registry, className, propertyName); return $"System.Collections.Generic.List<{itemType}>"; }
/// <summary> /// Generates an interface name for a union property, scoped to the class. /// </summary> private static string GenerateUnionInterfaceName(string className, string propertyName) { // Strip @ prefix from className if present (for escaped keywords like @Event) var cleanClassName = NsidHelper.StripEscapePrefix(className); var cleanPropertyName = NsidHelper.StripEscapePrefix(NsidHelper.ToPascalCase(propertyName)); return $"I{cleanClassName}{cleanPropertyName}"; }
/// <summary> /// Maps a string type with format to the appropriate C# type. /// </summary> private static string MapStringType(LexiconDefinition def) { if (def.Format == null) { return "string"; }
return def.Format switch { "at-identifier" => "CarpaNet.ATIdentifier", "at-uri" => "CarpaNet.ATUri", "cid" => "string", "datetime" => "System.DateTimeOffset", "did" => "CarpaNet.ATDid", "handle" => "CarpaNet.ATHandle", "nsid" => "string", "tid" => "string", "record-key" => "string", "uri" => "string", "language" => "string", _ => "string" }; }
/// <summary> /// Makes a type nullable. /// </summary> private static string MakeNullable(string typeName) { return typeName + "?"; }
/// <summary> /// Gets the default value for a type. /// </summary> private static string? GetDefaultValue(LexiconDefinition def) { if (!def.Default.HasValue) { return null; }
var jsonDefault = def.Default.Value;
return jsonDefault.ValueKind switch { System.Text.Json.JsonValueKind.True => "true", System.Text.Json.JsonValueKind.False => "false", System.Text.Json.JsonValueKind.Number => jsonDefault.GetRawText(), System.Text.Json.JsonValueKind.String => $"\"{jsonDefault.GetString()}\"", System.Text.Json.JsonValueKind.Null => "null", _ => null }; }}