-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYamlSourceGenerator.cs
More file actions
3901 lines (3500 loc) · 177 KB
/
Copy pathYamlSourceGenerator.cs
File metadata and controls
3901 lines (3500 loc) · 177 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Yamlify.SourceGenerator;
/// <summary>
/// Incremental source generator for AOT-compatible YAML serialization.
/// </summary>
/// <remarks>
/// This generator creates compile-time serialization/deserialization code
/// that doesn't use any reflection, making it fully AOT-compatible.
/// </remarks>
[Generator(LanguageNames.CSharp)]
public sealed class YamlSourceGenerator : IIncrementalGenerator
{
private const string YamlSerializableAttribute = "Yamlify.Serialization.YamlSerializableAttribute";
private const string YamlSerializableAttributeGeneric = "Yamlify.Serialization.YamlSerializableAttribute<T>";
private const string YamlDerivedTypeMappingAttributeGeneric = "Yamlify.Serialization.YamlDerivedTypeMappingAttribute<TBase, TDerived>";
private const string YamlSerializerContextBase = "Yamlify.Serialization.YamlSerializerContext";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Find all classes with [YamlSerializable] attributes
var contextDeclarations = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: static (node, _) => IsCandidateClass(node),
transform: static (ctx, _) => GetSemanticTarget(ctx))
.Where(static target => target is not null)
.Select(static (target, _) => target!);
// Combine with compilation
var compilationAndClasses = context.CompilationProvider.Combine(contextDeclarations.Collect());
// Generate source
context.RegisterSourceOutput(compilationAndClasses,
static (spc, source) => Execute(source.Left, source.Right, spc));
}
private static bool IsCandidateClass(SyntaxNode node)
{
return node is ClassDeclarationSyntax classDecl &&
classDecl.AttributeLists.Count > 0 &&
classDecl.Modifiers.Any(SyntaxKind.PartialKeyword);
}
private static ContextToGenerate? GetSemanticTarget(GeneratorSyntaxContext context)
{
var classDecl = (ClassDeclarationSyntax)context.Node;
var classSymbol = context.SemanticModel.GetDeclaredSymbol(classDecl);
if (classSymbol is null)
{
return null;
}
// Check if it derives from YamlSerializerContext
var baseType = classSymbol.BaseType;
var isSerializerContext = false;
while (baseType is not null)
{
if (baseType.ToDisplayString() == YamlSerializerContextBase)
{
isSerializerContext = true;
break;
}
baseType = baseType.BaseType;
}
if (!isSerializerContext)
{
return null;
}
// Collect [YamlSerializable] attributes and parse options
var typesToGenerate = new List<TypeToGenerate>();
var propertyOrdering = PropertyOrderingMode.DeclarationOrder;
var indentSequenceItems = true;
var ignoreNullValues = false;
var ignoreEmptyObjects = false;
var discriminatorPosition = DiscriminatorPositionMode.PropertyOrder;
// First pass: collect YamlDerivedTypeMapping attributes
// Key: base type display string, Value: list of (discriminator, derivedType)
var derivedTypeMappingsFromAttrs = new Dictionary<string, List<(string Discriminator, INamedTypeSymbol DerivedType)>>();
foreach (var attributeData in classSymbol.GetAttributes())
{
var attrOriginalDef = attributeData.AttributeClass?.OriginalDefinition?.ToDisplayString();
if (attrOriginalDef == YamlDerivedTypeMappingAttributeGeneric)
{
// [YamlDerivedTypeMapping<TBase, TDerived>("discriminator")]
if (attributeData.AttributeClass is { IsGenericType: true, TypeArguments.Length: 2 } attrClass &&
attrClass.TypeArguments[0] is INamedTypeSymbol mappingBaseType &&
attrClass.TypeArguments[1] is INamedTypeSymbol mappingDerivedType)
{
var baseTypeKey = mappingBaseType.ToDisplayString();
// Get discriminator from constructor argument (optional)
string? discriminator = null;
if (attributeData.ConstructorArguments.Length > 0 &&
attributeData.ConstructorArguments[0].Value is string discValue)
{
discriminator = discValue;
}
discriminator ??= mappingDerivedType.Name;
if (!derivedTypeMappingsFromAttrs.TryGetValue(baseTypeKey, out var mappings))
{
mappings = new List<(string, INamedTypeSymbol)>();
derivedTypeMappingsFromAttrs[baseTypeKey] = mappings;
}
mappings.Add((discriminator, mappingDerivedType));
}
}
}
// Second pass: process YamlSerializable attributes
foreach (var attributeData in classSymbol.GetAttributes())
{
var attrName = attributeData.AttributeClass?.ToDisplayString();
var attrOriginalDef = attributeData.AttributeClass?.OriginalDefinition?.ToDisplayString();
// Support both [YamlSerializable(typeof(T))] and [YamlSerializable<T>]
INamedTypeSymbol? typeArg = null;
var isYamlSerializableAttribute = false;
if (attrName == YamlSerializableAttribute)
{
// Non-generic: [YamlSerializable(typeof(T))]
if (attributeData.ConstructorArguments.Length > 0 &&
attributeData.ConstructorArguments[0].Value is INamedTypeSymbol ctorArg)
{
typeArg = ctorArg;
isYamlSerializableAttribute = true;
}
}
else if (attrOriginalDef == YamlSerializableAttributeGeneric)
{
// Generic: [YamlSerializable<T>]
if (attributeData.AttributeClass is { IsGenericType: true, TypeArguments.Length: > 0 } attrClass &&
attrClass.TypeArguments[0] is INamedTypeSymbol genericArg)
{
typeArg = genericArg;
isYamlSerializableAttribute = true;
}
}
if (isYamlSerializableAttribute && typeArg is not null)
{
// Check for per-type PropertyOrdering override
PropertyOrderingMode? typeOrdering = null;
string? typeDiscriminatorPropertyName = null;
List<INamedTypeSymbol>? derivedTypes = null;
List<string>? derivedTypeDiscriminators = null;
foreach (var namedArg in attributeData.NamedArguments)
{
if (namedArg.Key == "PropertyOrdering" && namedArg.Value.Value is int orderingValue && orderingValue >= 0)
{
// Only set if not Inherit (-1)
typeOrdering = (PropertyOrderingMode)orderingValue;
}
else if (namedArg.Key == "TypeDiscriminatorPropertyName" && namedArg.Value.Value is string discPropName)
{
typeDiscriminatorPropertyName = discPropName;
}
else if (namedArg.Key == "DerivedTypes" && !namedArg.Value.IsNull)
{
derivedTypes = namedArg.Value.Values
.Where(v => v.Value is INamedTypeSymbol)
.Select(v => (INamedTypeSymbol)v.Value!)
.ToList();
}
else if (namedArg.Key == "DerivedTypeDiscriminators" && !namedArg.Value.IsNull)
{
derivedTypeDiscriminators = namedArg.Value.Values
.Where(v => v.Value is string)
.Select(v => (string)v.Value!)
.ToList();
}
}
// Build PolymorphicInfo if polymorphic configuration is specified
PolymorphicInfo? polymorphicConfig = null;
var typeKey = typeArg.ToDisplayString();
// Check for derived type mappings from YamlDerivedTypeMappingAttribute
if (typeDiscriminatorPropertyName is not null &&
derivedTypeMappingsFromAttrs.TryGetValue(typeKey, out var mappingsFromAttr) &&
mappingsFromAttr.Count > 0)
{
// Use mappings from YamlDerivedTypeMappingAttribute
polymorphicConfig = new PolymorphicInfo(typeDiscriminatorPropertyName, mappingsFromAttr);
}
else if (typeDiscriminatorPropertyName is not null && derivedTypes is not null && derivedTypes.Count > 0)
{
// Use inline DerivedTypes/DerivedTypeDiscriminators arrays
var derivedTypeMappings = new List<(string Discriminator, INamedTypeSymbol DerivedType)>();
for (int i = 0; i < derivedTypes.Count; i++)
{
var derivedType = derivedTypes[i];
// Use explicit discriminator if provided, otherwise use type name
var discriminator = (derivedTypeDiscriminators is not null && i < derivedTypeDiscriminators.Count)
? derivedTypeDiscriminators[i]
: derivedType.Name;
derivedTypeMappings.Add((discriminator, derivedType));
}
polymorphicConfig = new PolymorphicInfo(typeDiscriminatorPropertyName, derivedTypeMappings);
}
// Check if type has [YamlConverter] attribute for custom converter support
INamedTypeSymbol? customConverterType = null;
foreach (var typeAttr in typeArg.GetAttributes())
{
if (typeAttr.AttributeClass?.ToDisplayString() == "Yamlify.Serialization.YamlConverterAttribute")
{
if (typeAttr.ConstructorArguments.Length > 0 &&
typeAttr.ConstructorArguments[0].Value is INamedTypeSymbol converterType)
{
customConverterType = converterType;
}
break;
}
}
typesToGenerate.Add(new TypeToGenerate(typeArg, typeOrdering, polymorphicConfig, customConverterType));
}
else if (attrName == "Yamlify.Serialization.YamlSourceGenerationOptionsAttribute")
{
// Parse PropertyOrdering and IndentSequenceItems from named arguments
foreach (var namedArg in attributeData.NamedArguments)
{
if (namedArg.Key == "PropertyOrdering" && namedArg.Value.Value is int orderingValue)
{
propertyOrdering = (PropertyOrderingMode)orderingValue;
}
else if (namedArg.Key == "IndentSequenceItems" && namedArg.Value.Value is bool indentSeqValue)
{
indentSequenceItems = indentSeqValue;
}
else if (namedArg.Key == "IgnoreNullValues" && namedArg.Value.Value is bool ignoreNullValue)
{
ignoreNullValues = ignoreNullValue;
}
else if (namedArg.Key == "IgnoreEmptyObjects" && namedArg.Value.Value is bool ignoreEmptyValue)
{
ignoreEmptyObjects = ignoreEmptyValue;
}
else if (namedArg.Key == "DiscriminatorPosition" && namedArg.Value.Value is int discPosValue)
{
discriminatorPosition = (DiscriminatorPositionMode)discPosValue;
}
}
}
}
if (typesToGenerate.Count == 0)
{
return null;
}
return new ContextToGenerate(
classSymbol.Name,
classSymbol.ContainingNamespace.ToDisplayString(),
typesToGenerate,
propertyOrdering,
indentSequenceItems,
ignoreNullValues,
ignoreEmptyObjects,
discriminatorPosition);
}
private static readonly DiagnosticDescriptor AlphabeticalOrderingConflict = new(
id: "YAML001",
title: "Property ordering conflict",
messageFormat: "Property '{0}' in type '{1}' has [YamlPropertyOrder] attribute, but the serializer context uses alphabetical property ordering. Remove the attribute or switch to declaration order.",
category: "Yamlify",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static void Execute(
Compilation compilation,
ImmutableArray<ContextToGenerate> contexts,
SourceProductionContext spc)
{
if (contexts.IsDefaultOrEmpty)
{
return;
}
foreach (var ctx in contexts.Distinct())
{
// Validate: if alphabetical ordering, no property should have YamlPropertyOrder attribute
if (ctx.PropertyOrdering == PropertyOrderingMode.Alphabetical)
{
foreach (var type in ctx.Types)
{
foreach (var prop in GetAllProperties(type.Symbol))
{
if (HasPropertyOrderAttribute(prop))
{
var diagnostic = Diagnostic.Create(
AlphabeticalOrderingConflict,
prop.Locations.FirstOrDefault(),
prop.Name,
type.Symbol.Name);
spc.ReportDiagnostic(diagnostic);
}
}
}
}
var source = GenerateContextSource(ctx, compilation);
spc.AddSource($"{ctx.ClassName}.g.cs", SourceText.From(source, Encoding.UTF8));
}
}
private static string GenerateContextSource(ContextToGenerate ctx, Compilation compilation)
{
var sb = new StringBuilder();
sb.AppendLine("// <auto-generated />");
sb.AppendLine("// This file was generated by Yamlify.SourceGenerator.");
sb.AppendLine("// It is AOT-compatible and uses no reflection at runtime.");
sb.AppendLine("#nullable enable");
sb.AppendLine();
sb.AppendLine("using System;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("using Yamlify;");
sb.AppendLine("using Yamlify.Serialization;");
sb.AppendLine();
if (!string.IsNullOrEmpty(ctx.Namespace))
{
sb.AppendLine($"namespace {ctx.Namespace};");
sb.AppendLine();
}
sb.AppendLine($"partial class {ctx.ClassName}");
sb.AppendLine("{");
// Generate constructor that configures options if any non-default settings
var hasNonDefaultOptions = !ctx.IndentSequenceItems || ctx.IgnoreNullValues || ctx.IgnoreEmptyObjects;
if (hasNonDefaultOptions)
{
var optionsList = new List<string>();
if (!ctx.IndentSequenceItems)
{
optionsList.Add("IndentSequenceItems = false");
}
if (ctx.IgnoreNullValues)
{
optionsList.Add("IgnoreNullValues = true");
}
if (ctx.IgnoreEmptyObjects)
{
optionsList.Add("IgnoreEmptyObjects = true");
}
var optionsStr = string.Join(", ", optionsList);
sb.AppendLine($" public {ctx.ClassName}() : base(new YamlSerializerOptions {{ {optionsStr} }})");
sb.AppendLine(" {");
sb.AppendLine(" }");
sb.AppendLine();
}
// Generate static Default singleton
sb.AppendLine($" private static {ctx.ClassName}? _default;");
sb.AppendLine($" public static {ctx.ClassName} Default => _default ??= new {ctx.ClassName}();");
sb.AppendLine();
// Build a map of property names to handle collisions
var propertyNameMap = BuildPropertyNameMap(ctx.Types);
// Generate type info properties
foreach (var type in ctx.Types)
{
var propertyName = propertyNameMap[type.Symbol.ToDisplayString()];
var fullTypeName = type.Symbol.ToDisplayString();
sb.AppendLine($" private YamlTypeInfo<{fullTypeName}>? _{propertyName.ToLowerInvariant()};");
sb.AppendLine($" public YamlTypeInfo<{fullTypeName}> {propertyName} => _{propertyName.ToLowerInvariant()} ??= Create{propertyName}TypeInfo();");
sb.AppendLine();
}
// Generate GetTypeInfo override
sb.AppendLine(" public override YamlTypeInfo? GetTypeInfo(Type type, YamlSerializerOptions options)");
sb.AppendLine(" {");
foreach (var type in ctx.Types)
{
var fullTypeName = type.Symbol.ToDisplayString();
var propertyName = propertyNameMap[fullTypeName];
sb.AppendLine($" if (type == typeof({fullTypeName})) return {propertyName};");
}
sb.AppendLine(" return null;");
sb.AppendLine(" }");
sb.AppendLine();
// Generate type info creation methods
foreach (var type in ctx.Types)
{
GenerateTypeInfoMethod(sb, type, propertyNameMap, compilation);
}
// Generate converter classes
foreach (var type in ctx.Types)
{
// Use per-type ordering if specified, otherwise fall back to context-level ordering
var effectiveOrdering = type.PropertyOrdering ?? ctx.PropertyOrdering;
GenerateConverterClass(sb, type, ctx.Types, compilation, effectiveOrdering, ctx.DiscriminatorPosition, ctx.IgnoreEmptyObjects);
}
// Generate IsEmpty helper methods for IgnoreEmptyObjects support
if (ctx.IgnoreEmptyObjects)
{
sb.AppendLine(" // IsEmpty helper methods for IgnoreEmptyObjects support");
foreach (var type in ctx.Types)
{
GenerateIsEmptyMethod(sb, type);
}
}
sb.AppendLine("}");
return sb.ToString();
}
private static void GenerateTypeInfoMethod(StringBuilder sb, TypeToGenerate type, Dictionary<string, string> propertyNameMap, Compilation compilation)
{
var propertyName = propertyNameMap[type.Symbol.ToDisplayString()];
var fullTypeName = type.Symbol.ToDisplayString();
var converterName = GetConverterName(type.Symbol);
var hasCustomConverter = type.CustomConverterType is not null;
sb.AppendLine($" private YamlTypeInfo<{fullTypeName}> Create{propertyName}TypeInfo()");
sb.AppendLine(" {");
if (hasCustomConverter)
{
// Use the custom converter with GeneratedRead/GeneratedWrite delegates set via object initializer
var customConverterTypeName = type.CustomConverterType!.ToDisplayString();
sb.AppendLine($" var converter = new {customConverterTypeName}");
sb.AppendLine(" {");
sb.AppendLine($" GeneratedRead = {converterName}.ReadCore,");
sb.AppendLine($" GeneratedWrite = {converterName}.WriteCore");
sb.AppendLine(" };");
}
else
{
sb.AppendLine($" var converter = new {converterName}();");
}
sb.AppendLine($" var properties = new List<YamlPropertyInfo>();");
sb.AppendLine();
// Add property metadata (including inherited properties)
foreach (var prop in GetAllProperties(type.Symbol))
{
var propName = prop.Name;
var yamlName = ToKebabCase(propName);
var propTypeName = prop.Type.ToDisplayString();
sb.AppendLine($" properties.Add(new YamlPropertyInfo<{fullTypeName}, {propTypeName}>(");
sb.AppendLine($" name: \"{propName}\",");
sb.AppendLine($" serializedName: \"{yamlName}\",");
if (prop.GetMethod is not null)
{
sb.AppendLine($" getter: static obj => obj.{propName},");
}
else
{
sb.AppendLine($" getter: null,");
}
// Init-only properties cannot have setters (they must be set in object initializer/constructor)
if (prop.SetMethod is not null
&& prop.SetMethod.DeclaredAccessibility == Accessibility.Public
&& !prop.SetMethod.IsInitOnly)
{
sb.AppendLine($" setter: static (obj, value) => obj.{propName} = value));");
}
else
{
sb.AppendLine($" setter: null));");
}
sb.AppendLine();
}
// Check if type has parameterless constructor and no required members
var hasParameterlessConstructor = type.Symbol.Constructors
.Any(c => c.Parameters.Length == 0 && c.DeclaredAccessibility == Accessibility.Public);
// Check for required members including inherited (cannot use default CreateInstance)
var hasRequiredMembers = GetAllProperties(type.Symbol)
.Any(p => p.IsRequired);
sb.AppendLine($" return new YamlTypeInfo<{fullTypeName}>(converter, properties, Options)");
sb.AppendLine(" {");
// Only generate CreateInstance if no required members
if (hasParameterlessConstructor && !hasRequiredMembers)
{
sb.AppendLine($" CreateInstance = static () => new {fullTypeName}(),");
}
// For custom converters, use the custom converter's methods (which may delegate to generated code)
if (hasCustomConverter)
{
sb.AppendLine($" SerializeAction = (writer, value, options) => converter.Write(writer, value, options),");
sb.AppendLine($" DeserializeFunc = (ref Utf8YamlReader reader, YamlSerializerOptions options) => converter.Read(ref reader, options)");
}
else
{
sb.AppendLine($" SerializeAction = static (writer, value, options) => new {converterName}().Write(writer, value, options),");
sb.AppendLine($" DeserializeFunc = static (ref Utf8YamlReader reader, YamlSerializerOptions options) => new {converterName}().Read(ref reader, options)");
}
sb.AppendLine(" };");
sb.AppendLine(" }");
sb.AppendLine();
}
private static void GenerateConverterClass(StringBuilder sb, TypeToGenerate type, IReadOnlyList<TypeToGenerate> allTypes, Compilation compilation, PropertyOrderingMode propertyOrdering, DiscriminatorPositionMode discriminatorPosition, bool ignoreEmptyObjects)
{
var converterName = GetConverterName(type.Symbol);
var fullTypeName = type.Symbol.ToDisplayString();
// Check if this type has a custom converter - if so, generate static methods instead
if (type.CustomConverterType is not null)
{
GenerateStaticConverterMethods(sb, type, allTypes, compilation, propertyOrdering, discriminatorPosition, ignoreEmptyObjects);
return;
}
sb.AppendLine($" private sealed class {converterName} : YamlConverter<{fullTypeName}>");
sb.AppendLine(" {");
// Check if this is a polymorphic base type (from [YamlSerializable] or [YamlPolymorphic] attributes)
var polyInfo = GetPolymorphicInfoForType(type);
var isPolymorphicBase = polyInfo is not null && polyInfo.DerivedTypes.Count > 0;
// Read method
GenerateReadMethod(sb, type, allTypes, compilation);
sb.AppendLine();
// Write method - use polymorphic dispatch for types with [YamlPolymorphic] and derived types
if (isPolymorphicBase)
{
GeneratePolymorphicWriteMethod(sb, type, polyInfo!, allTypes, compilation);
}
else
{
GenerateWriteMethod(sb, type, allTypes, compilation, propertyOrdering, discriminatorPosition, ignoreEmptyObjects);
}
sb.AppendLine(" }");
sb.AppendLine();
}
/// <summary>
/// Generates static ReadCore and WriteCore methods for types with custom converters.
/// These methods are wired up to the GeneratedRead/GeneratedWrite delegates on the custom converter.
/// We generate a full converter class internally and wrap calls to it via static methods.
/// </summary>
private static void GenerateStaticConverterMethods(StringBuilder sb, TypeToGenerate type, IReadOnlyList<TypeToGenerate> allTypes, Compilation compilation, PropertyOrderingMode propertyOrdering, DiscriminatorPositionMode discriminatorPosition, bool ignoreEmptyObjects)
{
var converterName = GetConverterName(type.Symbol);
var fullTypeName = type.Symbol.ToDisplayString();
var isValueType = type.Symbol.IsValueType;
var nullableAnnotation = isValueType ? "" : "?";
// Check if this is a polymorphic base type
var polyInfo = GetPolymorphicInfoForType(type);
var isPolymorphicBase = polyInfo is not null && polyInfo.DerivedTypes.Count > 0;
sb.AppendLine($" /// <summary>");
sb.AppendLine($" /// Generated converter for {type.Symbol.Name}. Since a custom converter exists ({type.CustomConverterType!.ToDisplayString()}),");
sb.AppendLine($" /// static ReadCore/WriteCore methods are provided for delegation from the custom converter.");
sb.AppendLine($" /// </summary>");
sb.AppendLine($" private sealed class {converterName} : YamlConverter<{fullTypeName}>");
sb.AppendLine(" {");
// Instance field for lazy initialization
sb.AppendLine($" private static {converterName}? _instance;");
sb.AppendLine($" private static {converterName} Instance => _instance ??= new {converterName}();");
sb.AppendLine();
// Generate static ReadCore method that delegates to instance Read
sb.AppendLine($" public static {fullTypeName}{nullableAnnotation} ReadCore(ref Utf8YamlReader reader, YamlSerializerOptions options)");
sb.AppendLine(" {");
sb.AppendLine(" return Instance.Read(ref reader, options);");
sb.AppendLine(" }");
sb.AppendLine();
// Generate static WriteCore method that delegates to instance Write
sb.AppendLine($" public static void WriteCore(Utf8YamlWriter writer, {fullTypeName} value, YamlSerializerOptions options)");
sb.AppendLine(" {");
sb.AppendLine(" Instance.Write(writer, value, options);");
sb.AppendLine(" }");
sb.AppendLine();
// Read method
GenerateReadMethod(sb, type, allTypes, compilation);
sb.AppendLine();
// Write method - use polymorphic dispatch for types with [YamlPolymorphic] and derived types
if (isPolymorphicBase)
{
GeneratePolymorphicWriteMethod(sb, type, polyInfo!, allTypes, compilation);
}
else
{
GenerateWriteMethod(sb, type, allTypes, compilation, propertyOrdering, discriminatorPosition, ignoreEmptyObjects);
}
sb.AppendLine(" }");
sb.AppendLine();
}
private static void GenerateReadMethod(StringBuilder sb, TypeToGenerate type, IReadOnlyList<TypeToGenerate> allTypes, Compilation compilation)
{
var typeName = type.Symbol.Name;
var fullTypeName = type.Symbol.ToDisplayString();
// For value types (structs), the return type must not include ? because:
// - The base class has T? which for value types means Nullable<T>
// - When overriding, we must match the signature exactly
// For reference types, T? is just an annotation and we can use it
var isValueType = type.Symbol.IsValueType;
var nullableAnnotation = isValueType ? "" : "?";
sb.AppendLine($" public override {fullTypeName}{nullableAnnotation} Read(ref Utf8YamlReader reader, YamlSerializerOptions options)");
sb.AppendLine(" {");
// Special handling for enums - they are scalar values, not mappings
if (type.Symbol.TypeKind == TypeKind.Enum)
{
sb.AppendLine($" var stringValue = reader.GetString();");
sb.AppendLine(" reader.Read();");
sb.AppendLine($" if (System.Enum.TryParse<{fullTypeName}>(stringValue, true, out var enumValue))");
sb.AppendLine(" {");
sb.AppendLine(" return enumValue;");
sb.AppendLine(" }");
sb.AppendLine(" return default;");
sb.AppendLine(" }");
return;
}
// Special handling for collection types (List<T>, T[], etc.) at root level
if (IsListOrArray(type.Symbol, out var elementType, out var isHashSet))
{
GenerateRootCollectionRead(sb, type.Symbol, elementType!, isHashSet, allTypes);
return;
}
// Special handling for dictionary types at root level
if (IsDictionary(type.Symbol, out var keyType, out var valueType))
{
GenerateRootDictionaryRead(sb, type.Symbol, keyType!, valueType!, allTypes);
return;
}
sb.AppendLine(" if (reader.TokenType != YamlTokenType.MappingStart)");
sb.AppendLine(" {");
sb.AppendLine(" // Skip unexpected token to prevent infinite loops when reading collections");
sb.AppendLine(" reader.Skip();");
sb.AppendLine(" return default;");
sb.AppendLine(" }");
sb.AppendLine();
// Check if this type is polymorphic (from [YamlSerializable] or [YamlPolymorphic] attributes)
var polyInfo = GetPolymorphicInfoForType(type);
if (polyInfo is { DerivedTypes.Count: > 0 } && (type.Symbol.IsAbstract || type.Symbol.TypeKind == TypeKind.Interface))
{
// Generate polymorphic read - dispatch to correct derived type based on discriminator
GeneratePolymorphicRead(sb, type, polyInfo, allTypes, fullTypeName);
sb.AppendLine(" }");
return;
}
else if (polyInfo is { DerivedTypes.Count: > 0 })
{
// Non-abstract base type with derived types - still needs polymorphic dispatch
// but must also handle the case where the base type itself is serialized
GeneratePolymorphicReadWithBaseType(sb, type, polyInfo, allTypes, fullTypeName);
sb.AppendLine(" }");
return;
}
// Collect all public readable properties including inherited (for reading values from YAML)
// Exclude properties with YamlIgnore attribute
var allReadableProperties = GetAllProperties(type.Symbol)
.Where(p => p.GetMethod is not null && !ShouldIgnoreProperty(p))
.ToList();
// Collect settable properties (for object initializer syntax)
// Include both regular setters and init-only setters
var settableProperties = allReadableProperties
.Where(p => p.SetMethod is not null
&& p.SetMethod.DeclaredAccessibility == Accessibility.Public)
.ToList();
// Init-only properties must be set in object initializer, not via assignment
var initOnlyProperties = settableProperties
.Where(p => p.SetMethod!.IsInitOnly)
.ToList();
// Regular settable properties can be set after construction
var regularSettableProperties = settableProperties
.Where(p => !p.SetMethod!.IsInitOnly)
.ToList();
// Find the constructor we'll use (to extract default parameter values)
var constructors = type.Symbol.Constructors
.Where(c => c.DeclaredAccessibility == Accessibility.Public && !c.IsStatic)
.OrderByDescending(c => c.Parameters.Length)
.ToList();
var parameterlessConstructor = constructors.FirstOrDefault(c => c.Parameters.Length == 0);
var primaryConstructor = parameterlessConstructor is null ? constructors.FirstOrDefault() : null;
// Check if any properties have the 'required' modifier - these must always be set
var hasRequiredProperties = settableProperties.Any(p => p.IsRequired);
// Only use the "preserve defaults" optimization if we have a parameterless constructor
// AND no required properties (can't create defaults object with required properties)
var canPreserveDefaults = parameterlessConstructor is not null && !hasRequiredProperties;
// Build a dictionary of property name -> default value from constructor parameters
var constructorDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (primaryConstructor is not null)
{
foreach (var param in primaryConstructor.Parameters)
{
if (param.HasExplicitDefaultValue)
{
var defaultValueStr = GetExplicitDefaultValueString(param);
constructorDefaults[param.Name] = defaultValueStr;
}
}
}
// Declare variables for ALL readable properties (we need to capture values for constructor params too)
foreach (var prop in allReadableProperties)
{
var propName = prop.Name;
var propTypeName = prop.Type.ToDisplayString();
// Use constructor default if available, otherwise use type default
var defaultValue = constructorDefaults.TryGetValue(propName, out var ctorDefault)
? ctorDefault
: GetDefaultValue(prop.Type);
sb.AppendLine($" {propTypeName} _{propName.ToLowerInvariant()} = {defaultValue};");
}
// For types where we can preserve defaults, track which settable properties were actually set from YAML
// This allows the object's property initializers/constructor defaults to be preserved for properties not in YAML
if (canPreserveDefaults)
{
foreach (var prop in settableProperties)
{
sb.AppendLine($" bool _has{prop.Name} = false;");
}
}
sb.AppendLine();
sb.AppendLine(" reader.Read(); // Move past MappingStart");
sb.AppendLine();
sb.AppendLine(" while (reader.TokenType != YamlTokenType.MappingEnd && reader.TokenType != YamlTokenType.None)");
sb.AppendLine(" {");
sb.AppendLine(" if (reader.TokenType != YamlTokenType.Scalar)");
sb.AppendLine(" {");
sb.AppendLine(" reader.Read();");
sb.AppendLine(" continue;");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" var propertyName = reader.GetString();");
sb.AppendLine(" reader.Read();");
sb.AppendLine();
sb.AppendLine(" switch (propertyName)");
sb.AppendLine(" {");
// Generate cases for ALL readable properties (not just settable)
foreach (var prop in allReadableProperties)
{
var propName = prop.Name;
var yamlName = GetYamlPropertyName(prop);
sb.AppendLine($" case \"{yamlName}\":");
// Also accept the original property name and kebab-case as fallbacks
var kebabName = ToKebabCase(propName);
if (yamlName != propName && yamlName != propName.ToLowerInvariant())
{
sb.AppendLine($" case \"{propName}\":");
}
if (yamlName != kebabName && kebabName != propName.ToLowerInvariant())
{
sb.AppendLine($" case \"{kebabName}\":");
}
// Check for sibling discriminator - for simple types, the discriminator applies to the property itself
// For dictionaries, the discriminator applies to the value type (polymorphic dictionary values)
SiblingDiscriminatorInfo? siblingInfo = null;
if (!IsListOrArray(prop.Type, out _, out _))
{
siblingInfo = GetSiblingDiscriminatorInfo(prop);
}
GeneratePropertyRead(sb, propName, prop.Type, allTypes, siblingInfo);
// For types where we can preserve defaults, mark that this settable property was actually set from YAML
// For reference types, only mark as "has value" if the deserialized value is not null
// This ensures that `property:` (empty/null in YAML) preserves the class default value
if (canPreserveDefaults && settableProperties.Contains(prop))
{
var varName = $"_{propName.ToLowerInvariant()}";
if (prop.Type.IsValueType)
{
// Value types are always "set"
sb.AppendLine($" _has{propName} = true;");
}
else
{
// Reference types - only mark as set if not null
sb.AppendLine($" _has{propName} = {varName} is not null;");
}
}
sb.AppendLine(" break;");
}
sb.AppendLine(" default:");
sb.AppendLine(" reader.Skip();");
sb.AppendLine(" break;");
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(" reader.Read(); // Move past MappingEnd");
sb.AppendLine();
// Create instance - reuse constructor info from earlier
if (canPreserveDefaults)
{
// Use parameterless constructor with "preserve defaults" optimization
// Both init-only and regular settable properties: only set if they were actually found in YAML
// This preserves the class's default property values (from constructor or property initializers)
if (initOnlyProperties.Count > 0)
{
sb.AppendLine($" // Create temporary object to capture default values from parameterless constructor");
sb.AppendLine($" var _defaults = new {fullTypeName}();");
sb.AppendLine($" var result = new {fullTypeName}");
sb.AppendLine(" {");
for (int i = 0; i < initOnlyProperties.Count; i++)
{
var prop = initOnlyProperties[i];
var comma = i < initOnlyProperties.Count - 1 ? "," : "";
// Use ternary to pick between YAML value and constructor default
sb.AppendLine($" {prop.Name} = _has{prop.Name} ? _{prop.Name.ToLowerInvariant()} : _defaults.{prop.Name}{comma}");
}
sb.AppendLine(" };");
}
else
{
sb.AppendLine($" var result = new {fullTypeName}();");
}
// Regular properties - only set if present in YAML to preserve class default values
foreach (var prop in regularSettableProperties)
{
sb.AppendLine($" if (_has{prop.Name})");
sb.AppendLine(" {");
sb.AppendLine($" result.{prop.Name} = _{prop.Name.ToLowerInvariant()};");
sb.AppendLine(" }");
}
sb.AppendLine(" return result;");
}
else if (parameterlessConstructor is not null)
{
// Use parameterless constructor but can't preserve defaults (has required properties)
// Must set all properties in object initializer
if (settableProperties.Count > 0)
{
sb.AppendLine($" return new {fullTypeName}");
sb.AppendLine(" {");
for (int i = 0; i < settableProperties.Count; i++)
{
var prop = settableProperties[i];
var comma = i < settableProperties.Count - 1 ? "," : "";
sb.AppendLine($" {prop.Name} = _{prop.Name.ToLowerInvariant()}{comma}");
}
sb.AppendLine(" };");
}
else
{
sb.AppendLine($" return new {fullTypeName}();");
}
}
else
{
// Use primary constructor with matching parameters
if (primaryConstructor is not null)
{
var args = new List<string>();
var usedPropertyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var param in primaryConstructor.Parameters)
{
// Find matching property from ALL readable properties (not just settable)
var matchingProp = allReadableProperties
.FirstOrDefault(p => p.Name.Equals(param.Name, StringComparison.OrdinalIgnoreCase));
if (matchingProp is not null)
{
args.Add($"_{matchingProp.Name.ToLowerInvariant()}");
usedPropertyNames.Add(matchingProp.Name);
}
else
{
args.Add(GetDefaultValue(param.Type));
}
}
// Find settable properties that aren't covered by constructor parameters
var additionalSettableProps = settableProperties
.Where(p => !usedPropertyNames.Contains(p.Name))
.ToList();
if (additionalSettableProps.Count > 0)
{
// Use object initializer syntax after constructor call
sb.AppendLine($" return new {fullTypeName}({string.Join(", ", args)})");
sb.AppendLine(" {");
for (int i = 0; i < additionalSettableProps.Count; i++)
{
var prop = additionalSettableProps[i];
var comma = i < additionalSettableProps.Count - 1 ? "," : "";
sb.AppendLine($" {prop.Name} = _{prop.Name.ToLowerInvariant()}{comma}");
}
sb.AppendLine(" };");
}
else
{
sb.AppendLine($" return new {fullTypeName}({string.Join(", ", args)});");
}
}
else
{
sb.AppendLine($" return default;");
}
}
sb.AppendLine(" }");
}
/// <summary>
/// Generates polymorphic read code using the combined converter approach.
/// This reads ALL properties from ALL derived types in a single pass,
/// then constructs the correct concrete type based on the discriminator value.
/// </summary>
private static void GeneratePolymorphicRead(
StringBuilder sb,
TypeToGenerate type,
PolymorphicInfo polyInfo,
IReadOnlyList<TypeToGenerate> allTypes,
string fullTypeName)
{
// Collect all properties from all derived types
// Key: PropertyName -> (VariableName, TypeSymbol, List of YamlNames)
var allProperties = new Dictionary<string, (string VarName, ITypeSymbol PropType, HashSet<string> YamlNames)>(StringComparer.OrdinalIgnoreCase);
var discriminatorPropertyName = polyInfo.TypeDiscriminatorPropertyName;
// Get properties from the base type first
foreach (var prop in GetAllProperties(type.Symbol).Where(p => p.GetMethod is not null && !ShouldIgnoreProperty(p)))
{
var varName = $"_{prop.Name.ToLowerInvariant()}";
var yamlNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
GetYamlPropertyName(prop),
prop.Name,
ToKebabCase(prop.Name)
};
allProperties[prop.Name] = (varName, prop.Type, yamlNames);
}
// Collect properties from all derived types
foreach (var (_, derivedTypeSymbol) in polyInfo.DerivedTypes)
{