-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
JsonSourceGenerator.Emitter.cs
1498 lines (1204 loc) · 78.8 KB
/
JsonSourceGenerator.Emitter.cs
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.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text.Json.Serialization;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using SourceGenerators;
namespace System.Text.Json.SourceGeneration
{
public sealed partial class JsonSourceGenerator
{
private sealed partial class Emitter
{
// Literals in generated source
private const string CreateValueInfoMethodName = "CreateValueInfo";
private const string CtorParamInitMethodNameSuffix = "CtorParamInit";
private const string DefaultOptionsStaticVarName = "s_defaultOptions";
private const string InstanceMemberBindingFlagsVariableName = "InstanceMemberBindingFlags";
private const string OriginatingResolverPropertyName = "OriginatingResolver";
private const string InfoVarName = "info";
private const string NumberHandlingPropName = "NumberHandling";
private const string UnmappedMemberHandlingPropName = "UnmappedMemberHandling";
private const string PreferredPropertyObjectCreationHandlingPropName = "PreferredPropertyObjectCreationHandling";
private const string ObjectCreatorPropName = "ObjectCreator";
private const string OptionsInstanceVariableName = "Options";
private const string JsonTypeInfoLocalVariableName = "jsonTypeInfo";
private const string PropInitMethodNameSuffix = "PropInit";
private const string TryGetTypeInfoForRuntimeCustomConverterMethodName = "TryGetTypeInfoForRuntimeCustomConverter";
private const string ExpandConverterMethodName = "ExpandConverter";
private const string GetConverterForNullablePropertyMethodName = "GetConverterForNullableProperty";
private const string SerializeHandlerPropName = "SerializeHandler";
private const string OptionsLocalVariableName = "options";
private const string ValueVarName = "value";
private const string WriterVarName = "writer";
private static readonly AssemblyName s_assemblyName = typeof(Emitter).Assembly.GetName();
// global::fully.qualified.name for referenced types
private const string InvalidOperationExceptionTypeRef = "global::System.InvalidOperationException";
private const string JsonExceptionTypeRef = "global::System.Text.Json.JsonException";
private const string TypeTypeRef = "global::System.Type";
private const string UnsafeTypeRef = "global::System.Runtime.CompilerServices.Unsafe";
private const string EqualityComparerTypeRef = "global::System.Collections.Generic.EqualityComparer";
private const string KeyValuePairTypeRef = "global::System.Collections.Generic.KeyValuePair";
private const string JsonEncodedTextTypeRef = "global::System.Text.Json.JsonEncodedText";
private const string JsonNamingPolicyTypeRef = "global::System.Text.Json.JsonNamingPolicy";
private const string JsonSerializerTypeRef = "global::System.Text.Json.JsonSerializer";
private const string JsonSerializerOptionsTypeRef = "global::System.Text.Json.JsonSerializerOptions";
private const string JsonSerializerContextTypeRef = "global::System.Text.Json.Serialization.JsonSerializerContext";
private const string Utf8JsonWriterTypeRef = "global::System.Text.Json.Utf8JsonWriter";
private const string JsonCommentHandlingTypeRef = "global::System.Text.Json.JsonCommentHandling";
private const string JsonConverterTypeRef = "global::System.Text.Json.Serialization.JsonConverter";
private const string JsonConverterFactoryTypeRef = "global::System.Text.Json.Serialization.JsonConverterFactory";
private const string JsonCollectionInfoValuesTypeRef = "global::System.Text.Json.Serialization.Metadata.JsonCollectionInfoValues";
private const string JsonIgnoreConditionTypeRef = "global::System.Text.Json.Serialization.JsonIgnoreCondition";
private const string JsonSerializerDefaultsTypeRef = "global::System.Text.Json.JsonSerializerDefaults";
private const string JsonNumberHandlingTypeRef = "global::System.Text.Json.Serialization.JsonNumberHandling";
private const string JsonObjectCreationHandlingTypeRef = "global::System.Text.Json.Serialization.JsonObjectCreationHandling";
private const string JsonUnmappedMemberHandlingTypeRef = "global::System.Text.Json.Serialization.JsonUnmappedMemberHandling";
private const string JsonUnknownTypeHandlingTypeRef = "global::System.Text.Json.Serialization.JsonUnknownTypeHandling";
private const string JsonMetadataServicesTypeRef = "global::System.Text.Json.Serialization.Metadata.JsonMetadataServices";
private const string JsonObjectInfoValuesTypeRef = "global::System.Text.Json.Serialization.Metadata.JsonObjectInfoValues";
private const string JsonParameterInfoValuesTypeRef = "global::System.Text.Json.Serialization.Metadata.JsonParameterInfoValues";
private const string JsonPropertyInfoTypeRef = "global::System.Text.Json.Serialization.Metadata.JsonPropertyInfo";
private const string JsonPropertyInfoValuesTypeRef = "global::System.Text.Json.Serialization.Metadata.JsonPropertyInfoValues";
private const string JsonTypeInfoTypeRef = "global::System.Text.Json.Serialization.Metadata.JsonTypeInfo";
private const string JsonTypeInfoResolverTypeRef = "global::System.Text.Json.Serialization.Metadata.IJsonTypeInfoResolver";
private const string EmptyTypeArray = "global::System.Array.Empty<global::System.Type>()";
/// <summary>
/// Contains an index from TypeRef to TypeGenerationSpec for the current ContextGenerationSpec.
/// </summary>
private readonly Dictionary<TypeRef, TypeGenerationSpec> _typeIndex = new();
/// <summary>
/// Cache of property names (statically determined) found across the type graph of the JsonSerializerContext.
/// The dictionary Key is the JSON property name, and the Value is the variable name which is the same as the property
/// name except for cases where special characters are used with [JsonPropertyName].
/// </summary>
private readonly Dictionary<string, string> _propertyNames = new();
/// <summary>
/// Indicates that the type graph contains a nullable property with a design-time custom converter declaration.
/// </summary>
private bool _emitGetConverterForNullablePropertyMethod;
/// <summary>
/// The SourceText emit implementation filled by the individual Roslyn versions.
/// </summary>
private partial void AddSource(string hintName, SourceText sourceText);
public void Emit(ContextGenerationSpec contextGenerationSpec)
{
Debug.Assert(_typeIndex.Count == 0);
Debug.Assert(_propertyNames.Count == 0);
Debug.Assert(!_emitGetConverterForNullablePropertyMethod);
foreach (TypeGenerationSpec spec in contextGenerationSpec.GeneratedTypes)
{
_typeIndex.Add(spec.TypeRef, spec);
}
foreach (TypeGenerationSpec typeGenerationSpec in contextGenerationSpec.GeneratedTypes)
{
SourceText? sourceText = GenerateTypeInfo(contextGenerationSpec, typeGenerationSpec);
if (sourceText != null)
{
AddSource($"{contextGenerationSpec.ContextType.Name}.{typeGenerationSpec.TypeInfoPropertyName}.g.cs", sourceText);
}
}
string contextName = contextGenerationSpec.ContextType.Name;
// Add root context implementation.
AddSource($"{contextName}.g.cs", GetRootJsonContextImplementation(contextGenerationSpec, _emitGetConverterForNullablePropertyMethod));
// Add GetJsonTypeInfo override implementation.
AddSource($"{contextName}.GetJsonTypeInfo.g.cs", GetGetTypeInfoImplementation(contextGenerationSpec));
// Add property name initialization.
AddSource($"{contextName}.PropertyNames.g.cs", GetPropertyNameInitialization(contextGenerationSpec));
_emitGetConverterForNullablePropertyMethod = false;
_propertyNames.Clear();
_typeIndex.Clear();
}
private static SourceWriter CreateSourceWriterWithContextHeader(ContextGenerationSpec contextSpec, bool isPrimaryContextSourceFile = false, string? interfaceImplementation = null)
{
var writer = new SourceWriter();
writer.WriteLine("""
// <auto-generated/>
#nullable enable annotations
#nullable disable warnings
// Suppress warnings about [Obsolete] member usage in generated code.
#pragma warning disable CS0612, CS0618
""");
if (contextSpec.Namespace != null)
{
writer.WriteLine($"namespace {contextSpec.Namespace}");
writer.WriteLine('{');
writer.Indentation++;
}
ImmutableEquatableArray<string> contextClasses = contextSpec.ContextClassDeclarations;
Debug.Assert(contextClasses.Count > 0);
// Emit any containing classes first.
for (int i = contextClasses.Count - 1; i > 0; i--)
{
writer.WriteLine(contextClasses[i]);
writer.WriteLine('{');
writer.Indentation++;
}
if (isPrimaryContextSourceFile)
{
// Annotate context class with the GeneratedCodeAttribute
writer.WriteLine($"""[global::System.CodeDom.Compiler.GeneratedCodeAttribute("{s_assemblyName.Name}", "{s_assemblyName.Version}")]""");
}
// Emit the JsonSerializerContext class declaration
writer.WriteLine($"{contextClasses[0]}{(interfaceImplementation is null ? "" : " : " + interfaceImplementation)}");
writer.WriteLine('{');
writer.Indentation++;
return writer;
}
private static SourceText CompleteSourceFileAndReturnText(SourceWriter writer)
{
while (writer.Indentation > 0)
{
writer.Indentation--;
writer.WriteLine('}');
}
return writer.ToSourceText();
}
private SourceText? GenerateTypeInfo(ContextGenerationSpec contextSpec, TypeGenerationSpec typeGenerationSpec)
{
switch (typeGenerationSpec.ClassType)
{
case ClassType.BuiltInSupportType:
return GenerateForTypeWithBuiltInConverter(contextSpec, typeGenerationSpec);
case ClassType.TypeWithDesignTimeProvidedCustomConverter:
return GenerateForTypeWithCustomConverter(contextSpec, typeGenerationSpec);
case ClassType.Nullable:
return GenerateForNullable(contextSpec, typeGenerationSpec);
case ClassType.Enum:
return GenerateForEnum(contextSpec, typeGenerationSpec);
case ClassType.Enumerable:
case ClassType.Dictionary:
return GenerateForCollection(contextSpec, typeGenerationSpec);
case ClassType.Object:
return GenerateForObject(contextSpec, typeGenerationSpec);
case ClassType.UnsupportedType:
return GenerateForUnsupportedType(contextSpec, typeGenerationSpec);
case ClassType.TypeUnsupportedBySourceGen:
return null; // Do not emit a source file for the type.
default:
Debug.Fail($"Unexpected class type {typeGenerationSpec.ClassType}");
return null;
}
}
private static SourceText GenerateForTypeWithBuiltInConverter(ContextGenerationSpec contextSpec, TypeGenerationSpec typeMetadata)
{
SourceWriter writer = CreateSourceWriterWithContextHeader(contextSpec);
string typeFQN = typeMetadata.TypeRef.FullyQualifiedName;
string typeInfoPropertyName = typeMetadata.TypeInfoPropertyName;
GenerateTypeInfoFactoryHeader(writer, typeMetadata);
writer.WriteLine($"""
{JsonTypeInfoLocalVariableName} = {JsonMetadataServicesTypeRef}.{GetCreateValueInfoMethodRef(typeFQN)}({OptionsLocalVariableName}, {JsonMetadataServicesTypeRef}.{typeInfoPropertyName}Converter);
""");
GenerateTypeInfoFactoryFooter(writer);
return CompleteSourceFileAndReturnText(writer);
}
private static SourceText GenerateForTypeWithCustomConverter(ContextGenerationSpec contextSpec, TypeGenerationSpec typeMetadata)
{
Debug.Assert(typeMetadata.ConverterType != null);
SourceWriter writer = CreateSourceWriterWithContextHeader(contextSpec);
string typeFQN = typeMetadata.TypeRef.FullyQualifiedName;
string converterFQN = typeMetadata.ConverterType.FullyQualifiedName;
GenerateTypeInfoFactoryHeader(writer, typeMetadata);
writer.WriteLine($"""
{JsonConverterTypeRef} converter = {ExpandConverterMethodName}(typeof({typeFQN}), new {converterFQN}(), {OptionsLocalVariableName});
{JsonTypeInfoLocalVariableName} = {JsonMetadataServicesTypeRef}.{GetCreateValueInfoMethodRef(typeFQN)} ({OptionsLocalVariableName}, converter);
""");
GenerateTypeInfoFactoryFooter(writer);
return CompleteSourceFileAndReturnText(writer);
}
private static SourceText GenerateForNullable(ContextGenerationSpec contextSpec, TypeGenerationSpec typeMetadata)
{
Debug.Assert(typeMetadata.NullableUnderlyingType != null);
SourceWriter writer = CreateSourceWriterWithContextHeader(contextSpec);
string typeFQN = typeMetadata.TypeRef.FullyQualifiedName;
string underlyingTypeFQN = typeMetadata.NullableUnderlyingType.FullyQualifiedName;
GenerateTypeInfoFactoryHeader(writer, typeMetadata);
writer.WriteLine($$"""
{{JsonConverterTypeRef}} converter = {{JsonMetadataServicesTypeRef}}.GetNullableConverter<{{underlyingTypeFQN}}>({{OptionsLocalVariableName}});
{{JsonTypeInfoLocalVariableName}} = {{JsonMetadataServicesTypeRef}}.{{GetCreateValueInfoMethodRef(typeFQN)}}({{OptionsLocalVariableName}}, converter);
""");
GenerateTypeInfoFactoryFooter(writer);
return CompleteSourceFileAndReturnText(writer);
}
private static SourceText GenerateForUnsupportedType(ContextGenerationSpec contextSpec, TypeGenerationSpec typeMetadata)
{
SourceWriter writer = CreateSourceWriterWithContextHeader(contextSpec);
string typeFQN = typeMetadata.TypeRef.FullyQualifiedName;
GenerateTypeInfoFactoryHeader(writer, typeMetadata);
writer.WriteLine($"""
{JsonTypeInfoLocalVariableName} = {JsonMetadataServicesTypeRef}.{GetCreateValueInfoMethodRef(typeFQN)}({OptionsLocalVariableName}, {JsonMetadataServicesTypeRef}.GetUnsupportedTypeConverter<{typeFQN}>());
""");
GenerateTypeInfoFactoryFooter(writer);
return CompleteSourceFileAndReturnText(writer);
}
private static SourceText GenerateForEnum(ContextGenerationSpec contextSpec, TypeGenerationSpec typeMetadata)
{
SourceWriter writer = CreateSourceWriterWithContextHeader(contextSpec);
string typeFQN = typeMetadata.TypeRef.FullyQualifiedName;
GenerateTypeInfoFactoryHeader(writer, typeMetadata);
writer.WriteLine($"""
{JsonTypeInfoLocalVariableName} = {JsonMetadataServicesTypeRef}.{GetCreateValueInfoMethodRef(typeFQN)}({OptionsLocalVariableName}, {JsonMetadataServicesTypeRef}.GetEnumConverter<{typeFQN}>({OptionsLocalVariableName}));
""");
GenerateTypeInfoFactoryFooter(writer);
return CompleteSourceFileAndReturnText(writer);
}
private SourceText GenerateForCollection(ContextGenerationSpec contextSpec, TypeGenerationSpec typeGenerationSpec)
{
SourceWriter writer = CreateSourceWriterWithContextHeader(contextSpec);
// Key metadata
TypeRef? collectionKeyType = typeGenerationSpec.CollectionKeyType;
Debug.Assert(!(typeGenerationSpec.ClassType == ClassType.Dictionary && collectionKeyType == null));
string? keyTypeFQN = collectionKeyType?.FullyQualifiedName;
// Value metadata
TypeRef? collectionValueType = typeGenerationSpec.CollectionValueType;
Debug.Assert(collectionValueType != null);
string valueTypeFQN = collectionValueType.FullyQualifiedName;
CollectionType collectionType = typeGenerationSpec.CollectionType;
string? serializeMethodName = ShouldGenerateSerializationLogic(typeGenerationSpec)
? $"{typeGenerationSpec.TypeInfoPropertyName}{SerializeHandlerPropName}"
: null;
string typeFQN = typeGenerationSpec.TypeRef.FullyQualifiedName;
string createCollectionInfoMethodName = GetCollectionInfoMethodName(collectionType);
string createCollectionMethodExpr;
switch (collectionType)
{
case CollectionType.Array:
case CollectionType.MemoryOfT:
case CollectionType.ReadOnlyMemoryOfT:
createCollectionMethodExpr = $"{createCollectionInfoMethodName}<{valueTypeFQN}>({OptionsLocalVariableName}, {InfoVarName})";
break;
case CollectionType.IEnumerable:
case CollectionType.IDictionary:
case CollectionType.IList:
createCollectionMethodExpr = $"{createCollectionInfoMethodName}<{typeFQN}>({OptionsLocalVariableName}, {InfoVarName})";
break;
case CollectionType.Stack:
case CollectionType.Queue:
string addMethod = collectionType == CollectionType.Stack ? "Push" : "Enqueue";
string addFuncNamedArg = $"(collection, {ValueVarName}) => collection.{addMethod}({ValueVarName})";
createCollectionMethodExpr = $"{createCollectionInfoMethodName}<{typeFQN}>({OptionsLocalVariableName}, {InfoVarName}, addFunc: {addFuncNamedArg})";
break;
case CollectionType.ImmutableEnumerable:
createCollectionMethodExpr = $"{createCollectionInfoMethodName}<{typeFQN}, {valueTypeFQN}>({OptionsLocalVariableName}, {InfoVarName}, createRangeFunc: {typeGenerationSpec.ImmutableCollectionFactoryMethod})";
break;
case CollectionType.Dictionary:
case CollectionType.IDictionaryOfTKeyTValue:
case CollectionType.IReadOnlyDictionary:
Debug.Assert(keyTypeFQN != null);
createCollectionMethodExpr = $"{createCollectionInfoMethodName}<{typeFQN}, {keyTypeFQN!}, {valueTypeFQN}>({OptionsLocalVariableName}, {InfoVarName})";
break;
case CollectionType.ImmutableDictionary:
Debug.Assert(keyTypeFQN != null);
createCollectionMethodExpr = $"{createCollectionInfoMethodName}<{typeFQN}, {keyTypeFQN!}, {valueTypeFQN}>({OptionsLocalVariableName}, {InfoVarName}, createRangeFunc: {typeGenerationSpec.ImmutableCollectionFactoryMethod})";
break;
default:
createCollectionMethodExpr = $"{createCollectionInfoMethodName}<{typeFQN}, {valueTypeFQN}>({OptionsLocalVariableName}, {InfoVarName})";
break;
}
GenerateTypeInfoFactoryHeader(writer, typeGenerationSpec);
writer.WriteLine($$"""
var {{InfoVarName}} = new {{JsonCollectionInfoValuesTypeRef}}<{{typeFQN}}>
{
{{ObjectCreatorPropName}} = {{FormatDefaultConstructorExpr(typeGenerationSpec)}},
{{SerializeHandlerPropName}} = {{serializeMethodName ?? "null"}}
};
{{JsonTypeInfoLocalVariableName}} = {{JsonMetadataServicesTypeRef}}.{{createCollectionMethodExpr}};
{{JsonTypeInfoLocalVariableName}}.{{NumberHandlingPropName}} = {{FormatNumberHandling(typeGenerationSpec.NumberHandling)}};
""");
GenerateTypeInfoFactoryFooter(writer);
if (serializeMethodName != null)
{
writer.WriteLine();
if (typeGenerationSpec.ClassType == ClassType.Enumerable)
{
GenerateFastPathFuncForEnumerable(writer, serializeMethodName, typeGenerationSpec);
}
else
{
GenerateFastPathFuncForDictionary(writer, serializeMethodName, typeGenerationSpec);
}
}
return CompleteSourceFileAndReturnText(writer);
}
private void GenerateFastPathFuncForEnumerable(SourceWriter writer, string serializeMethodName, TypeGenerationSpec typeGenerationSpec)
{
Debug.Assert(typeGenerationSpec.CollectionValueType != null);
TypeGenerationSpec valueTypeGenerationSpec = _typeIndex[typeGenerationSpec.CollectionValueType];
GenerateFastPathFuncHeader(writer, typeGenerationSpec, serializeMethodName);
writer.WriteLine($"{WriterVarName}.WriteStartArray();");
writer.WriteLine();
string getCurrentElementExpr;
const string elementVarName = "element";
switch (typeGenerationSpec.CollectionType)
{
case CollectionType.Array:
writer.WriteLine($"for (int i = 0; i < {ValueVarName}.Length; i++)");
getCurrentElementExpr = $"{ValueVarName}[i]";
break;
case CollectionType.MemoryOfT:
case CollectionType.ReadOnlyMemoryOfT:
writer.WriteLine($"foreach ({valueTypeGenerationSpec.TypeRef.FullyQualifiedName} {elementVarName} in {ValueVarName}.Span)");
getCurrentElementExpr = elementVarName;
break;
case CollectionType.IListOfT:
case CollectionType.List:
case CollectionType.IList:
writer.WriteLine($"for (int i = 0; i < {ValueVarName}.Count; i++)");
getCurrentElementExpr = $"{ValueVarName}[i]";
break;
default:
writer.WriteLine($"foreach ({valueTypeGenerationSpec.TypeRef.FullyQualifiedName} {elementVarName} in {ValueVarName})");
getCurrentElementExpr = elementVarName;
break;
};
writer.WriteLine('{');
writer.Indentation++;
GenerateSerializeValueStatement(writer, valueTypeGenerationSpec, getCurrentElementExpr);
writer.Indentation--;
writer.WriteLine('}');
writer.WriteLine();
writer.WriteLine($"{WriterVarName}.WriteEndArray();");
writer.Indentation--;
writer.WriteLine('}');
}
private void GenerateFastPathFuncForDictionary(SourceWriter writer, string serializeMethodName, TypeGenerationSpec typeGenerationSpec)
{
Debug.Assert(typeGenerationSpec.CollectionKeyType != null);
Debug.Assert(typeGenerationSpec.CollectionValueType != null);
TypeRef keyType = typeGenerationSpec.CollectionKeyType;
TypeGenerationSpec valueTypeGenerationSpec = _typeIndex[typeGenerationSpec.CollectionValueType];
GenerateFastPathFuncHeader(writer, typeGenerationSpec, serializeMethodName);
writer.WriteLine($"{WriterVarName}.WriteStartObject();");
writer.WriteLine();
writer.WriteLine($"foreach ({KeyValuePairTypeRef}<{keyType.FullyQualifiedName}, {valueTypeGenerationSpec.TypeRef.FullyQualifiedName}> entry in {ValueVarName})");
writer.WriteLine('{');
writer.Indentation++;
GenerateSerializePropertyStatement(writer, valueTypeGenerationSpec, propertyNameExpr: "entry.Key", valueExpr: "entry.Value");
writer.Indentation--;
writer.WriteLine('}');
writer.WriteLine();
writer.WriteLine($"{WriterVarName}.WriteEndObject();");
writer.Indentation--;
writer.WriteLine('}');
}
private SourceText GenerateForObject(ContextGenerationSpec contextSpec, TypeGenerationSpec typeMetadata)
{
SourceWriter writer = CreateSourceWriterWithContextHeader(contextSpec);
string typeFriendlyName = typeMetadata.TypeInfoPropertyName;
ObjectConstructionStrategy constructionStrategy = typeMetadata.ConstructionStrategy;
string creatorInvocation = FormatDefaultConstructorExpr(typeMetadata);
string parameterizedCreatorInvocation = constructionStrategy == ObjectConstructionStrategy.ParameterizedConstructor
? GetParameterizedCtorInvocationFunc(typeMetadata)
: "null";
string? propInitMethodName = null;
string? propInitAdapterFunc = null;
string? constructorInfoFactoryFunc = null;
string? ctorParamMetadataInitMethodName = null;
string? serializeMethodName = null;
if (ShouldGenerateMetadata(typeMetadata))
{
propInitMethodName = $"{typeFriendlyName}{PropInitMethodNameSuffix}";
propInitAdapterFunc = $"_ => {propInitMethodName}({OptionsLocalVariableName})";
if (constructionStrategy is ObjectConstructionStrategy.ParameterizedConstructor)
{
ctorParamMetadataInitMethodName = $"{typeFriendlyName}{CtorParamInitMethodNameSuffix}";
}
if (constructionStrategy is ObjectConstructionStrategy.ParameterlessConstructor
or ObjectConstructionStrategy.ParameterizedConstructor)
{
string argTypes = typeMetadata.CtorParamGenSpecs.Count == 0
? EmptyTypeArray
: $$"""new[] {{{string.Join(", ", typeMetadata.CtorParamGenSpecs.Select(p => $"typeof({p.ParameterType.FullyQualifiedName})"))}}}""";
constructorInfoFactoryFunc = $"static () => typeof({typeMetadata.TypeRef.FullyQualifiedName}).GetConstructor({InstanceMemberBindingFlagsVariableName}, binder: null, {argTypes}, modifiers: null)";
}
}
if (ShouldGenerateSerializationLogic(typeMetadata))
{
serializeMethodName = $"{typeFriendlyName}{SerializeHandlerPropName}";
}
const string ObjectInfoVarName = "objectInfo";
string genericArg = typeMetadata.TypeRef.FullyQualifiedName;
GenerateTypeInfoFactoryHeader(writer, typeMetadata);
writer.WriteLine($$"""
var {{ObjectInfoVarName}} = new {{JsonObjectInfoValuesTypeRef}}<{{genericArg}}>
{
{{ObjectCreatorPropName}} = {{creatorInvocation}},
ObjectWithParameterizedConstructorCreator = {{parameterizedCreatorInvocation}},
PropertyMetadataInitializer = {{propInitAdapterFunc ?? "null"}},
ConstructorParameterMetadataInitializer = {{ctorParamMetadataInitMethodName ?? "null"}},
ConstructorAttributeProviderFactory = {{constructorInfoFactoryFunc ?? "null"}},
{{SerializeHandlerPropName}} = {{serializeMethodName ?? "null"}},
};
{{JsonTypeInfoLocalVariableName}} = {{JsonMetadataServicesTypeRef}}.CreateObjectInfo<{{typeMetadata.TypeRef.FullyQualifiedName}}>({{OptionsLocalVariableName}}, {{ObjectInfoVarName}});
{{JsonTypeInfoLocalVariableName}}.{{NumberHandlingPropName}} = {{FormatNumberHandling(typeMetadata.NumberHandling)}};
""");
if (typeMetadata is { UnmappedMemberHandling: not null } or { PreferredPropertyObjectCreationHandling: not null })
{
writer.WriteLine();
if (typeMetadata.UnmappedMemberHandling != null)
{
writer.WriteLine($"{JsonTypeInfoLocalVariableName}.{UnmappedMemberHandlingPropName} = {FormatUnmappedMemberHandling(typeMetadata.UnmappedMemberHandling.Value)};");
}
if (typeMetadata.PreferredPropertyObjectCreationHandling != null)
{
writer.WriteLine($"{JsonTypeInfoLocalVariableName}.{PreferredPropertyObjectCreationHandlingPropName} = {FormatObjectCreationHandling(typeMetadata.PreferredPropertyObjectCreationHandling.Value)};");
}
}
GenerateTypeInfoFactoryFooter(writer);
if (propInitMethodName != null)
{
writer.WriteLine();
GeneratePropMetadataInitFunc(writer, propInitMethodName, typeMetadata);
}
if (serializeMethodName != null)
{
writer.WriteLine();
GenerateFastPathFuncForObject(writer, contextSpec, serializeMethodName, typeMetadata);
}
if (ctorParamMetadataInitMethodName != null)
{
writer.WriteLine();
GenerateCtorParamMetadataInitFunc(writer, ctorParamMetadataInitMethodName, typeMetadata);
}
writer.Indentation--;
writer.WriteLine('}');
return CompleteSourceFileAndReturnText(writer);
}
private void GeneratePropMetadataInitFunc(SourceWriter writer, string propInitMethodName, TypeGenerationSpec typeGenerationSpec)
{
ImmutableEquatableArray<PropertyGenerationSpec> properties = typeGenerationSpec.PropertyGenSpecs;
writer.WriteLine($"private static {JsonPropertyInfoTypeRef}[] {propInitMethodName}({JsonSerializerOptionsTypeRef} {OptionsLocalVariableName})");
writer.WriteLine('{');
writer.Indentation++;
writer.WriteLine($"var properties = new {JsonPropertyInfoTypeRef}[{properties.Count}];");
writer.WriteLine();
for (int i = 0; i < properties.Count; i++)
{
PropertyGenerationSpec property = properties[i];
string propertyName = property.NameSpecifiedInSourceCode;
string declaringTypeFQN = property.DeclaringType.FullyQualifiedName;
string propertyTypeFQN = property.PropertyType.FullyQualifiedName;
string getterValue = property switch
{
{ DefaultIgnoreCondition: JsonIgnoreCondition.Always } => "null",
{ CanUseGetter: true } => $"static obj => (({declaringTypeFQN})obj).{propertyName}",
{ CanUseGetter: false, HasJsonInclude: true }
=> $"""static _ => throw new {InvalidOperationExceptionTypeRef}("{string.Format(ExceptionMessages.InaccessibleJsonIncludePropertiesNotSupported, typeGenerationSpec.TypeRef.Name, propertyName)}")""",
_ => "null"
};
string setterValue = property switch
{
{ DefaultIgnoreCondition: JsonIgnoreCondition.Always } => "null",
{ CanUseSetter: true, IsInitOnlySetter: true }
=> $"""static (obj, value) => throw new {InvalidOperationExceptionTypeRef}("{ExceptionMessages.InitOnlyPropertySetterNotSupported}")""",
{ CanUseSetter: true } when typeGenerationSpec.TypeRef.IsValueType
=> $"""static (obj, value) => {UnsafeTypeRef}.Unbox<{declaringTypeFQN}>(obj).{propertyName} = value!""",
{ CanUseSetter: true }
=> $"""static (obj, value) => (({declaringTypeFQN})obj).{propertyName} = value!""",
{ CanUseSetter: false, HasJsonInclude: true }
=> $"""static (obj, value) => throw new {InvalidOperationExceptionTypeRef}("{string.Format(ExceptionMessages.InaccessibleJsonIncludePropertiesNotSupported, typeGenerationSpec.TypeRef.Name, property.MemberName)}")""",
_ => "null",
};
string ignoreConditionNamedArg = property.DefaultIgnoreCondition.HasValue
? $"{JsonIgnoreConditionTypeRef}.{property.DefaultIgnoreCondition.Value}"
: "null";
string? converterInstantiationExpr = null;
if (property.ConverterType != null)
{
string converterFQN = property.ConverterType.FullyQualifiedName;
TypeRef? nullableUnderlyingType = _typeIndex[property.PropertyType].NullableUnderlyingType;
_emitGetConverterForNullablePropertyMethod |= nullableUnderlyingType != null;
converterInstantiationExpr = nullableUnderlyingType != null
? $"{GetConverterForNullablePropertyMethodName}<{nullableUnderlyingType.FullyQualifiedName}>(new {converterFQN}(), {OptionsLocalVariableName})"
: $"({JsonConverterTypeRef}<{propertyTypeFQN}>){ExpandConverterMethodName}(typeof({propertyTypeFQN}), new {converterFQN}(), {OptionsLocalVariableName})";
}
string attributeProviderFactoryExpr = property.IsProperty
? $"typeof({property.DeclaringType.FullyQualifiedName}).GetProperty({FormatStringLiteral(property.MemberName)}, {InstanceMemberBindingFlagsVariableName}, null, typeof({property.PropertyType.FullyQualifiedName}), {EmptyTypeArray}, null)"
: $"typeof({property.DeclaringType.FullyQualifiedName}).GetField({FormatStringLiteral(property.MemberName)}, {InstanceMemberBindingFlagsVariableName})";
writer.WriteLine($$"""
var {{InfoVarName}}{{i}} = new {{JsonPropertyInfoValuesTypeRef}}<{{propertyTypeFQN}}>
{
IsProperty = {{FormatBoolLiteral(property.IsProperty)}},
IsPublic = {{FormatBoolLiteral(property.IsPublic)}},
IsVirtual = {{FormatBoolLiteral(property.IsVirtual)}},
DeclaringType = typeof({{property.DeclaringType.FullyQualifiedName}}),
Converter = {{converterInstantiationExpr ?? "null"}},
Getter = {{getterValue}},
Setter = {{setterValue}},
IgnoreCondition = {{ignoreConditionNamedArg}},
HasJsonInclude = {{FormatBoolLiteral(property.HasJsonInclude)}},
IsExtensionData = {{FormatBoolLiteral(property.IsExtensionData)}},
NumberHandling = {{FormatNumberHandling(property.NumberHandling)}},
PropertyName = {{FormatStringLiteral(property.MemberName)}},
JsonPropertyName = {{FormatStringLiteral(property.JsonPropertyName)}},
AttributeProviderFactory = static () => {{attributeProviderFactoryExpr}},
};
properties[{{i}}] = {{JsonMetadataServicesTypeRef}}.CreatePropertyInfo<{{propertyTypeFQN}}>({{OptionsLocalVariableName}}, {{InfoVarName}}{{i}});
""");
if (property.HasJsonRequiredAttribute ||
(property.IsRequired && !typeGenerationSpec.ConstructorSetsRequiredParameters))
{
writer.WriteLine($"properties[{i}].IsRequired = true;");
}
if (property.ObjectCreationHandling != null)
{
writer.WriteLine($"properties[{i}].ObjectCreationHandling = {FormatObjectCreationHandling(property.ObjectCreationHandling.Value)};");
}
if (property.Order != 0)
{
writer.WriteLine($"properties[{i}].Order = {property.Order};");
}
if (property.IsGetterNonNullableAnnotation)
{
writer.WriteLine($"properties[{i}].IsGetNullable = false;");
}
if (property.IsSetterNonNullableAnnotation)
{
writer.WriteLine($"properties[{i}].IsSetNullable = false;");
}
writer.WriteLine();
}
writer.WriteLine($"return properties;");
writer.Indentation--;
writer.WriteLine('}');
}
private static void GenerateCtorParamMetadataInitFunc(SourceWriter writer, string ctorParamMetadataInitMethodName, TypeGenerationSpec typeGenerationSpec)
{
ImmutableEquatableArray<ParameterGenerationSpec> parameters = typeGenerationSpec.CtorParamGenSpecs;
ImmutableEquatableArray<PropertyInitializerGenerationSpec> propertyInitializers = typeGenerationSpec.PropertyInitializerSpecs;
int paramCount = parameters.Count + propertyInitializers.Count(propInit => !propInit.MatchesConstructorParameter);
Debug.Assert(paramCount > 0);
writer.WriteLine($"private static {JsonParameterInfoValuesTypeRef}[] {ctorParamMetadataInitMethodName}() => new {JsonParameterInfoValuesTypeRef}[]");
writer.WriteLine('{');
writer.Indentation++;
int i = 0;
foreach (ParameterGenerationSpec spec in parameters)
{
writer.WriteLine($$"""
new()
{
Name = {{FormatStringLiteral(spec.Name)}},
ParameterType = typeof({{spec.ParameterType.FullyQualifiedName}}),
Position = {{spec.ParameterIndex}},
HasDefaultValue = {{FormatBoolLiteral(spec.HasDefaultValue)}},
DefaultValue = {{(spec.HasDefaultValue ? CSharpSyntaxUtilities.FormatLiteral(spec.DefaultValue, spec.ParameterType) : "null")}},
IsNullable = {{FormatBoolLiteral(spec.IsNullable)}},
},
""");
if (++i < paramCount)
{
writer.WriteLine();
}
}
foreach (PropertyInitializerGenerationSpec spec in propertyInitializers)
{
if (spec.MatchesConstructorParameter)
{
continue;
}
writer.WriteLine($$"""
new()
{
Name = {{FormatStringLiteral(spec.Name)}},
ParameterType = typeof({{spec.ParameterType.FullyQualifiedName}}),
Position = {{spec.ParameterIndex}},
IsNullable = {{FormatBoolLiteral(spec.IsNullable)}},
IsMemberInitializer = true,
},
""");
if (++i < paramCount)
{
writer.WriteLine();
}
}
writer.Indentation--;
writer.WriteLine("};");
}
private void GenerateFastPathFuncForObject(SourceWriter writer, ContextGenerationSpec contextSpec, string serializeMethodName, TypeGenerationSpec typeGenSpec)
{
if (typeGenSpec.FastPathPropertyIndices is null)
{
// Type uses configuration that doesn't support fast-path: emit a stub that just throws.
GenerateFastPathFuncHeader(writer, typeGenSpec, serializeMethodName, skipNullCheck: true);
string exceptionMessage = string.Format(ExceptionMessages.InvalidSerializablePropertyConfiguration, typeGenSpec.TypeRef.FullyQualifiedName);
writer.WriteLine($"""throw new {InvalidOperationExceptionTypeRef}("{exceptionMessage}");""");
writer.Indentation--;
writer.WriteLine('}');
return;
}
GenerateFastPathFuncHeader(writer, typeGenSpec, serializeMethodName);
if (typeGenSpec.ImplementsIJsonOnSerializing)
{
writer.WriteLine($"((global::{JsonConstants.IJsonOnSerializingFullName}){ValueVarName}).OnSerializing();");
writer.WriteLine();
}
writer.WriteLine($"{WriterVarName}.WriteStartObject();");
writer.WriteLine();
bool generateDisallowNullThrowHelper = false;
// Provide generation logic for each prop.
foreach (int i in typeGenSpec.FastPathPropertyIndices)
{
PropertyGenerationSpec propertyGenSpec = typeGenSpec.PropertyGenSpecs[i];
if (!propertyGenSpec.ShouldIncludePropertyForFastPath(contextSpec))
{
continue;
}
TypeGenerationSpec propertyTypeSpec = _typeIndex[propertyGenSpec.PropertyType];
if (propertyTypeSpec.ClassType is ClassType.TypeUnsupportedBySourceGen)
{
continue;
}
string effectiveJsonPropertyName = propertyGenSpec.EffectiveJsonPropertyName;
string propertyNameFieldName = propertyGenSpec.PropertyNameFieldName;
// Add the property names to the context-wide cache; we'll generate the source to initialize them at the end of generation.
Debug.Assert(!_propertyNames.TryGetValue(effectiveJsonPropertyName, out string? existingName) || existingName == propertyNameFieldName);
_propertyNames.TryAdd(effectiveJsonPropertyName, propertyNameFieldName);
SerializedValueCheckType defaultCheckType = GetCheckType(contextSpec, propertyGenSpec);
// For properties whose declared type differs from that of the serialized type
// perform an explicit cast -- this is to account for hidden properties or diamond ambiguity.
string? objectExpr = propertyGenSpec.DeclaringType != typeGenSpec.TypeRef
? $"(({propertyGenSpec.DeclaringType.FullyQualifiedName}){ValueVarName})"
: ValueVarName;
string propValueExpr;
if (defaultCheckType != SerializedValueCheckType.None)
{
// Use temporary variable to evaluate property value only once
string localVariableName = $"__value_{propertyGenSpec.NameSpecifiedInSourceCode.TrimStart('@')}";
writer.WriteLine($"{propertyGenSpec.PropertyType.FullyQualifiedName} {localVariableName} = {objectExpr}.{propertyGenSpec.NameSpecifiedInSourceCode};");
propValueExpr = localVariableName;
}
else
{
propValueExpr = $"{objectExpr}.{propertyGenSpec.NameSpecifiedInSourceCode}";
}
switch (defaultCheckType)
{
case SerializedValueCheckType.IgnoreWhenNull:
writer.WriteLine($"if ({propValueExpr} is not null)");
writer.WriteLine('{');
writer.Indentation++;
GenerateSerializePropertyStatement(writer, propertyTypeSpec, propertyNameFieldName, propValueExpr);
writer.Indentation--;
writer.WriteLine('}');
break;
case SerializedValueCheckType.IgnoreWhenDefault:
writer.WriteLine($"if (!{EqualityComparerTypeRef}<{propertyGenSpec.PropertyType.FullyQualifiedName}>.Default.Equals(default, {propValueExpr}))");
writer.WriteLine('{');
writer.Indentation++;
GenerateSerializePropertyStatement(writer, propertyTypeSpec, propertyNameFieldName, propValueExpr);
writer.Indentation--;
writer.WriteLine('}');
break;
case SerializedValueCheckType.DisallowNull:
writer.WriteLine($$"""
if ({{propValueExpr}} is null)
{
ThrowPropertyNullException({{FormatStringLiteral(propertyGenSpec.EffectiveJsonPropertyName)}});
}
""");
GenerateSerializePropertyStatement(writer, propertyTypeSpec, propertyNameFieldName, propValueExpr);
generateDisallowNullThrowHelper = true;
break;
default:
GenerateSerializePropertyStatement(writer, propertyTypeSpec, propertyNameFieldName, propValueExpr);
break;
}
}
// End method logic.
writer.WriteLine();
writer.WriteLine($"{WriterVarName}.WriteEndObject();");
if (typeGenSpec.ImplementsIJsonOnSerialized)
{
writer.WriteLine();
writer.WriteLine($"((global::{JsonConstants.IJsonOnSerializedFullName}){ValueVarName}).OnSerialized();");
}
if (generateDisallowNullThrowHelper)
{
writer.WriteLine();
writer.WriteLine($$"""
static void ThrowPropertyNullException(string propertyName)
{
throw new {{JsonExceptionTypeRef}}(string.Format("{{ExceptionMessages.PropertyGetterDisallowNull}}", propertyName, {{FormatStringLiteral(typeGenSpec.TypeRef.Name)}}));
}
""");
}
writer.Indentation--;
writer.WriteLine('}');
}
private static string GetParameterizedCtorInvocationFunc(TypeGenerationSpec typeGenerationSpec)
{
ImmutableEquatableArray<ParameterGenerationSpec> parameters = typeGenerationSpec.CtorParamGenSpecs;
ImmutableEquatableArray<PropertyInitializerGenerationSpec> propertyInitializers = typeGenerationSpec.PropertyInitializerSpecs;
const string ArgsVarName = "args";
StringBuilder sb = new($"static {ArgsVarName} => new {typeGenerationSpec.TypeRef.FullyQualifiedName}(");
if (parameters.Count > 0)
{
foreach (ParameterGenerationSpec param in parameters)
{
int index = param.ParameterIndex;
sb.Append($"{GetParamUnboxing(param.ParameterType, index)}, ");
}
sb.Length -= 2; // delete the last ", " token
}
sb.Append(')');
if (propertyInitializers.Count > 0)
{
sb.Append("{ ");
foreach (PropertyInitializerGenerationSpec property in propertyInitializers)
{
sb.Append($"{property.Name} = {GetParamUnboxing(property.ParameterType, property.ParameterIndex)}, ");
}
sb.Length -= 2; // delete the last ", " token
sb.Append(" }");
}
return sb.ToString();
static string GetParamUnboxing(TypeRef type, int index)
=> $"({type.FullyQualifiedName}){ArgsVarName}[{index}]";
}
private static string? GetPrimitiveWriterMethod(TypeGenerationSpec type)
{
return type.PrimitiveTypeKind switch
{
JsonPrimitiveTypeKind.Number => "WriteNumber",
JsonPrimitiveTypeKind.String or JsonPrimitiveTypeKind.Char => "WriteString",
JsonPrimitiveTypeKind.Boolean => "WriteBoolean",
JsonPrimitiveTypeKind.ByteArray => "WriteBase64String",
_ => null
};
}
private static void GenerateFastPathFuncHeader(SourceWriter writer, TypeGenerationSpec typeGenSpec, string methodName, bool skipNullCheck = false)
{
// fast path serializers for reference types always support null inputs.
string valueTypeRef = typeGenSpec.TypeRef.IsValueType
? typeGenSpec.TypeRef.FullyQualifiedName
: typeGenSpec.TypeRef.FullyQualifiedName + "?";
writer.WriteLine($$"""
// Intentionally not a static method because we create a delegate to it. Invoking delegates to instance
// methods is almost as fast as virtual calls. Static methods need to go through a shuffle thunk.
private void {{methodName}}({{Utf8JsonWriterTypeRef}} {{WriterVarName}}, {{valueTypeRef}} {{ValueVarName}})
{
""");
writer.Indentation++;
if (!skipNullCheck && typeGenSpec.TypeRef.CanBeNull)
{
writer.WriteLine($$"""
if ({{ValueVarName}} is null)
{
{{WriterVarName}}.WriteNullValue();
return;
}
""");
}
}
private static void GenerateSerializeValueStatement(SourceWriter writer, TypeGenerationSpec typeSpec, string valueExpr)
{
if (GetPrimitiveWriterMethod(typeSpec) is string primitiveWriterMethod)
{
if (typeSpec.PrimitiveTypeKind is JsonPrimitiveTypeKind.Char)
{
writer.WriteLine($"{WriterVarName}.{primitiveWriterMethod}Value({valueExpr}.ToString());");
}