This repository was archived by the owner on May 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 251
Expand file tree
/
Copy pathZeroFormatterAnalyzer.cs
More file actions
581 lines (508 loc) · 27.5 KB
/
ZeroFormatterAnalyzer.cs
File metadata and controls
581 lines (508 loc) · 27.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
using Microsoft.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Generic;
using System.Collections.Immutable;
using System;
namespace ZeroFormatter.Analyzer
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ZeroFormatterAnalyzer : DiagnosticAnalyzer
{
const string DiagnosticIdBase = "ZeroFormatterAnalyzer";
internal const string Title = "Lint of ZeroFormattable Type.";
internal const string Category = "Usage";
internal const string ZeroFormattableAttributeShortName = "ZeroFormattableAttribute";
internal const string IndexAttributeShortName = "IndexAttribute";
internal const string IgnoreShortName = "IgnoreFormatAttribute";
internal const string UnionAttributeShortName = "UnionAttribute";
internal const string DynamicUnionAttributeShortName = "DynamicUnionAttribute";
internal const string UnionKeyAttributeShortName = "UnionKeyAttribute";
internal const string ZeroFormattableFormatterProperty = "FormatterType";
internal const string FormatterTypeName = "Formatter";
internal static readonly DiagnosticDescriptor TypeMustBeZeroFormattable = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(TypeMustBeZeroFormattable), title: Title, category: Category,
messageFormat: "Type must be marked with ZeroFormattableAttribute. {0}.", // type.Name
description: "Type must be marked with ZeroFormattableAttribute.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor PublicPropertyNeedsIndex = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(PublicPropertyNeedsIndex), title: Title, category: Category,
messageFormat: "Public property must be marked with IndexAttribute or IgnoreFormatAttribute. {0}.{1}.", // type.Name + "." + item.Name
description: "Public property must be marked with IndexAttribute or IgnoreFormatAttribute.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor PublicPropertyNeedsGetAndSetAccessor = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(PublicPropertyNeedsGetAndSetAccessor), title: Title, category: Category,
messageFormat: "Public property must needs both public/protected get and set accessor. {0}.{1}.", // type.Name + "." + item.Name
description: "Public property must needs both public/protected get and set accessor.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor PublicPropertyMustBeVirtual = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(PublicPropertyMustBeVirtual), title: Title, category: Category,
messageFormat: "Public property's accessor must be virtual. {0}.{1}.", // type.Name + "." + item.Name
description: "Public property's accessor must be virtual.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor ClassNotSupportPublicField = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(ClassNotSupportPublicField), title: Title, category: Category,
messageFormat: "Class's public field is not supported. {0}.{1}.", // type.Name + "." + item.Name
description: "Class's public field is not supported.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor IndexAttributeDuplicate = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(IndexAttributeDuplicate), title: Title, category: Category,
messageFormat: "IndexAttribute is not allow duplicate number. {0}.{1}, Index:{2}", // type.Name, item.Name index.Index
description: "IndexAttribute is not allow duplicate number.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor IndexIsTooLarge = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(IndexIsTooLarge), title: Title, category: Category,
messageFormat: "MaxIndex is {0}, it is large. Index is size of binary, recommended to small. {1}", // index, type.Name
description: "MaxIndex is large. Index is size of binary, recommended to small.",
defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor TypeMustNeedsParameterlessConstructor = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(TypeMustNeedsParameterlessConstructor), title: Title, category: Category,
messageFormat: "Type must needs parameterless constructor. {0}", // type.Name
description: "Type must needs parameterless constructor.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor StructIndexMustBeStartedWithZeroAndSequential = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(StructIndexMustBeStartedWithZeroAndSequential), title: Title, category: Category,
messageFormat: "Struct index must be started with 0 and be sequential. Type: {0}, InvalidIndex: {1}", // type.Name, index
description: "Struct index must be started with 0 and be sequential.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor StructMustNeedsSameConstructorWithIndexes = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(StructIndexMustBeStartedWithZeroAndSequential), title: Title, category: Category,
messageFormat: "Struct needs full parameter constructor of index property types. Type: {0}", // type.Name
description: "Struct needs full parameter constructor of index property types.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor UnionTypeRequiresUnionKey = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(UnionTypeRequiresUnionKey), title: Title, category: Category,
messageFormat: "Union class requires abstract [UnionKey]property. Type: {0}", // type.Name
description: "Union class requires abstract [UnionKey]property.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor UnionKeyDoesNotAllowMultipleKey = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(UnionKeyDoesNotAllowMultipleKey), title: Title, category: Category,
messageFormat: "[UnionKey]property does not allow multiple key. Type: {0}", // type.Name
description: "[UnionKey]property does not allow multiple key.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor AllUnionSubTypesMustBeInheritedType = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(UnionKeyDoesNotAllowMultipleKey), title: Title, category: Category,
messageFormat: "All Union subTypes must be inherited type. Type: {0}, SubType: {1}", // type.Name subType.Name
description: "All Union subTypes must be inherited type.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor ExplicitFormatterMustInheritFormatter = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(ExplicitFormatterMustInheritFormatter), title: Title, category: Category,
messageFormat: "Explicit Formatter type must inherit from Formatter<>. Type: {0}, Formatter: {1}", // type.Name subType.Name
description: "Explicit Formatter type must inherit from Formatter<>.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
static readonly ImmutableArray<DiagnosticDescriptor> supportedDiagnostics = ImmutableArray.Create(
TypeMustBeZeroFormattable,
PublicPropertyNeedsIndex,
PublicPropertyNeedsGetAndSetAccessor,
PublicPropertyMustBeVirtual,
ClassNotSupportPublicField,
IndexAttributeDuplicate,
IndexIsTooLarge,
TypeMustNeedsParameterlessConstructor,
StructIndexMustBeStartedWithZeroAndSequential,
StructMustNeedsSameConstructorWithIndexes,
UnionTypeRequiresUnionKey,
UnionKeyDoesNotAllowMultipleKey,
AllUnionSubTypesMustBeInheritedType
);
static readonly HashSet<string> AllowTypes = new HashSet<string>
{
"short",
"int",
"long",
"ushort",
"uint",
"ulong",
"float",
"double",
"bool",
"byte",
"sbyte",
"decimal",
"char",
"string",
"System.Guid",
"System.TimeSpan",
"System.DateTime",
"System.DateTimeOffset"
};
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return supportedDiagnostics;
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.InterfaceDeclaration);
}
static void Analyze(SyntaxNodeAnalysisContext context)
{
var model = context.SemanticModel;
var typeDeclaration = context.Node as TypeDeclarationSyntax;
if (typeDeclaration == null) return;
var declaredSymbol = model.GetDeclaredSymbol(typeDeclaration);
if (declaredSymbol == null) return;
var isUnion = declaredSymbol.GetAttributes().FindAttributeShortName(UnionAttributeShortName) != null;
var zeroFormattableAttribute = declaredSymbol.GetAttributes().FindAttributeShortName(ZeroFormattableAttributeShortName);
if (!isUnion && zeroFormattableAttribute == null)
{
return;
}
var reportContext = new DiagnosticsReportContext(context);
if (isUnion)
{
VerifyUnion(reportContext, typeDeclaration.GetLocation(), declaredSymbol);
}
if (zeroFormattableAttribute != null)
{
var explicitFormatter =
zeroFormattableAttribute.NamedArguments.Where(
x => x.Key == ZeroFormattableFormatterProperty);
if (explicitFormatter.Any())
{
if (explicitFormatter.First().Value.Type.BaseType.Name != FormatterTypeName)
reportContext.Add(Diagnostic.Create(ExplicitFormatterMustInheritFormatter,
typeDeclaration.GetLocation(), typeDeclaration.GetLocation(),
explicitFormatter.First().Value.Type));
return;
}
VerifyType(reportContext, typeDeclaration.GetLocation(), declaredSymbol, new HashSet<ITypeSymbol>(), null);
}
reportContext.ReportAll();
}
static void VerifyType(DiagnosticsReportContext context, Location callerLocation, ITypeSymbol type, HashSet<ITypeSymbol> alreadyAnalyzed, ISymbol callFromProperty)
{
if (!alreadyAnalyzed.Add(type))
{
return;
}
var displayString = type.ToDisplayString();
if (AllowTypes.Contains(displayString))
{
return; // it is primitive...
}
else if (context.AdditionalAllowTypes.Contains(displayString))
{
return;
}
if (type.GetAttributes().FindAttributeShortName(UnionAttributeShortName) != null)
{
return;
}
if (type.GetAttributes().FindAttributeShortName(DynamicUnionAttributeShortName) != null)
{
return;
}
if (type.TypeKind == TypeKind.Enum)
{
return;
}
if (type.TypeKind == TypeKind.Array)
{
var array = type as IArrayTypeSymbol;
var t = array.ElementType;
VerifyType(context, callerLocation, t, alreadyAnalyzed, callFromProperty);
return;
}
var namedType = type as INamedTypeSymbol;
if (namedType != null && namedType.IsGenericType && callFromProperty != null)
{
var genericType = namedType.ConstructUnboundGenericType();
var genericTypeString = genericType.ToDisplayString();
if (genericTypeString == "T?")
{
VerifyType(context, callerLocation, namedType.TypeArguments[0], alreadyAnalyzed, callFromProperty);
return;
}
else if (genericTypeString == "System.Collections.Generic.IList<>"
|| genericTypeString == "System.Collections.Generic.IDictionary<,>"
|| genericTypeString == "System.Collections.Generic.Dictionary<,>"
|| genericTypeString == "ZeroFormatter.ILazyDictionary<,>"
|| genericTypeString == "System.Collections.Generic.IReadOnlyList<>"
|| genericTypeString == "System.Collections.Generic.IReadOnlyCollection<>"
|| genericTypeString == "System.Collections.Generic.IReadOnlyDictionary<,>"
|| genericTypeString == "System.Collections.Generic.ICollection<>"
|| genericTypeString == "System.Collections.Generic.IEnumerable<>"
|| genericTypeString == "System.Collections.Generic.ISet<>"
|| genericTypeString == "System.Collections.ObjectModel.ReadOnlyCollection<>"
|| genericTypeString == "System.Collections.ObjectModel.ReadOnlyDictionary<,>"
|| genericTypeString == "ZeroFormatter.ILazyReadOnlyDictionary<,>"
|| genericTypeString == "System.Linq.ILookup<,>"
|| genericTypeString == "ZeroFormatter.ILazyLookup<,>"
|| genericTypeString.StartsWith("System.Collections.Generic.KeyValuePair")
|| genericTypeString.StartsWith("System.Tuple")
|| genericTypeString.StartsWith("ZeroFormatter.KeyTuple")
|| context.AdditionalAllowTypes.Contains(genericTypeString)
)
{
foreach (var t in namedType.TypeArguments)
{
VerifyType(context, callerLocation, t, alreadyAnalyzed, callFromProperty);
}
return;
}
else
{
if (namedType.AllInterfaces.Any(x => (x.IsGenericType ? x.ConstructUnboundGenericType().ToDisplayString() : "") == "System.Collections.Generic.ICollection<>"))
{
foreach (var t in namedType.TypeArguments)
{
VerifyType(context, callerLocation, t, alreadyAnalyzed, callFromProperty);
}
return;
}
}
}
if (type.GetAttributes().FindAttributeShortName(ZeroFormattableAttributeShortName) == null)
{
context.Add(Diagnostic.Create(TypeMustBeZeroFormattable, callerLocation, type.Locations, type.Name));
return;
}
if (namedType != null && !namedType.IsValueType)
{
if (!namedType.Constructors.Any(x => x.Parameters.Length == 0))
{
context.Add(Diagnostic.Create(TypeMustNeedsParameterlessConstructor, callerLocation, type.Locations, type.Name));
return;
}
}
// If in another project, we can not report so stop analyze.
if (callFromProperty == null)
{
var definedIndexes = new HashSet<int>();
foreach (var member in type.GetAllMembers().OfType<IPropertySymbol>())
{
VerifyProperty(context, member, alreadyAnalyzed, definedIndexes);
}
foreach (var member in type.GetAllMembers().OfType<IFieldSymbol>())
{
VerifyField(context, member, alreadyAnalyzed, definedIndexes);
}
if (type.IsValueType && context.Diagnostics.Count == 0)
{
var indexes = new List<Tuple<int, ITypeSymbol>>();
foreach (var item in type.GetMembers())
{
var propSymbol = item as IPropertySymbol;
var fieldSymbol = item as IFieldSymbol;
if ((propSymbol == null && fieldSymbol == null))
{
continue;
}
var indexAttr = item.GetAttributes().FindAttributeShortName(IndexAttributeShortName);
if (indexAttr != null)
{
var index = (int)indexAttr.ConstructorArguments[0].Value;
indexes.Add(Tuple.Create(index, (propSymbol != null) ? propSymbol.Type : fieldSymbol.Type));
}
}
indexes = indexes.OrderBy(x => x.Item1).ToList();
var expected = 0;
foreach (var item in indexes)
{
if (item.Item1 != expected)
{
context.Add(Diagnostic.Create(StructIndexMustBeStartedWithZeroAndSequential, callerLocation, type.Locations, type.Name, item.Item1));
return;
}
expected++;
}
var foundConstructor = false;
var ctors = (type as INamedTypeSymbol)?.Constructors;
foreach (var ctor in ctors)
{
var isMatch = indexes.Select(x => x.Item2.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))
.SequenceEqual(ctor.Parameters.Select(x => x.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)));
if (isMatch)
{
foundConstructor = true;
}
}
if (!foundConstructor && indexes.Count != 0)
{
context.Add(Diagnostic.Create(StructMustNeedsSameConstructorWithIndexes, callerLocation, type.Locations, type.Name));
return;
}
return;
}
}
}
static void VerifyProperty(DiagnosticsReportContext context, IPropertySymbol property, HashSet<ITypeSymbol> alreadyAnalyzed, HashSet<int> definedIndexes)
{
if (property.IsStatic)
{
return;
}
if (property.DeclaredAccessibility != Accessibility.Public)
{
return;
}
var attributes = property.GetAttributes();
if (attributes.FindAttributeShortName(IgnoreShortName) != null)
{
return;
}
if (property.FindAttributeIncludeBasePropertyShortName(UnionKeyAttributeShortName) != null)
{
return;
}
if (!property.IsVirtual && !property.ContainingType.IsValueType)
{
if (property.IsOverride && !property.IsSealed)
{
// ok, base type's override property.
}
else
{
context.Add(Diagnostic.Create(PublicPropertyMustBeVirtual, property.Locations[0], property.ContainingType?.Name, property.Name));
return;
}
}
var indexAttr = attributes.FindAttributeShortName(IndexAttributeShortName);
if (indexAttr == null || indexAttr.ConstructorArguments.Length == 0)
{
context.Add(Diagnostic.Create(PublicPropertyNeedsIndex, property.Locations[0], property.ContainingType?.Name, property.Name));
return;
}
var index = indexAttr.ConstructorArguments[0];
if (index.IsNull)
{
return; // null is normal compiler error.
}
if (!definedIndexes.Add((int)index.Value))
{
context.Add(Diagnostic.Create(IndexAttributeDuplicate, property.Locations[0], property.ContainingType?.Name, property.Name, index.Value));
return;
}
if ((int)index.Value >= 100)
{
context.Add(Diagnostic.Create(IndexIsTooLarge, property.Locations[0], index.Value, property.Name));
}
if (!property.ContainingType.IsValueType)
{
if (property.GetMethod == null || property.SetMethod == null
|| property.GetMethod.DeclaredAccessibility == Accessibility.Private
|| property.SetMethod.DeclaredAccessibility == Accessibility.Private)
{
context.Add(Diagnostic.Create(PublicPropertyNeedsGetAndSetAccessor, property.Locations[0], property.ContainingType?.Name, property.Name));
return;
}
}
var namedType = property.Type as INamedTypeSymbol;
if (namedType != null) // if <T> is unnamed type, it can't analyze.
{
VerifyType(context, property.Locations[0], property.Type, alreadyAnalyzed, property);
return;
}
if (property.Type.TypeKind == TypeKind.Array)
{
var array = property.Type as IArrayTypeSymbol;
var t = array.ElementType;
VerifyType(context, property.Locations[0], property.Type, alreadyAnalyzed, property);
return;
}
}
static void VerifyField(DiagnosticsReportContext context, IFieldSymbol field, HashSet<ITypeSymbol> alreadyAnalyzed, HashSet<int> definedIndexes)
{
if (field.IsStatic)
{
return;
}
if (field.DeclaredAccessibility != Accessibility.Public)
{
return;
}
var attributes = field.GetAttributes();
if (attributes.FindAttributeShortName(IgnoreShortName) != null)
{
return;
}
if (!field.ContainingType.IsValueType)
{
context.Add(Diagnostic.Create(ClassNotSupportPublicField, field.Locations[0], field.ContainingType?.Name, field.Name));
return;
}
var indexAttr = attributes.FindAttributeShortName(IndexAttributeShortName);
if (indexAttr == null || indexAttr.ConstructorArguments.Length == 0)
{
context.Add(Diagnostic.Create(PublicPropertyNeedsIndex, field.Locations[0], field.ContainingType?.Name, field.Name));
return;
}
var index = indexAttr.ConstructorArguments[0];
if (index.IsNull)
{
return; // null is normal compiler error.
}
if (!definedIndexes.Add((int)index.Value))
{
context.Add(Diagnostic.Create(IndexAttributeDuplicate, field.Locations[0], field.ContainingType?.Name, field.Name, index.Value));
return;
}
if ((int)index.Value >= 100)
{
context.Add(Diagnostic.Create(IndexIsTooLarge, field.Locations[0], index.Value, field.Name));
}
var namedType = field.Type as INamedTypeSymbol;
if (namedType != null) // if <T> is unnamed type, it can't analyze.
{
VerifyType(context, field.Locations[0], field.Type, alreadyAnalyzed, field);
}
}
static void VerifyUnion(DiagnosticsReportContext context, Location callerLocation, ITypeSymbol type)
{
var unionKeys = type.GetMembers().OfType<IPropertySymbol>().Where(x => x.GetAttributes().FindAttributeShortName(UnionKeyAttributeShortName) != null).ToArray();
if (unionKeys.Length == 0)
{
context.Add(Diagnostic.Create(UnionTypeRequiresUnionKey, callerLocation, type.Locations, type.Name));
return;
}
else if (unionKeys.Length != 1)
{
context.Add(Diagnostic.Create(UnionKeyDoesNotAllowMultipleKey, callerLocation, type.Locations, type.Name));
return;
}
var unionKeyProperty = unionKeys[0];
if (type.TypeKind != TypeKind.Interface && !unionKeyProperty.GetMethod.IsAbstract)
{
context.Add(Diagnostic.Create(UnionTypeRequiresUnionKey, callerLocation, type.Locations, type.Name));
return;
}
var ctorArguments = type.GetAttributes().FindAttributeShortName(UnionAttributeShortName)?.ConstructorArguments;
var firstArguments = ctorArguments?.FirstOrDefault();
if (firstArguments == null) return;
TypedConstant fallbackType = default(TypedConstant);
if (ctorArguments.Value.Length == 2)
{
fallbackType = ctorArguments.Value[1];
}
if (type.TypeKind != TypeKind.Interface)
{
foreach (var item in firstArguments.Value.Values.Concat(new[] { fallbackType }).Where(x => !x.IsNull).Select(x => x.Value).OfType<ITypeSymbol>())
{
var found = item.FindBaseTargetType(type.ToDisplayString());
if (found == null)
{
context.Add(Diagnostic.Create(AllUnionSubTypesMustBeInheritedType, callerLocation, type.Locations, type.Name, item.Name));
return;
}
}
}
else
{
foreach (var item in firstArguments.Value.Values.Concat(new[] { fallbackType }).Where(x => !x.IsNull).Select(x => x.Value).OfType<ITypeSymbol>())
{
var typeString = type.ToDisplayString();
if (!(item as INamedTypeSymbol).AllInterfaces.Any(x => x.OriginalDefinition?.ToDisplayString() == typeString))
{
context.Add(Diagnostic.Create(AllUnionSubTypesMustBeInheritedType, callerLocation, type.Locations, type.Name, item.Name));
return;
}
}
}
}
}
}