-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathExpanderGenerator.cs
More file actions
1580 lines (1439 loc) · 77.5 KB
/
Copy pathExpanderGenerator.cs
File metadata and controls
1580 lines (1439 loc) · 77.5 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using System.Text;
#nullable enable
namespace Popcorn.SourceGenerator
{
[Generator(LanguageNames.CSharp)]
public class ExpanderGenerator : IIncrementalGenerator
{
private const string JsonSerializableAttributeTypeName = "System.Text.Json.Serialization.JsonSerializableAttribute";
private const string JsonSerializerContextTypeName = "System.Text.Json.Serialization.JsonSerializerContext";
private const string IEnumerableTypeName = "System.Collections.Generic.IEnumerable<T>";
// NOTE: whitespace matters. Roslyn's ToDisplayString emits generic argument lists with
// ", " (comma + space). If the constant uses a no-space form, InheritsOrImplements will
// never match — Dictionary<K,V> happens to fall through a separate Dictionary<TKey,TValue>
// OriginalDefinition check in GenerateJsonConverter, but IDictionary<K,V> and
// ReadOnlyDictionary<K,V> as the *target* type have no such fallback, so they silently
// hit the IEnumerable branch and emit broken iterators (treating KeyValuePair<K,V> as K).
// Fixed as part of Bug 5.
private const string IDictionaryTypeName = "System.Collections.Generic.IDictionary<TKey, TValue>";
private static readonly HashSet<string> NumberTypes = new HashSet<string>([
typeof(Decimal).FullName,
typeof(Byte).FullName,
typeof(UInt16).FullName,
typeof(UInt32).FullName,
typeof(UInt64).FullName,
typeof(SByte).FullName,
typeof(Int16).FullName,
typeof(Int32).FullName,
typeof(Int64).FullName,
"decimal",
"byte",
"sbyte",
"short",
"ushort",
"int",
"uint",
"long",
"ulong",
]);
private static readonly HashSet<string> StringTypes = new HashSet<string>([
"string",
typeof(string).FullName,
typeof(Span<char>).FullName,
typeof(ReadOnlySpan<char>).FullName,
typeof(Memory<char>).FullName,
typeof(ReadOnlyMemory<char>).FullName
]);
private static readonly HashSet<string> BoolTypes = new HashSet<string>([
"bool",
typeof(bool).FullName,
]);
private static readonly HashSet<string> IgnoreTypes = new HashSet<string>([
"char",
typeof(Single).FullName,
typeof(Double).FullName,
"float",
"double",
typeof(char).FullName,
typeof(Guid).FullName,
typeof(DateTime).FullName,
typeof(TimeSpan).FullName,
typeof(DateTimeOffset).FullName, // We need a way to say "opt out of expanding these"
]);
// True when the type is a primitive / ignored / enum — one that we do NOT emit a Pop<T>
// body for and must NOT have in `allTypeNames`. Value-type nullable wrappers (Nullable<int>)
// are treated the same as their underlying primitive here: both collapse to "int" under the
// Replace("?", "") convention used throughout the generator.
private static bool IsBlindSerializableType(ITypeSymbol? type)
{
if (type == null) return false;
if (type.TypeKind == TypeKind.Enum) return true;
if (type is INamedTypeSymbol named
&& named.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T
&& named.TypeArguments.Length == 1
&& named.TypeArguments[0].TypeKind == TypeKind.Enum)
{
return true;
}
var name = type.ToDisplayString().Replace("?", "");
return NumberTypes.Contains(name)
|| StringTypes.Contains(name)
|| BoolTypes.Contains(name)
|| IgnoreTypes.Contains(name);
}
// Unwrap Nullable<T>, arrays, IEnumerable<T>, IDictionary<K,V> → the inner element/value
// type that a converter would recurse into. Non-collection named types pass through.
private static ITypeSymbol? UnwrapPayloadType(ITypeSymbol? type)
{
if (type == null) return null;
if (type is INamedTypeSymbol named
&& named.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T
&& named.TypeArguments.Length == 1)
{
return UnwrapPayloadType(named.TypeArguments[0]);
}
if (type is IArrayTypeSymbol array)
{
return UnwrapPayloadType(array.ElementType);
}
if (type is INamedTypeSymbol namedDict && InheritsOrImplements(namedDict, IDictionaryTypeName)
&& namedDict.TypeArguments.Length >= 2)
{
return UnwrapPayloadType(namedDict.TypeArguments[1]);
}
if (type is INamedTypeSymbol namedEnum && InheritsOrImplements(namedEnum, IEnumerableTypeName)
&& namedEnum.TypeArguments.Length >= 1)
{
return UnwrapPayloadType(namedEnum.TypeArguments[0]);
}
return type;
}
// True if the payload type's transitive property graph (limited to types Popcorn itself
// recurses into — i.e. members of `allTypeNames`) never contains a path back to itself.
// A cycle-safe converter can skip the per-call HashSet<object> allocation used for
// circular-reference detection.
private static bool IsConverterCycleSafe(ITypeSymbol rootType, HashSet<string> allTypeNames)
{
var payload = UnwrapPayloadType(rootType);
if (payload is not INamedTypeSymbol named) return true;
if (IsBlindSerializableType(named)) return true;
return IsNamedTypeCycleSafe(named, allTypeNames, new HashSet<string>());
}
private static bool IsNamedTypeCycleSafe(INamedTypeSymbol type, HashSet<string> allTypeNames, HashSet<string> onPath)
{
var typeName = type.ToDisplayString().Replace("?", "");
// Types Popcorn doesn't have a Pop<T> body for (primitives, enums, unregistered externals)
// don't participate in Popcorn's recursion — the visited HashSet is never consulted for them.
if (IsBlindSerializableType(type)) return true;
if (!allTypeNames.Contains(typeName)) return true;
if (!onPath.Add(typeName)) return false; // reached an ancestor of ourselves → cycle risk
try
{
foreach (var prop in GetSerializableProperties(type))
{
if (!ShouldSerializeMember(prop)) continue;
var payload = UnwrapPayloadType(prop.Type);
if (payload is INamedTypeSymbol p && !IsNamedTypeCycleSafe(p, allTypeNames, onPath))
return false;
}
foreach (var field in GetSerializableFields(type))
{
if (!ShouldSerializeMember(field)) continue;
var payload = UnwrapPayloadType(field.Type);
if (payload is INamedTypeSymbol f && !IsNamedTypeCycleSafe(f, allTypeNames, onPath))
return false;
}
return true;
}
finally
{
onPath.Remove(typeName);
}
}
// Emit type arguments for Pop<...> without NRT annotations on reference types. Preserves
// `Nullable<T>` on value types (a distinct CLR type). Registered converter method
// signatures and every Pop<...> callsite use this same formatter so they never diverge by
// `?` annotation — which was the root cause of the CS8620 warnings (Bug 3).
//
// SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier affects ONLY
// reference-type `?` annotations. `Nullable<int>` still renders as `int?` under
// `UseSpecialTypes` regardless of that flag — because `int?` there is syntactic sugar for
// the real CLR type `System.Nullable<Int32>`, not an NRT annotation.
private static readonly SymbolDisplayFormat PopTypeArgumentFormat = new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
private static string TypeNameForPop(ITypeSymbol type)
=> type.ToDisplayString(PopTypeArgumentFormat);
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Step 1: Find all classes that inherit from JsonSerializerContext
var jsonSerializerContextClasses = context.SyntaxProvider
.ForAttributeWithMetadataName(JsonSerializableAttributeTypeName,
predicate: (node, _) => node is ClassDeclarationSyntax classDecl && classDecl.AttributeLists.Count > 0,
transform: (ctx, _) => GetJsonSerializerContextClass(ctx))
.Where(symbol => symbol != null);
// Step 2: Extract [JsonSerializable] attributes and their target types
var jsonSerializableAttributes = jsonSerializerContextClasses
.Select((classSymbol, _) => new GeneratorClassReference(classSymbol, GetJsonSerializableTypes(classSymbol!)))
.Where(data => data.Attributes.Any());
// Step 3: Devolve to the actual types referenced.
// Step 3: Generate the JsonConverter class for each target type
context.RegisterSourceOutput(jsonSerializableAttributes, (spc, data) =>
{
if (data.ClassSymbol == null)
{
return;
}
var targetTypes = new HashSet<ITypeSymbol>(
data.Attributes
.Select(attribute => attribute.ConstructorArguments[0].Value as INamedTypeSymbol)
.Where(a => a != null && a.TypeArguments.Length > 0)
.Select(a => a?.TypeArguments[0] as ITypeSymbol)
.Where(a => a != null)!,
SymbolEqualityComparer.Default);
foreach (var targetType in targetTypes.ToList())
{
foreach (var t in GetReferencedTypes(targetType, data.ClassSymbol, spc))
{
targetTypes.Add(t);
}
}
foreach (var targetType in targetTypes)
{
try
{
var source = GenerateJsonConverter(targetType, data.ClassSymbol, targetTypes, spc);
spc.AddSource($"{NameType(targetType)}JsonConverter.g.cs", SourceText.From(source, Encoding.UTF8));
}
catch (Exception ex)
{
spc.ReportDiagnostic(Diagnostic.Create(
new DiagnosticDescriptor(
id: "JSG001",
title: "Source Generation Error",
messageFormat: $"Error generating source for type '{targetType}': {ex.Message}",
category: "SourceGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true),
Location.None));
}
}
try
{
// Collect custom envelope open-generic definitions from the JsonSerializable attrs.
var customEnvelopes = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default);
foreach (var attr in data.Attributes)
{
if (attr.ConstructorArguments[0].Value is INamedTypeSymbol envType
&& HasPopcornEnvelopeAttribute(envType))
{
customEnvelopes.Add(envType.OriginalDefinition);
}
}
var errorWriterBody = new StringBuilder();
foreach (var envelope in customEnvelopes)
{
var analysis = AnalyzeEnvelope(envelope);
ReportEnvelopeDiagnostics(spc, envelope, analysis);
if (analysis.PayloadName == null)
{
// Missing payload already reported as JSG003; skip emission for this envelope.
continue;
}
if (HasGenericContainingType(envelope))
{
// Nested inside a generic outer — open-generic typeof syntax can't be expressed.
// Reported as JSG007; skip emission.
continue;
}
errorWriterBody.Append($@"
if (envelopeType == typeof({OpenGenericCSharpName(envelope)}))
{{
writer.WriteStartObject();
{(analysis.SuccessName != null ? $@"writer.WriteBoolean(Convert(""{analysis.SuccessName}""), false);" : "")}
{(analysis.ErrorName != null ? $@"writer.WriteStartObject(Convert(""{analysis.ErrorName}""));
writer.WriteString(Convert(""Code""), error.Code);
writer.WriteString(Convert(""Message""), error.Message);
if (error.Detail != null) writer.WriteString(Convert(""Detail""), error.Detail);
writer.WriteEndObject();" : "")}
writer.WriteEndObject();
return;
}}");
}
var envelopeRegistrationCall = customEnvelopes.Count == 0
? ""
: $@"
global::Popcorn.Shared.PopcornErrorWriterRegistry.Register(WriteCustomErrorEnvelope);";
var envelopeWriterMethod = customEnvelopes.Count == 0 || errorWriterBody.Length == 0
? ""
: $@"
private static void WriteCustomErrorEnvelope(
global::System.Text.Json.Utf8JsonWriter writer,
global::System.Type envelopeType,
global::Popcorn.Shared.ApiError error,
global::System.Text.Json.JsonNamingPolicy? namingPolicy)
{{
string Convert(string name) => namingPolicy?.ConvertName(name) ?? name;{errorWriterBody}
}}";
// Now add the top-level extension method for registering all our converters to the WebApi pipeline.
// Both AddPopcornOptions (JsonSerializerOptions-level) and AddPopcornEnvelopes (IServiceCollection-level)
// register the error-envelope writer. AddPopcornEnvelopes is the AOT-friendly DI-time hook; AddPopcornOptions
// remains the JSON-level hook that was added alongside the converter registration.
spc.AddSource("RegisterConverters.g.cs", SourceText.From($@"// <auto-generated/>
#nullable enable
namespace Popcorn.Shared;
public static class PopcornJsonOptionsExtension
{{
public static void AddPopcornOptions(this global::System.Text.Json.JsonSerializerOptions options)
{{
options.NumberHandling = global::System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals;
{String.Join("", targetTypes.Select(targetType => $@"
options.Converters.Add(new global::Popcorn.Generated.Converters.{NameType(targetType)}JsonConverter());")
)}{envelopeRegistrationCall}
}}
public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddPopcornEnvelopes(
this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services)
{{{envelopeRegistrationCall}
return services;
}}{envelopeWriterMethod}
}}
", Encoding.UTF8));
}
catch (Exception ex)
{
spc.ReportDiagnostic(Diagnostic.Create(
new DiagnosticDescriptor(
id: "JSG001",
title: "Source Generation Error",
messageFormat: $"Error generating registration source': {ex.Message}",
category: "SourceGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true),
Location.None));
}
});
}
private static INamedTypeSymbol? GetJsonSerializerContextClass(GeneratorAttributeSyntaxContext context)
{
var classSymbol = context.TargetSymbol as INamedTypeSymbol;
// Check if the class is a subclass of JsonSerializerContext
var baseType = classSymbol?.BaseType;
var typeName = baseType?.ToDisplayString();
return typeName == JsonSerializerContextTypeName ? classSymbol : null;
}
private static IEnumerable<AttributeData> GetJsonSerializableTypes(INamedTypeSymbol classSymbol)
{
return classSymbol.GetAttributes()
.Where(attr => attr.AttributeClass?.ToDisplayString() == JsonSerializableAttributeTypeName &&
attr.ConstructorArguments.Length > 0
&& attr.ConstructorArguments[0].Value is INamedTypeSymbol typeSymbol
&& (InheritsOrImplements(typeSymbol, "Popcorn.Shared.ApiResponse<T>")
|| HasPopcornEnvelopeAttribute(typeSymbol)));
}
private static bool HasPopcornEnvelopeAttribute(INamedTypeSymbol typeSymbol)
{
return typeSymbol.GetAttributes().Any(a =>
a.AttributeClass?.ToDisplayString() == "Popcorn.PopcornEnvelopeAttribute");
}
private class EnvelopeAnalysis
{
public string? SuccessName;
public string? PayloadName;
public string? ErrorName;
public ITypeSymbol? PayloadType;
public ITypeSymbol? ErrorType;
public Location? EnvelopeLocation;
public Location? PayloadLocation;
public Location? ErrorLocation;
public List<Location> DuplicateSuccessLocations = new List<Location>();
public List<Location> DuplicatePayloadLocations = new List<Location>();
public List<Location> DuplicateErrorLocations = new List<Location>();
}
private static EnvelopeAnalysis AnalyzeEnvelope(INamedTypeSymbol envelope)
{
var analysis = new EnvelopeAnalysis
{
EnvelopeLocation = envelope.Locations.FirstOrDefault(),
};
// Walk the base chain so markers on a base envelope class are honored.
foreach (var prop in GetSerializableProperties(envelope))
{
var wireName = GetJsonPropertyNameOverride(prop) ?? prop.Name;
foreach (var attr in prop.GetAttributes())
{
var attrName = attr.AttributeClass?.ToDisplayString();
var location = prop.Locations.FirstOrDefault();
if (attrName == "Popcorn.PopcornSuccessAttribute")
{
if (analysis.SuccessName != null) analysis.DuplicateSuccessLocations.Add(location ?? Location.None);
analysis.SuccessName = wireName;
}
else if (attrName == "Popcorn.PopcornPayloadAttribute")
{
if (analysis.PayloadName != null) analysis.DuplicatePayloadLocations.Add(location ?? Location.None);
analysis.PayloadName = wireName;
analysis.PayloadType = prop.Type;
analysis.PayloadLocation = location;
}
else if (attrName == "Popcorn.PopcornErrorAttribute")
{
if (analysis.ErrorName != null) analysis.DuplicateErrorLocations.Add(location ?? Location.None);
analysis.ErrorName = wireName;
analysis.ErrorType = prop.Type;
analysis.ErrorLocation = location;
}
}
}
return analysis;
}
private static string? GetJsonPropertyNameOverride(IPropertySymbol prop)
{
var attr = prop.GetAttributes().FirstOrDefault(a =>
a.AttributeClass?.ToDisplayString() == "System.Text.Json.Serialization.JsonPropertyNameAttribute");
if (attr?.ConstructorArguments.Length > 0 && attr.ConstructorArguments[0].Value is string name)
{
return name;
}
return null;
}
private static bool IsPopOfT(ITypeSymbol? type)
{
if (type is not INamedTypeSymbol named) return false;
return named.OriginalDefinition.ToDisplayString() == "Popcorn.Shared.Pop<T>";
}
private static bool IsApiError(ITypeSymbol? type)
{
if (type is null) return false;
// Accept ApiError and ApiError? (Nullable<T> for value types, or annotated reference)
if (type is INamedTypeSymbol nullable
&& nullable.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T
&& nullable.TypeArguments.Length == 1)
{
type = nullable.TypeArguments[0];
}
return type.ToDisplayString().TrimEnd('?') == "Popcorn.Shared.ApiError";
}
/// <summary>
/// Emits the C# open-generic syntax for <c>typeof(...)</c>, walking the containing-type chain so
/// nested types render as <c>Outer.Inner<></c>. Generic outer types are not supported and
/// will produce code that does not compile — flagged by diagnostic JSG007.
/// </summary>
private static string OpenGenericCSharpName(INamedTypeSymbol type)
{
var parts = new List<string>();
var cursor = (INamedTypeSymbol?)type;
while (cursor != null)
{
var name = cursor.Name;
if (cursor.Arity == 0)
{
parts.Insert(0, name);
}
else
{
var commas = new string(',', cursor.Arity - 1);
parts.Insert(0, $"{name}<{commas}>");
}
cursor = cursor.ContainingType;
}
var ns = type.ContainingNamespace?.IsGlobalNamespace == true
? null
: type.ContainingNamespace?.ToDisplayString();
var joined = string.Join(".", parts);
return string.IsNullOrEmpty(ns) ? $"global::{joined}" : $"global::{ns}.{joined}";
}
private static bool HasGenericContainingType(INamedTypeSymbol type)
{
for (var c = type.ContainingType; c != null; c = c.ContainingType)
{
if (c.Arity > 0) return true;
}
return false;
}
private static readonly DiagnosticDescriptor EnvelopeMissingPayloadDescriptor = new DiagnosticDescriptor(
id: "JSG003",
title: "Envelope missing [PopcornPayload]",
messageFormat: "Envelope '{0}' is marked with [PopcornEnvelope] but has no [PopcornPayload] property. The exception middleware will fall back to the default ApiResponse shape for this envelope type.",
category: "SourceGenerator",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor EnvelopeDuplicateMarkerDescriptor = new DiagnosticDescriptor(
id: "JSG004",
title: "Envelope has duplicate marker",
messageFormat: "Envelope '{0}' has multiple properties marked with [Popcorn{1}]. Only the last one is used.",
category: "SourceGenerator",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor EnvelopePayloadTypeDescriptor = new DiagnosticDescriptor(
id: "JSG005",
title: "Envelope [PopcornPayload] should be Pop<T>",
messageFormat: "Property '{0}' on envelope '{1}' is marked with [PopcornPayload] but is typed as '{2}' instead of Pop<T>. Property-reference filtering will not be applied to this payload.",
category: "SourceGenerator",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor EnvelopeErrorTypeDescriptor = new DiagnosticDescriptor(
id: "JSG006",
title: "Envelope [PopcornError] should be ApiError",
messageFormat: "Property '{0}' on envelope '{1}' is marked with [PopcornError] but is typed as '{2}' instead of ApiError or ApiError?. The exception middleware may produce a shape that does not round-trip to your envelope type.",
category: "SourceGenerator",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor EnvelopeGenericOuterDescriptor = new DiagnosticDescriptor(
id: "JSG007",
title: "Envelope nested in a generic outer type is not supported",
messageFormat: "Envelope '{0}' is nested inside a generic outer type. The generator cannot emit the open-generic typeof expression required to dispatch error envelopes for this shape. Move the envelope to the top level or inside a non-generic container.",
category: "SourceGenerator",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
// JSG008: a property (or collection/array/dictionary element of a property) on a registered
// type is declared with a static type whose concrete runtime identity cannot be resolved at
// build time — `object`, an abstract class, or an interface. The source generator cannot
// emit a Pop<T> converter for these shapes under Native AOT or IL trimming, because the
// metadata reflection would need to discover unknown derived types has been stripped by the
// trimmer. Documented as the one genuine AOT non-starter in migrationAnalysis.md.
private static readonly DiagnosticDescriptor PolymorphicUnknownDescriptor = new DiagnosticDescriptor(
id: "JSG008",
title: "Property type cannot be resolved at build time (AOT non-starter)",
messageFormat: "Member '{0}.{1}' is typed as '{2}', whose concrete runtime type cannot be resolved at build time. Popcorn's source generator cannot emit a converter for this shape under Native AOT or IL trimming. Expose the concrete type(s) through a typed property, register derived types via [JsonDerivedType] and a non-polymorphic wrapper, or handle this member outside Popcorn.",
category: "SourceGenerator",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
// True iff GenerateJsonConverter would set emitInnerOverload=true for this target — i.e.
// the target's converter file emits a Pop{X}Inner overload. Only complex-object targets do
// (the final `else` branch in GenerateJsonConverter); every other dispatch branch (blind,
// Nullable<T>, IDictionary<K,V>, array, IEnumerable<T>) leaves emitInnerOverload=false.
// Used by CreateArraySerializer / CreateDictionarySerializer to decide whether the per-item
// call can take the fast path (Pop{X}Inner with hoisted naming/useAll/useDefault) or must
// fall back to the 4-arg Pop{X} wrapper. Failing to fall back produces CS0103 at consumer
// build time on nested-collection shapes — the regression fixed here.
private static bool TargetEmitsInner(ITypeSymbol? type)
{
if (type == null) return false;
if (IsBlindSerializableType(type)) return false;
if (type is IArrayTypeSymbol) return false;
if (type is INamedTypeSymbol named)
{
if (named.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) return false;
if (InheritsOrImplements(named, IDictionaryTypeName)) return false;
if (InheritsOrImplements(named, IEnumerableTypeName)) return false;
}
return true;
}
// Unwrap arrays / IEnumerable<T> / IDictionary<K,V> (value) / Nullable<T> until we reach a
// leaf type. Used by JSG008 to evaluate the eventual payload type seen at the wire, not the
// container.
private static ITypeSymbol UnwrapMemberType(ITypeSymbol type)
{
while (true)
{
if (type is IArrayTypeSymbol arr)
{
type = arr.ElementType;
continue;
}
if (type is INamedTypeSymbol named)
{
if (named.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T
&& named.TypeArguments.Length == 1)
{
type = named.TypeArguments[0];
continue;
}
if (InheritsOrImplements(named, IDictionaryTypeName)
&& named.TypeArguments.Length > 1)
{
type = named.TypeArguments[1];
continue;
}
if (InheritsOrImplements(named, IEnumerableTypeName)
&& named.TypeArguments.Length > 0)
{
// Skip string (which implements IEnumerable<char>) — strings are blind-serialized.
if (named.SpecialType == SpecialType.System_String) return type;
type = named.TypeArguments[0];
continue;
}
}
return type;
}
}
// Emits JSG008 if the member's eventual payload type is polymorphically unresolvable
// (object, abstract class, interface). Called once per property/field as GetReferencedTypes
// walks. Duplicate diagnostics across multiple registrations targeting the same member are
// acceptable — the warning is still correct and useful in each context.
private static void CheckForUnresolvablePolymorphism(
ISymbol member, ITypeSymbol memberType, SourceProductionContext context)
{
var unwrapped = UnwrapMemberType(memberType);
bool problematic =
unwrapped.SpecialType == SpecialType.System_Object
|| (unwrapped.TypeKind == TypeKind.Class && unwrapped.IsAbstract)
|| unwrapped.TypeKind == TypeKind.Interface;
if (!problematic) return;
var location = member.Locations.FirstOrDefault() ?? Location.None;
context.ReportDiagnostic(Diagnostic.Create(
PolymorphicUnknownDescriptor,
location,
member.ContainingType?.ToDisplayString() ?? "?",
member.Name,
memberType.ToDisplayString()));
}
private static void ReportEnvelopeDiagnostics(SourceProductionContext spc, INamedTypeSymbol envelope, EnvelopeAnalysis analysis)
{
var envelopeName = envelope.ToDisplayString();
var envelopeLocation = analysis.EnvelopeLocation ?? Location.None;
if (analysis.PayloadName == null)
{
spc.ReportDiagnostic(Diagnostic.Create(EnvelopeMissingPayloadDescriptor, envelopeLocation, envelopeName));
}
foreach (var loc in analysis.DuplicateSuccessLocations)
{
spc.ReportDiagnostic(Diagnostic.Create(EnvelopeDuplicateMarkerDescriptor, loc, envelopeName, "Success"));
}
foreach (var loc in analysis.DuplicatePayloadLocations)
{
spc.ReportDiagnostic(Diagnostic.Create(EnvelopeDuplicateMarkerDescriptor, loc, envelopeName, "Payload"));
}
foreach (var loc in analysis.DuplicateErrorLocations)
{
spc.ReportDiagnostic(Diagnostic.Create(EnvelopeDuplicateMarkerDescriptor, loc, envelopeName, "Error"));
}
if (analysis.PayloadType != null && !IsPopOfT(analysis.PayloadType))
{
spc.ReportDiagnostic(Diagnostic.Create(
EnvelopePayloadTypeDescriptor,
analysis.PayloadLocation ?? envelopeLocation,
analysis.PayloadName,
envelopeName,
analysis.PayloadType.ToDisplayString()));
}
if (analysis.ErrorType != null && !IsApiError(analysis.ErrorType))
{
spc.ReportDiagnostic(Diagnostic.Create(
EnvelopeErrorTypeDescriptor,
analysis.ErrorLocation ?? envelopeLocation,
analysis.ErrorName,
envelopeName,
analysis.ErrorType.ToDisplayString()));
}
if (HasGenericContainingType(envelope))
{
spc.ReportDiagnostic(Diagnostic.Create(EnvelopeGenericOuterDescriptor, envelopeLocation, envelopeName));
}
}
private static bool InheritsOrImplements(ITypeSymbol typeSymbol, string baseTypeName)
{
var visitedTypes = new HashSet<ITypeSymbol>(SymbolEqualityComparer.Default);
var typesToVisit = new Queue<ITypeSymbol>();
typesToVisit.Enqueue(typeSymbol);
while (typesToVisit.Any())
{
var cursorSymbol = typesToVisit.Dequeue();
if (!visitedTypes.Add(cursorSymbol))
{
continue;
}
if (cursorSymbol.OriginalDefinition.ToDisplayString() == baseTypeName)
{
return true;
}
if (cursorSymbol.BaseType != null && !visitedTypes.Contains(cursorSymbol.BaseType))
{
typesToVisit.Enqueue(cursorSymbol.BaseType);
}
foreach (var interfaceType in cursorSymbol.AllInterfaces)
{
if (!visitedTypes.Contains(interfaceType))
{
typesToVisit.Enqueue(interfaceType);
}
}
}
return false;
}
private static HashSet<ITypeSymbol> GetReferencedTypes(ITypeSymbol targetType, INamedTypeSymbol classSymbol, SourceProductionContext context)
{
// We need to build out the recursive references here
// Visit each type and find each property that could be serialized and ensure that its type is added to the list.
var visitedTypes = new HashSet<ITypeSymbol>(SymbolEqualityComparer.Default);
var typesToVisit = new Queue<ITypeSymbol>();
typesToVisit.Enqueue(targetType);
while (typesToVisit.Count > 0)
{
var currentType = typesToVisit.Dequeue();
// Handle array types
if (currentType is IArrayTypeSymbol arrayType)
{
// Add the array type itself to visitedTypes
if (!visitedTypes.Add(arrayType))
{
continue;
}
if (arrayType.ElementType is INamedTypeSymbol elementNamedType)
{
var propertyTypeName = elementNamedType.ToDisplayString().Replace("?", "");
if (!IgnoreTypes.Contains(propertyTypeName)
&& !NumberTypes.Contains(propertyTypeName)
&& !StringTypes.Contains(propertyTypeName)
&& !BoolTypes.Contains(propertyTypeName))
{
if (!visitedTypes.Contains(elementNamedType))
{
typesToVisit.Enqueue(elementNamedType);
}
}
}
continue;
}
// Handle named types
if (currentType is INamedTypeSymbol namedType)
{
var propertyTypeName = namedType.ToDisplayString().Replace("?", "");
if (IgnoreTypes.Contains(propertyTypeName)
|| NumberTypes.Contains(propertyTypeName)
|| StringTypes.Contains(propertyTypeName)
|| BoolTypes.Contains(propertyTypeName))
{
continue;
}
// Enums (and Nullable<Enum>) are handled by System.Text.Json directly.
// Skipping here prevents the generator from treating them as complex objects
// and keeps them out of allTypeNames, so the default JsonSerializer.Serialize
// fallback in AddMemberSerializationCode handles them correctly. This also
// means global options.Converters (e.g. JsonStringEnumConverter) and per-type
// [JsonConverter] attributes on the enum work transparently.
if (namedType.TypeKind == TypeKind.Enum)
{
continue;
}
if (namedType.OriginalDefinition?.SpecialType == SpecialType.System_Nullable_T &&
namedType.TypeArguments.Length == 1 &&
namedType.TypeArguments[0].TypeKind == TypeKind.Enum)
{
continue;
}
if (!visitedTypes.Add(namedType))
{
continue;
}
// Check if this is a collection type and extract its item type
if (namedType.OriginalDefinition != null)
{
// Handle "dictionary" types eg IDictionary<K,V> - only consider the value type V, not the key type K
if (InheritsOrImplements(namedType, IDictionaryTypeName) &&
namedType.TypeArguments.Length > 1)
{
var valueType = namedType.TypeArguments[1];
if (valueType is INamedTypeSymbol valueNamedType && !visitedTypes.Contains(valueNamedType))
{
typesToVisit.Enqueue(valueNamedType);
}
continue;
}
// Handle "list" types
else if (InheritsOrImplements(namedType, IEnumerableTypeName) &&
namedType.TypeArguments.Length > 0)
{
var itemType = namedType.TypeArguments[0];
if (itemType is INamedTypeSymbol itemNamedType && !visitedTypes.Contains(itemNamedType))
{
typesToVisit.Enqueue(itemNamedType);
}
continue;
}
}
// Walk inherited members too — GetMembers() only returns declared-on-this-type,
// but [Always]/[Default] on a base class must apply to derived types.
foreach (var property in GetSerializableProperties(namedType))
{
CheckForUnresolvablePolymorphism(property, property.Type, context);
typesToVisit.Enqueue(property.Type);
}
foreach (var field in GetSerializableFields(namedType))
{
CheckForUnresolvablePolymorphism(field, field.Type, context);
typesToVisit.Enqueue(field.Type);
}
}
}
return visitedTypes;
}
// Check if a type is nullable
private static bool IsNullableType(ITypeSymbol typeSymbol)
{
// Arrays are reference types and thus nullable
if (typeSymbol is IArrayTypeSymbol)
{
return true;
}
// Handle named types
if (typeSymbol is INamedTypeSymbol namedType)
{
// Case 1: Reference types are inherently nullable
if (!namedType.IsValueType)
{
return true;
}
// Case 2: Nullable value types (Nullable<T>)
if (namedType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
{
return true;
}
}
// Not nullable
return false;
}
private static string GenerateJsonConverter(ITypeSymbol targetType, INamedTypeSymbol classSymbol, HashSet<ITypeSymbol> allTypes, SourceProductionContext context)
{
// Bug 4 fix: primitives/enums/ignored types never get a Pop<T> body emitted, so they
// must NOT appear in `allTypeNames` either. If they did, every downstream dict/list/array
// converter that checks `allTypeNames.Contains(itemTypeName)` would decide to emit a
// call to the non-existent Pop<primitive> method. One bad registration (e.g.
// `ApiResponse<int?>` at root) used to cascade into compile errors across unrelated
// converters. Filter at the source.
var allTypeNames = new HashSet<string>(
allTypes.Where(t => t != null && !IsBlindSerializableType(t))
.Select(t => t!.ToDisplayString().Replace("?", "")));
var typeName = TypeNameForPop(targetType);
var converterName = $"{NameType(targetType)}JsonConverter";
// Logging statement for allTypeNames
Show($"{targetType.ToDisplayString()}: All registered type names: {string.Join(", ", allTypeNames)}", context);
// Accumulates `private static readonly` declarations for [SubPropertyDefault(...)]
// includes — one per attributed member in this target type. Emitted inline in the
// partial-class fragment below so they co-locate with the Pop{T} method.
var subPropertyDefaultFields = new StringBuilder();
string internalSerializationCode = "";
// Only complex-object targets get the split into a flag-computing 4-arg wrapper + an
// Inner overload that takes pre-computed useAll/useDefault/naming. Collection, blind,
// and nullable-wrapper targets have no flag-dependent body and keep the single 4-arg.
bool emitInnerOverload = false;
// Cycle-safety analysis: if the converter's effective payload type can never reach
// itself (directly or through any property graph Popcorn recurses into), the visit-
// tracking HashSet is dead weight. Skip the allocation at the entry point and let the
// body's null-conditional ops no-op.
var isCycleSafe = IsConverterCycleSafe(targetType, allTypeNames);
Show($"{targetType.ToDisplayString()}: cycle-safe = {isCycleSafe}", context);
// Bug 4 fix: root-level primitive / ignored / enum registration
// (e.g. [JsonSerializable(typeof(ApiResponse<int?>))]). Emit a converter that simply
// delegates to System.Text.Json — there is no Pop<int> method to dispatch to, and we
// don't want to force the user to special-case these at the consumer level.
if (IsBlindSerializableType(targetType))
{
Show($"{targetType} Is a blind-serializable (primitive/enum/ignored) type — emitting default JsonSerializer path", context);
internalSerializationCode = @"
JsonSerializer.Serialize(writer, value.Data, options);
";
}
// Check if this is a nullable value type (Nullable<T>) whose underlying type is one
// we DO emit a Pop<T> for. Primitives/enums wrapped in Nullable<T> are handled by the
// IsBlindSerializableType branch above.
else if (targetType is INamedTypeSymbol namedType &&
namedType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T &&
namedType.TypeArguments.Length == 1)
{
var underlyingType = namedType.TypeArguments[0];
Show($"{targetType} Is a Nullable of {underlyingType.ToDisplayString()}", context);
// Generate code to unwrap the nullable value and use the converter for the underlying type
internalSerializationCode = $@"
// Unwrap the nullable value and use the converter for the underlying type
var unwrappedValue = value.Data.Value;
Pop{NameType(underlyingType)}(
writer,
new global::Popcorn.Shared.Pop<{TypeNameForPop(underlyingType)}> {{
Data = unwrappedValue,
PropertyReferences = value.PropertyReferences
}},
options, visitedObjects);
";
}
else if (targetType is INamedTypeSymbol namedDictionaryTypeNonNullable && InheritsOrImplements(namedDictionaryTypeNonNullable, IDictionaryTypeName))
{
// Covers Dictionary<K,V>, IDictionary<K,V>, ReadOnlyDictionary<K,V>, and any user
// subclass that implements IDictionary<TKey, TValue>. A previous secondary check
// keyed on Dictionary<K,V>'s OriginalDefinition existed to work around a whitespace
// bug in IDictionaryTypeName that made this branch dead; the constant is now
// correct ("IDictionary<TKey, TValue>" with the same ", " Roslyn emits), so the
// secondary check is redundant and has been removed.
var valueType = namedDictionaryTypeNonNullable.TypeArguments[1] as INamedTypeSymbol;
Show($"DICTIONARY DETECTED: {namedDictionaryTypeNonNullable} Is an IDictionary of {valueType?.ToDisplayString()}", context);
internalSerializationCode = CreateDictionarySerializer(allTypeNames, valueType, context);
}
// If this targetType implement IEnumerable, write out as an array and use the item type as target type instead for each element.
else if (targetType is IArrayTypeSymbol arrayType)
{
var itemType = arrayType.ElementType as INamedTypeSymbol;
Show($"{targetType} Is an Array of {itemType?.ToDisplayString()}", context);
internalSerializationCode = CreateArraySerializer(allTypeNames, itemType);
}
else if (targetType is INamedTypeSymbol namedTypeNonNullable)
{
if (InheritsOrImplements(namedTypeNonNullable, IEnumerableTypeName))
{
var itemType = namedTypeNonNullable.TypeArguments[0] as INamedTypeSymbol;
Show($"{namedTypeNonNullable} Is an IEnumerable of {itemType?.ToDisplayString()}", context);
internalSerializationCode = CreateArraySerializer(allTypeNames, itemType);
}
else
{
internalSerializationCode = CreateComplexObjectInnerBody(namedTypeNonNullable, context, allTypeNames, subPropertyDefaultFields);
emitInnerOverload = true;
}
}
else
{
// We shouldn't really get here, but if we do, just serialize the object normally
internalSerializationCode = @"
// 411: Just serialize the field normally
JsonSerializer.Serialize(writer, value.Data, options);
";
}
var jsonContextName = classSymbol.ContainingNamespace.IsGlobalNamespace ? classSymbol.Name : $"{ classSymbol.ContainingNamespace}.{classSymbol.Name}";
// First, determine if the type is nullable
bool isNullable = IsNullableType(targetType);
var nullCheck = "";
if (isNullable)
{
nullCheck = $@"
if(value.Data == null)
{{
writer.WriteNullValue();
return;
}}";
}
// The cast at every property-Pop callsite (`Data = (T)value.Data.Prop`) can still fire
// CS8619 when Prop's declared type has nullable-element annotations (e.g. List<string?>)
// that T (normalized by TypeNameForPop) lacks. Those two types are CLR-identical, so
// the warning is noise in generated code. Suppress the nullability family at the file