// #nullable enable using System; using System.Collections.Generic; using System.Linq; using CarpaNet.Models; using CarpaNet.Utilities; namespace CarpaNet.Generation; /// /// Generates C# classes from Lexicon object definitions. /// public static class ObjectGenerator { /// /// Generates a C# class for a Lexicon object type. /// 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(); var nullableProps = def.Nullable ?? new List(); var properties = def.Properties ?? new Dictionary(); // 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(); } /// /// Generates inline union interfaces for properties with union types. /// private static void GenerateInlineUnionInterfaces( SourceBuilder sb, string className, Dictionary 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(); } } } /// /// Generates a C# property. /// public static void GenerateProperty( SourceBuilder sb, string className, string propertyName, LexiconDefinition def, string currentNsid, TypeRegistry registry, List requiredProps, List 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(); } /// /// Writes validation attributes based on lexicon constraints. /// Uses AOT-safe custom attributes from CarpaNet.Validation. /// 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})"); } } } } /// /// Gets the C# type for a property, handling unions and refs via the registry. /// 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" }; } /// /// Gets the C# type for an array. /// private static string GetArrayType( LexiconDefinition def, string currentNsid, TypeRegistry registry, string className, string propertyName) { if (def.Items == null) { return "System.Collections.Generic.List"; } var itemType = GetPropertyType(def.Items, currentNsid, registry, className, propertyName); return $"System.Collections.Generic.List<{itemType}>"; } /// /// Generates an interface name for a union property, scoped to the class. /// 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}"; } /// /// Maps a string type with format to the appropriate C# type. /// 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" }; } /// /// Makes a type nullable. /// private static string MakeNullable(string typeName) { return typeName + "?"; } /// /// Gets the default value for a type. /// 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 }; } }