// #nullable enable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using CarpaNet.Generation; using CarpaNet.Models; using CarpaNet.Parsing; using CarpaNet.Utilities; namespace CarpaNet; /// /// Configuration options for the generator. /// public sealed class GeneratorOptions { /// /// Optional root namespace to prefix all generated namespaces. /// public string? RootNamespace { get; set; } /// /// Whether to emit validation attributes. Default is true. /// public bool EmitValidationAttributes { get; set; } = true; /// /// Name of the generated CBOR serializer context class. Default is "ATProtoCborContext". /// public string CborContextName { get; set; } = "ATProtoCborContext"; /// /// Name of the generated JSON resolver context class. Default is "ATProtoJsonContext". /// public string JsonContextName { get; set; } = "ATProtoJsonContext"; /// /// Whether to emit XRPC server endpoint controllers. Default is false. /// public bool EmitXrpcEndpoints { get; set; } = false; } /// /// Roslyn Incremental Source Generator for ATProtocol Lexicon files. /// [Generator(LanguageNames.CSharp)] public sealed class LexiconGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) { // Filter to only files marked as LexiconFiles (via IsATProtoLexicon metadata) var lexiconFiles = context.AdditionalTextsProvider .Combine(context.AnalyzerConfigOptionsProvider) .Where(static pair => { var (file, optionsProvider) = pair; var options = optionsProvider.GetOptions(file); return options.TryGetValue("build_metadata.AdditionalFiles.IsATProtoLexicon", out var isLexicon) && isLexicon.Equals("true", StringComparison.OrdinalIgnoreCase); }) .Select(static (pair, _) => pair.Left); // Parse each lexicon file var lexicons = lexiconFiles.Select(static (file, ct) => { var content = file.GetText(ct)?.ToString(); var document = LexiconParser.Parse(content); return (Path: file.Path, Document: document); }).Where(static x => x.Document != null); // Collect all lexicons var allLexicons = lexicons.Collect(); // Get configuration from MSBuild properties var configOptions = context.AnalyzerConfigOptionsProvider.Select(static (provider, _) => { var options = new GeneratorOptions(); if (provider.GlobalOptions.TryGetValue("build_property.CarpaNet_RootNamespace", out var rootNs) && !string.IsNullOrWhiteSpace(rootNs)) { options.RootNamespace = rootNs; } if (provider.GlobalOptions.TryGetValue("build_property.CarpaNet_EmitValidationAttributes", out var emitValidation) && bool.TryParse(emitValidation, out var emitValidationValue)) { options.EmitValidationAttributes = emitValidationValue; } if (provider.GlobalOptions.TryGetValue("build_property.CarpaNet_CborContextName", out var cborContextName) && !string.IsNullOrWhiteSpace(cborContextName)) { options.CborContextName = cborContextName; } if (provider.GlobalOptions.TryGetValue("build_property.CarpaNet_JsonContextName", out var jsonContextName) && !string.IsNullOrWhiteSpace(jsonContextName)) { options.JsonContextName = jsonContextName; } if (provider.GlobalOptions.TryGetValue("build_property.CarpaNet_EmitXrpcEndpoints", out var emitXrpc) && bool.TryParse(emitXrpc, out var emitXrpcValue)) { options.EmitXrpcEndpoints = emitXrpcValue; } return options; }); // Combine lexicons with configuration var combined = allLexicons.Combine(configOptions); // Register source output context.RegisterSourceOutput(combined, static (ctx, data) => GenerateSource(ctx, data.Left, data.Right)); } private static void GenerateSource( SourceProductionContext context, ImmutableArray<(string Path, LexiconDocument? Document)> lexicons, GeneratorOptions options) { if (lexicons.IsDefaultOrEmpty) { return; } var rootNamespace = options.RootNamespace; // PHASE 1: Build type registry from all documents var registry = new TypeRegistry(rootNamespace); var documents = new List(); foreach (var (path, document) in lexicons) { if (document == null) continue; documents.Add(document); registry.RegisterDocument(document); } // PHASE 2: Group by namespace var byNamespace = new Dictionary>(); foreach (var document in documents) { var ns = NsidHelper.ToNamespace(document.Id, rootNamespace); if (!byNamespace.TryGetValue(ns, out var list)) { list = new List<(string, LexiconDocument)>(); byNamespace[ns] = list; } list.Add((document.Id, document)); } // PHASE 3: Generate source for each namespace foreach (var kvp in byNamespace) { var source = GenerateNamespaceSource(kvp.Key, kvp.Value, registry, context, options); if (!string.IsNullOrEmpty(source)) { var fileName = kvp.Key.Replace(".", "_") + ".g.cs"; context.AddSource(fileName, SourceText.From(source, Encoding.UTF8)); } } // PHASE 3.5: Generate union interface implementations for cross-namespace types var unionMappings = CollectUnionImplementations(byNamespace, registry); var unionImplSource = GenerateUnionImplementationsSource(unionMappings); if (!string.IsNullOrEmpty(unionImplSource)) { context.AddSource("UnionImplementations.g.cs", SourceText.From(unionImplSource, Encoding.UTF8)); } // PHASE 4: Generate API extensions file var extensionsSource = GenerateExtensionsSource(byNamespace, registry, context, options); if (!string.IsNullOrEmpty(extensionsSource)) { context.AddSource("ATProtoExtensions.g.cs", SourceText.From(extensionsSource, Encoding.UTF8)); } // PHASE 5: Generate CBOR serialization context var cborSource = GenerateCborContextSource(byNamespace, registry, context, options); if (!string.IsNullOrEmpty(cborSource)) { context.AddSource("ATProtoCborContext.g.cs", SourceText.From(cborSource, Encoding.UTF8)); } // PHASE 6: Generate JSON serialization context var (jsonSource, concreteTypes) = GenerateJsonContextSource(byNamespace, registry, context, options); if (!string.IsNullOrEmpty(jsonSource)) { context.AddSource($"{options.JsonContextName}.g.cs", SourceText.From(jsonSource, Encoding.UTF8)); } // PHASE 6.5: Generate ToJson()/FromJson() serialization helper methods on concrete types var serializationMethodsSource = GenerateSerializationMethodsSource(concreteTypes, options); if (!string.IsNullOrEmpty(serializationMethodsSource)) { context.AddSource("SerializationMethods.g.cs", SourceText.From(serializationMethodsSource, Encoding.UTF8)); } // PHASE 7: Generate client factory class var factorySource = GenerateFactorySource(options); if (!string.IsNullOrEmpty(factorySource)) { context.AddSource("ATProtoClientFactory.g.cs", SourceText.From(factorySource, Encoding.UTF8)); } // PHASE 8: Generate XRPC endpoint controllers (opt-in) if (options.EmitXrpcEndpoints) { var xrpcSource = XrpcEndpointGenerator.Generate(byNamespace, registry, options); if (!string.IsNullOrEmpty(xrpcSource)) { context.AddSource("XrpcControllers.g.cs", SourceText.From(xrpcSource, Encoding.UTF8)); } } // PHASE 9: Report diagnostics for unresolved lexicon references var unresolvedRefs = registry.GetUnresolvedReferences(); if (unresolvedRefs.Count > 0) { // Group by NSID (the part before #) to deduplicate and give actionable info var unresolvedByNsid = new Dictionary>(StringComparer.Ordinal); foreach (var fullRef in unresolvedRefs) { var hashIndex = fullRef.IndexOf('#'); var nsid = hashIndex >= 0 ? fullRef.Substring(0, hashIndex) : fullRef; if (!unresolvedByNsid.TryGetValue(nsid, out var list)) { list = new List(); unresolvedByNsid[nsid] = list; } list.Add(fullRef); } foreach (var kvp in unresolvedByNsid) { var nsid = kvp.Key; var refs = string.Join(", ", kvp.Value); context.ReportDiagnostic(Diagnostic.Create( new DiagnosticDescriptor( "ATPG002", "Unresolved Lexicon Reference", "Lexicon '{0}' is referenced but not included in the project. Unresolved references: {1}. Add the corresponding lexicon JSON file to resolve this.", "CarpaNet", DiagnosticSeverity.Warning, isEnabledByDefault: true), Location.None, nsid, refs)); } } } private static string GenerateNamespaceSource( string ns, List<(string Nsid, LexiconDocument Doc)> documents, TypeRegistry registry, SourceProductionContext context, GeneratorOptions options) { var sb = new SourceBuilder(); sb.WriteHeader(); sb.WriteUsing("System"); sb.WriteUsing("System.Collections.Generic"); sb.WriteUsing("CarpaNet.Validation"); sb.WriteUsing("System.Text.Json.Serialization"); sb.AppendLine(); sb.WriteNamespace(ns); foreach (var (nsid, doc) in documents) { try { GenerateDefinitions(sb, nsid, doc, ns, registry, context); } catch (Exception ex) { context.ReportDiagnostic(Diagnostic.Create( new DiagnosticDescriptor( "ATPG001", "Generation Error", "Error generating code for {0}: {1}", "CarpaNet", DiagnosticSeverity.Warning, isEnabledByDefault: true), Location.None, nsid, ex.Message)); } } return sb.ToString(); } private static void GenerateDefinitions( SourceBuilder sb, string nsid, LexiconDocument doc, string currentNamespace, TypeRegistry registry, SourceProductionContext context) { foreach (var def in doc.Defs) { var defName = def.Key; var defValue = def.Value; // Determine class name - prefix non-main defs with main type name to avoid collisions var mainTypeName = NsidHelper.ToTypeName(nsid); var className = defName == "main" ? mainTypeName : mainTypeName + NsidHelper.ToPascalCase(defName); switch (defValue.Type) { case "record": GenerateRecordType(sb, className, defValue, nsid, registry); break; case "query": GenerateQueryType(sb, className, defValue, nsid, currentNamespace, registry); break; case "procedure": GenerateProcedureType(sb, className, defValue, nsid, currentNamespace, registry); break; case "subscription": GenerateSubscriptionType(sb, className, defValue, nsid, currentNamespace, registry); break; case "object": var objectTypeId = defName == "main" ? nsid : $"{nsid}#{defName}"; ObjectGenerator.GenerateClass(sb, className, defValue, nsid, registry, typeId: objectTypeId); sb.AppendLine(); break; case "array": // Array types with union items need to generate the union interface if (defValue.Items?.Type == "union" && defValue.Items.Refs != null && !(defValue.Items.Closed != true && defValue.Items.Refs.Count == 0)) { var interfaceName = $"I{className}"; UnionGenerator.GenerateUnionInterface(sb, interfaceName, defValue.Items, nsid, registry); sb.AppendLine(); } break; case "string": // String types with knownValues/enum are handled as string primitives // No class generation needed - refs resolve to "string" break; case "token": // Tokens are string constants - refs resolve to "string" // Optionally generate a static class with the token value GenerateToken(sb, className, defValue, nsid); break; } } } private static void GenerateRecordType( SourceBuilder sb, string className, LexiconDefinition def, string nsid, TypeRegistry registry) { if (def.Record == null) { return; } ObjectGenerator.GenerateClass( sb, className, def.Record, nsid, registry, isRecord: true, recordType: nsid, typeId: nsid); sb.AppendLine(); } private static void GenerateQueryType( SourceBuilder sb, string className, LexiconDefinition def, string nsid, string currentNamespace, TypeRegistry registry) { // Generate parameters class if needed if (def.Parameters?.Properties != null && def.Parameters.Properties.Count > 0) { ApiGenerator.GenerateParametersClass(sb, className, def, nsid, registry); sb.AppendLine(); } // Generate output class (skip if schema is a direct ref — the referenced type already exists) if (def.Output?.Schema != null && !ApiGenerator.IsOutputRef(def)) { ApiGenerator.GenerateOutputClass(sb, className, def.Output, nsid, registry); sb.AppendLine(); } // Generate error constants if (def.Errors != null && def.Errors.Count > 0) { ApiGenerator.GenerateErrorClasses(sb, className, def.Errors, nsid); sb.AppendLine(); } } private static void GenerateProcedureType( SourceBuilder sb, string className, LexiconDefinition def, string nsid, string currentNamespace, TypeRegistry registry) { // Generate input class (skip if schema is a direct ref — the referenced type already exists) if (def.Input?.Schema != null && !ApiGenerator.IsInputRef(def)) { ApiGenerator.GenerateInputClass(sb, className, def.Input, nsid, registry); sb.AppendLine(); } // Generate output class (skip if schema is a direct ref — the referenced type already exists) if (def.Output?.Schema != null && !ApiGenerator.IsOutputRef(def)) { ApiGenerator.GenerateOutputClass(sb, className, def.Output, nsid, registry); sb.AppendLine(); } // Generate error constants if (def.Errors != null && def.Errors.Count > 0) { ApiGenerator.GenerateErrorClasses(sb, className, def.Errors, nsid); sb.AppendLine(); } } private static void GenerateSubscriptionType( SourceBuilder sb, string className, LexiconDefinition def, string nsid, string currentNamespace, TypeRegistry registry) { // Generate parameters class if needed if (def.Parameters?.Properties != null && def.Parameters.Properties.Count > 0) { ApiGenerator.GenerateParametersClass(sb, className, def, nsid, registry); sb.AppendLine(); } // Generate message types (interface only, extension goes in extensions file) if (def.Message?.Schema != null) { ApiGenerator.GenerateSubscriptionMessageTypes(sb, className, def, nsid, registry); sb.AppendLine(); } // Generate error constants if (def.Errors != null && def.Errors.Count > 0) { ApiGenerator.GenerateErrorClasses(sb, className, def.Errors, nsid); sb.AppendLine(); } } private static void GenerateToken( SourceBuilder sb, string className, LexiconDefinition def, string nsid) { sb.WriteSummary(def.Description ?? $"Token: {nsid}#{className}"); sb.AppendLine($"public static class {className}Token"); sb.OpenBrace(); sb.AppendLine($"public const string Value = \"{nsid}#{NsidHelper.ToCamelCase(className)}\";"); sb.CloseBrace(); sb.AppendLine(); } private static string GenerateExtensionsSource( Dictionary> byNamespace, TypeRegistry registry, SourceProductionContext context, GeneratorOptions options) { var sb = new SourceBuilder(); sb.WriteHeader(); sb.WriteUsing("System"); sb.WriteUsing("System.Collections.Generic"); sb.WriteUsing("System.Threading"); sb.WriteUsing("System.Threading.Tasks"); sb.AppendLine(); var extensionsNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet" : $"{options.RootNamespace}"; sb.WriteNamespace(extensionsNs); sb.WriteSummary("Extension methods for ATProto API calls."); sb.AppendLine("public static partial class ATProtoClientExtensions"); sb.OpenBrace(); foreach (var kvp in byNamespace) { var ns = kvp.Key; foreach (var (nsid, doc) in kvp.Value) { foreach (var def in doc.Defs) { if (def.Key != "main") continue; var className = NsidHelper.ToTypeName(nsid); switch (def.Value.Type) { case "query": ApiGenerator.GenerateQueryExtension(sb, className, def.Value, nsid, ns, registry); sb.AppendLine(); break; case "procedure": ApiGenerator.GenerateProcedureExtension(sb, className, def.Value, nsid, ns, registry); sb.AppendLine(); break; case "subscription": ApiGenerator.GenerateSubscriptionExtension(sb, className, def.Value, nsid, ns, registry); sb.AppendLine(); break; } } } } sb.CloseBrace(); return sb.ToString(); } private static string GenerateCborContextSource( Dictionary> byNamespace, TypeRegistry registry, SourceProductionContext context, GeneratorOptions options) { var sb = new SourceBuilder(); sb.WriteHeader(); sb.AppendLine(); var generatedTypes = new HashSet(); // Collect all type registrations: (ClassSuffix, QualifiedTypeName, TypeDiscriminator) var typesToRegister = new List<(string ClassSuffix, string QualifiedTypeName, string? TypeDiscriminator)>(); // Single namespace for all CBOR type info classes (matches JSON generator pattern) var contextNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet.Cbor" : $"{options.RootNamespace}.Cbor"; sb.WriteNamespace(contextNs); // Iterate all namespaces and types to generate CborTypeInfo classes foreach (var kvp in byNamespace) { var ns = kvp.Key; foreach (var (nsid, doc) in kvp.Value) { foreach (var def in doc.Defs) { var defName = def.Key; var defValue = def.Value; var mainTypeName = NsidHelper.ToTypeName(nsid); var className = defName == "main" ? mainTypeName : mainTypeName + NsidHelper.ToPascalCase(defName); switch (defValue.Type) { case "record": if (defValue.Record != null) { var fullName = $"{ns}.{className}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborTypeInfo(sb, fullName, suffix, defValue.Record, nsid, registry, options, isRecord: true, generatedTypes: generatedTypes); typesToRegister.Add((suffix, fullName, nsid)); } break; case "object": { var fullName = $"{ns}.{className}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborTypeInfo(sb, fullName, suffix, defValue, nsid, registry, options, generatedTypes: generatedTypes); typesToRegister.Add((suffix, fullName, null)); break; } case "union": if (defValue.Refs != null && !(defValue.Closed != true && defValue.Refs.Count == 0)) { var interfaceName = $"I{className}"; var fullName = $"{ns}.{interfaceName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborUnionTypeInfo(sb, fullName, suffix, defValue.Refs, nsid, registry, options, generatedTypes); typesToRegister.Add((suffix, fullName, null)); } break; case "query": if (defValue.Output?.Schema != null && !ApiGenerator.IsOutputRef(defValue)) { var outputClassName = className + "Output"; var fullName = $"{ns}.{outputClassName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborTypeInfo(sb, fullName, suffix, defValue.Output.Schema, nsid, registry, options, generatedTypes: generatedTypes); typesToRegister.Add((suffix, fullName, null)); } break; case "procedure": if (defValue.Input?.Schema != null && !ApiGenerator.IsInputRef(defValue)) { var inputClassName = className + "Input"; var fullName = $"{ns}.{inputClassName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborTypeInfo(sb, fullName, suffix, defValue.Input.Schema, nsid, registry, options, generatedTypes: generatedTypes); typesToRegister.Add((suffix, fullName, null)); } if (defValue.Output?.Schema != null && !ApiGenerator.IsOutputRef(defValue)) { var outputClassName = className + "Output"; var fullName = $"{ns}.{outputClassName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborTypeInfo(sb, fullName, suffix, defValue.Output.Schema, nsid, registry, options, generatedTypes: generatedTypes); typesToRegister.Add((suffix, fullName, null)); } break; case "subscription": if (defValue.Parameters?.Properties != null && defValue.Parameters.Properties.Count > 0) { var paramsClassName = className + "Parameters"; var fullName = $"{ns}.{paramsClassName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborTypeInfo(sb, fullName, suffix, defValue.Parameters, nsid, registry, options, generatedTypes: generatedTypes); typesToRegister.Add((suffix, fullName, null)); } if (defValue.Message?.Schema?.Type == "union" && defValue.Message.Schema.Refs != null) { var interfaceName = $"I{className}Message"; var fullName = $"{ns}.{interfaceName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborUnionTypeInfo(sb, fullName, suffix, defValue.Message.Schema.Refs, nsid, registry, options, generatedTypes); typesToRegister.Add((suffix, fullName, null)); } break; case "array": if (defValue.Items?.Type == "union" && defValue.Items.Refs != null && !(defValue.Items.Closed != true && defValue.Items.Refs.Count == 0)) { var interfaceName = $"I{className}"; var fullName = $"{ns}.{interfaceName}"; var suffix = CborContextGenerator.ToClassSuffix(fullName); CborContextGenerator.GenerateCborUnionTypeInfo(sb, fullName, suffix, defValue.Items.Refs, nsid, registry, options, generatedTypes); typesToRegister.Add((suffix, fullName, null)); } break; } } } } // Generate the context class sb.WriteSummary("CBOR serialization context for all AT Protocol types."); sb.AppendLine($"public partial class {options.CborContextName} : CarpaNet.Cbor.CborSerializerContext"); sb.OpenBrace(); sb.WriteSummary("Gets the default singleton instance."); sb.AppendLine($"public static new {options.CborContextName} Default {{ get; }} = new {options.CborContextName}();"); sb.AppendLine(); sb.WriteSummary("Initializes a new instance and registers all AT Protocol types."); sb.AppendLine($"public {options.CborContextName}()"); sb.OpenBrace(); foreach (var type in typesToRegister) { sb.AppendLine($"RegisterTypeInfo(new {type.ClassSuffix}CborTypeInfo());"); if (!string.IsNullOrEmpty(type.TypeDiscriminator)) { sb.AppendLine($"RegisterDerivedType(\"{type.TypeDiscriminator}\", typeof(global::{type.QualifiedTypeName}));"); } } sb.CloseBrace(); // constructor sb.CloseBrace(); // class return sb.ToString(); } private static (string Source, HashSet ConcreteTypes) GenerateJsonContextSource( Dictionary> byNamespace, TypeRegistry registry, SourceProductionContext context, GeneratorOptions options) { var sb = new SourceBuilder(); sb.WriteHeader(); var generatedTypes = new HashSet(); var collectedPropertyTypes = new HashSet(); var nestedTypeDispatch = new List<(string FullTypeName, string MethodSuffix)>(); var concreteTypes = new HashSet(); // Collect all type dispatch entries: (fullCSharpTypeName, methodSuffix) var typeDispatch = new List<(string FullTypeName, string MethodSuffix)>(); var contextNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet.Json" : $"{options.RootNamespace}.Json"; sb.WriteNamespace(contextNs); sb.WriteSummary("JSON serialization context implementing IJsonTypeInfoResolver for all AT Protocol types."); sb.AppendLine($"public sealed class {options.JsonContextName} : global::System.Text.Json.Serialization.Metadata.IJsonTypeInfoResolver"); sb.OpenBrace(); sb.WriteSummary("Gets the default singleton instance."); sb.AppendLine($"public static {options.JsonContextName} Default {{ get; }} = new {options.JsonContextName}();"); sb.AppendLine(); // Default options for use by serialization helper methods sb.AppendLine("private static readonly global::System.Text.Json.JsonSerializerOptions s_defaultOptions = new global::System.Text.Json.JsonSerializerOptions"); sb.OpenBrace(); sb.AppendLine("PropertyNamingPolicy = global::System.Text.Json.JsonNamingPolicy.CamelCase,"); sb.AppendLine("DefaultIgnoreCondition = global::System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,"); sb.AppendLine($"TypeInfoResolver = Default,"); sb.CloseBrace(withSemicolon: true); sb.AppendLine(); sb.WriteSummary("Gets the default JsonSerializerOptions configured with the generated JSON type info resolver."); sb.AppendLine("public static global::System.Text.Json.JsonSerializerOptions DefaultOptions => s_defaultOptions;"); sb.AppendLine(); // Iterate all namespaces and types to generate factory methods foreach (var kvp in byNamespace) { var ns = kvp.Key; foreach (var (nsid, doc) in kvp.Value) { foreach (var def in doc.Defs) { var defName = def.Key; var defValue = def.Value; var mainTypeName = NsidHelper.ToTypeName(nsid); var className = defName == "main" ? mainTypeName : mainTypeName + NsidHelper.ToPascalCase(defName); switch (defValue.Type) { case "record": if (defValue.Record != null) { var fullName = $"{ns}.{className}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonTypeInfo(sb, fullName, suffix, defValue.Record, nsid, registry, options, isRecord: true, generatedTypes: generatedTypes, collectedPropertyTypes: collectedPropertyTypes, nestedTypeDispatch: nestedTypeDispatch, concreteTypes: concreteTypes); typeDispatch.Add((fullName, suffix)); } break; case "object": { var fullName = $"{ns}.{className}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonTypeInfo(sb, fullName, suffix, defValue, nsid, registry, options, generatedTypes: generatedTypes, collectedPropertyTypes: collectedPropertyTypes, nestedTypeDispatch: nestedTypeDispatch, concreteTypes: concreteTypes); typeDispatch.Add((fullName, suffix)); break; } case "union": if (defValue.Refs != null && !(defValue.Closed != true && defValue.Refs.Count == 0)) { var interfaceName = $"I{className}"; var fullName = $"{ns}.{interfaceName}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonUnionTypeInfo(sb, fullName, suffix, defValue.Refs, nsid, registry, options, isClosed: defValue.Closed == true, generatedTypes: generatedTypes, nestedTypeDispatch: nestedTypeDispatch); typeDispatch.Add((fullName, suffix)); } break; case "query": if (defValue.Output?.Schema != null && !ApiGenerator.IsOutputRef(defValue)) { var outputClassName = className + "Output"; var fullName = $"{ns}.{outputClassName}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonTypeInfo(sb, fullName, suffix, defValue.Output.Schema, nsid, registry, options, generatedTypes: generatedTypes, collectedPropertyTypes: collectedPropertyTypes, nestedTypeDispatch: nestedTypeDispatch, concreteTypes: concreteTypes); typeDispatch.Add((fullName, suffix)); } break; case "procedure": if (defValue.Input?.Schema != null && !ApiGenerator.IsInputRef(defValue)) { var inputClassName = className + "Input"; var fullName = $"{ns}.{inputClassName}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonTypeInfo(sb, fullName, suffix, defValue.Input.Schema, nsid, registry, options, generatedTypes: generatedTypes, collectedPropertyTypes: collectedPropertyTypes, nestedTypeDispatch: nestedTypeDispatch, concreteTypes: concreteTypes); typeDispatch.Add((fullName, suffix)); } if (defValue.Output?.Schema != null && !ApiGenerator.IsOutputRef(defValue)) { var outputClassName = className + "Output"; var fullName = $"{ns}.{outputClassName}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonTypeInfo(sb, fullName, suffix, defValue.Output.Schema, nsid, registry, options, generatedTypes: generatedTypes, collectedPropertyTypes: collectedPropertyTypes, nestedTypeDispatch: nestedTypeDispatch, concreteTypes: concreteTypes); typeDispatch.Add((fullName, suffix)); } break; case "subscription": if (defValue.Message?.Schema?.Type == "union" && defValue.Message.Schema.Refs != null) { var interfaceName = $"I{className}Message"; var fullName = $"{ns}.{interfaceName}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonUnionTypeInfo(sb, fullName, suffix, defValue.Message.Schema.Refs, nsid, registry, options, isClosed: defValue.Message.Schema.Closed == true, generatedTypes: generatedTypes, nestedTypeDispatch: nestedTypeDispatch); typeDispatch.Add((fullName, suffix)); } break; case "array": if (defValue.Items?.Type == "union" && defValue.Items.Refs != null && !(defValue.Items.Closed != true && defValue.Items.Refs.Count == 0)) { var interfaceName = $"I{className}"; var fullName = $"{ns}.{interfaceName}"; var suffix = JsonContextGenerator.ToMethodSuffix(fullName); JsonContextGenerator.GenerateJsonUnionTypeInfo(sb, fullName, suffix, defValue.Items.Refs, nsid, registry, options, isClosed: defValue.Items.Closed == true, generatedTypes: generatedTypes, nestedTypeDispatch: nestedTypeDispatch); typeDispatch.Add((fullName, suffix)); } break; } } } } // Merge nested type dispatch entries (inline objects/unions generated recursively) typeDispatch.AddRange(nestedTypeDispatch); // Generate built-in type info factories for leaf property types (primitives, runtime types, List) var generatedObjectTypeNames = new HashSet(typeDispatch.Select(t => t.FullTypeName.Replace("@", ""))); var builtInDispatchLines = JsonContextGenerator.GenerateBuiltInTypeInfos(sb, collectedPropertyTypes, generatedObjectTypeNames); // Generate the GetTypeInfo dispatch method sb.WriteSummary("Gets the JSON type info for the specified type, or null if not handled."); sb.AppendLine("public global::System.Text.Json.Serialization.Metadata.JsonTypeInfo? GetTypeInfo(global::System.Type type, global::System.Text.Json.JsonSerializerOptions options)"); sb.OpenBrace(); foreach (var entry in typeDispatch) { sb.AppendLine($"if (type == typeof(global::{entry.FullTypeName})) return Create_{entry.MethodSuffix}_TypeInfo(options);"); } // Built-in type dispatch (primitives, runtime types, nullables, collections) foreach (var line in builtInDispatchLines) { sb.AppendLine(line); } sb.AppendLine("return null;"); sb.CloseBrace(); sb.CloseBrace(); // class sb.AppendLine(); return (sb.ToString(), concreteTypes); } private static string GenerateSerializationMethodsSource( HashSet concreteTypes, GeneratorOptions options) { if (concreteTypes.Count == 0) { return string.Empty; } var contextNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet.Json" : $"{options.RootNamespace}.Json"; var sb = new SourceBuilder(); sb.WriteHeader(); // Group types by namespace var byNamespace = concreteTypes .OrderBy(t => t) .GroupBy(t => t.Contains(".") ? t.Substring(0, t.LastIndexOf('.')) : ""); foreach (var nsGroup in byNamespace) { var ns = nsGroup.Key; if (!string.IsNullOrEmpty(ns)) { sb.WriteNamespaceBlock(ns); } foreach (var fullTypeName in nsGroup) { var shortName = fullTypeName.Contains(".") ? fullTypeName.Substring(fullTypeName.LastIndexOf('.') + 1) : fullTypeName; sb.AppendLine($"partial class {shortName}"); sb.OpenBrace(); // ToJson() sb.WriteSummary("Serializes this instance to a ."); sb.AppendLine("public global::System.Text.Json.JsonElement ToJson()"); sb.OpenBrace(); sb.AppendLine("return global::System.Text.Json.JsonSerializer.SerializeToElement("); sb.Indent(); sb.AppendLine("this,"); sb.AppendLine($"(global::System.Text.Json.Serialization.Metadata.JsonTypeInfo<{shortName}>)"); sb.AppendLine($" global::{contextNs}.{options.JsonContextName}.DefaultOptions.GetTypeInfo(typeof({shortName}))!);"); sb.Unindent(); sb.CloseBrace(); sb.AppendLine(); // FromJson() sb.WriteSummary("Deserializes a to an instance of this type."); sb.AppendLine($"public static {shortName}? FromJson(global::System.Text.Json.JsonElement element)"); sb.OpenBrace(); sb.AppendLine($"return global::System.Text.Json.JsonSerializer.Deserialize("); sb.Indent(); sb.AppendLine("element,"); sb.AppendLine($"(global::System.Text.Json.Serialization.Metadata.JsonTypeInfo<{shortName}>)"); sb.AppendLine($" global::{contextNs}.{options.JsonContextName}.DefaultOptions.GetTypeInfo(typeof({shortName}))!);"); sb.Unindent(); sb.CloseBrace(); sb.CloseBrace(); // partial class sb.AppendLine(); } if (!string.IsNullOrEmpty(ns)) { sb.CloseBrace(); // namespace sb.AppendLine(); } } return sb.ToString(); } /// /// Collects all union interface-to-implementation mappings across all namespaces. /// Returns a mapping of fully-qualified derived type name -> set of fully-qualified interface names. /// private static Dictionary> CollectUnionImplementations( Dictionary> byNamespace, TypeRegistry registry) { var result = new Dictionary>(); void AddMapping(string derivedType, string interfaceName) { if (!result.TryGetValue(derivedType, out var set)) { set = new HashSet(); result[derivedType] = set; } set.Add(interfaceName); } void ProcessUnionRefs(List refs, string fullyQualifiedInterfaceName, string currentNsid) { foreach (var refString in refs) { var fullRef = refString.StartsWith("#") ? $"{currentNsid}{refString}" : refString; var typeInfo = registry.Lookup(fullRef); // Only add mapping for concrete class types (object/record) if (typeInfo != null && (typeInfo.Kind == LexiconTypeKind.Object || typeInfo.Kind == LexiconTypeKind.Record)) { AddMapping(typeInfo.FullCSharpTypeName, fullyQualifiedInterfaceName); } } } void ProcessObjectProperties(Dictionary properties, string className, string ns, string currentNsid) { foreach (var prop in properties) { if (prop.Value.Type == "union" && prop.Value.Refs != null && !(prop.Value.Closed != true && prop.Value.Refs.Count == 0)) { var cleanClassName = NsidHelper.StripEscapePrefix(className); var cleanPropertyName = NsidHelper.StripEscapePrefix(NsidHelper.ToPascalCase(prop.Key)); var interfaceName = $"I{cleanClassName}{cleanPropertyName}"; var fullyQualifiedInterface = $"{ns}.{interfaceName}"; ProcessUnionRefs(prop.Value.Refs, fullyQualifiedInterface, currentNsid); } 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 cleanClassName = NsidHelper.StripEscapePrefix(className); var cleanPropertyName = NsidHelper.StripEscapePrefix(NsidHelper.ToPascalCase(prop.Key)); var interfaceName = $"I{cleanClassName}{cleanPropertyName}"; var fullyQualifiedInterface = $"{ns}.{interfaceName}"; ProcessUnionRefs(prop.Value.Items.Refs, fullyQualifiedInterface, currentNsid); } } } foreach (var kvp in byNamespace) { var ns = kvp.Key; foreach (var (nsid, doc) in kvp.Value) { foreach (var def in doc.Defs) { var defName = def.Key; var defValue = def.Value; var mainTypeName = NsidHelper.ToTypeName(nsid); var className = defName == "main" ? mainTypeName : mainTypeName + NsidHelper.ToPascalCase(defName); switch (defValue.Type) { case "record": if (defValue.Record?.Properties != null) { ProcessObjectProperties(defValue.Record.Properties, className, ns, nsid); } break; case "object": if (defValue.Properties != null) { ProcessObjectProperties(defValue.Properties, className, ns, nsid); } break; case "union": if (defValue.Refs != null && !(defValue.Closed != true && defValue.Refs.Count == 0)) { var interfaceName = $"I{className}"; var fullyQualifiedInterface = $"{ns}.{interfaceName}"; ProcessUnionRefs(defValue.Refs, fullyQualifiedInterface, nsid); } break; case "array": if (defValue.Items?.Type == "union" && defValue.Items.Refs != null && !(defValue.Items.Closed != true && defValue.Items.Refs.Count == 0)) { var interfaceName = $"I{className}"; var fullyQualifiedInterface = $"{ns}.{interfaceName}"; ProcessUnionRefs(defValue.Items.Refs, fullyQualifiedInterface, nsid); } break; case "query": if (defValue.Output?.Schema != null && !ApiGenerator.IsOutputRef(defValue) && defValue.Output.Schema.Properties != null) { var outputClassName = className + "Output"; ProcessObjectProperties(defValue.Output.Schema.Properties, outputClassName, ns, nsid); } break; case "procedure": if (defValue.Input?.Schema != null && !ApiGenerator.IsInputRef(defValue) && defValue.Input.Schema.Properties != null) { var inputClassName = className + "Input"; ProcessObjectProperties(defValue.Input.Schema.Properties, inputClassName, ns, nsid); } if (defValue.Output?.Schema != null && !ApiGenerator.IsOutputRef(defValue) && defValue.Output.Schema.Properties != null) { var outputClassName = className + "Output"; ProcessObjectProperties(defValue.Output.Schema.Properties, outputClassName, ns, nsid); } break; case "subscription": if (defValue.Message?.Schema?.Type == "union" && defValue.Message.Schema.Refs != null) { var interfaceName = $"I{className}Message"; var fullyQualifiedInterface = $"{ns}.{interfaceName}"; ProcessUnionRefs(defValue.Message.Schema.Refs, fullyQualifiedInterface, nsid); } break; } } } } return result; } /// /// Generates partial class declarations that add union interface implementations. /// private static string GenerateUnionImplementationsSource( Dictionary> unionMappings) { if (unionMappings.Count == 0) return string.Empty; var sb = new SourceBuilder(); sb.WriteHeader(); // Group by namespace of the derived type var byNamespace = new Dictionary Interfaces)>>(); foreach (var kvp in unionMappings) { var lastDot = kvp.Key.LastIndexOf('.'); if (lastDot < 0) continue; var ns = kvp.Key.Substring(0, lastDot); var className = kvp.Key.Substring(lastDot + 1); if (!byNamespace.TryGetValue(ns, out var list)) { list = new List<(string, HashSet)>(); byNamespace[ns] = list; } list.Add((className, kvp.Value)); } foreach (var nsKvp in byNamespace) { sb.WriteNamespaceBlock(nsKvp.Key); foreach (var (className, interfaces) in nsKvp.Value) { var interfaceList = string.Join(", ", interfaces.OrderBy(i => i).Select(i => $"global::{i}")); sb.AppendLine($"public partial class {className} : {interfaceList}"); sb.OpenBrace(); sb.CloseBrace(); sb.AppendLine(); } sb.CloseBrace(); // namespace sb.AppendLine(); } return sb.ToString(); } private static string GenerateFactorySource(GeneratorOptions options) { var sb = new SourceBuilder(); sb.WriteHeader(); sb.WriteUsing("System"); sb.WriteUsing("System.Collections.Generic"); sb.WriteUsing("System.Net.Http"); sb.WriteUsing("System.Text.Json"); sb.WriteUsing("System.Text.Json.Serialization"); sb.WriteUsing("System.Text.Json.Serialization.Metadata"); sb.WriteUsing("System.Threading"); sb.WriteUsing("System.Threading.Tasks"); sb.WriteUsing("CarpaNet"); sb.WriteUsing("CarpaNet.Cbor"); sb.WriteUsing("CarpaNet.Identity"); sb.WriteUsing("CarpaNet.Storage"); sb.AppendLine(); var jsonContextNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet.Json" : $"{options.RootNamespace}.Json"; var cborContextNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet.Cbor" : $"{options.RootNamespace}.Cbor"; var factoryNs = string.IsNullOrEmpty(options.RootNamespace) ? "CarpaNet" : $"{options.RootNamespace}"; sb.WriteNamespace(factoryNs); sb.WriteSummary("Factory class that creates pre-configured ATProto client instances with the generated JSON and CBOR serialization contexts."); sb.AppendLine("public static class ATProtoClientFactory"); sb.OpenBrace(); // CreateJsonOptions sb.WriteSummary("Creates JsonSerializerOptions configured with the generated JSON type info resolver."); sb.AppendLine("public static JsonSerializerOptions CreateJsonOptions()"); sb.OpenBrace(); sb.AppendLine($"return global::{jsonContextNs}.{options.JsonContextName}.DefaultOptions;"); sb.CloseBrace(); sb.AppendLine(); // Create sb.WriteSummary("Creates an ATProtoClient with the generated serialization contexts. By default, creates a public (unauthenticated) client."); sb.AppendLine("public static ATProtoClient Create(ATProtoClientOptions? options = null)"); sb.OpenBrace(); sb.AppendLine("options ??= new ATProtoClientOptions { JsonOptions = CreateJsonOptions(), CborContext = global::" + cborContextNs + "." + options.CborContextName + ".Default };"); sb.AppendLine("return ATProtoClient.Create(options);"); sb.CloseBrace(); sb.AppendLine(); // CreateWithSessionAsync sb.WriteSummary("Creates an authenticated ATProtoClient with the generated serialization contexts."); sb.AppendLine("public static async Task CreateWithSessionAsync("); sb.Indent(); sb.AppendLine("string identifier, string password,"); sb.AppendLine("Uri? serviceUrl = null,"); sb.AppendLine("ATProtoClientOptions? options = null,"); sb.AppendLine("CancellationToken cancellationToken = default)"); sb.Unindent(); sb.OpenBrace(); sb.AppendLine("options ??= new ATProtoClientOptions { JsonOptions = CreateJsonOptions(), CborContext = global::" + cborContextNs + "." + options.CborContextName + ".Default };"); sb.AppendLine("return await ATProtoClient.CreateWithSessionAsync("); sb.Indent(); sb.AppendLine("identifier, password, serviceUrl, options, cancellationToken);"); sb.Unindent(); sb.CloseBrace(); sb.AppendLine(); // CreateClient sb.WriteSummary("Creates an ATProtoClient with the generated serialization contexts."); sb.AppendLine("public static ATProtoClient CreateClient("); sb.Indent(); sb.AppendLine("HttpClient? httpClient = null,"); sb.AppendLine("Uri? baseUrl = null,"); sb.AppendLine("IdentityResolver? identityResolver = null,"); sb.AppendLine("IReadOnlyList? labelerDids = null)"); sb.Unindent(); sb.OpenBrace(); sb.AppendLine("return ATProtoClient.Create(new ATProtoClientOptions"); sb.OpenBrace(); sb.AppendLine("HttpClient = httpClient,"); sb.AppendLine("JsonOptions = CreateJsonOptions(),"); sb.AppendLine($"CborContext = global::{cborContextNs}.{options.CborContextName}.Default,"); sb.AppendLine("BaseUrl = baseUrl,"); sb.AppendLine("IdentityResolver = identityResolver,"); sb.AppendLine("LabelerDids = labelerDids"); sb.CloseBrace(); sb.AppendLine(");"); sb.CloseBrace(); sb.AppendLine(); // CreateSessionClient sb.WriteSummary("Creates an ATProtoClient configured for session-based authentication with the generated serialization contexts."); sb.AppendLine("public static ATProtoClient CreateSessionClient("); sb.Indent(); sb.AppendLine("HttpClient? httpClient = null,"); sb.AppendLine("IdentityResolver? identityResolver = null,"); sb.AppendLine("IReadOnlyList? labelerDids = null)"); sb.Unindent(); sb.OpenBrace(); sb.AppendLine("return ATProtoClient.Create(new ATProtoClientOptions"); sb.OpenBrace(); sb.AppendLine("HttpClient = httpClient,"); sb.AppendLine("JsonOptions = CreateJsonOptions(),"); sb.AppendLine($"CborContext = global::{cborContextNs}.{options.CborContextName}.Default,"); sb.AppendLine("IdentityResolver = identityResolver,"); sb.AppendLine("LabelerDids = labelerDids"); sb.CloseBrace(); sb.AppendLine(");"); sb.CloseBrace(); sb.AppendLine(); // CreateSessionClient with ISessionStore sb.WriteSummary("Creates an ATProtoClient configured for session-based authentication with the generated serialization contexts and a session store for automatic persistence."); sb.AppendLine("public static ATProtoClient CreateSessionClient("); sb.Indent(); sb.AppendLine("ISessionStore sessionStore,"); sb.AppendLine("HttpClient? httpClient = null,"); sb.AppendLine("IdentityResolver? identityResolver = null,"); sb.AppendLine("IReadOnlyList? labelerDids = null)"); sb.Unindent(); sb.OpenBrace(); sb.AppendLine("return ATProtoClient.Create(new ATProtoClientOptions"); sb.OpenBrace(); sb.AppendLine("HttpClient = httpClient,"); sb.AppendLine("JsonOptions = CreateJsonOptions(),"); sb.AppendLine($"CborContext = global::{cborContextNs}.{options.CborContextName}.Default,"); sb.AppendLine("IdentityResolver = identityResolver,"); sb.AppendLine("LabelerDids = labelerDids,"); sb.AppendLine("SessionStore = sessionStore"); sb.CloseBrace(); sb.AppendLine(");"); sb.CloseBrace(); sb.CloseBrace(); // class sb.AppendLine(); return sb.ToString(); } }