-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathJsonSourceGenerator.Parser.cs
More file actions
2167 lines (1901 loc) · 109 KB
/
JsonSourceGenerator.Parser.cs
File metadata and controls
2167 lines (1901 loc) · 109 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SourceGenerators;
namespace System.Text.Json.SourceGeneration
{
public sealed partial class JsonSourceGenerator
{
// The source generator requires NRT and init-only property support.
private const LanguageVersion MinimumSupportedLanguageVersion = LanguageVersion.CSharp9;
private sealed class Parser
{
private const string SystemTextJsonNamespace = "System.Text.Json";
private const string JsonExtensionDataAttributeFullName = "System.Text.Json.Serialization.JsonExtensionDataAttribute";
private const string JsonIgnoreAttributeFullName = "System.Text.Json.Serialization.JsonIgnoreAttribute";
private const string JsonIgnoreConditionFullName = "System.Text.Json.Serialization.JsonIgnoreCondition";
private const string JsonIncludeAttributeFullName = "System.Text.Json.Serialization.JsonIncludeAttribute";
private const string JsonNumberHandlingAttributeFullName = "System.Text.Json.Serialization.JsonNumberHandlingAttribute";
private const string JsonObjectCreationHandlingAttributeFullName = "System.Text.Json.Serialization.JsonObjectCreationHandlingAttribute";
private const string JsonPropertyNameAttributeFullName = "System.Text.Json.Serialization.JsonPropertyNameAttribute";
private const string JsonPropertyOrderAttributeFullName = "System.Text.Json.Serialization.JsonPropertyOrderAttribute";
private const string JsonRequiredAttributeFullName = "System.Text.Json.Serialization.JsonRequiredAttribute";
internal const string JsonSerializableAttributeFullName = "System.Text.Json.Serialization.JsonSerializableAttribute";
private readonly KnownTypeSymbols _knownSymbols;
private readonly bool _compilationContainsCoreJsonTypes;
// Keeps track of generated context type names
private readonly HashSet<(string ContextName, string TypeName)> _generatedContextAndTypeNames = new();
private readonly HashSet<ITypeSymbol> _builtInSupportTypes;
private readonly Queue<TypeToGenerate> _typesToGenerate = new();
#pragma warning disable RS1024 // Compare symbols correctly https://github.com/dotnet/roslyn-analyzers/issues/5804
private readonly Dictionary<ITypeSymbol, TypeGenerationSpec> _generatedTypes = new(SymbolEqualityComparer.Default);
#pragma warning restore
public List<Diagnostic> Diagnostics { get; } = new();
private Location? _contextClassLocation;
public void ReportDiagnostic(DiagnosticDescriptor descriptor, Location? location, params object?[]? messageArgs)
{
Debug.Assert(_contextClassLocation != null);
if (location is null || !_knownSymbols.Compilation.ContainsLocation(location))
{
// If location is null or is a location outside of the current compilation, fall back to the location of the context class.
location = _contextClassLocation;
}
Diagnostics.Add(Diagnostic.Create(descriptor, location, messageArgs));
}
public Parser(KnownTypeSymbols knownSymbols)
{
_knownSymbols = knownSymbols;
_compilationContainsCoreJsonTypes =
knownSymbols.JsonSerializerContextType != null &&
knownSymbols.JsonSerializableAttributeType != null &&
knownSymbols.JsonSourceGenerationOptionsAttributeType != null &&
knownSymbols.JsonConverterType != null;
_builtInSupportTypes = (knownSymbols.BuiltInSupportTypes ??= CreateBuiltInSupportTypeSet(knownSymbols));
}
public ContextGenerationSpec? ParseContextGenerationSpec(ClassDeclarationSyntax contextClassDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (!_compilationContainsCoreJsonTypes)
{
return null;
}
Debug.Assert(_knownSymbols.JsonSerializerContextType != null);
// Ensure context-scoped metadata caches are empty.
Debug.Assert(_typesToGenerate.Count == 0);
Debug.Assert(_generatedTypes.Count == 0);
Debug.Assert(_contextClassLocation is null);
INamedTypeSymbol? contextTypeSymbol = semanticModel.GetDeclaredSymbol(contextClassDeclaration, cancellationToken);
Debug.Assert(contextTypeSymbol != null);
_contextClassLocation = contextTypeSymbol.GetLocation();
Debug.Assert(_contextClassLocation is not null);
if (!_knownSymbols.JsonSerializerContextType.IsAssignableFrom(contextTypeSymbol))
{
ReportDiagnostic(DiagnosticDescriptors.JsonSerializableAttributeOnNonContextType, _contextClassLocation, contextTypeSymbol.ToDisplayString());
return null;
}
// When a context class is split across multiple partial declarations with
// [JsonSerializable] attributes on different partials, we only want to
// generate code once (from the canonical partial) to avoid duplicate hintNames.
if (!IsCanonicalPartialDeclaration(contextTypeSymbol, contextClassDeclaration))
{
_contextClassLocation = null;
return null;
}
ParseJsonSerializerContextAttributes(contextTypeSymbol,
out List<TypeToGenerate>? rootSerializableTypes,
out SourceGenerationOptionsSpec? options);
if (rootSerializableTypes is null)
{
// No types were annotated with JsonSerializableAttribute.
// Can only be reached if a [JsonSerializable(null)] declaration has been made.
// Do not emit a diagnostic since a NRT warning will also be emitted.
return null;
}
Debug.Assert(rootSerializableTypes.Count > 0);
LanguageVersion? langVersion = _knownSymbols.Compilation.GetLanguageVersion();
if (langVersion is null or < MinimumSupportedLanguageVersion)
{
// Unsupported lang version should be the first (and only) diagnostic emitted by the generator.
ReportDiagnostic(DiagnosticDescriptors.JsonUnsupportedLanguageVersion, _contextClassLocation, langVersion?.ToDisplayString(), MinimumSupportedLanguageVersion.ToDisplayString());
return null;
}
if (!TryGetNestedTypeDeclarations(contextClassDeclaration, semanticModel, cancellationToken, out List<string>? classDeclarationList))
{
// Class or one of its containing types is not partial so we can't add to it.
ReportDiagnostic(DiagnosticDescriptors.ContextClassesMustBePartial, _contextClassLocation, contextTypeSymbol.Name);
return null;
}
// Enqueue attribute data for spec generation
foreach (TypeToGenerate rootSerializableType in rootSerializableTypes)
{
_typesToGenerate.Enqueue(rootSerializableType);
}
// Walk the transitive type graph generating specs for every encountered type.
while (_typesToGenerate.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
TypeToGenerate typeToGenerate = _typesToGenerate.Dequeue();
if (!_generatedTypes.ContainsKey(typeToGenerate.Type))
{
TypeGenerationSpec spec = ParseTypeGenerationSpec(typeToGenerate, contextTypeSymbol, options);
_generatedTypes.Add(typeToGenerate.Type, spec);
}
}
Debug.Assert(_generatedTypes.Count > 0);
ContextGenerationSpec contextGenSpec = new()
{
ContextType = new(contextTypeSymbol),
GeneratedTypes = _generatedTypes.Values.OrderBy(t => t.TypeRef.FullyQualifiedName).ToImmutableEquatableArray(),
Namespace = contextTypeSymbol.ContainingNamespace is { IsGlobalNamespace: false } ns ? ns.ToDisplayString() : null,
ContextClassDeclarations = classDeclarationList.ToImmutableEquatableArray(),
GeneratedOptionsSpec = options,
};
// Clear the caches of generated metadata between the processing of context classes.
_generatedTypes.Clear();
_typesToGenerate.Clear();
_contextClassLocation = null;
return contextGenSpec;
}
private static bool TryGetNestedTypeDeclarations(ClassDeclarationSyntax contextClassSyntax, SemanticModel semanticModel, CancellationToken cancellationToken, [NotNullWhen(true)] out List<string>? typeDeclarations)
{
typeDeclarations = null;
for (TypeDeclarationSyntax? currentType = contextClassSyntax; currentType != null; currentType = currentType.Parent as TypeDeclarationSyntax)
{
StringBuilder stringBuilder = new();
bool isPartialType = false;
foreach (SyntaxToken modifier in currentType.Modifiers)
{
stringBuilder.Append(modifier.Text);
stringBuilder.Append(' ');
isPartialType |= modifier.IsKind(SyntaxKind.PartialKeyword);
}
if (!isPartialType)
{
typeDeclarations = null;
return false;
}
stringBuilder.Append(currentType.GetTypeKindKeyword());
stringBuilder.Append(' ');
INamedTypeSymbol? typeSymbol = semanticModel.GetDeclaredSymbol(currentType, cancellationToken);
Debug.Assert(typeSymbol != null);
string typeName = typeSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
stringBuilder.Append(typeName);
(typeDeclarations ??= new()).Add(stringBuilder.ToString());
}
Debug.Assert(typeDeclarations?.Count > 0);
return true;
}
private TypeRef EnqueueType(ITypeSymbol type, JsonSourceGenerationMode? generationMode)
{
// Trim compile-time erased metadata such as tuple labels and NRT annotations.
type = _knownSymbols.Compilation.EraseCompileTimeMetadata(type);
if (_generatedTypes.TryGetValue(type, out TypeGenerationSpec? spec))
{
return spec.TypeRef;
}
_typesToGenerate.Enqueue(new TypeToGenerate
{
Type = type,
Mode = generationMode,
TypeInfoPropertyName = null,
Location = type.GetLocation(),
AttributeLocation = null,
});
return new TypeRef(type);
}
private void ParseJsonSerializerContextAttributes(
INamedTypeSymbol contextClassSymbol,
out List<TypeToGenerate>? rootSerializableTypes,
out SourceGenerationOptionsSpec? options)
{
Debug.Assert(_knownSymbols.JsonSerializableAttributeType != null);
Debug.Assert(_knownSymbols.JsonSourceGenerationOptionsAttributeType != null);
rootSerializableTypes = null;
options = null;
foreach (AttributeData attributeData in contextClassSymbol.GetAttributes())
{
INamedTypeSymbol? attributeClass = attributeData.AttributeClass;
if (SymbolEqualityComparer.Default.Equals(attributeClass, _knownSymbols.JsonSerializableAttributeType))
{
TypeToGenerate? typeToGenerate = ParseJsonSerializableAttribute(attributeData);
if (typeToGenerate is null)
{
continue;
}
(rootSerializableTypes ??= new()).Add(typeToGenerate.Value);
}
else if (SymbolEqualityComparer.Default.Equals(attributeClass, _knownSymbols.JsonSourceGenerationOptionsAttributeType))
{
options = ParseJsonSourceGenerationOptionsAttribute(contextClassSymbol, attributeData);
}
}
}
/// <summary>
/// Determines if the given class declaration is the canonical partial declaration
/// for the context type. When a context class is split across multiple partial
/// declarations with [JsonSerializable] attributes on different partials, we only
/// want to generate code once (from the canonical partial) to avoid duplicate hintNames.
/// The canonical partial is determined by picking the first syntax tree alphabetically
/// by file path among all trees that have at least one [JsonSerializable] attribute.
/// If file paths are empty or identical, comparison falls back to ordinal string order
/// which provides deterministic behavior. If no attributes are found (edge case that
/// shouldn't occur since this method is called from a context triggered by the attribute),
/// the current partial is treated as canonical.
/// </summary>
private bool IsCanonicalPartialDeclaration(INamedTypeSymbol contextTypeSymbol, ClassDeclarationSyntax contextClassDeclaration)
{
Debug.Assert(_knownSymbols.JsonSerializableAttributeType != null);
// Collect all distinct syntax trees that have [JsonSerializable] attributes for this type
SyntaxTree? canonicalTree = null;
foreach (AttributeData attributeData in contextTypeSymbol.GetAttributes())
{
if (!SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, _knownSymbols.JsonSerializableAttributeType))
{
continue;
}
SyntaxTree? attributeTree = attributeData.ApplicationSyntaxReference?.SyntaxTree;
if (attributeTree is null)
{
continue;
}
// Pick the first tree alphabetically by file path.
// Empty file paths compare as less than non-empty paths with ordinal comparison.
if (canonicalTree is null ||
string.Compare(attributeTree.FilePath, canonicalTree.FilePath, StringComparison.Ordinal) < 0)
{
canonicalTree = attributeTree;
}
}
// This partial is canonical if its syntax tree is the canonical tree.
// If canonicalTree is null (no attributes found), treat current partial as canonical.
// This is a fallback that shouldn't normally occur since this method is called
// from a context triggered by ForAttributeWithMetadataName for JsonSerializableAttribute.
return canonicalTree is null || canonicalTree == contextClassDeclaration.SyntaxTree;
}
private SourceGenerationOptionsSpec ParseJsonSourceGenerationOptionsAttribute(INamedTypeSymbol contextType, AttributeData attributeData)
{
JsonSourceGenerationMode? generationMode = null;
List<TypeRef>? converters = null;
JsonSerializerDefaults? defaults = null;
bool? allowOutOfOrderMetadataProperties = null;
bool? allowTrailingCommas = null;
int? defaultBufferSize = null;
JsonIgnoreCondition? defaultIgnoreCondition = null;
JsonKnownNamingPolicy? dictionaryKeyPolicy = null;
bool? respectNullableAnnotations = null;
bool? ignoreReadOnlyFields = null;
bool? respectRequiredConstructorParameters = null;
bool? ignoreReadOnlyProperties = null;
bool? includeFields = null;
int? maxDepth = null;
string? newLine = null;
JsonNumberHandling? numberHandling = null;
JsonObjectCreationHandling? preferredObjectCreationHandling = null;
bool? propertyNameCaseInsensitive = null;
JsonKnownNamingPolicy? propertyNamingPolicy = null;
JsonCommentHandling? readCommentHandling = null;
JsonKnownReferenceHandler? referenceHandler = null;
JsonUnknownTypeHandling? unknownTypeHandling = null;
JsonUnmappedMemberHandling? unmappedMemberHandling = null;
bool? useStringEnumConverter = null;
bool? writeIndented = null;
char? indentCharacter = null;
int? indentSize = null;
bool? allowDuplicateProperties = null;
if (attributeData.ConstructorArguments.Length > 0)
{
Debug.Assert(attributeData.ConstructorArguments.Length == 1 & attributeData.ConstructorArguments[0].Type?.Name is nameof(JsonSerializerDefaults));
defaults = (JsonSerializerDefaults)attributeData.ConstructorArguments[0].Value!;
}
foreach (KeyValuePair<string, TypedConstant> namedArg in attributeData.NamedArguments)
{
switch (namedArg.Key)
{
case nameof(JsonSourceGenerationOptionsAttribute.AllowOutOfOrderMetadataProperties):
allowOutOfOrderMetadataProperties = (bool)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.AllowTrailingCommas):
allowTrailingCommas = (bool)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.Converters):
converters = new List<TypeRef>();
foreach (TypedConstant element in namedArg.Value.Values)
{
var converterType = (ITypeSymbol?)element.Value;
TypeRef? typeRef = GetConverterTypeFromAttribute(contextType, converterType, contextType, attributeData);
if (typeRef != null)
{
converters.Add(typeRef);
}
}
break;
case nameof(JsonSourceGenerationOptionsAttribute.DefaultBufferSize):
defaultBufferSize = (int)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.DefaultIgnoreCondition):
defaultIgnoreCondition = (JsonIgnoreCondition)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.DictionaryKeyPolicy):
dictionaryKeyPolicy = (JsonKnownNamingPolicy)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.RespectNullableAnnotations):
respectNullableAnnotations = (bool)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.RespectRequiredConstructorParameters):
respectRequiredConstructorParameters = (bool)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.IgnoreReadOnlyFields):
ignoreReadOnlyFields = (bool)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.IgnoreReadOnlyProperties):
ignoreReadOnlyProperties = (bool)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.IncludeFields):
includeFields = (bool)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.MaxDepth):
maxDepth = (int)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.NewLine):
newLine = (string)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.NumberHandling):
numberHandling = (JsonNumberHandling)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.PreferredObjectCreationHandling):
preferredObjectCreationHandling = (JsonObjectCreationHandling)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.PropertyNameCaseInsensitive):
propertyNameCaseInsensitive = (bool)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.PropertyNamingPolicy):
propertyNamingPolicy = (JsonKnownNamingPolicy)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.ReadCommentHandling):
readCommentHandling = (JsonCommentHandling)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.ReferenceHandler):
referenceHandler = (JsonKnownReferenceHandler)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.UnknownTypeHandling):
unknownTypeHandling = (JsonUnknownTypeHandling)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.UnmappedMemberHandling):
unmappedMemberHandling = (JsonUnmappedMemberHandling)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.UseStringEnumConverter):
useStringEnumConverter = (bool)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.WriteIndented):
writeIndented = (bool)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.IndentCharacter):
indentCharacter = (char)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.IndentSize):
indentSize = (int)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.GenerationMode):
generationMode = (JsonSourceGenerationMode)namedArg.Value.Value!;
break;
case nameof(JsonSourceGenerationOptionsAttribute.AllowDuplicateProperties):
allowDuplicateProperties = (bool)namedArg.Value.Value!;
break;
default:
throw new InvalidOperationException();
}
}
return new SourceGenerationOptionsSpec
{
GenerationMode = generationMode,
Defaults = defaults,
AllowOutOfOrderMetadataProperties = allowOutOfOrderMetadataProperties,
AllowTrailingCommas = allowTrailingCommas,
DefaultBufferSize = defaultBufferSize,
Converters = converters?.ToImmutableEquatableArray(),
DefaultIgnoreCondition = defaultIgnoreCondition,
DictionaryKeyPolicy = dictionaryKeyPolicy,
RespectNullableAnnotations = respectNullableAnnotations,
RespectRequiredConstructorParameters = respectRequiredConstructorParameters,
IgnoreReadOnlyFields = ignoreReadOnlyFields,
IgnoreReadOnlyProperties = ignoreReadOnlyProperties,
IncludeFields = includeFields,
MaxDepth = maxDepth,
NewLine = newLine,
NumberHandling = numberHandling,
PreferredObjectCreationHandling = preferredObjectCreationHandling,
PropertyNameCaseInsensitive = propertyNameCaseInsensitive,
PropertyNamingPolicy = propertyNamingPolicy,
ReadCommentHandling = readCommentHandling,
ReferenceHandler = referenceHandler,
UnknownTypeHandling = unknownTypeHandling,
UnmappedMemberHandling = unmappedMemberHandling,
UseStringEnumConverter = useStringEnumConverter,
WriteIndented = writeIndented,
IndentCharacter = indentCharacter,
IndentSize = indentSize,
AllowDuplicateProperties = allowDuplicateProperties,
};
}
private TypeToGenerate? ParseJsonSerializableAttribute(AttributeData attributeData)
{
Debug.Assert(attributeData.ConstructorArguments.Length == 1);
var typeSymbol = (ITypeSymbol?)attributeData.ConstructorArguments[0].Value;
if (typeSymbol is null)
{
return null;
}
JsonSourceGenerationMode? generationMode = null;
string? typeInfoPropertyName = null;
foreach (KeyValuePair<string, TypedConstant> namedArg in attributeData.NamedArguments)
{
switch (namedArg.Key)
{
case nameof(JsonSerializableAttribute.TypeInfoPropertyName):
typeInfoPropertyName = (string)namedArg.Value.Value!;
break;
case nameof(JsonSerializableAttribute.GenerationMode):
generationMode = (JsonSourceGenerationMode)namedArg.Value.Value!;
break;
default:
throw new InvalidOperationException();
}
}
Location? location = typeSymbol.GetLocation();
Location? attributeLocation = attributeData.GetLocation();
Debug.Assert(attributeLocation != null);
if (location is null || !_knownSymbols.Compilation.ContainsLocation(location))
{
// For symbols located outside the compilation, fall back to attribute location instead.
location = attributeLocation;
}
return new TypeToGenerate
{
Type = _knownSymbols.Compilation.EraseCompileTimeMetadata(typeSymbol),
Mode = generationMode,
TypeInfoPropertyName = typeInfoPropertyName,
Location = location,
AttributeLocation = attributeLocation,
};
}
private TypeGenerationSpec ParseTypeGenerationSpec(in TypeToGenerate typeToGenerate, INamedTypeSymbol contextType, SourceGenerationOptionsSpec? options)
{
Debug.Assert(IsSymbolAccessibleWithin(typeToGenerate.Type, within: contextType), "should not generate metadata for inaccessible types.");
ITypeSymbol type = typeToGenerate.Type;
ClassType classType;
JsonPrimitiveTypeKind? primitiveTypeKind = GetPrimitiveTypeKind(type);
TypeRef? collectionKeyType = null;
TypeRef? collectionValueType = null;
TypeRef? nullableUnderlyingType = null;
bool hasExtensionDataProperty = false;
TypeRef? runtimeTypeRef = null;
List<PropertyGenerationSpec>? propertySpecs = null;
List<int>? fastPathPropertyIndices = null;
ObjectConstructionStrategy constructionStrategy = default;
bool constructorSetsRequiredMembers = false;
bool constructorIsInaccessible = false;
ParameterGenerationSpec[]? ctorParamSpecs = null;
List<PropertyInitializerGenerationSpec>? propertyInitializerSpecs = null;
CollectionType collectionType = CollectionType.NotApplicable;
string? immutableCollectionFactoryTypeFullName = null;
bool implementsIJsonOnSerialized = false;
bool implementsIJsonOnSerializing = false;
ProcessTypeCustomAttributes(typeToGenerate, contextType,
out JsonNumberHandling? numberHandling,
out JsonUnmappedMemberHandling? unmappedMemberHandling,
out JsonObjectCreationHandling? preferredPropertyObjectCreationHandling,
out JsonKnownNamingPolicy? typeNamingPolicy,
out JsonIgnoreCondition? typeIgnoreCondition,
out bool foundJsonConverterAttribute,
out TypeRef? customConverterType,
out bool isPolymorphic);
if (type is { IsRefLikeType: true } or INamedTypeSymbol { IsUnboundGenericType: true } or IErrorTypeSymbol)
{
classType = ClassType.TypeUnsupportedBySourceGen;
}
else if (foundJsonConverterAttribute)
{
classType = customConverterType != null
? ClassType.TypeWithDesignTimeProvidedCustomConverter
: ClassType.TypeUnsupportedBySourceGen;
}
else if (IsBuiltInSupportType(type))
{
classType = ClassType.BuiltInSupportType;
}
else if (IsUnsupportedType(type))
{
classType = ClassType.UnsupportedType;
}
else if (type.IsNullableValueType(out ITypeSymbol? underlyingType))
{
classType = ClassType.Nullable;
nullableUnderlyingType = EnqueueType(underlyingType, typeToGenerate.Mode);
}
else if (type.TypeKind is TypeKind.Enum)
{
if (options?.UseStringEnumConverter == true)
{
Debug.Assert(_knownSymbols.JsonStringEnumConverterOfTType != null);
INamedTypeSymbol converterSymbol = _knownSymbols.JsonStringEnumConverterOfTType.Construct(type);
customConverterType = new TypeRef(converterSymbol);
classType = ClassType.TypeWithDesignTimeProvidedCustomConverter;
}
else
{
classType = ClassType.Enum;
}
}
else if (TryResolveCollectionType(type,
out ITypeSymbol? valueType,
out ITypeSymbol? keyType,
out collectionType,
out immutableCollectionFactoryTypeFullName,
out bool needsRuntimeType))
{
if (!IsSymbolAccessibleWithin(valueType, within: contextType) ||
(keyType != null && !IsSymbolAccessibleWithin(keyType, within: contextType)))
{
classType = ClassType.UnsupportedType;
immutableCollectionFactoryTypeFullName = null;
collectionType = default;
}
else if (valueType.IsRefLikeType || keyType?.IsRefLikeType is true)
{
classType = ClassType.TypeUnsupportedBySourceGen;
immutableCollectionFactoryTypeFullName = null;
collectionType = default;
}
else
{
if (type.CanUseDefaultConstructorForDeserialization(out IMethodSymbol? defaultCtor))
{
constructionStrategy = ObjectConstructionStrategy.ParameterlessConstructor;
constructorSetsRequiredMembers = defaultCtor?.ContainsAttribute(_knownSymbols.SetsRequiredMembersAttributeType) == true;
}
classType = keyType != null ? ClassType.Dictionary : ClassType.Enumerable;
collectionValueType = EnqueueType(valueType, typeToGenerate.Mode);
if (keyType != null)
{
collectionKeyType = EnqueueType(keyType, typeToGenerate.Mode);
if (needsRuntimeType)
{
runtimeTypeRef = GetDictionaryTypeRef(keyType, valueType);
}
}
}
}
else
{
bool useDefaultCtorInAnnotatedStructs = type.GetCompatibleGenericBaseType(_knownSymbols.KeyValuePair) is null;
if (!TryGetDeserializationConstructor(type, useDefaultCtorInAnnotatedStructs, out IMethodSymbol? constructor))
{
ReportDiagnostic(DiagnosticDescriptors.MultipleJsonConstructorAttribute, typeToGenerate.Location, type.ToDisplayString());
}
constructorIsInaccessible = constructor is not null && !IsSymbolAccessibleWithin(constructor, within: contextType);
classType = ClassType.Object;
implementsIJsonOnSerializing = _knownSymbols.IJsonOnSerializingType.IsAssignableFrom(type);
implementsIJsonOnSerialized = _knownSymbols.IJsonOnSerializedType.IsAssignableFrom(type);
ctorParamSpecs = ParseConstructorParameters(typeToGenerate, constructor, out constructionStrategy, out constructorSetsRequiredMembers);
propertySpecs = ParsePropertyGenerationSpecs(contextType, typeToGenerate, typeIgnoreCondition, options, typeNamingPolicy, out hasExtensionDataProperty, out fastPathPropertyIndices);
propertyInitializerSpecs = ParsePropertyInitializers(ctorParamSpecs, propertySpecs, constructorSetsRequiredMembers, ref constructionStrategy);
}
var typeRef = new TypeRef(type);
string typeInfoPropertyName = typeToGenerate.TypeInfoPropertyName ?? GetTypeInfoPropertyName(type);
if (classType is ClassType.TypeUnsupportedBySourceGen)
{
ReportDiagnostic(DiagnosticDescriptors.TypeNotSupported, typeToGenerate.AttributeLocation ?? typeToGenerate.Location, type.ToDisplayString());
}
if (!_generatedContextAndTypeNames.Add((contextType.Name, typeInfoPropertyName)))
{
// The context name/property name combination will result in a conflict in generated types.
// Workaround for https://github.com/dotnet/roslyn/issues/54185 by keeping track of the file names we've used.
ReportDiagnostic(DiagnosticDescriptors.DuplicateTypeName, typeToGenerate.AttributeLocation ?? _contextClassLocation, typeInfoPropertyName);
classType = ClassType.TypeUnsupportedBySourceGen;
}
return new TypeGenerationSpec
{
TypeRef = typeRef,
TypeInfoPropertyName = typeInfoPropertyName,
GenerationMode = typeToGenerate.Mode ?? options?.GenerationMode ?? JsonSourceGenerationMode.Default,
ClassType = classType,
PrimitiveTypeKind = primitiveTypeKind,
IsPolymorphic = isPolymorphic,
NumberHandling = numberHandling,
UnmappedMemberHandling = unmappedMemberHandling,
PreferredPropertyObjectCreationHandling = preferredPropertyObjectCreationHandling,
PropertyGenSpecs = propertySpecs?.ToImmutableEquatableArray() ?? ImmutableEquatableArray<PropertyGenerationSpec>.Empty,
FastPathPropertyIndices = fastPathPropertyIndices?.ToImmutableEquatableArray(),
PropertyInitializerSpecs = propertyInitializerSpecs?.ToImmutableEquatableArray() ?? ImmutableEquatableArray<PropertyInitializerGenerationSpec>.Empty,
CtorParamGenSpecs = ctorParamSpecs?.ToImmutableEquatableArray() ?? ImmutableEquatableArray<ParameterGenerationSpec>.Empty,
CollectionType = collectionType,
CollectionKeyType = collectionKeyType,
CollectionValueType = collectionValueType,
ConstructionStrategy = constructionStrategy,
ConstructorSetsRequiredParameters = constructorSetsRequiredMembers,
ConstructorIsInaccessible = constructorIsInaccessible,
CanUseUnsafeAccessorForConstructor = constructorIsInaccessible
&& _knownSymbols.UnsafeAccessorAttributeType is not null
&& type is not INamedTypeSymbol { IsGenericType: true },
NullableUnderlyingType = nullableUnderlyingType,
RuntimeTypeRef = runtimeTypeRef,
IsValueTuple = type.IsTupleType,
HasExtensionDataPropertyType = hasExtensionDataProperty,
ConverterType = customConverterType,
ImplementsIJsonOnSerialized = implementsIJsonOnSerialized,
ImplementsIJsonOnSerializing = implementsIJsonOnSerializing,
ImmutableCollectionFactoryMethod = DetermineImmutableCollectionFactoryMethod(immutableCollectionFactoryTypeFullName),
};
}
private void ProcessTypeCustomAttributes(
in TypeToGenerate typeToGenerate,
INamedTypeSymbol contextType,
out JsonNumberHandling? numberHandling,
out JsonUnmappedMemberHandling? unmappedMemberHandling,
out JsonObjectCreationHandling? objectCreationHandling,
out JsonKnownNamingPolicy? namingPolicy,
out JsonIgnoreCondition? typeIgnoreCondition,
out bool foundJsonConverterAttribute,
out TypeRef? customConverterType,
out bool isPolymorphic)
{
numberHandling = null;
unmappedMemberHandling = null;
objectCreationHandling = null;
namingPolicy = null;
typeIgnoreCondition = null;
customConverterType = null;
foundJsonConverterAttribute = false;
isPolymorphic = false;
foreach (AttributeData attributeData in typeToGenerate.Type.GetAttributes())
{
INamedTypeSymbol? attributeType = attributeData.AttributeClass;
if (SymbolEqualityComparer.Default.Equals(attributeType, _knownSymbols.JsonNumberHandlingAttributeType))
{
numberHandling = (JsonNumberHandling)attributeData.ConstructorArguments[0].Value!;
continue;
}
else if (SymbolEqualityComparer.Default.Equals(attributeType, _knownSymbols.JsonUnmappedMemberHandlingAttributeType))
{
unmappedMemberHandling = (JsonUnmappedMemberHandling)attributeData.ConstructorArguments[0].Value!;
continue;
}
else if (SymbolEqualityComparer.Default.Equals(attributeType, _knownSymbols.JsonObjectCreationHandlingAttributeType))
{
objectCreationHandling = (JsonObjectCreationHandling)attributeData.ConstructorArguments[0].Value!;
continue;
}
else if (_knownSymbols.JsonNamingPolicyAttributeType?.IsAssignableFrom(attributeType) == true)
{
if (attributeData.ConstructorArguments.Length == 1 &&
attributeData.ConstructorArguments[0].Value is int knownPolicyValue)
{
namingPolicy = (JsonKnownNamingPolicy)knownPolicyValue;
}
else
{
// The attribute uses a custom naming policy that can't be resolved at compile time.
// Use Unspecified to prevent the global naming policy from incorrectly applying.
namingPolicy = JsonKnownNamingPolicy.Unspecified;
}
continue;
}
else if (!foundJsonConverterAttribute && _knownSymbols.JsonConverterAttributeType.IsAssignableFrom(attributeType))
{
customConverterType = GetConverterTypeFromJsonConverterAttribute(contextType, typeToGenerate.Type, attributeData);
foundJsonConverterAttribute = true;
}
if (SymbolEqualityComparer.Default.Equals(attributeType, _knownSymbols.JsonIgnoreAttributeType))
{
ImmutableArray<KeyValuePair<string, TypedConstant>> namedArgs = attributeData.NamedArguments;
if (namedArgs.Length == 0)
{
typeIgnoreCondition = JsonIgnoreCondition.Always;
}
else if (namedArgs.Length == 1 &&
namedArgs[0].Value.Type?.ToDisplayString() == JsonIgnoreConditionFullName)
{
typeIgnoreCondition = (JsonIgnoreCondition)namedArgs[0].Value.Value!;
}
if (typeIgnoreCondition == JsonIgnoreCondition.Always)
{
ReportDiagnostic(DiagnosticDescriptors.JsonIgnoreConditionAlwaysInvalidOnType, typeToGenerate.Location, typeToGenerate.Type.ToDisplayString());
typeIgnoreCondition = null; // Reset so it doesn't affect properties
}
}
if (SymbolEqualityComparer.Default.Equals(attributeType, _knownSymbols.JsonDerivedTypeAttributeType))
{
Debug.Assert(attributeData.ConstructorArguments.Length > 0);
var derivedType = (ITypeSymbol)attributeData.ConstructorArguments[0].Value!;
EnqueueType(derivedType, typeToGenerate.Mode);
if (!isPolymorphic && typeToGenerate.Mode == JsonSourceGenerationMode.Serialization)
{
ReportDiagnostic(DiagnosticDescriptors.PolymorphismNotSupported, typeToGenerate.Location, typeToGenerate.Type.ToDisplayString());
}
isPolymorphic = true;
}
}
}
private bool TryResolveCollectionType(
ITypeSymbol type,
[NotNullWhen(true)] out ITypeSymbol? valueType,
out ITypeSymbol? keyType,
out CollectionType collectionType,
out string? immutableCollectionFactoryTypeFullName,
out bool needsRuntimeType)
{
INamedTypeSymbol? actualTypeToConvert;
valueType = null;
keyType = null;
collectionType = default;
immutableCollectionFactoryTypeFullName = null;
needsRuntimeType = false;
if (SymbolEqualityComparer.Default.Equals(type.OriginalDefinition, _knownSymbols.MemoryType))
{
Debug.Assert(!SymbolEqualityComparer.Default.Equals(type, _knownSymbols.MemoryByteType));
valueType = ((INamedTypeSymbol)type).TypeArguments[0];
collectionType = CollectionType.MemoryOfT;
return true;
}
if (SymbolEqualityComparer.Default.Equals(type.OriginalDefinition, _knownSymbols.ReadOnlyMemoryType))
{
Debug.Assert(!SymbolEqualityComparer.Default.Equals(type, _knownSymbols.ReadOnlyMemoryByteType));
valueType = ((INamedTypeSymbol)type).TypeArguments[0];
collectionType = CollectionType.ReadOnlyMemoryOfT;
return true;
}
// IAsyncEnumerable<T> takes precedence over IEnumerable.
if (type.GetCompatibleGenericBaseType(_knownSymbols.IAsyncEnumerableOfTType) is INamedTypeSymbol iAsyncEnumerableType)
{
valueType = iAsyncEnumerableType.TypeArguments[0];
collectionType = CollectionType.IAsyncEnumerableOfT;
return true;
}
if (!_knownSymbols.IEnumerableType.IsAssignableFrom(type))
{
// Type is not IEnumerable and therefore not a collection type
return false;
}
if (type is IArrayTypeSymbol arraySymbol)
{
Debug.Assert(arraySymbol.Rank == 1, "multi-dimensional arrays should have been handled earlier.");
collectionType = CollectionType.Array;
valueType = arraySymbol.ElementType;
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.KeyedCollectionType)) != null)
{
collectionType = CollectionType.ICollectionOfT;
valueType = actualTypeToConvert.TypeArguments[1];
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.ListOfTType)) != null)
{
collectionType = CollectionType.List;
valueType = actualTypeToConvert.TypeArguments[0];
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.DictionaryOfTKeyTValueType)) != null)
{
collectionType = CollectionType.Dictionary;
keyType = actualTypeToConvert.TypeArguments[0];
valueType = actualTypeToConvert.TypeArguments[1];
}
else if (_knownSymbols.IsImmutableDictionaryType(type, out immutableCollectionFactoryTypeFullName))
{
collectionType = CollectionType.ImmutableDictionary;
ImmutableArray<ITypeSymbol> genericArgs = ((INamedTypeSymbol)type).TypeArguments;
keyType = genericArgs[0];
valueType = genericArgs[1];
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.IDictionaryOfTKeyTValueType)) != null)
{
collectionType = CollectionType.IDictionaryOfTKeyTValue;
keyType = actualTypeToConvert.TypeArguments[0];
valueType = actualTypeToConvert.TypeArguments[1];
needsRuntimeType = SymbolEqualityComparer.Default.Equals(type, actualTypeToConvert);
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.IReadonlyDictionaryOfTKeyTValueType)) != null)
{
collectionType = CollectionType.IReadOnlyDictionary;
keyType = actualTypeToConvert.TypeArguments[0];
valueType = actualTypeToConvert.TypeArguments[1];
needsRuntimeType = SymbolEqualityComparer.Default.Equals(type, actualTypeToConvert);
}
else if (_knownSymbols.IsImmutableEnumerableType(type, out immutableCollectionFactoryTypeFullName))
{
collectionType = CollectionType.ImmutableEnumerable;
valueType = ((INamedTypeSymbol)type).TypeArguments[0];
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.IListOfTType)) != null)
{
collectionType = CollectionType.IListOfT;
valueType = actualTypeToConvert.TypeArguments[0];
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.ISetOfTType)) != null)
{
collectionType = CollectionType.ISet;
valueType = actualTypeToConvert.TypeArguments[0];
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.IReadOnlySetOfTType)) != null)
{
collectionType = CollectionType.IReadOnlySetOfT;
valueType = actualTypeToConvert.TypeArguments[0];
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.ICollectionOfTType)) != null)
{
collectionType = CollectionType.ICollectionOfT;
valueType = actualTypeToConvert.TypeArguments[0];
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.StackOfTType)) != null)
{
collectionType = CollectionType.StackOfT;
valueType = actualTypeToConvert.TypeArguments[0];
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.QueueOfTType)) != null)
{
collectionType = CollectionType.QueueOfT;
valueType = actualTypeToConvert.TypeArguments[0];
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.ConcurrentStackType)) != null)
{
collectionType = CollectionType.ConcurrentStack;
valueType = actualTypeToConvert.TypeArguments[0];
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.ConcurrentQueueType)) != null)
{
collectionType = CollectionType.ConcurrentQueue;
valueType = actualTypeToConvert.TypeArguments[0];
}
else if ((actualTypeToConvert = type.GetCompatibleGenericBaseType(_knownSymbols.IEnumerableOfTType)) != null)
{
collectionType = CollectionType.IEnumerableOfT;
valueType = actualTypeToConvert.TypeArguments[0];
}
else if (_knownSymbols.IDictionaryType.IsAssignableFrom(type))
{
collectionType = CollectionType.IDictionary;
keyType = _knownSymbols.StringType;
valueType = _knownSymbols.ObjectType;
needsRuntimeType = SymbolEqualityComparer.Default.Equals(type, actualTypeToConvert);
}
else if (_knownSymbols.IListType.IsAssignableFrom(type))
{
collectionType = CollectionType.IList;
valueType = _knownSymbols.ObjectType;
}
else if (_knownSymbols.StackType.IsAssignableFrom(type))
{
collectionType = CollectionType.Stack;