-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathTypeSymbolExtensions.cs
694 lines (585 loc) · 36 KB
/
TypeSymbolExtensions.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
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
namespace Architect.DomainModeling.Generator;
/// <summary>
/// Provides extensions on <see cref="ITypeSymbol"/>.
/// </summary>
internal static class TypeSymbolExtensions
{
private const string ComparisonsNamespace = "Architect.DomainModeling.Comparisons";
private static IReadOnlyCollection<string> ConversionOperatorNames { get; } = ["op_Implicit", "op_Explicit",];
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is of type <typeparamref name="T"/>.
/// </summary>
public static bool IsType<T>(this ITypeSymbol typeSymbol)
{
return typeSymbol.IsType(typeof(T));
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is of type <paramref name="comparand"/>.
/// </summary>
[Obsolete("Use ITypeSymbol.Equals(ITypeSymbol, SymbolEqualityComparer) instead.")]
public static bool IsType(this ITypeSymbol typeSymbol, ITypeSymbol comparand)
{
var containingNamespace = comparand.ContainingNamespace;
Span<char> freeBuffer = stackalloc char[128];
ReadOnlySpan<char> chars = freeBuffer;
while (containingNamespace?.IsGlobalNamespace == false && freeBuffer.Length >= containingNamespace.Name.Length)
{
containingNamespace.Name.AsSpan().CopyTo(freeBuffer);
freeBuffer = freeBuffer.Slice(containingNamespace.Name.Length);
containingNamespace = containingNamespace.ContainingNamespace;
}
chars = chars.Slice(0, chars.Length - freeBuffer.Length);
if (containingNamespace?.IsGlobalNamespace != false)
chars = (typeSymbol.ContainingNamespace?.ToString() ?? "").AsSpan();
if (!typeSymbol.IsType(typeSymbol.Name.AsSpan(), chars))
return false;
var namedTypeSymbol = typeSymbol as INamedTypeSymbol;
var namedComparand = comparand as INamedTypeSymbol;
if (namedTypeSymbol?.Arity > 0 && namedComparand?.Arity > 0)
return namedTypeSymbol.TypeArguments.SequenceEqual(namedComparand.TypeArguments, (left, right) => left.IsType(right));
return (namedTypeSymbol?.Arity ?? -1) == (namedComparand?.Arity ?? -1);
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is of the given type.
/// </summary>
public static bool IsType(this ITypeSymbol typeSymbol, Type type)
{
if (type.IsGenericTypeDefinition) ThrowOpenGenericTypeException();
if (!IsType(typeSymbol, type.Name, type.Namespace)) return false;
return !type.IsGenericType || HasGenericTypeArguments(typeSymbol, type);
// Local function that throws for open generic types
static void ThrowOpenGenericTypeException()
{
throw new NotSupportedException("This method does not support open generic types.");
}
// Local function that returns whether the input types have matching generic type arguments
static bool HasGenericTypeArguments(ITypeSymbol typeSymbol, Type type)
{
if (typeSymbol is not INamedTypeSymbol namedTypeSymbol) return false;
var requiredTypeArgs = type.GenericTypeArguments;
var actualTypeArgs = namedTypeSymbol.TypeArguments;
if (requiredTypeArgs.Length != actualTypeArgs.Length) return false;
for (var i = 0; i < requiredTypeArgs.Length; i++)
if (!actualTypeArgs[i].IsType(requiredTypeArgs[i]))
return false;
return true;
}
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> has the given <paramref name="fullTypeName"/>.
/// </summary>
/// <param name="fullTypeName">The type name including the namespace, e.g. System.Object.</param>
public static bool IsType(this ITypeSymbol typeSymbol, string fullTypeName, int? arity = null)
{
var fullTypeNameSpan = fullTypeName.AsSpan();
var lastDotIndex = fullTypeNameSpan.LastIndexOf('.');
if (lastDotIndex < 1) return false;
var typeName = fullTypeNameSpan.Slice(1 + lastDotIndex);
var containingNamespace = fullTypeNameSpan.Slice(0, lastDotIndex);
return IsType(typeSymbol, typeName, containingNamespace, arity);
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> has the given <paramref name="typeName"/> and <paramref name="containingNamespace"/>.
/// </summary>
public static bool IsType(this ITypeSymbol typeSymbol, string typeName, string containingNamespace, int? arity = null)
{
return IsType(typeSymbol, typeName.AsSpan(), containingNamespace.AsSpan(), arity);
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> has the given <paramref name="typeName"/> and <paramref name="containingNamespace"/>.
/// </summary>
/// <param name="generic">If not null, the being-generic of the type must match this value.</param>
private static bool IsType(this ITypeSymbol typeSymbol, ReadOnlySpan<char> typeName, ReadOnlySpan<char> containingNamespace, int? arity = null)
{
var backtickIndex = typeName.IndexOf('`');
if (backtickIndex >= 0)
typeName = typeName.Slice(0, backtickIndex);
var result = typeSymbol.Name.AsSpan().Equals(typeName, StringComparison.Ordinal) &&
typeSymbol.ContainingNamespace.HasFullName(containingNamespace);
if (result && arity is not null)
result = typeSymbol is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.Arity == arity;
return result;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is or inherits from a certain class, as determined by the given <paramref name="predicate"/>.
/// </summary>
public static bool IsOrInheritsClass(this ITypeSymbol typeSymbol, Func<INamedTypeSymbol, bool> predicate, out INamedTypeSymbol targetType)
{
if (typeSymbol is INamedTypeSymbol namedTypeSymbol && predicate(namedTypeSymbol))
{
targetType = namedTypeSymbol;
return true;
}
var baseType = typeSymbol.BaseType;
while (baseType is not null)
{
// End of inheritance chain
if (baseType.IsType<object>())
break;
if (predicate(baseType))
{
targetType = baseType;
return true;
}
baseType = baseType.BaseType;
}
targetType = null!;
return false;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is or implements a certain interface, as determined by the given <paramref name="predicate"/>.
/// </summary>
public static bool IsOrImplementsInterface(this ITypeSymbol typeSymbol, Func<INamedTypeSymbol, bool> predicate, out INamedTypeSymbol targetType)
{
if (typeSymbol is INamedTypeSymbol namedTypeSymbol && predicate(namedTypeSymbol))
{
targetType = namedTypeSymbol;
return true;
}
foreach (var interf in typeSymbol.AllInterfaces)
{
if (predicate(interf))
{
targetType = interf;
return true;
}
}
targetType = null!;
return false;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is a constructed generic type with a single type argument matching the <paramref name="requiredTypeArgument"/>.
/// </summary>
public static bool HasSingleGenericTypeArgument(this ITypeSymbol typeSymbol, ITypeSymbol requiredTypeArgument)
{
return typeSymbol is INamedTypeSymbol namedTypeSymbol &&
namedTypeSymbol.TypeArguments.Length == 1 &&
namedTypeSymbol.TypeArguments[0].Equals(requiredTypeArgument, SymbolEqualityComparer.Default);
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> represents an integral type, such as <see cref="Int32"/> or <see cref="UInt64"/>.
/// </summary>
/// <param name="seeThroughNullable">Whether to return true for a <see cref="Nullable{T}"/> of a matching underlying type.</param>
/// <param name="includeDecimal">Whether to consider <see cref="Decimal"/> as an integral type.</param>
public static bool IsIntegral(this ITypeSymbol typeSymbol, bool seeThroughNullable, bool includeDecimal = false)
{
if (typeSymbol.IsNullable(out var underlyingType) && seeThroughNullable)
typeSymbol = underlyingType;
var result = typeSymbol.IsType<byte>() ||
typeSymbol.IsType<sbyte>() ||
typeSymbol.IsType<ushort>() ||
typeSymbol.IsType<short>() ||
typeSymbol.IsType<uint>() ||
typeSymbol.IsType<int>() ||
typeSymbol.IsType<ulong>() ||
typeSymbol.IsType<long>() ||
(includeDecimal && typeSymbol.IsType<decimal>());
return result;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is a nested type.
/// </summary>
public static bool IsNested(this ITypeSymbol typeSymbol)
{
var result = typeSymbol.ContainingType is not null;
return result;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is a generic type.
/// </summary>
public static bool IsGeneric(this ITypeSymbol typeSymbol)
{
if (typeSymbol is not INamedTypeSymbol namedTypeSymbol) return false;
var result = namedTypeSymbol.IsGenericType;
return result;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is a generic type with the given number of type parameters.
/// </summary>
public static bool IsGeneric(this ITypeSymbol typeSymbol, int typeParameterCount)
{
if (typeSymbol is not INamedTypeSymbol namedTypeSymbol) return false;
var result = namedTypeSymbol.IsGenericType && namedTypeSymbol.Arity == typeParameterCount;
return result;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is a generic type with the given number of type parameters.
/// Outputs the type arguments on true.
/// </summary>
public static bool IsGeneric(this ITypeSymbol typeSymbol, int typeParameterCount, out ImmutableArray<ITypeSymbol> typeArguments)
{
typeArguments = default;
if (typeSymbol is not INamedTypeSymbol namedTypeSymbol) return false;
if (!IsGeneric(typeSymbol, typeParameterCount)) return false;
typeArguments = namedTypeSymbol.TypeArguments;
return true;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is a <see cref="Nullable{T}"/>.
/// </summary>
public static bool IsNullable(this ITypeSymbol typeSymbol)
{
return typeSymbol.IsNullable(out _);
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is a <see cref="Nullable{T}"/>, outputting the underlying type if so.
/// </summary>
public static bool IsNullable(this ITypeSymbol typeSymbol, out ITypeSymbol underlyingType)
{
if (typeSymbol.IsValueType && typeSymbol is INamedTypeSymbol namedTypeSymbol && typeSymbol.IsType("System.Nullable", arity: 1))
{
underlyingType = namedTypeSymbol.TypeArguments[0];
return true;
}
underlyingType = null!;
return false;
}
/// <summary>
/// Returns whether the given <see cref="ITypeSymbol"/> implements <see cref="IEquatable{T}"/> against itself.
/// </summary>
public static bool IsSelfEquatable(this ITypeSymbol typeSymbol)
{
return typeSymbol.IsOrImplementsInterface(interf => interf.IsType("IEquatable", "System", arity: 1) && interf.HasSingleGenericTypeArgument(typeSymbol), out _);
}
/// <summary>
/// <para>
/// Returns whether the <see cref="ITypeSymbol"/> implements any <see cref="IComparable"/> or <see cref="IComparable{T}"/> interface.
/// </para>
/// <para>
/// This method can optionally see through <see cref="Nullable{T}"/> (which does not implement the necessary interface) to the underlying type.
/// Beware that nullables <em>cannot</em> simply be compared with left.CompareTo(right).
/// </para>
/// </summary>
/// <param name="seeThroughNullable">Whether to return true for a <see cref="Nullable{T}"/> of a matching underlying type.</param>
public static bool IsComparable(this ITypeSymbol typeSymbol, bool seeThroughNullable)
{
if (seeThroughNullable && typeSymbol.IsNullable(out var underlyingType))
typeSymbol = underlyingType;
var result = typeSymbol.AllInterfaces.Any(interf => interf.IsType("System.IComparable"));
return result;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is or implements <see cref="System.Collections.IEnumerable"/>.
/// If so, this method outputs the element type of the most <em>concrete</em> <see cref="IEnumerable{T}"/> type it implements, if any.
/// </summary>
public static bool IsEnumerable(this ITypeSymbol typeSymbol, out INamedTypeSymbol? elementType)
{
elementType = null;
if (!typeSymbol.IsOrImplementsInterface(type => type.IsType("IEnumerable", "System.Collections", arity: 0), out var nonGenericEnumerableInterface))
return false;
if (typeSymbol.Kind == SymbolKind.ArrayType)
{
elementType = ((IArrayTypeSymbol)typeSymbol).ElementType as INamedTypeSymbol; // Does not work for nested arrays
return elementType is not null;
}
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("IList", "System.Collections.Generic", arity: 1), out var interf))
{
elementType = interf.TypeArguments[0] as INamedTypeSymbol;
return true;
}
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("IReadOnlyList", "System.Collections.Generic", arity: 1), out interf))
{
elementType = interf.TypeArguments[0] as INamedTypeSymbol;
return true;
}
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("ISet", "System.Collections.Generic", arity: 1), out interf))
{
elementType = interf.TypeArguments[0] as INamedTypeSymbol;
return true;
}
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("IReadOnlySet", "System.Collections.Generic", arity: 1), out interf))
{
elementType = interf.TypeArguments[0] as INamedTypeSymbol;
return true;
}
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("ICollection", "System.Collections.Generic", arity: 1), out interf))
{
elementType = interf.TypeArguments[0] as INamedTypeSymbol;
return true;
}
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("IReadOnlyCollection", "System.Collections.Generic", arity: 1), out interf))
{
elementType = interf.TypeArguments[0] as INamedTypeSymbol;
return true;
}
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("IEnumerable", "System.Collections.Generic", arity: 1), out interf))
{
elementType = interf.TypeArguments[0] as INamedTypeSymbol;
return true;
}
return true;
}
/// <summary>
/// Extracts the array's element type, digging through any nested arrays if necessary.
/// </summary>
public static ITypeSymbol ExtractNonArrayElementType(this IArrayTypeSymbol arrayTypeSymbol)
{
var elementType = arrayTypeSymbol.ElementType;
return elementType is IArrayTypeSymbol arrayElementType
? ExtractNonArrayElementType(arrayElementType)
: elementType;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> or a base type has an override of <see cref="Object.Equals(Object)"/> more specific than <see cref="Object"/>'s implementation.
/// </summary>
public static bool HasEqualsOverride(this ITypeSymbol typeSymbol)
{
// Technically this could match an overridden "new" Equals defined by a base type, but that is a nonsense scenario
var result = typeSymbol.GetMembers(nameof(Object.Equals)).OfType<IMethodSymbol>().Any(method => method.IsOverride && !method.IsStatic &&
method.Arity == 0 && method.Parameters.Length == 1 && method.Parameters[0].Type.IsType<object>());
return result;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is annotated with the specified attribute.
/// </summary>
public static AttributeData? GetAttribute<TAttribute>(this ITypeSymbol typeSymbol)
{
var result = typeSymbol.GetAttribute(attribute => attribute.IsType<TAttribute>());
return result;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is annotated with the specified attribute.
/// </summary>
public static AttributeData? GetAttribute(this ITypeSymbol typeSymbol, string typeName, string containingNamespace, int? arity = null)
{
var result = typeSymbol.GetAttribute(attribute => (arity is null || attribute.Arity == arity) && attribute.IsType(typeName, containingNamespace));
return result;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> is annotated with the specified attribute.
/// </summary>
public static AttributeData? GetAttribute(this ITypeSymbol typeSymbol, Func<INamedTypeSymbol, bool> predicate)
{
var result = typeSymbol.GetAttributes().FirstOrDefault(attribute => attribute.AttributeClass is not null && predicate(attribute.AttributeClass));
return result;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> defines a conversion to the specified type.
/// </summary>
public static bool HasConversionTo(this ITypeSymbol typeSymbol, string typeName, string containingNamespace)
{
var result = !typeSymbol.IsType(typeName, containingNamespace) && typeSymbol.GetMembers().Any(member =>
member is IMethodSymbol method && ConversionOperatorNames.Contains(method.Name) && member.DeclaredAccessibility == Accessibility.Public &&
method.ReturnType.IsType(typeName, containingNamespace));
return result;
}
/// <summary>
/// Returns whether the <see cref="ITypeSymbol"/> defines a conversion from the specified type.
/// </summary>
public static bool HasConversionFrom(this ITypeSymbol typeSymbol, string typeName, string containingNamespace)
{
var result = !typeSymbol.IsType(typeName, containingNamespace) && typeSymbol.GetMembers().Any(member =>
member is IMethodSymbol method && ConversionOperatorNames.Contains(method.Name) && member.DeclaredAccessibility == Accessibility.Public &&
method.Parameters.Length == 1 && method.Parameters[0].Type.IsType(typeName, containingNamespace));
return result;
}
/// <summary>
/// Enumerates the primitive types (string, int, bool, etc.) from which the given <see cref="ITypeSymbol"/> is convertible.
/// </summary>
/// <param name="skipForSystemTypes">If true, if the given type is directly under the System namespace, this method yields nothing.</param>
public static IEnumerable<Type> GetAvailableConversionsFromPrimitives(this ITypeSymbol typeSymbol, bool skipForSystemTypes)
{
if (skipForSystemTypes && typeSymbol.ContainingNamespace.HasFullName("System") && (typeSymbol.ContainingNamespace.ContainingNamespace?.IsGlobalNamespace ?? true))
yield break;
if (typeSymbol.HasConversionFrom("String", "System")) yield return typeof(string);
if (typeSymbol.HasConversionFrom("Boolean", "System")) yield return typeof(bool);
if (typeSymbol.HasConversionFrom("Byte", "System")) yield return typeof(byte);
if (typeSymbol.HasConversionFrom("SByte", "System")) yield return typeof(sbyte);
if (typeSymbol.HasConversionFrom("UInt16", "System")) yield return typeof(ushort);
if (typeSymbol.HasConversionFrom("Int16", "System")) yield return typeof(short);
if (typeSymbol.HasConversionFrom("UInt32", "System")) yield return typeof(uint);
if (typeSymbol.HasConversionFrom("Int32", "System")) yield return typeof(int);
if (typeSymbol.HasConversionFrom("UInt64", "System")) yield return typeof(ulong);
if (typeSymbol.HasConversionFrom("Int64", "System")) yield return typeof(long);
}
/// <summary>
/// Returns the code for a string expression of the given <paramref name="memberName"/> of "this".
/// </summary>
/// <param name="memberName">The member name. For example, "Value" leads to a string of "this.Value".</param>
/// <param name="stringVariant">The expression to use for strings. Any {0} is replaced by the member name.</param>
public static string CreateStringExpression(this ITypeSymbol typeSymbol, string memberName, string stringVariant = "this.{0}")
{
if (typeSymbol.IsValueType && !typeSymbol.IsNullable()) return $"this.{memberName}.ToString()";
if (typeSymbol.IsType<string>()) return String.Format(stringVariant, memberName);
return $"this.{memberName}?.ToString()"; // Null-safety can be especially relevant for instances created with RuntimeHelpers.GetUninitializedObject()
}
/// <summary>
/// Returns whether the sensible code for <see cref="Object.ToString"/> might return null for the given type, according to its annotations or lack thereof.
/// </summary>
public static bool IsToStringNullable(this ITypeSymbol typeSymbol)
{
if (typeSymbol.IsNullable()) return true;
var nullableAnnotation = typeSymbol.IsType<string>()
? typeSymbol.NullableAnnotation
: typeSymbol.GetMembers(nameof(Object.ToString)).OfType<IMethodSymbol>().SingleOrDefault(method => !method.IsGenericMethod && method.Parameters.Length == 0)?.ReturnType.NullableAnnotation
?? NullableAnnotation.None; // Could inspect base members, but that is going a bit far
return nullableAnnotation != NullableAnnotation.NotAnnotated;
}
/// <summary>
/// Returns the code for a hash code expression of the given <paramref name="memberName"/> of "this".
/// </summary>
/// <param name="memberName">The member name. For example, "Value" leads to a hash code of "this.Value".</param>
/// <param name="stringVariant">The expression to use for strings. Any {0} is replaced by the member name.</param>
public static string CreateHashCodeExpression(this ITypeSymbol typeSymbol, string memberName, string stringVariant = "(this.{0} is null ? 0 : String.GetHashCode(this.{0}))")
{
// DO NOT REORDER
if (typeSymbol.IsType<string>()) return String.Format(stringVariant, memberName);
if (typeSymbol.IsType("Memory", "System", arity: 1)) return $"{ComparisonsNamespace}.EnumerableComparer.GetMemoryHashCode(this.{memberName})";
if (typeSymbol.IsType("ReadOnlyMemory", "System", arity: 1)) return $"{ComparisonsNamespace}.EnumerableComparer.GetMemoryHashCode(this.{memberName})";
if (typeSymbol.IsNullable(out var underlyingType) && underlyingType.IsType("Memory", "System", arity: 1)) return $"{ComparisonsNamespace}.EnumerableComparer.GetMemoryHashCode(this.{memberName})";
if (typeSymbol.IsNullable(out underlyingType) && underlyingType.IsType("ReadOnlyMemory", "System", arity: 1)) return $"{ComparisonsNamespace}.EnumerableComparer.GetMemoryHashCode(this.{memberName})";
// Special-case certain specific collections, provided that they have no custom equality
if (!typeSymbol.HasEqualsOverride())
{
if (typeSymbol.IsType("Dictionary", "System.Collections.Generic", arity: 2)) return $"{ComparisonsNamespace}.DictionaryComparer.GetDictionaryHashCode(this.{memberName})";
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("IDictionary", "System.Collections.Generic", arity: 2), out var interf)) return $"{ComparisonsNamespace}.DictionaryComparer.GetDictionaryHashCode(({interf})this.{memberName})"; // Disambiguate
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("IReadOnlyDictionary", "System.Collections.Generic", arity: 2), out _)) return $"{ComparisonsNamespace}.DictionaryComparer.GetDictionaryHashCode(this.{memberName})";
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("ILookup", "System.Linq", arity: 2), out _)) return $"{ComparisonsNamespace}.LookupComparer.GetLookupHashCode(this.{memberName})";
}
// Special-case collections, provided that they either (A) have no custom equality or (B) implement IStructuralEquatable (where the latter tend to override regular Equals() with explicit reference equality)
if (typeSymbol.IsEnumerable(out var elementType) &&
(!typeSymbol.HasEqualsOverride() || typeSymbol.IsOrImplementsInterface(type => type.IsType("IStructuralEquatable", "System.Collections", arity: 0), out _)))
{
if (elementType is not null) return $"{ComparisonsNamespace}.EnumerableComparer.GetEnumerableHashCode<{elementType}>(this.{memberName})";
else return $"{ComparisonsNamespace}.EnumerableComparer.GetEnumerableHashCode(this.{memberName})";
}
// Special-case collections wrapped in nullable, provided that they either (A) have no custom equality or (B) implement IStructuralEquatable (where the latter tend to override regular Equals() with explicit reference equality)
if (typeSymbol.IsNullable(out underlyingType) && underlyingType.IsEnumerable(out elementType) &&
(!underlyingType.HasEqualsOverride() || underlyingType.IsOrImplementsInterface(type => type.IsType("IStructuralEquatable", "System.Collections", arity: 0), out _)))
{
if (elementType is not null) return $"{ComparisonsNamespace}.EnumerableComparer.GetEnumerableHashCode<{elementType}>(this.{memberName})";
else return $"{ComparisonsNamespace}.EnumerableComparer.GetEnumerableHashCode(this.{memberName})";
}
if (typeSymbol.IsValueType && !typeSymbol.IsNullable()) return $"this.{memberName}.GetHashCode()";
return $"(this.{memberName}?.GetHashCode() ?? 0)";
}
/// <summary>
/// Returns the code for an equality expression on the given <paramref name="memberName"/> between "this" and "other".
/// </summary>
/// <param name="memberName">The member name. For example, "Value" leads to an equality check between "this.Value" and "other.Value".</param>
/// <param name="stringVariant">The expression to use for strings. Any {0} is replaced by the member name.</param>
public static string CreateEqualityExpression(this ITypeSymbol typeSymbol, string memberName, string stringVariant = "String.Equals(this.{0}, other.{0})")
{
// DO NOT REORDER
// Not yet source-generated
if (typeSymbol.TypeKind == TypeKind.Error) return $"Equals(this.{memberName}, other.{memberName})";
if (typeSymbol.IsType<string>()) return String.Format(stringVariant, memberName);
if (typeSymbol.IsType("Memory", "System", arity: 1)) return $"MemoryExtensions.SequenceEqual(this.{memberName}.Span, other.{memberName}.Span)";
if (typeSymbol.IsType("ReadOnlyMemory", "System", arity: 1)) return $"MemoryExtensions.SequenceEqual(this.{memberName}.Span, other.{memberName}.Span)";
if (typeSymbol.IsNullable(out var underlyingType) && underlyingType.IsType("Memory", "System", arity: 1)) return $"(this.{memberName} is null || other.{memberName} is null ? this.{memberName} is null & other.{memberName} is null : MemoryExtensions.SequenceEqual(this.{memberName}.Value.Span, other.{memberName}.Value.Span))";
if (typeSymbol.IsNullable(out underlyingType) && underlyingType.IsType("ReadOnlyMemory", "System", arity: 1)) return $"(this.{memberName} is null || other.{memberName} is null ? this.{memberName} is null & other.{memberName} is null : MemoryExtensions.SequenceEqual(this.{memberName}.Value.Span, other.{memberName}.Value.Span))";
// Special-case certain specific collections, provided that they have no custom equality
if (!typeSymbol.HasEqualsOverride())
{
if (typeSymbol.IsType("Dictionary", "System.Collections.Generic", arity: 2))
return $"{ComparisonsNamespace}.DictionaryComparer.DictionaryEquals(this.{memberName}, other.{memberName})";
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("IDictionary", "System.Collections.Generic", arity: 2), out var interf))
return $"{ComparisonsNamespace}.DictionaryComparer.DictionaryEquals(this.{memberName}, other.{memberName})";
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("IReadOnlyDictionary", "System.Collections.Generic", arity: 2), out interf))
return $"{ComparisonsNamespace}.DictionaryComparer.DictionaryEquals(this.{memberName}, other.{memberName})";
if (typeSymbol.IsOrImplementsInterface(type => type.IsType("ILookup", "System.Linq", arity: 2), out interf))
return $"{ComparisonsNamespace}.LookupComparer.LookupEquals(this.{memberName}, other.{memberName})";
}
// Special-case collections, provided that they either (A) have no custom equality or (B) implement IStructuralEquatable (where the latter tend to override regular Equals() with explicit reference equality)
if (typeSymbol.IsEnumerable(out var elementType) &&
(!typeSymbol.HasEqualsOverride() || typeSymbol.IsOrImplementsInterface(type => type.IsType("IStructuralEquatable", "System.Collections", arity: 0), out _)))
{
if (elementType is not null) return $"{ComparisonsNamespace}.EnumerableComparer.EnumerableEquals<{elementType}>(this.{memberName}, other.{memberName})";
else return $"{ComparisonsNamespace}.EnumerableComparer.EnumerableEquals(this.{memberName}, other.{memberName})";
}
// Special-case collections wrapped in nullable, provided that they either (A) have no custom equality or (B) implement IStructuralEquatable (where the latter tend to override regular Equals() with explicit reference equality)
if (typeSymbol.IsNullable(out underlyingType) && underlyingType.IsEnumerable(out elementType) &&
(!underlyingType.HasEqualsOverride() || underlyingType.IsOrImplementsInterface(type => type.IsType("IStructuralEquatable", "System.Collections", arity: 0), out _)))
{
if (elementType is not null) return $"{ComparisonsNamespace}.EnumerableComparer.EnumerableEquals<{elementType}>(this.{memberName}, other.{memberName})";
else return $"{ComparisonsNamespace}.EnumerableComparer.EnumerableEquals(this.{memberName}, other.{memberName})";
}
if (typeSymbol.IsNullable()) return $"(this.{memberName} is null || other.{memberName} is null ? this.{memberName} is null & other.{memberName} is null : this.{memberName}.Value.Equals(other.{memberName}.Value))";
if (typeSymbol.IsValueType) return $"this.{memberName}.Equals(other.{memberName})";
return $"(this.{memberName}?.Equals(other.{memberName}) ?? other.{memberName} is null)";
}
/// <summary>
/// Returns the code for a comparison expression on the given <paramref name="memberName"/> between "this" and "other".
/// </summary>
/// <param name="memberName">The member name. For example, "Value" leads to a comparison between "this.Value" and "other.Value".</param>
/// <param name="stringVariant">The expression to use for strings. Any {0} is replaced by the member name.</param>
public static string CreateComparisonExpression(this ITypeSymbol typeSymbol, string memberName, string stringVariant = "String.Compare(this.{0}, other.{0}, StringComparison.Ordinal)")
{
// DO NOT REORDER
// Not yet source-generated
if (typeSymbol.TypeKind == TypeKind.Error) return $"Compare(this.{memberName}, other.{memberName})";
// Collections have not been implemented, as we do not generate CompareTo() if any data member is not IComparable (as is the case for collections)
if (typeSymbol.IsType<string>()) return String.Format(stringVariant, memberName);
if (typeSymbol.IsNullable()) return $"(this.{memberName} is null || other.{memberName} is null ? -(this.{memberName} is null).CompareTo(other.{memberName} is null) : this.{memberName}.Value.CompareTo(other.{memberName}.Value))";
if (typeSymbol.IsValueType) return $"this.{memberName}.CompareTo(other.{memberName})";
return $"(this.{memberName} is null || other.{memberName} is null ? -(this.{memberName} is null).CompareTo(other.{memberName} is null) : this.{memberName}.CompareTo(other.{memberName}))";
}
/// <summary>
/// Returns the code for an expression that instantiates a dummy instance of the specified type.
/// </summary>
/// <param name="symbolName">The name of the member/parameter/... to instantiate an instance for. May be used as the dummy string value if applicable.</param>
public static string CreateDummyInstantiationExpression(this ITypeSymbol typeSymbol, string symbolName)
{
return typeSymbol.CreateDummyInstantiationExpression(symbolName, [], _ => null!);
}
/// <summary>
/// Returns the code for an expression that instantiates a dummy instance of the specified type.
/// </summary>
/// <param name="symbolName">The name of the member/parameter/... to instantiate an instance for. May be used as the dummy string value if applicable.</param>
/// <param name="customizedTypes">Encountered types that match one of these are instead instantiated by the expression resulting from <paramref name="createCustomTypeExpression"/>.</param>
/// <param name="createCustomTypeExpression">Returns an instantiation expression for a given <see cref="ITypeSymbol"/> that is present in <paramref name="customizedTypes"/>.</param>
public static string CreateDummyInstantiationExpression(this ITypeSymbol typeSymbol, string symbolName,
IEnumerable<ITypeSymbol> customizedTypes, Func<ITypeSymbol, string> createCustomTypeExpression)
{
return CreateDummyInstantiationExpression(typeSymbol, symbolName, customizedTypes, createCustomTypeExpression,
seenTypeSymbols: new HashSet<ITypeSymbol>(SymbolEqualityComparer.Default));
}
private static string CreateDummyInstantiationExpression(this ITypeSymbol typeSymbol, string symbolName,
IEnumerable<ITypeSymbol> customizedTypes, Func<ITypeSymbol, string> createCustomTypeExpression,
HashSet<ITypeSymbol> seenTypeSymbols)
{
if (typeSymbol.IsNullable(out var nullabeUnderlyingType))
typeSymbol = nullabeUnderlyingType;
// Avoid stack overflow due to recursion
if (!seenTypeSymbols.Add(typeSymbol)) return typeSymbol.IsReferenceType ? "null" : $"default({typeSymbol})";
try
{
customizedTypes = customizedTypes as IReadOnlyCollection<ITypeSymbol> ?? customizedTypes.ToList();
if (customizedTypes.Any(type => type.Equals(typeSymbol, SymbolEqualityComparer.Default))) return createCustomTypeExpression(typeSymbol);
// Special-case wrapper value objects to use the param name rather than the type name (e.g. "FirstName" and "LastName" instead of "ProperName" and "ProperName")
// As a bonus, this also handles constructors generated by this very package (which are not visible to us)
if ((typeSymbol.GetAttribute("WrapperValueObjectAttribute", Constants.DomainModelingNamespace, arity: 1) ??
typeSymbol.GetAttribute("IdentityValueObjectAttribute", Constants.DomainModelingNamespace, arity: 1))
is AttributeData wrapperAttribute)
{
return $"new {typeSymbol.WithNullableAnnotation(NullableAnnotation.None)}({wrapperAttribute.AttributeClass!.TypeArguments[0].CreateDummyInstantiationExpression(symbolName, customizedTypes, createCustomTypeExpression, seenTypeSymbols)})";
}
if (typeSymbol.IsType<string>()) return $@"""{symbolName.ToTitleCase()}""";
if (typeSymbol.IsType<decimal>() || (typeSymbol.IsNullable(out var underlyingType) && underlyingType.IsType<decimal>())) return $"1m";
if (typeSymbol.IsType<DateTime>() || (typeSymbol.IsNullable(out underlyingType) && underlyingType.IsType<DateTime>())) return $"new DateTime(2000, 01, 01, 00, 00, 00, DateTimeKind.Utc)";
if (typeSymbol.IsType<DateTimeOffset>() || (typeSymbol.IsNullable(out underlyingType) && underlyingType.IsType<DateTimeOffset>())) return $"new DateTime(2000, 01, 01, 00, 00, 00, DateTimeKind.Utc)";
if (typeSymbol.IsType("DateOnly", "System") || (typeSymbol.IsNullable(out underlyingType) && underlyingType.IsType("DateOnly", "System"))) return $"new DateOnly(2000, 01, 01)";
if (typeSymbol.IsType("TimeOnly", "System") || (typeSymbol.IsNullable(out underlyingType) && underlyingType.IsType("TimeOnly", "System"))) return $"new TimeOnly(01, 00, 00)";
if (typeSymbol.TypeKind == TypeKind.Enum) return typeSymbol.GetMembers().OfType<IFieldSymbol>().Any() ? $"{typeSymbol}.{typeSymbol.GetMembers().OfType<IFieldSymbol>().FirstOrDefault()!.Name}" : $"default({typeSymbol})";
if (typeSymbol.TypeKind == TypeKind.Array) return $"new[] {{ {((IArrayTypeSymbol)typeSymbol).ElementType.CreateDummyInstantiationExpression($"{symbolName}Element", customizedTypes, createCustomTypeExpression, seenTypeSymbols)} }}";
if (typeSymbol.IsIntegral(seeThroughNullable: true, includeDecimal: true)) return $"({typeSymbol})1";
if (typeSymbol is not INamedTypeSymbol namedTypeSymbol) return typeSymbol.IsReferenceType ? "null" : $"default({typeSymbol})";
var suitableCtor = namedTypeSymbol.Constructors
.Where(ctor => ctor.Parameters.Length > 0)
.OrderByDescending(ctor => ctor.DeclaredAccessibility) // Most accessible first
.ThenBy(ctor => ctor.Parameters.Length) // Shortest first (the most basic non-default option)
.FirstOrDefault();
if (suitableCtor is null) return typeSymbol.IsReferenceType ? "null" : $"default({typeSymbol})";
// TODO Enhancement: We could use an object initializer if there are accessible setters
// For objects taking a parameter named "value", instead prefer the name of the outer constructor's parameter
var parameters = String.Join(", ", suitableCtor.Parameters.Select(param => param.Type.CreateDummyInstantiationExpression(param.Name == "value" ? symbolName : param.Name, customizedTypes, createCustomTypeExpression, seenTypeSymbols)));
return $"new {typeSymbol.WithNullableAnnotation(NullableAnnotation.None)}({parameters})";
}
finally
{
seenTypeSymbols.Remove(typeSymbol);
}
}
}