using System;
using System.Collections.Generic;
using System.Linq;
using CarpaNet.Models;
using CarpaNet.Utilities;
namespace CarpaNet.Generation;
///
/// Generates CBOR serialization context and type info classes.
/// Follows the same structural pattern as JsonContextGenerator: all CborTypeInfo classes
/// are emitted into a single namespace with encoded class names (e.g., AppBsky_Actor_DefsProfileViewBasicCborTypeInfo).
///
public static class CborContextGenerator
{
///
/// Converts a fully-qualified type name to a safe class name suffix.
/// Replaces dots with underscores, strips @ escapes.
/// Example: "AppBsky.Actor.DefsProfileViewBasic" -> "AppBsky_Actor_DefsProfileViewBasic"
///
public static string ToClassSuffix(string qualifiedTypeName)
{
return qualifiedTypeName.Replace(".", "_").Replace("@", "");
}
///
/// Generates a CborObjectTypeInfo subclass for an object or record type.
///
/// Source builder.
/// Fully qualified C# type name (e.g., "AppBsky.Actor.DefsProfileViewBasic").
/// Encoded name for the CborTypeInfo class (no dots).
/// Lexicon definition for the type.
/// Current NSID context.
/// Type registry.
/// Generator options.
/// Whether this is a record type with $type discriminator.
/// Set to track already-generated types.
public static void GenerateCborTypeInfo(
SourceBuilder sb,
string qualifiedTypeName,
string classSuffix,
LexiconDefinition def,
string currentNsid,
TypeRegistry registry,
GeneratorOptions options,
bool isRecord = false,
HashSet? generatedTypes = null)
{
generatedTypes ??= new HashSet();
if (!generatedTypes.Add(classSuffix))
{
return;
}
var properties = def.Properties ?? new Dictionary();
var requiredProps = new HashSet(def.Required ?? Enumerable.Empty());
// Extract short class name and namespace for property type resolution
var shortClassName = ExtractShortName(qualifiedTypeName);
var typeNamespace = ExtractNamespace(qualifiedTypeName);
// Generate nested type infos first (inline objects, unions)
foreach (var prop in properties)
{
GenerateNestedTypeInfosForProperty(sb, qualifiedTypeName, classSuffix, prop.Key, prop.Value, currentNsid, registry, options, generatedTypes);
}
var globalType = ResolveToGlobalType(qualifiedTypeName);
sb.WriteSummary($"CBOR type info for {shortClassName}.");
sb.AppendLine($"public sealed class {classSuffix}CborTypeInfo : CarpaNet.Cbor.CborObjectTypeInfo<{globalType}>");
sb.OpenBrace();
// CreateInstance override using Activator to bypass required member checks
sb.AppendLine($"public override {globalType} CreateInstance() => ({globalType})System.Activator.CreateInstance(typeof({globalType}))!;");
sb.AppendLine();
// Type discriminator for records
if (isRecord)
{
sb.AppendLine($"public override string? TypeDiscriminator => \"{currentNsid}\";");
sb.AppendLine();
}
// Properties array
sb.AppendLine($"private static readonly CarpaNet.Cbor.CborPropertyInfo<{globalType}>[] _properties = new CarpaNet.Cbor.CborPropertyInfo<{globalType}>[]");
sb.OpenBrace();
var propList = properties.ToList();
for (int i = 0; i < propList.Count; i++)
{
var prop = propList[i];
var propName = NsidHelper.ToPascalCase(prop.Key);
var jsonName = prop.Key;
// Property name collision handling (matching ObjectGenerator/JsonContextGenerator)
var cleanClassName = NsidHelper.StripEscapePrefix(shortClassName);
if (propName.Equals(cleanClassName, 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);
var propType = GetPropertyCSharpType(prop.Value, currentNsid, registry, shortClassName, prop.Key, typeNamespace);
var converterExpr = GetConverterExpression(prop.Value, currentNsid, registry, shortClassName, prop.Key, typeNamespace, sb, options, generatedTypes, qualifiedTypeName, classSuffix);
var isRequired = requiredProps.Contains(prop.Key) || prop.Value.IsRequired;
var isNullable = IsNullableProperty(prop.Value, def, prop.Key);
var isValueType = !IsReferenceType(propType);
// Resolve property type for the CborPropertyInfo generic parameter
var globalPropType = ResolveToGlobalType(propType);
// Generate CborPropertyInfo with appropriate getter/setter for nullable handling
if (isNullable && isValueType && !propType.EndsWith("?"))
{
// Nullable value type: use non-nullable for CborPropertyInfo, getter uses GetValueOrDefault
sb.AppendLine($"new CarpaNet.Cbor.CborPropertyInfo<{globalType}, {globalPropType}>(");
sb.AppendLine($" \"{jsonName}\",");
sb.AppendLine($" obj => obj.{propName}.GetValueOrDefault(),");
sb.AppendLine($" (obj, val) => obj.{propName} = val,");
}
else if (isNullable && IsReferenceType(propType))
{
// Nullable reference type - use null-forgiving on getter to suppress CS8603
sb.AppendLine($"new CarpaNet.Cbor.CborPropertyInfo<{globalType}, {globalPropType}>(");
sb.AppendLine($" \"{jsonName}\",");
sb.AppendLine($" obj => obj.{propName}!,");
sb.AppendLine($" (obj, val) => obj.{propName} = val,");
}
else if (!isNullable && IsReferenceType(propType))
{
// Non-nullable reference type
sb.AppendLine($"new CarpaNet.Cbor.CborPropertyInfo<{globalType}, {globalPropType}>(");
sb.AppendLine($" \"{jsonName}\",");
sb.AppendLine($" obj => obj.{propName},");
sb.AppendLine($" (obj, val) => obj.{propName} = val ?? throw new System.InvalidOperationException(\"Property {propName} cannot be null\"),");
}
else
{
// Non-nullable value type
sb.AppendLine($"new CarpaNet.Cbor.CborPropertyInfo<{globalType}, {globalPropType}>(");
sb.AppendLine($" \"{jsonName}\",");
sb.AppendLine($" obj => obj.{propName},");
sb.AppendLine($" (obj, val) => obj.{propName} = val,");
}
sb.AppendLine($" {converterExpr},");
// ShouldSerialize predicate
if (isRequired)
{
sb.AppendLine(" _ => true)");
}
else if (isNullable && isValueType)
{
sb.AppendLine(" _ => true)");
}
else
{
sb.AppendLine(" val => val != null)");
}
if (i < propList.Count - 1)
{
sb.AppendLine(",");
}
}
sb.CloseBrace(withSemicolon: true);
sb.AppendLine();
sb.AppendLine($"protected override System.Collections.Generic.IReadOnlyList> Properties => _properties;");
sb.CloseBrace();
sb.AppendLine();
}
///
/// Generates a CborUnionTypeInfo subclass for a union type.
///
public static void GenerateCborUnionTypeInfo(
SourceBuilder sb,
string qualifiedTypeName,
string classSuffix,
List refs,
string currentNsid,
TypeRegistry registry,
GeneratorOptions options,
HashSet? generatedTypes = null)
{
generatedTypes ??= new HashSet();
if (!generatedTypes.Add(classSuffix))
{
return;
}
var globalType = ResolveToGlobalType(qualifiedTypeName);
sb.WriteSummary($"CBOR type info for union {qualifiedTypeName}.");
sb.AppendLine($"public sealed class {classSuffix}CborTypeInfo : CarpaNet.Cbor.CborUnionTypeInfo<{globalType}>");
sb.OpenBrace();
sb.AppendLine("private static readonly System.Collections.Generic.Dictionary _derivedTypes = new()");
sb.OpenBrace();
foreach (var refString in refs)
{
var typeName = registry.ResolveToCSharpType(refString, currentNsid);
typeName = QualifyUnionNames(typeName, refString, currentNsid, registry);
var discriminator = GetTypeDiscriminator(refString, currentNsid, registry);
if (registry.RefGeneratesClass(refString, currentNsid))
{
var refSuffix = ToClassSuffix(typeName);
sb.AppendLine($"{{ \"{discriminator}\", new {refSuffix}CborTypeInfo() }},");
}
}
sb.CloseBrace(withSemicolon: true);
sb.AppendLine();
sb.AppendLine("protected override System.Collections.Generic.IReadOnlyDictionary DerivedTypes => _derivedTypes;");
sb.CloseBrace();
sb.AppendLine();
}
///
/// Generates nested type infos for a property (handles inline objects, unions, array items).
///
private static void GenerateNestedTypeInfosForProperty(
SourceBuilder sb,
string parentQualifiedTypeName,
string parentClassSuffix,
string propertyName,
LexiconDefinition prop,
string currentNsid,
TypeRegistry registry,
GeneratorOptions options,
HashSet generatedTypes)
{
// 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 = $"{parentClassSuffix}_{pascalProp}";
GenerateCborTypeInfo(sb, nestedQualified, nestedSuffix, prop, currentNsid, registry, options, generatedTypes: generatedTypes);
}
// 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);
var shortParent = ExtractShortName(parentQualifiedTypeName);
var ns = ExtractNamespace(parentQualifiedTypeName);
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 = ToClassSuffix(interfaceQualified);
GenerateCborUnionTypeInfo(sb, interfaceQualified, interfaceSuffix, prop.Refs, currentNsid, registry, options, generatedTypes);
}
// Handle arrays
if (prop.Type == "array" && prop.Items != null)
{
// Arrays of inline objects
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 = $"{parentClassSuffix}_{pascalProp}Item";
GenerateCborTypeInfo(sb, nestedQualified, nestedSuffix, prop.Items, currentNsid, registry, options, generatedTypes: generatedTypes);
}
// Arrays of unions (no Item suffix, matching ObjectGenerator)
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 = ExtractShortName(parentQualifiedTypeName);
var ns = ExtractNamespace(parentQualifiedTypeName);
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 = ToClassSuffix(interfaceQualified);
GenerateCborUnionTypeInfo(sb, interfaceQualified, interfaceSuffix, prop.Items.Refs, currentNsid, registry, options, generatedTypes);
}
}
}
///
/// Gets the C# type for a property, fully qualified with namespace.
/// Mirrors JsonContextGenerator.GetPropertyCSharpType.
///
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",
"at-uri" => "CarpaNet.ATUri",
"did" => "CarpaNet.ATDid",
"handle" => "CarpaNet.ATHandle",
"at-identifier" => "CarpaNet.ATIdentifier",
"uri" => "string",
"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"
};
}
///
/// Gets the C# type for an array property.
///
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