-
Notifications
You must be signed in to change notification settings - Fork 4k
/
TypeSymbol.cs
2257 lines (1963 loc) · 114 KB
/
TypeSymbol.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
#pragma warning disable CS0660
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A TypeSymbol is a base class for all the symbols that represent a type
/// in C#.
/// </summary>
internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbolInternal
{
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Changes to the public interface of this class should remain synchronized with the VB version.
// Do not make any changes to the public interface without making the corresponding change
// to the VB version.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages.
internal const string ImplicitTypeName = "<invalid-global-code>";
// InterfaceInfo for a common case of a type not implementing anything directly or indirectly.
private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo();
private ImmutableHashSet<Symbol> _lazyAbstractMembers;
private InterfaceInfo _lazyInterfaceInfo;
private class InterfaceInfo
{
// all directly implemented interfaces, their bases and all interfaces to the bases of the type recursively
internal ImmutableArray<NamedTypeSymbol> allInterfaces;
/// <summary>
/// <see cref="TypeSymbol.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics"/>
/// </summary>
internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBaseInterfaces;
internal static readonly MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> EmptyInterfacesAndTheirBaseInterfaces =
new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(0, SymbolEqualityComparer.CLRSignature);
// Key is implemented member (method, property, or event), value is implementing member (from the
// perspective of this type). Don't allocate until someone needs it.
private ConcurrentDictionary<Symbol, SymbolAndDiagnostics> _implementationForInterfaceMemberMap;
public ConcurrentDictionary<Symbol, SymbolAndDiagnostics> ImplementationForInterfaceMemberMap
{
get
{
var map = _implementationForInterfaceMemberMap;
if (map != null)
{
return map;
}
// PERF: Avoid over-allocation. In many cases, there's only 1 entry and we don't expect concurrent updates.
map = new ConcurrentDictionary<Symbol, SymbolAndDiagnostics>(concurrencyLevel: 1, capacity: 1, comparer: SymbolEqualityComparer.ConsiderEverything);
return Interlocked.CompareExchange(ref _implementationForInterfaceMemberMap, map, null) ?? map;
}
}
/// <summary>
/// key = interface method/property/event compared using <see cref="ExplicitInterfaceImplementationTargetMemberEqualityComparer"/>,
/// value = explicitly implementing methods/properties/events declared on this type (normally a single value, multiple in case of
/// an error).
/// </summary>
internal MultiDictionary<Symbol, Symbol> explicitInterfaceImplementationMap;
internal bool IsDefaultValue()
{
return allInterfaces.IsDefault &&
interfacesAndTheirBaseInterfaces == null &&
_implementationForInterfaceMemberMap == null &&
explicitInterfaceImplementationMap == null;
}
}
private InterfaceInfo GetInterfaceInfo()
{
var info = _lazyInterfaceInfo;
if (info != null)
{
Debug.Assert(info != s_noInterfaces || info.IsDefaultValue(), "default value was modified");
return info;
}
for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics)
{
var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics();
if (!interfaces.IsEmpty)
{
// it looks like we or one of our bases implements something.
info = new InterfaceInfo();
// NOTE: we are assigning lazyInterfaceInfo via interlocked not for correctness,
// we just do not want to override an existing info that could be partially filled.
return Interlocked.CompareExchange(ref _lazyInterfaceInfo, info, null) ?? info;
}
}
// if we have got here it means neither we nor our bases implement anything
_lazyInterfaceInfo = info = s_noInterfaces;
return info;
}
/// <summary>
/// The original definition of this symbol. If this symbol is constructed from another
/// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in
/// source or metadata.
/// </summary>
public new TypeSymbol OriginalDefinition
{
get
{
return OriginalTypeSymbolDefinition;
}
}
protected virtual TypeSymbol OriginalTypeSymbolDefinition
{
get
{
return this;
}
}
protected sealed override Symbol OriginalSymbolDefinition
{
get
{
return this.OriginalTypeSymbolDefinition;
}
}
/// <summary>
/// Gets the BaseType of this type. If the base type could not be determined, then
/// an instance of ErrorType is returned. If this kind of type does not have a base type
/// (for example, interfaces), null is returned. Also the special class System.Object
/// always has a BaseType of null.
/// </summary>
internal abstract NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; }
internal NamedTypeSymbol BaseTypeWithDefinitionUseSiteDiagnostics(ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
var result = BaseTypeNoUseSiteDiagnostics;
if ((object)result != null)
{
result.OriginalDefinition.AddUseSiteDiagnostics(ref useSiteDiagnostics);
}
return result;
}
internal NamedTypeSymbol BaseTypeOriginalDefinition(ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
var result = BaseTypeNoUseSiteDiagnostics;
if ((object)result != null)
{
result = result.OriginalDefinition;
result.AddUseSiteDiagnostics(ref useSiteDiagnostics);
}
return result;
}
/// <summary>
/// Gets the set of interfaces that this type directly implements. This set does not include
/// interfaces that are base interfaces of directly implemented interfaces.
/// </summary>
internal abstract ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null);
/// <summary>
/// The list of all interfaces of which this type is a declared subtype, excluding this type
/// itself. This includes all declared base interfaces, all declared base interfaces of base
/// types, and all declared base interfaces of those results (recursively). Each result
/// appears exactly once in the list. This list is topologically sorted by the inheritance
/// relationship: if interface type A extends interface type B, then A precedes B in the
/// list. This is not quite the same as "all interfaces of which this type is a proper
/// subtype" because it does not take into account variance: AllInterfaces for
/// IEnumerable<string> will not include IEnumerable<object>
/// </summary>
internal ImmutableArray<NamedTypeSymbol> AllInterfacesNoUseSiteDiagnostics
{
get
{
return GetAllInterfaces();
}
}
internal ImmutableArray<NamedTypeSymbol> AllInterfacesWithDefinitionUseSiteDiagnostics(ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
var result = AllInterfacesNoUseSiteDiagnostics;
// Since bases affect content of AllInterfaces set, we need to make sure they all are good.
var current = this;
do
{
current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
}
while ((object)current != null);
foreach (var iface in result)
{
iface.OriginalDefinition.AddUseSiteDiagnostics(ref useSiteDiagnostics);
}
return result;
}
/// <summary>
/// If this is a type parameter returns its effective base class, otherwise returns this type.
/// </summary>
internal TypeSymbol EffectiveTypeNoUseSiteDiagnostics
{
get
{
return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClassNoUseSiteDiagnostics : this;
}
}
internal TypeSymbol EffectiveType(ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClass(ref useSiteDiagnostics) : this;
}
/// <summary>
/// Returns true if this type derives from a given type.
/// </summary>
internal bool IsDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
Debug.Assert((object)type != null);
Debug.Assert(!type.IsTypeParameter());
if ((object)this == (object)type)
{
return false;
}
var t = this.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
while ((object)t != null)
{
if (type.Equals(t, comparison))
{
return true;
}
t = t.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics);
}
return false;
}
/// <summary>
/// Returns true if this type is equal or derives from a given type.
/// </summary>
internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
return this.Equals(type, comparison) || this.IsDerivedFrom(type, comparison, ref useSiteDiagnostics);
}
/// <summary>
/// Determines if this type symbol represent the same type as another, according to the language
/// semantics.
/// </summary>
/// <param name="t2">The other type.</param>
/// <param name="compareKind">
/// What kind of comparison to use?
/// You can ignore custom modifiers, ignore the distinction between object and dynamic, or ignore tuple element names differences.
/// </param>
/// <returns>True if the types are equivalent.</returns>
internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind)
{
return ReferenceEquals(this, t2);
}
public sealed override bool Equals(Symbol other, TypeCompareKind compareKind)
{
var t2 = other as TypeSymbol;
if (t2 is null)
{
return false;
}
return this.Equals(t2, compareKind);
}
/// <summary>
/// We ignore custom modifiers, and the distinction between dynamic and object, when computing a type's hash code.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
protected virtual ImmutableArray<NamedTypeSymbol> GetAllInterfaces()
{
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
if (info.allInterfaces.IsDefault)
{
ImmutableInterlocked.InterlockedInitialize(ref info.allInterfaces, MakeAllInterfaces());
}
return info.allInterfaces;
}
/// Produce all implemented interfaces in topologically sorted order. We use
/// TypeSymbol.Interfaces as the source of edge data, which has had cycles and infinitely
/// long dependency cycles removed. Consequently, it is possible (and we do) use the
/// simplest version of Tarjan's topological sorting algorithm.
protected virtual ImmutableArray<NamedTypeSymbol> MakeAllInterfaces()
{
var result = ArrayBuilder<NamedTypeSymbol>.GetInstance();
var visited = new HashSet<NamedTypeSymbol>(SymbolEqualityComparer.ConsiderEverything);
for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics)
{
var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics();
for (int i = interfaces.Length - 1; i >= 0; i--)
{
addAllInterfaces(interfaces[i], visited, result);
}
}
result.ReverseContents();
return result.ToImmutableAndFree();
static void addAllInterfaces(NamedTypeSymbol @interface, HashSet<NamedTypeSymbol> visited, ArrayBuilder<NamedTypeSymbol> result)
{
if (visited.Add(@interface))
{
ImmutableArray<NamedTypeSymbol> baseInterfaces = @interface.InterfacesNoUseSiteDiagnostics();
for (int i = baseInterfaces.Length - 1; i >= 0; i--)
{
var baseInterface = baseInterfaces[i];
addAllInterfaces(baseInterface, visited, result);
}
result.Add(@interface);
}
}
}
/// <summary>
/// Gets the set of interfaces that this type directly implements, plus the base interfaces
/// of all such types. Keys are compared using <see cref="SymbolEqualityComparer.CLRSignature"/>,
/// values are distinct interfaces corresponding to the key, according to <see cref="TypeCompareKind.ConsiderEverything"/> rules.
/// </summary>
/// <remarks>
/// CONSIDER: it probably isn't truly necessary to cache this. If space gets tight, consider
/// alternative approaches (recompute every time, cache on the side, only store on some types,
/// etc).
/// </remarks>
internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics
{
get
{
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
Debug.Assert(InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces.IsEmpty);
return InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces;
}
if (info.interfacesAndTheirBaseInterfaces == null)
{
Interlocked.CompareExchange(ref info.interfacesAndTheirBaseInterfaces, MakeInterfacesAndTheirBaseInterfaces(this.InterfacesNoUseSiteDiagnostics()), null);
}
return info.interfacesAndTheirBaseInterfaces;
}
}
internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
var result = InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics;
foreach (var iface in result.Keys)
{
iface.OriginalDefinition.AddUseSiteDiagnostics(ref useSiteDiagnostics);
}
return result;
}
// Note: Unlike MakeAllInterfaces, this doesn't need to be virtual. It depends on
// AllInterfaces for its implementation, so it will pick up all changes to MakeAllInterfaces
// indirectly.
private static MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> MakeInterfacesAndTheirBaseInterfaces(ImmutableArray<NamedTypeSymbol> declaredInterfaces)
{
var resultBuilder = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(declaredInterfaces.Length, SymbolEqualityComparer.CLRSignature, SymbolEqualityComparer.ConsiderEverything);
foreach (var @interface in declaredInterfaces)
{
if (resultBuilder.Add(@interface, @interface))
{
foreach (var baseInterface in @interface.AllInterfacesNoUseSiteDiagnostics)
{
resultBuilder.Add(baseInterface, baseInterface);
}
}
}
return resultBuilder;
}
/// <summary>
/// Returns the corresponding symbol in this type or a base type that implements
/// interfaceMember (either implicitly or explicitly), or null if no such symbol exists
/// (which might be either because this type doesn't implement the container of
/// interfaceMember, or this type doesn't supply a member that successfully implements
/// interfaceMember).
/// </summary>
/// <param name="interfaceMember">
/// Must be a non-null interface property, method, or event.
/// </param>
public Symbol FindImplementationForInterfaceMember(Symbol interfaceMember)
{
if ((object)interfaceMember == null)
{
throw new ArgumentNullException(nameof(interfaceMember));
}
if (!interfaceMember.IsImplementableInterfaceMember())
{
return null;
}
if (this.IsInterfaceType())
{
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
return FindMostSpecificImplementation(interfaceMember, (NamedTypeSymbol)this, ref useSiteDiagnostics);
}
return FindImplementationForInterfaceMemberInNonInterface(interfaceMember);
}
/// <summary>
/// Returns true if this type is known to be a reference type. It is never the case that
/// IsReferenceType and IsValueType both return true. However, for an unconstrained type
/// parameter, IsReferenceType and IsValueType will both return false.
/// </summary>
public abstract bool IsReferenceType { get; }
/// <summary>
/// Returns true if this type is known to be a value type. It is never the case that
/// IsReferenceType and IsValueType both return true. However, for an unconstrained type
/// parameter, IsReferenceType and IsValueType will both return false.
/// </summary>
public abstract bool IsValueType { get; }
// Only the compiler can create TypeSymbols.
internal TypeSymbol()
{
}
/// <summary>
/// Gets the kind of this type.
/// </summary>
public abstract TypeKind TypeKind { get; }
/// <summary>
/// Gets corresponding special TypeId of this type.
/// </summary>
/// <remarks>
/// Not preserved in types constructed from this one.
/// </remarks>
public virtual SpecialType SpecialType
{
get
{
return SpecialType.None;
}
}
/// <summary>
/// Gets corresponding primitive type code for this type declaration.
/// </summary>
internal Microsoft.Cci.PrimitiveTypeCode PrimitiveTypeCode
=> TypeKind switch
{
TypeKind.Pointer => Microsoft.Cci.PrimitiveTypeCode.Pointer,
TypeKind.FunctionPointer => Microsoft.Cci.PrimitiveTypeCode.FunctionPointer,
_ => SpecialTypes.GetTypeCode(SpecialType)
};
#region Use-Site Diagnostics
/// <summary>
/// Return error code that has highest priority while calculating use site error for this symbol.
/// </summary>
protected override int HighestPriorityUseSiteError
{
get
{
return (int)ErrorCode.ERR_BogusType;
}
}
public sealed override bool HasUnsupportedMetadata
{
get
{
DiagnosticInfo info = GetUseSiteDiagnostic();
return (object)info != null && info.Code == (int)ErrorCode.ERR_BogusType;
}
}
internal abstract bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes);
#endregion
/// <summary>
/// Is this a symbol for an anonymous type (including delegate).
/// </summary>
public virtual bool IsAnonymousType
{
get
{
return false;
}
}
/// <summary>
/// Is this a symbol for a Tuple.
/// </summary>
public virtual bool IsTupleType => false;
/// <summary>
/// True if the type represents a native integer. In C#, the types represented
/// by language keywords 'nint' and 'nuint'.
/// </summary>
internal virtual bool IsNativeIntegerType => false;
/// <summary>
/// Verify if the given type is a tuple of a given cardinality, or can be used to back a tuple type
/// with the given cardinality.
/// </summary>
public bool IsTupleTypeOfCardinality(int targetCardinality)
{
if (IsTupleType)
{
return TupleElementTypesWithAnnotations.Length == targetCardinality;
}
return false;
}
/// <summary>
/// If this symbol represents a tuple type, get the types of the tuple's elements.
/// </summary>
public virtual ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => default(ImmutableArray<TypeWithAnnotations>);
/// <summary>
/// If this symbol represents a tuple type, get the names of the tuple's elements.
/// </summary>
public virtual ImmutableArray<string> TupleElementNames => default(ImmutableArray<string>);
/// <summary>
/// If this symbol represents a tuple type, get the fields for the tuple's elements.
/// Otherwise, returns default.
/// </summary>
public virtual ImmutableArray<FieldSymbol> TupleElements => default(ImmutableArray<FieldSymbol>);
#nullable enable
/// <summary>
/// Is this type a managed type (false for everything but enum, pointer, and
/// some struct types).
/// </summary>
/// <remarks>
/// See Type::computeManagedType.
/// </remarks>
internal bool IsManagedType(ref HashSet<DiagnosticInfo>? useSiteDiagnostics) => GetManagedKind(ref useSiteDiagnostics) == ManagedKind.Managed;
internal bool IsManagedTypeNoUseSiteDiagnostics
{
get
{
HashSet<DiagnosticInfo>? useSiteDiagnostics = null;
return IsManagedType(ref useSiteDiagnostics);
}
}
/// <summary>
/// Indicates whether a type is managed or not (i.e. you can take a pointer to it).
/// Contains additional cases to help implement FeatureNotAvailable diagnostics.
/// </summary>
internal abstract ManagedKind GetManagedKind(ref HashSet<DiagnosticInfo>? useSiteDiagnostics);
internal ManagedKind ManagedKindNoUseSiteDiagnostics
{
get
{
HashSet<DiagnosticInfo>? useSiteDiagnostics = null;
return GetManagedKind(ref useSiteDiagnostics);
}
}
#nullable disable
internal bool NeedsNullableAttribute()
{
return TypeWithAnnotations.NeedsNullableAttribute(typeWithAnnotationsOpt: default, typeOpt: this);
}
internal abstract void AddNullableTransforms(ArrayBuilder<byte> transforms);
internal abstract bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result);
internal abstract TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform);
internal TypeSymbol SetUnknownNullabilityForReferenceTypes()
{
return SetNullabilityForReferenceTypes(s_setUnknownNullability);
}
private static readonly Func<TypeWithAnnotations, TypeWithAnnotations> s_setUnknownNullability =
(type) => type.SetUnknownNullabilityForReferenceTypes();
/// <summary>
/// Merges features of the type with another type where there is an identity conversion between them.
/// The features to be merged are
/// object vs dynamic (dynamic wins), tuple names (dropped in case of conflict), and nullable
/// annotations (e.g. in type arguments).
/// </summary>
internal abstract TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance);
/// <summary>
/// Returns true if the type may contain embedded references
/// </summary>
public abstract bool IsRefLikeType { get; }
/// <summary>
/// Returns true if the type is a readonly struct
/// </summary>
public abstract bool IsReadOnly { get; }
public string ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToDisplayString((ITypeSymbol)ISymbol, topLevelNullability, format);
}
public ImmutableArray<SymbolDisplayPart> ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, format);
}
public string ToMinimalDisplayString(
SemanticModel semanticModel,
CodeAnalysis.NullableFlowState topLevelNullability,
int position,
SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format);
}
public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(
SemanticModel semanticModel,
CodeAnalysis.NullableFlowState topLevelNullability,
int position,
SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format);
}
#region Interface member checks
/// <summary>
/// Locate implementation of the <paramref name="interfaceMember"/> in context of the current type.
/// The method is using cache to optimize subsequent calls for the same <paramref name="interfaceMember"/>.
/// </summary>
/// <param name="interfaceMember">Member for which an implementation should be found.</param>
/// <param name="ignoreImplementationInInterfacesIfResultIsNotReady">
/// The process of looking up an implementation for an accessor can involve figuring out how corresponding event/property is implemented,
/// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. And the process of looking up an implementation for a property can
/// involve figuring out how corresponding accessors are implemented, <see cref="FindMostSpecificImplementationInInterfaces"/>. This can
/// lead to cycles, which could be avoided if we ignore the presence of implementations in interfaces for the purpose of
/// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. Fortunately, logic in it allows us to ignore the presence of
/// implementations in interfaces and we use that.
/// When the value of this parameter is true and the result that takes presence of implementations in interfaces into account is not
/// available from the cache, the lookup will be performed ignoring the presence of implementations in interfaces. Otherwise, result from
/// the cache is returned.
/// When the value of the parameter is false, the result from the cache is returned, or calculated, taking presence of implementations
/// in interfaces into account and then cached.
/// This means that:
/// - A symbol from an interface can still be returned even when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true.
/// A subsequent call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value.
/// - If symbol from a non-interface is returned when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. A subsequent
/// call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value.
/// - If no symbol is returned for <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> true. A subsequent call with
/// <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> might return a symbol, but that symbol guaranteed to be from an interface.
/// - If the first request is done with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false. A subsequent call
/// is guaranteed to return the same result regardless of <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> value.
/// </param>
protected SymbolAndDiagnostics FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false)
{
Debug.Assert((object)interfaceMember != null);
Debug.Assert(!this.IsInterfaceType());
if (this.IsInterfaceType())
{
return SymbolAndDiagnostics.Empty;
}
var interfaceType = interfaceMember.ContainingType;
if ((object)interfaceType == null || !interfaceType.IsInterface)
{
return SymbolAndDiagnostics.Empty;
}
switch (interfaceMember.Kind)
{
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Event:
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
return SymbolAndDiagnostics.Empty;
}
// PERF: Avoid delegate allocation by splitting GetOrAdd into TryGetValue+TryAdd
var map = info.ImplementationForInterfaceMemberMap;
SymbolAndDiagnostics result;
if (map.TryGetValue(interfaceMember, out result))
{
return result;
}
result = ComputeImplementationAndDiagnosticsForInterfaceMember(interfaceMember, ignoreImplementationInInterfaces: ignoreImplementationInInterfacesIfResultIsNotReady,
out bool implementationInInterfacesMightChangeResult);
Debug.Assert(ignoreImplementationInInterfacesIfResultIsNotReady || !implementationInInterfacesMightChangeResult);
Debug.Assert(!implementationInInterfacesMightChangeResult || result.Symbol is null);
if (!implementationInInterfacesMightChangeResult)
{
map.TryAdd(interfaceMember, result);
}
return result;
default:
return SymbolAndDiagnostics.Empty;
}
}
internal Symbol FindImplementationForInterfaceMemberInNonInterface(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false)
{
return FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady).Symbol;
}
private SymbolAndDiagnostics ComputeImplementationAndDiagnosticsForInterfaceMember(Symbol interfaceMember, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult)
{
var diagnostics = DiagnosticBag.GetInstance();
var implementingMember = ComputeImplementationForInterfaceMember(interfaceMember, this, diagnostics, ignoreImplementationInInterfaces, out implementationInInterfacesMightChangeResult);
var implementingMemberAndDiagnostics = new SymbolAndDiagnostics(implementingMember, diagnostics.ToReadOnlyAndFree());
return implementingMemberAndDiagnostics;
}
/// <summary>
/// Performs interface mapping (spec 13.4.4).
/// </summary>
/// <remarks>
/// CONSIDER: we could probably do less work in the metadata and retargeting cases - we won't use the diagnostics.
/// </remarks>
/// <param name="interfaceMember">A non-null implementable member on an interface type.</param>
/// <param name="implementingType">The type implementing the interface property (usually "this").</param>
/// <param name="diagnostics">Bag to which to add diagnostics.</param>
/// <param name="ignoreImplementationInInterfaces">Do not consider implementation in an interface as a valid candidate for the purpose of this computation.</param>
/// <param name="implementationInInterfacesMightChangeResult">
/// Returns true when <paramref name="ignoreImplementationInInterfaces"/> is true, the method fails to locate an implementation and an implementation in
/// an interface, if any (its presence is not checked), could potentially be a candidate. Returns false otherwise.
/// When true is returned, a different call with <paramref name="ignoreImplementationInInterfaces"/> false might return a symbol. That symbol, if any,
/// is guaranteed to be from an interface.
/// This parameter is used to optimize caching in <see cref="FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics"/>.
/// </param>
/// <returns>The implementing property or null, if there isn't one.</returns>
private static Symbol ComputeImplementationForInterfaceMember(Symbol interfaceMember, TypeSymbol implementingType, DiagnosticBag diagnostics,
bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult)
{
Debug.Assert(!implementingType.IsInterfaceType());
Debug.Assert(interfaceMember.Kind == SymbolKind.Method || interfaceMember.Kind == SymbolKind.Property || interfaceMember.Kind == SymbolKind.Event);
Debug.Assert(interfaceMember.IsImplementableInterfaceMember());
NamedTypeSymbol interfaceType = interfaceMember.ContainingType;
Debug.Assert((object)interfaceType != null && interfaceType.IsInterface);
bool seenTypeDeclaringInterface = false;
// NOTE: In other areas of the compiler, we check whether the member is from a specific compilation.
// We could do the same thing here, but that would mean that callers of the public API would have
// to pass in a Compilation object when asking about interface implementation. This extra cost eliminates
// the small benefit of getting identical answers from "imported" symbols, regardless of whether they
// are imported as source or metadata symbols.
//
// ACASEY: As of 2013/01/24, we are not aware of any cases where the source and metadata behaviors
// disagree *in code that can be emitted*. (If there are any, they are likely to involved ambiguous
// overrides, which typically arise through combinations of ref/out and generics.) In incorrect code,
// the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type),
// but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata.
//
// NOTE: The batch compiler is not affected by this discrepancy, since compilations don't call these
// APIs on symbols from other compilations.
bool implementingTypeIsFromSomeCompilation = implementingType.Dangerous_IsFromSomeCompilation;
Symbol implicitImpl = null;
Symbol closestMismatch = null;
bool canBeImplementedImplicitly = interfaceMember.DeclaredAccessibility == Accessibility.Public && !interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor();
TypeSymbol implementingBaseOpt = null; // Calculated only if canBeImplementedImplicitly == false
bool implementingTypeImplementsInterface = false;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
for (TypeSymbol currType = implementingType; (object)currType != null; currType = currType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics))
{
// NOTE: In the case of PE symbols, it is possible to see an explicit implementation
// on a type that does not declare the corresponding interface (or one of its
// subinterfaces). In such cases, we want to return the explicit implementation,
// even if it doesn't participate in interface mapping according to the C# rules.
// pass 1: check for explicit impls (can't assume name matches)
MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = currType.GetExplicitImplementationForInterfaceMember(interfaceMember);
if (explicitImpl.Count == 1)
{
implementationInInterfacesMightChangeResult = false;
return explicitImpl.Single();
}
else if (explicitImpl.Count > 1)
{
if ((object)currType == implementingType || implementingTypeImplementsInterface)
{
diagnostics.Add(ErrorCode.ERR_DuplicateExplicitImpl, implementingType.Locations[0], interfaceMember);
}
implementationInInterfacesMightChangeResult = false;
return null;
}
if (IsExplicitlyImplementedViaAccessors(interfaceMember, currType, out Symbol currTypeExplicitImpl))
{
// We are looking for a property or event implementation and found an explicit implementation
// for its accessor(s) in this type. Stop the process and return event/property associated
// with the accessor(s), if any.
implementationInInterfacesMightChangeResult = false;
// NOTE: may be null.
return currTypeExplicitImpl;
}
if (!seenTypeDeclaringInterface ||
(!canBeImplementedImplicitly && (object)implementingBaseOpt == null))
{
if (currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics).ContainsKey(interfaceType))
{
seenTypeDeclaringInterface = true;
if ((object)currType == implementingType)
{
implementingTypeImplementsInterface = true;
}
else if (!canBeImplementedImplicitly && (object)implementingBaseOpt == null)
{
implementingBaseOpt = currType;
}
}
}
// We want the implementation from the most derived type at or above the first one to
// include the interface (or a subinterface) in its interface list
if (seenTypeDeclaringInterface)
{
//pass 2: check for implicit impls (name must match)
Symbol currTypeImplicitImpl;
Symbol currTypeCloseMismatch;
FindPotentialImplicitImplementationMemberDeclaredInType(
interfaceMember,
implementingTypeIsFromSomeCompilation,
currType,
out currTypeImplicitImpl,
out currTypeCloseMismatch);
if ((object)currTypeImplicitImpl != null)
{
implicitImpl = currTypeImplicitImpl;
break;
}
if ((object)closestMismatch == null)
{
closestMismatch = currTypeCloseMismatch;
}
}
}
Debug.Assert(!canBeImplementedImplicitly || (object)implementingBaseOpt == null);
bool tryDefaultInterfaceImplementation = true;
// Dev10 has some extra restrictions and extra wiggle room when finding implicit
// implementations for interface accessors. Perform some extra checks and possibly
// update the result (i.e. implicitImpl).
if (interfaceMember.IsAccessor())
{
Symbol originalImplicitImpl = implicitImpl;
CheckForImplementationOfCorrespondingPropertyOrEvent((MethodSymbol)interfaceMember, implementingType, implementingTypeIsFromSomeCompilation, ref implicitImpl);
// If we discarded the candidate, we don't want default interface implementation to take over later, since runtime might still use the discarded candidate.
if (originalImplicitImpl is object && implicitImpl is null)
{
tryDefaultInterfaceImplementation = false;
}
}
Symbol defaultImpl = null;
if ((object)implicitImpl == null && seenTypeDeclaringInterface && tryDefaultInterfaceImplementation)
{
if (ignoreImplementationInInterfaces)
{
implementationInInterfacesMightChangeResult = true;
}
else
{
// Check for default interface implementations
defaultImpl = FindMostSpecificImplementationInInterfaces(interfaceMember, implementingType, ref useSiteDiagnostics, diagnostics);
implementationInInterfacesMightChangeResult = false;
}
}
else
{
implementationInInterfacesMightChangeResult = false;
}
#if !DEBUG
// Don't optimize in DEBUG for better coverage for the GetInterfaceLocation function.
if (useSiteDiagnostics != null && implementingTypeImplementsInterface)
#endif
{
diagnostics.Add(GetInterfaceLocation(interfaceMember, implementingType), useSiteDiagnostics);
}
if (defaultImpl is object)
{
if (implementingTypeImplementsInterface)
{
ReportDefaultInterfaceImplementationMatchDiagnostics(interfaceMember, implementingType, defaultImpl, diagnostics);
}
return defaultImpl;
}
if (implementingTypeImplementsInterface)
{
if ((object)implicitImpl != null)
{
if (!canBeImplementedImplicitly)
{
if (interfaceMember.Kind == SymbolKind.Method &&
(object)implementingBaseOpt == null) // Otherwise any approprite errors are going to be reported for the base.
{
diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, GetInterfaceLocation(interfaceMember, implementingType),
implementingType, interfaceMember, implicitImpl);
}
}
else
{
ReportImplicitImplementationMatchDiagnostics(interfaceMember, implementingType, implicitImpl, diagnostics);
}
}
else if ((object)closestMismatch != null)
{
Debug.Assert(interfaceMember.DeclaredAccessibility == Accessibility.Public);
Debug.Assert(!interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor());
ReportImplicitImplementationMismatchDiagnostics(interfaceMember, implementingType, closestMismatch, diagnostics);
}
}
return implicitImpl;
}
private static Symbol FindMostSpecificImplementationInInterfaces(Symbol interfaceMember, TypeSymbol implementingType,