//
#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