// #nullable enable using System; using System.Collections.Generic; using CarpaNet.Models; using CarpaNet.Utilities; namespace CarpaNet; /// /// Represents the kind of type a Lexicon definition represents. /// public enum LexiconTypeKind { /// Unknown or unresolved type. Unknown, /// A primitive string type (may have format, knownValues, enum). String, /// A primitive boolean type. Boolean, /// A primitive integer type. Integer, /// A bytes type. Bytes, /// A CID link type. CidLink, /// A blob type. Blob, /// An object type (generates a class). Object, /// A record type (generates a class with $type). Record, /// A query type (HTTP GET). Query, /// A procedure type (HTTP POST). Procedure, /// A subscription type (WebSocket). Subscription, /// A union type (generates an interface). Union, /// A token type (symbolic constant). Token, /// An array type. Array, /// A ref type (reference to another definition). Ref, /// An unknown/any type. Any, /// Params type (query parameters). Params, } /// /// Information about a registered type. /// public sealed class TypeInfo { /// The full reference string (NSID#defName or NSID for main). public string FullRef { get; set; } = string.Empty; /// The NSID of the lexicon containing this type. public string Nsid { get; set; } = string.Empty; /// The definition name within the lexicon. public string DefName { get; set; } = string.Empty; /// The kind of type this represents. public LexiconTypeKind Kind { get; set; } /// The C# namespace for this type. public string CSharpNamespace { get; set; } = string.Empty; /// The C# type name (class/interface name). public string CSharpTypeName { get; set; } = string.Empty; /// The fully qualified C# type name. public string FullCSharpTypeName => $"{CSharpNamespace}.{CSharpTypeName}"; /// The original Lexicon definition. public LexiconDefinition? Definition { get; set; } /// For union types, the list of variant refs. public List? UnionRefs { get; set; } /// Whether this type should generate a class (vs being mapped to a primitive). public bool GeneratesClass => Kind == LexiconTypeKind.Object || Kind == LexiconTypeKind.Record || Kind == LexiconTypeKind.Query || Kind == LexiconTypeKind.Procedure || Kind == LexiconTypeKind.Subscription; /// Whether this type should generate an interface (union). public bool GeneratesInterface => Kind == LexiconTypeKind.Union; /// Whether this type maps to a primitive C# type. public bool IsPrimitive => Kind == LexiconTypeKind.String || Kind == LexiconTypeKind.Boolean || Kind == LexiconTypeKind.Integer || Kind == LexiconTypeKind.Bytes || Kind == LexiconTypeKind.CidLink || Kind == LexiconTypeKind.Blob || Kind == LexiconTypeKind.Token || Kind == LexiconTypeKind.Any; } /// /// Registry that tracks all Lexicon type definitions and their resolved C# types. /// public sealed class TypeRegistry { private readonly Dictionary _types = new(StringComparer.Ordinal); private readonly HashSet _unresolvedRefs = new(StringComparer.Ordinal); private readonly string? _rootNamespace; public TypeRegistry(string? rootNamespace = null) { _rootNamespace = rootNamespace; } /// /// Registers all definitions from a lexicon document. /// public void RegisterDocument(LexiconDocument document) { var nsid = document.Id; var ns = NsidHelper.ToNamespace(nsid, _rootNamespace); foreach (var def in document.Defs) { var defName = def.Key; var defValue = def.Value; // Build the full reference var fullRef = defName == "main" ? nsid : $"{nsid}#{defName}"; // Determine the C# type name (escaped for C# keywords) // For non-main definitions, prefix with the main type name to avoid collisions var mainTypeName = NsidHelper.ToTypeName(nsid); var rawTypeName = defName == "main" ? mainTypeName : mainTypeName + NsidHelper.ToPascalCase(defName); var csharpTypeName = NsidHelper.EscapeIdentifier(rawTypeName); var typeInfo = new TypeInfo { FullRef = fullRef, Nsid = nsid, DefName = defName, CSharpNamespace = ns, CSharpTypeName = csharpTypeName, Definition = defValue, Kind = GetTypeKind(defValue), }; // For unions, track the variant refs if (typeInfo.Kind == LexiconTypeKind.Union && defValue.Refs != null) { typeInfo.UnionRefs = new List(defValue.Refs); } _types[fullRef] = typeInfo; // For main definitions, register under multiple keys for lookup flexibility if (defName == "main") { // Also register without fragment (just nsid) if (!_types.ContainsKey(nsid)) { _types[nsid] = typeInfo; } // Also register with explicit #main suffix var mainRef = $"{nsid}#main"; if (!_types.ContainsKey(mainRef)) { _types[mainRef] = typeInfo; } } } } /// /// Gets the type kind for a definition. /// private static LexiconTypeKind GetTypeKind(LexiconDefinition def) { return def.Type switch { "string" => LexiconTypeKind.String, "boolean" => LexiconTypeKind.Boolean, "integer" => LexiconTypeKind.Integer, "bytes" => LexiconTypeKind.Bytes, "cid-link" => LexiconTypeKind.CidLink, "blob" => LexiconTypeKind.Blob, "object" => LexiconTypeKind.Object, "record" => LexiconTypeKind.Record, "query" => LexiconTypeKind.Query, "procedure" => LexiconTypeKind.Procedure, "subscription" => LexiconTypeKind.Subscription, "union" => LexiconTypeKind.Union, "token" => LexiconTypeKind.Token, "array" => LexiconTypeKind.Array, "ref" => LexiconTypeKind.Ref, "unknown" => LexiconTypeKind.Any, "params" => LexiconTypeKind.Params, _ => LexiconTypeKind.Unknown }; } /// /// Looks up a type by its reference string. /// public TypeInfo? Lookup(string refString) { if (string.IsNullOrEmpty(refString)) { return null; } _types.TryGetValue(refString, out var typeInfo); return typeInfo; } /// /// Resolves a reference string to its C# type, handling primitives correctly. /// /// The reference string (e.g., "app.bsky.actor.defs#mutedWordTarget") /// The NSID of the current lexicon (for local refs) /// The C# type string to use. public string ResolveToCSharpType(string? refString, string currentNsid) { if (string.IsNullOrEmpty(refString)) { return "object"; } // Resolve local refs var fullRef = ResolveLocalRef(refString!, currentNsid); // Look up the type var typeInfo = Lookup(fullRef); if (typeInfo == null) { // Track unresolved external references if (!refString!.StartsWith("#")) { _unresolvedRefs.Add(fullRef); } // Unknown type - fall back to generating a type name return NsidHelper.RefToFullTypeName(refString!, currentNsid, _rootNamespace); } // Map to C# type based on kind return typeInfo.Kind switch { LexiconTypeKind.String => MapStringType(typeInfo.Definition), LexiconTypeKind.Boolean => "bool", LexiconTypeKind.Integer => "long", LexiconTypeKind.Bytes => "byte[]", LexiconTypeKind.CidLink => "CarpaNet.ATCid", LexiconTypeKind.Blob => "CarpaNet.ATBlob", LexiconTypeKind.Token => "string", // Tokens are just string constants LexiconTypeKind.Any => "System.Text.Json.JsonElement", LexiconTypeKind.Object => typeInfo.FullCSharpTypeName, LexiconTypeKind.Record => typeInfo.FullCSharpTypeName, LexiconTypeKind.Union => $"I{typeInfo.CSharpTypeName}", // Unions become interfaces // For array types, resolve the item type LexiconTypeKind.Array => ResolveArrayType(typeInfo, currentNsid), // For ref types, recursively resolve LexiconTypeKind.Ref when typeInfo.Definition?.Ref != null => ResolveToCSharpType(typeInfo.Definition.Ref, typeInfo.Nsid), _ => typeInfo.FullCSharpTypeName }; } /// /// Resolves a lexicon ref string to a fully-qualified C# type name. /// Unlike ResolveToCSharpType, this always includes the namespace for union interfaces. /// Used by CBOR context generation where types are in namespace blocks. /// public string ResolveToFullyQualifiedCSharpType(string? refString, string currentNsid) { if (string.IsNullOrEmpty(refString)) { return "object"; } var fullRef = ResolveLocalRef(refString!, currentNsid); var typeInfo = Lookup(fullRef); if (typeInfo == null) { // Track unresolved external references if (!refString!.StartsWith("#")) { _unresolvedRefs.Add(fullRef); } return NsidHelper.RefToFullTypeName(refString!, currentNsid, _rootNamespace); } return typeInfo.Kind switch { LexiconTypeKind.String => MapStringType(typeInfo.Definition), LexiconTypeKind.Boolean => "bool", LexiconTypeKind.Integer => "long", LexiconTypeKind.Bytes => "byte[]", LexiconTypeKind.CidLink => "CarpaNet.ATCid", LexiconTypeKind.Blob => "CarpaNet.ATBlob", LexiconTypeKind.Token => "string", LexiconTypeKind.Any => "System.Text.Json.JsonElement", LexiconTypeKind.Object => typeInfo.FullCSharpTypeName, LexiconTypeKind.Record => typeInfo.FullCSharpTypeName, LexiconTypeKind.Union => $"{typeInfo.CSharpNamespace}.I{typeInfo.CSharpTypeName}", LexiconTypeKind.Array => ResolveFullyQualifiedArrayType(typeInfo, currentNsid), LexiconTypeKind.Ref when typeInfo.Definition?.Ref != null => ResolveToFullyQualifiedCSharpType(typeInfo.Definition.Ref, typeInfo.Nsid), _ => typeInfo.FullCSharpTypeName }; } /// /// Resolves an array type to a fully-qualified C# equivalent. /// private string ResolveFullyQualifiedArrayType(TypeInfo typeInfo, string currentNsid) { if (typeInfo.Definition?.Items == null) { return "System.Collections.Generic.List"; } var items = typeInfo.Definition.Items; var itemType = items.Type switch { "ref" when items.Ref != null => ResolveToFullyQualifiedCSharpType(items.Ref, typeInfo.Nsid), "union" when items.Refs != null => $"{typeInfo.CSharpNamespace}.I{typeInfo.CSharpTypeName}", "string" => MapStringType(items), "integer" => "long", "boolean" => "bool", _ => "object" }; return $"System.Collections.Generic.List<{itemType}>"; } /// /// Resolves a local reference (#name) to a full reference. /// private static string ResolveLocalRef(string refString, string currentNsid) { if (refString.StartsWith("#")) { return $"{currentNsid}{refString}"; } return refString; } /// /// Maps a string type to its C# equivalent based on format. /// 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" }; } /// /// Resolves an array type to its C# equivalent. /// private string ResolveArrayType(TypeInfo typeInfo, string currentNsid) { if (typeInfo.Definition?.Items == null) { return "System.Collections.Generic.List"; } var items = typeInfo.Definition.Items; // Handle different item types var itemType = items.Type switch { "ref" when items.Ref != null => ResolveToCSharpType(items.Ref, typeInfo.Nsid), "union" when items.Refs != null => $"I{typeInfo.CSharpTypeName}", // Generate interface name for union items "string" => MapStringType(items), "integer" => "long", "boolean" => "bool", _ => "object" }; return $"System.Collections.Generic.List<{itemType}>"; } /// /// Gets all registered types. /// public IEnumerable GetAllTypes() => _types.Values; /// /// Gets all unresolved external references encountered during type resolution. /// Each entry is the full ref string (e.g. "app.bsky.actor.defs#profileViewBasic"). /// public IReadOnlyCollection GetUnresolvedReferences() => _unresolvedRefs; /// /// Gets types grouped by namespace. /// public Dictionary> GetTypesByNamespace() { var result = new Dictionary>(); foreach (var type in _types.Values) { if (!result.TryGetValue(type.CSharpNamespace, out var list)) { list = new List(); result[type.CSharpNamespace] = list; } // Avoid duplicates (main definitions are registered twice) if (!list.Exists(t => t.FullRef == type.FullRef)) { list.Add(type); } } return result; } /// /// Checks if a reference points to a type that generates a class. /// public bool RefGeneratesClass(string refString, string currentNsid) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = Lookup(fullRef); return typeInfo?.GeneratesClass ?? false; } /// /// Checks if a reference points to a union type. /// public bool RefIsUnion(string refString, string currentNsid) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = Lookup(fullRef); return typeInfo?.Kind == LexiconTypeKind.Union; } /// /// Gets the type kind for a reference. /// public LexiconTypeKind GetRefKind(string refString, string currentNsid) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = Lookup(fullRef); return typeInfo?.Kind ?? LexiconTypeKind.Unknown; } /// /// Gets the union variants (ref strings) for a union type. /// /// The reference to the union type. /// The current NSID context for resolving local refs. /// List of variant refs, or null if not a union type. public List? GetUnionVariants(string refString, string currentNsid) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = Lookup(fullRef); if (typeInfo?.Kind != LexiconTypeKind.Union) { return null; } return typeInfo.UnionRefs; } /// /// Gets all union variants with their resolved C# type names and discriminators. /// /// The reference to the union type. /// The current NSID context for resolving local refs. /// List of (CSharpTypeName, Discriminator) tuples for each variant. public List<(string CSharpType, string Discriminator)>? GetUnionVariantDetails(string refString, string currentNsid) { var variants = GetUnionVariants(refString, currentNsid); if (variants == null) { return null; } var result = new List<(string, string)>(); var unionFullRef = ResolveLocalRef(refString, currentNsid); var unionTypeInfo = Lookup(unionFullRef); foreach (var variantRef in variants) { var variantFullRef = ResolveLocalRef(variantRef, unionTypeInfo?.Nsid ?? currentNsid); var variantTypeInfo = Lookup(variantFullRef); var csharpType = ResolveToCSharpType(variantRef, unionTypeInfo?.Nsid ?? currentNsid); var discriminator = variantTypeInfo?.FullRef ?? variantFullRef; result.Add((csharpType, discriminator)); } return result; } /// /// Checks if a type has any union-typed properties. /// /// The reference to check. /// The current NSID context. /// True if the type has union properties. public bool HasUnionProperties(string refString, string currentNsid) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = Lookup(fullRef); if (typeInfo?.Definition?.Properties == null) { return false; } foreach (var prop in typeInfo.Definition.Properties.Values) { if (prop.Type == "union") { return true; } if (prop.Type == "array" && prop.Items?.Type == "union") { return true; } if (!string.IsNullOrEmpty(prop.Ref)) { var refKind = GetRefKind(prop.Ref!, typeInfo.Nsid); if (refKind == LexiconTypeKind.Union) { return true; } } } return false; } /// /// Gets the type discriminator (full NSID) for a type reference. /// Used for polymorphic serialization. /// /// The reference string. /// The current NSID context. /// The type discriminator string. public string GetTypeDiscriminator(string refString, string currentNsid) { var fullRef = ResolveLocalRef(refString, currentNsid); var typeInfo = Lookup(fullRef); return typeInfo?.FullRef ?? fullRef; } }