-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathSymbol.cs
1578 lines (1396 loc) · 64.7 KB
/
Symbol.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.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The base class for all symbols (namespaces, classes, method, parameters, etc.) that are
/// exposed by the compiler.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
internal abstract partial class Symbol : ISymbolInternal, IFormattable
{
private ISymbol _lazyISymbol;
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Changes to the public interface of this class should remain synchronized with the VB version of Symbol.
// Do not make any changes to the public interface without making the corresponding change
// to the VB version.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/// <summary>
/// True if this Symbol should be completed by calling ForceComplete.
/// Intuitively, true for source entities (from any compilation).
/// </summary>
internal virtual bool RequiresCompletion
{
get { return false; }
}
internal virtual void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken)
{
// must be overridden by source symbols, no-op for other symbols
Debug.Assert(!this.RequiresCompletion);
}
internal virtual bool HasComplete(CompletionPart part)
{
// must be overridden by source symbols, no-op for other symbols
Debug.Assert(!this.RequiresCompletion);
return true;
}
/// <summary>
/// Gets the name of this symbol. Symbols without a name return the empty string; null is
/// never returned.
/// </summary>
public virtual string Name
{
get
{
return string.Empty;
}
}
/// <summary>
/// Gets the name of a symbol as it appears in metadata. Most of the time, this
/// is the same as the Name property, with the following exceptions:
/// 1) The metadata name of generic types includes the "`1", "`2" etc. suffix that
/// indicates the number of type parameters (it does not include, however, names of
/// containing types or namespaces).
/// 2) The metadata name of explicit interface names have spaces removed, compared to
/// the name property.
/// </summary>
public virtual string MetadataName
{
get
{
return this.Name;
}
}
/// <summary>
/// Gets the kind of this symbol.
/// </summary>
public abstract SymbolKind Kind { get; }
/// <summary>
/// Get the symbol that logically contains this symbol.
/// </summary>
public abstract Symbol ContainingSymbol { get; }
/// <summary>
/// Returns the nearest lexically enclosing type, or null if there is none.
/// </summary>
public virtual NamedTypeSymbol ContainingType
{
get
{
Symbol container = this.ContainingSymbol;
NamedTypeSymbol containerAsType = container as NamedTypeSymbol;
// NOTE: container could be null, so we do not check
// whether containerAsType is not null, but
// instead check if it did not change after
// the cast.
if ((object)containerAsType == (object)container)
{
// this should be relatively uncommon
// most symbols that may be contained in a type
// know their containing type and can override ContainingType
// with a more precise implementation
return containerAsType;
}
// this is recursive, but recursion should be very short
// before we reach symbol that definitely knows its containing type.
return container.ContainingType;
}
}
/// <summary>
/// Gets the nearest enclosing namespace for this namespace or type. For a nested type,
/// returns the namespace that contains its container.
/// </summary>
public virtual NamespaceSymbol ContainingNamespace
{
get
{
for (var container = this.ContainingSymbol; (object)container != null; container = container.ContainingSymbol)
{
var ns = container as NamespaceSymbol;
if ((object)ns != null)
{
return ns;
}
}
return null;
}
}
/// <summary>
/// Returns the assembly containing this symbol. If this symbol is shared across multiple
/// assemblies, or doesn't belong to an assembly, returns null.
/// </summary>
public virtual AssemblySymbol ContainingAssembly
{
get
{
// Default implementation gets the containers assembly.
var container = this.ContainingSymbol;
return (object)container != null ? container.ContainingAssembly : null;
}
}
/// <summary>
/// For a source assembly, the associated compilation.
/// For any other assembly, null.
/// For a source module, the DeclaringCompilation of the associated source assembly.
/// For any other module, null.
/// For any other symbol, the DeclaringCompilation of the associated module.
/// </summary>
/// <remarks>
/// We're going through the containing module, rather than the containing assembly,
/// because of /addmodule (symbols in such modules should return null).
///
/// Remarks, not "ContainingCompilation" because it isn't transitive.
/// </remarks>
internal virtual CSharpCompilation DeclaringCompilation
{
get
{
switch (this.Kind)
{
case SymbolKind.ErrorType:
return null;
case SymbolKind.Assembly:
Debug.Assert(!(this is SourceAssemblySymbol), "SourceAssemblySymbol must override DeclaringCompilation");
return null;
case SymbolKind.NetModule:
Debug.Assert(!(this is SourceModuleSymbol), "SourceModuleSymbol must override DeclaringCompilation");
return null;
}
var sourceModuleSymbol = this.ContainingModule as SourceModuleSymbol;
return (object)sourceModuleSymbol == null ? null : sourceModuleSymbol.DeclaringCompilation;
}
}
Compilation ISymbolInternal.DeclaringCompilation
=> DeclaringCompilation;
string ISymbolInternal.Name => this.Name;
string ISymbolInternal.MetadataName => this.MetadataName;
ISymbolInternal ISymbolInternal.ContainingSymbol => this.ContainingSymbol;
IModuleSymbolInternal ISymbolInternal.ContainingModule => this.ContainingModule;
IAssemblySymbolInternal ISymbolInternal.ContainingAssembly => this.ContainingAssembly;
ImmutableArray<Location> ISymbolInternal.Locations => this.Locations;
INamespaceSymbolInternal ISymbolInternal.ContainingNamespace => this.ContainingNamespace;
bool ISymbolInternal.IsImplicitlyDeclared => this.IsImplicitlyDeclared;
INamedTypeSymbolInternal ISymbolInternal.ContainingType
{
get
{
return this.ContainingType;
}
}
ISymbol ISymbolInternal.GetISymbol() => this.ISymbol;
/// <summary>
/// Returns the module containing this symbol. If this symbol is shared across multiple
/// modules, or doesn't belong to a module, returns null.
/// </summary>
internal virtual ModuleSymbol ContainingModule
{
get
{
// Default implementation gets the containers module.
var container = this.ContainingSymbol;
return (object)container != null ? container.ContainingModule : null;
}
}
/// <summary>
/// The index of this member in the containing symbol. This is an optional
/// property, implemented by anonymous type properties only, for comparing
/// symbols in flow analysis.
/// </summary>
/// <remarks>
/// Should this be used for tuple fields as well?
/// </remarks>
internal virtual int? MemberIndexOpt => null;
/// <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 Symbol OriginalDefinition
{
get
{
return OriginalSymbolDefinition;
}
}
protected virtual Symbol OriginalSymbolDefinition
{
get
{
return this;
}
}
/// <summary>
/// Returns true if this is the original definition of this symbol.
/// </summary>
public bool IsDefinition
{
get
{
return (object)this == (object)OriginalDefinition;
}
}
/// <summary>
/// <para>
/// Get a source location key for sorting. For performance, it's important that this
/// be able to be returned from a symbol without doing any additional allocations (even
/// if nothing is cached yet.)
/// </para>
/// <para>
/// Only (original) source symbols and namespaces that can be merged
/// need implement this function if they want to do so for efficiency.
/// </para>
/// </summary>
internal virtual LexicalSortKey GetLexicalSortKey()
{
var locations = this.Locations;
var declaringCompilation = this.DeclaringCompilation;
Debug.Assert(declaringCompilation != null); // require that it is a source symbol
return (locations.Length > 0) ? new LexicalSortKey(locations[0], declaringCompilation) : LexicalSortKey.NotInSource;
}
/// <summary>
/// Gets the locations where this symbol was originally defined, either in source or
/// metadata. Some symbols (for example, partial classes) may be defined in more than one
/// location.
/// </summary>
public abstract ImmutableArray<Location> Locations { get; }
/// <summary>
/// <para>
/// Get the syntax node(s) where this symbol was declared in source. Some symbols (for
/// example, partial classes) may be defined in more than one location. This property should
/// return one or more syntax nodes only if the symbol was declared in source code and also
/// was not implicitly declared (see the <see cref="IsImplicitlyDeclared"/> property).
/// </para>
/// <para>
/// Note that for namespace symbol, the declaring syntax might be declaring a nested
/// namespace. For example, the declaring syntax node for N1 in "namespace N1.N2 {...}" is
/// the entire <see cref="NamespaceDeclarationSyntax"/> for N1.N2. For the global namespace, the declaring
/// syntax will be the <see cref="CompilationUnitSyntax"/>.
/// </para>
/// </summary>
/// <returns>
/// The syntax node(s) that declared the symbol. If the symbol was declared in metadata or
/// was implicitly declared, returns an empty read-only array.
/// </returns>
/// <remarks>
/// To go the opposite direction (from syntax node to symbol), see <see
/// cref="CSharpSemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)"/>.
/// </remarks>
public abstract ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get; }
/// <summary>
/// Helper for implementing <see cref="DeclaringSyntaxReferences"/> for derived classes that store a location but not a
/// <see cref="CSharpSyntaxNode"/> or <see cref="SyntaxReference"/>.
/// </summary>
internal static ImmutableArray<SyntaxReference> GetDeclaringSyntaxReferenceHelper<TNode>(ImmutableArray<Location> locations)
where TNode : CSharpSyntaxNode
{
if (locations.IsEmpty)
{
return ImmutableArray<SyntaxReference>.Empty;
}
ArrayBuilder<SyntaxReference> builder = ArrayBuilder<SyntaxReference>.GetInstance();
foreach (Location location in locations)
{
// Location may be null. See https://github.com/dotnet/roslyn/issues/28862.
if (location == null || !location.IsInSource)
{
continue;
}
if (location.SourceSpan.Length != 0)
{
SyntaxToken token = location.SourceTree.GetRoot().FindToken(location.SourceSpan.Start);
if (token.Kind() != SyntaxKind.None)
{
CSharpSyntaxNode node = token.Parent.FirstAncestorOrSelf<TNode>();
if (node != null)
{
builder.Add(node.GetReference());
}
}
}
else
{
// Since the location we're interested in can't contain a token, we'll inspect the whole tree,
// pruning away branches that don't contain that location. We'll pick the narrowest node of the type
// we're looking for.
// eg: finding the ParameterSyntax from the empty location of a blank identifier
SyntaxNode parent = location.SourceTree.GetRoot();
SyntaxNode found = null;
foreach (var descendant in parent.DescendantNodesAndSelf(c => c.Location.SourceSpan.Contains(location.SourceSpan)))
{
if (descendant is TNode && descendant.Location.SourceSpan.Contains(location.SourceSpan))
{
found = descendant;
}
}
if (found is object)
{
builder.Add(found.GetReference());
}
}
}
return builder.ToImmutableAndFree();
}
/// <summary>
/// Get this accessibility that was declared on this symbol. For symbols that do not have
/// accessibility declared on them, returns <see cref="Accessibility.NotApplicable"/>.
/// </summary>
public abstract Accessibility DeclaredAccessibility { get; }
/// <summary>
/// Returns true if this symbol is "static"; i.e., declared with the <c>static</c> modifier or
/// implicitly static.
/// </summary>
public abstract bool IsStatic { get; }
/// <summary>
/// Returns true if this symbol is "virtual", has an implementation, and does not override a
/// base class member; i.e., declared with the <c>virtual</c> modifier. Does not return true for
/// members declared as abstract or override.
/// </summary>
public abstract bool IsVirtual { get; }
/// <summary>
/// Returns true if this symbol was declared to override a base class member; i.e., declared
/// with the <c>override</c> modifier. Still returns true if member was declared to override
/// something, but (erroneously) no member to override exists.
/// </summary>
/// <remarks>
/// Even for metadata symbols, <see cref="IsOverride"/> = true does not imply that <see cref="IMethodSymbol.OverriddenMethod"/> will
/// be non-null.
/// </remarks>
public abstract bool IsOverride { get; }
/// <summary>
/// Returns true if this symbol was declared as requiring an override; i.e., declared with
/// the <c>abstract</c> modifier. Also returns true on a type declared as "abstract", all
/// interface types, and members of interface types.
/// </summary>
public abstract bool IsAbstract { get; }
/// <summary>
/// Returns true if this symbol was declared to override a base class member and was also
/// sealed from further overriding; i.e., declared with the <c>sealed</c> modifier. Also set for
/// types that do not allow a derived class (declared with <c>sealed</c> or <c>static</c> or <c>struct</c>
/// or <c>enum</c> or <c>delegate</c>).
/// </summary>
public abstract bool IsSealed { get; }
/// <summary>
/// Returns true if this symbol has external implementation; i.e., declared with the
/// <c>extern</c> modifier.
/// </summary>
public abstract bool IsExtern { get; }
/// <summary>
/// Returns true if this symbol was automatically created by the compiler, and does not
/// have an explicit corresponding source code declaration.
///
/// This is intended for symbols that are ordinary symbols in the language sense,
/// and may be used by code, but that are simply declared implicitly rather than
/// with explicit language syntax.
///
/// Examples include (this list is not exhaustive):
/// the default constructor for a class or struct that is created if one is not provided,
/// the BeginInvoke/Invoke/EndInvoke methods for a delegate,
/// the generated backing field for an auto property or a field-like event,
/// the "this" parameter for non-static methods,
/// the "value" parameter for a property setter,
/// the parameters on indexer accessor methods (not on the indexer itself),
/// methods in anonymous types,
/// anonymous functions
/// </summary>
public virtual bool IsImplicitlyDeclared
{
get { return false; }
}
/// <summary>
/// Returns true if this symbol can be referenced by its name in code. Examples of symbols
/// that cannot be referenced by name are:
/// constructors, destructors, operators, explicit interface implementations,
/// accessor methods for properties and events, array types.
/// </summary>
public bool CanBeReferencedByName
{
get
{
switch (this.Kind)
{
case SymbolKind.Local:
case SymbolKind.Label:
case SymbolKind.Alias:
case SymbolKind.RangeVariable:
// never imported, and always references by name.
return true;
case SymbolKind.Namespace:
case SymbolKind.Field:
case SymbolKind.ErrorType:
case SymbolKind.Parameter:
case SymbolKind.TypeParameter:
case SymbolKind.Event:
break;
case SymbolKind.NamedType:
if (((NamedTypeSymbol)this).IsSubmissionClass)
{
return false;
}
break;
case SymbolKind.Property:
var property = (PropertySymbol)this;
if (property.IsIndexer || property.MustCallMethodsDirectly)
{
return false;
}
break;
case SymbolKind.Method:
var method = (MethodSymbol)this;
switch (method.MethodKind)
{
case MethodKind.Ordinary:
case MethodKind.LocalFunction:
case MethodKind.ReducedExtension:
break;
case MethodKind.Destructor:
// You wouldn't think that destructors would be referenceable by name, but
// dev11 only prevents them from being invoked - they can still be assigned
// to delegates.
return true;
case MethodKind.DelegateInvoke:
return true;
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
if (!((PropertySymbol)method.AssociatedSymbol).CanCallMethodsDirectly())
{
return false;
}
break;
default:
return false;
}
break;
case SymbolKind.ArrayType:
case SymbolKind.PointerType:
case SymbolKind.FunctionPointerType:
case SymbolKind.Assembly:
case SymbolKind.DynamicType:
case SymbolKind.NetModule:
case SymbolKind.Discard:
return false;
default:
throw ExceptionUtilities.UnexpectedValue(this.Kind);
}
// This will eliminate backing fields for auto-props, explicit interface implementations,
// indexers, etc.
// See the comment on ContainsDroppedIdentifierCharacters for an explanation of why
// such names are not referenceable (or see DevDiv #14432).
return SyntaxFacts.IsValidIdentifier(this.Name) &&
!SyntaxFacts.ContainsDroppedIdentifierCharacters(this.Name);
}
}
/// <summary>
/// As an optimization, viability checking in the lookup code should use this property instead
/// of <see cref="CanBeReferencedByName"/>. The full name check will then be performed in the <see cref="CSharpSemanticModel"/>.
/// </summary>
/// <remarks>
/// This property exists purely for performance reasons.
/// </remarks>
internal bool CanBeReferencedByNameIgnoringIllegalCharacters
{
get
{
if (this.Kind == SymbolKind.Method)
{
var method = (MethodSymbol)this;
switch (method.MethodKind)
{
case MethodKind.Ordinary:
case MethodKind.LocalFunction:
case MethodKind.DelegateInvoke:
case MethodKind.Destructor: // See comment in CanBeReferencedByName.
return true;
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
return ((PropertySymbol)method.AssociatedSymbol).CanCallMethodsDirectly();
default:
return false;
}
}
return true;
}
}
/// <summary>
/// Perform additional checks after the member has been
/// added to the member list of the containing type.
/// </summary>
internal virtual void AfterAddingTypeMembersChecks(ConversionsBase conversions, DiagnosticBag diagnostics)
{
}
// Note: This is no public "IsNew". This is intentional, because new has no syntactic meaning.
// It serves only to remove a warning. Furthermore, it can not be inferred from
// metadata. For symbols defined in source, the modifiers in the syntax tree
// can be examined.
/// <summary>
/// Compare two symbol objects to see if they refer to the same symbol. You should always
/// use <see cref="operator =="/> and <see cref="operator !="/>, or the <see cref="Equals(object)"/> method, to compare two symbols for equality.
/// </summary>
public static bool operator ==(Symbol left, Symbol right)
{
//PERF: this function is often called with
// 1) left referencing same object as the right
// 2) right being null
// The code attempts to check for these conditions before
// resorting to .Equals
// the condition is expected to be folded when inlining "someSymbol == null"
if (right is null)
{
return left is null;
}
// this part is expected to disappear when inlining "someSymbol == null"
return (object)left == (object)right || right.Equals(left);
}
/// <summary>
/// Compare two symbol objects to see if they refer to the same symbol. You should always
/// use == and !=, or the Equals method, to compare two symbols for equality.
/// </summary>
public static bool operator !=(Symbol left, Symbol right)
{
//PERF: this function is often called with
// 1) left referencing same object as the right
// 2) right being null
// The code attempts to check for these conditions before
// resorting to .Equals
//
//NOTE: we do not implement this as !(left == right)
// since that sometimes results in a worse code
// the condition is expected to be folded when inlining "someSymbol != null"
if (right is null)
{
return left is object;
}
// this part is expected to disappear when inlining "someSymbol != null"
return (object)left != (object)right && !right.Equals(left);
}
public sealed override bool Equals(object obj)
{
return this.Equals(obj as Symbol, SymbolEqualityComparer.Default.CompareKind);
}
bool ISymbolInternal.Equals(ISymbolInternal other, TypeCompareKind compareKind)
{
return this.Equals(other as Symbol, compareKind);
}
// By default we don't consider the compareKind, and do reference equality. This can be overridden.
public virtual bool Equals(Symbol other, TypeCompareKind compareKind)
{
return (object)this == other;
}
// By default, we do reference equality. This can be overridden.
public override int GetHashCode()
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(this);
}
public static bool Equals(Symbol first, Symbol second, TypeCompareKind compareKind)
{
if (first is null)
{
return second is null;
}
return first.Equals(second, compareKind);
}
/// <summary>
/// Returns a string representation of this symbol, suitable for debugging purposes, or
/// for placing in an error message.
/// </summary>
/// <remarks>
/// This will provide a useful representation, but it would be clearer to call <see cref="ToDisplayString"/>
/// directly and provide an explicit format.
/// Sealed so that <see cref="ToString"/> and <see cref="ToDisplayString"/> can't get out of sync.
/// </remarks>
public sealed override string ToString()
{
return this.ToDisplayString();
}
// ---- End of Public Definition ---
// Below here can be various useful virtual methods that are useful to the compiler, but we don't
// want to expose publicly.
// ---- End of Public Definition ---
// Must override this in derived classes for visitor pattern.
internal abstract TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument a);
// Prevent anyone else from deriving from this class.
internal Symbol()
{
}
/// <summary>
/// Build and add synthesized attributes for this symbol.
/// </summary>
internal virtual void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
}
/// <summary>
/// Convenience helper called by subclasses to add a synthesized attribute to a collection of attributes.
/// </summary>
internal static void AddSynthesizedAttribute(ref ArrayBuilder<SynthesizedAttributeData> attributes, SynthesizedAttributeData attribute)
{
if (attribute != null)
{
if (attributes == null)
{
attributes = new ArrayBuilder<SynthesizedAttributeData>(1);
}
attributes.Add(attribute);
}
}
/// <summary>
/// <see cref="CharSet"/> effective for this symbol (type or DllImport method).
/// Nothing if <see cref="DefaultCharSetAttribute"/> isn't applied on the containing module or it doesn't apply on this symbol.
/// </summary>
/// <remarks>
/// Determined based upon value specified via <see cref="DefaultCharSetAttribute"/> applied on the containing module.
/// </remarks>
internal CharSet? GetEffectiveDefaultMarshallingCharSet()
{
Debug.Assert(this.Kind == SymbolKind.NamedType || this.Kind == SymbolKind.Method);
return this.ContainingModule.DefaultMarshallingCharSet;
}
internal bool IsFromCompilation(CSharpCompilation compilation)
{
Debug.Assert(compilation != null);
return compilation == this.DeclaringCompilation;
}
/// <summary>
/// Always prefer <see cref="IsFromCompilation"/>.
/// </summary>
/// <remarks>
/// <para>
/// Unfortunately, when determining overriding/hiding/implementation relationships, we don't
/// have the "current" compilation available. We could, but that would clutter up the API
/// without providing much benefit. As a compromise, we consider all compilations "current".
/// </para>
/// <para>
/// Unlike in VB, we are not allowing retargeting symbols. This method is used as an approximation
/// for <see cref="IsFromCompilation"/> when a compilation is not available and that method will never return
/// true for retargeting symbols.
/// </para>
/// </remarks>
internal bool Dangerous_IsFromSomeCompilation
{
get { return this.DeclaringCompilation != null; }
}
internal virtual bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken))
{
var declaringReferences = this.DeclaringSyntaxReferences;
if (this.IsImplicitlyDeclared && declaringReferences.Length == 0)
{
return this.ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken);
}
foreach (var syntaxRef in declaringReferences)
{
cancellationToken.ThrowIfCancellationRequested();
if (syntaxRef.SyntaxTree == tree &&
(!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value)))
{
return true;
}
}
return false;
}
internal static void ForceCompleteMemberByLocation(SourceLocation locationOpt, Symbol member, CancellationToken cancellationToken)
{
if (locationOpt == null || member.IsDefinedInSourceTree(locationOpt.SourceTree, locationOpt.SourceSpan, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
member.ForceComplete(locationOpt, cancellationToken);
}
}
/// <summary>
/// Returns the Documentation Comment ID for the symbol, or null if the symbol doesn't
/// support documentation comments.
/// </summary>
public virtual string GetDocumentationCommentId()
{
// NOTE: we're using a try-finally here because there's a test that specifically
// triggers an exception here to confirm that some symbols don't have documentation
// comment IDs. We don't care about "leaks" in such cases, but we don't want spew
// in the test output.
var pool = PooledStringBuilder.GetInstance();
try
{
StringBuilder builder = pool.Builder;
DocumentationCommentIDVisitor.Instance.Visit(this, builder);
return builder.Length == 0 ? null : builder.ToString();
}
finally
{
pool.Free();
}
}
/// <summary>
/// Fetches the documentation comment for this element with a cancellation token.
/// </summary>
/// <param name="preferredCulture">Optionally, retrieve the comments formatted for a particular culture. No impact on source documentation comments.</param>
/// <param name="expandIncludes">Optionally, expand <![CDATA[<include>]]> elements. No impact on non-source documentation comments.</param>
/// <param name="cancellationToken">Optionally, allow cancellation of documentation comment retrieval.</param>
/// <returns>The XML that would be written to the documentation file for the symbol.</returns>
public virtual string GetDocumentationCommentXml(
CultureInfo preferredCulture = null,
bool expandIncludes = false,
CancellationToken cancellationToken = default(CancellationToken))
{
return "";
}
private static readonly SymbolDisplayFormat s_debuggerDisplayFormat =
SymbolDisplayFormat.TestFormat
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier
| SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier)
.WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None);
internal virtual string GetDebuggerDisplay()
{
return $"{this.Kind} {this.ToDisplayString(s_debuggerDisplayFormat)}";
}
internal virtual void AddDeclarationDiagnostics(DiagnosticBag diagnostics)
{
if (!diagnostics.IsEmptyWithoutResolution)
{
CSharpCompilation compilation = this.DeclaringCompilation;
Debug.Assert(compilation != null);
compilation.DeclarationDiagnostics.AddRange(diagnostics);
}
}
#region Use-Site Diagnostics
/// <summary>
/// True if the symbol has a use-site diagnostic with error severity.
/// </summary>
internal bool HasUseSiteError
{
get
{
var diagnostic = GetUseSiteDiagnostic();
return diagnostic != null && diagnostic.Severity == DiagnosticSeverity.Error;
}
}
/// <summary>
/// Returns diagnostic info that should be reported at the use site of the symbol, or null if there is none.
/// </summary>
internal virtual DiagnosticInfo GetUseSiteDiagnostic()
{
return null;
}
/// <summary>
/// Return error code that has highest priority while calculating use site error for this symbol.
/// Supposed to be ErrorCode, but it causes inconsistent accessibility error.
/// </summary>
protected virtual int HighestPriorityUseSiteError
{
get
{
return int.MaxValue;
}
}
/// <summary>
/// Indicates that this symbol uses metadata that cannot be supported by the language.
///
/// Examples include:
/// - Pointer types in VB
/// - ByRef return type
/// - Required custom modifiers
///
/// This is distinguished from, for example, references to metadata symbols defined in assemblies that weren't referenced.
/// Symbols where this returns true can never be used successfully, and thus should never appear in any IDE feature.
///
/// This is set for metadata symbols, as follows:
/// Type - if a type is unsupported (e.g., a pointer type, etc.)
/// Method - parameter or return type is unsupported
/// Field - type is unsupported
/// Event - type is unsupported
/// Property - type is unsupported
/// Parameter - type is unsupported
/// </summary>
public virtual bool HasUnsupportedMetadata
{
get
{
return false;
}
}
internal DiagnosticInfo GetUseSiteDiagnosticForSymbolOrContainingType()
{
var info = this.GetUseSiteDiagnostic();
if (info != null && info.Severity == DiagnosticSeverity.Error)
{
return info;
}
return this.ContainingType.GetUseSiteDiagnostic() ?? info;
}
/// <summary>
/// Merges given diagnostic to the existing result diagnostic.
/// </summary>
internal bool MergeUseSiteDiagnostics(ref DiagnosticInfo result, DiagnosticInfo info)
{
if (info == null)
{
return false;
}
if (info.Severity == DiagnosticSeverity.Error && (info.Code == HighestPriorityUseSiteError || HighestPriorityUseSiteError == Int32.MaxValue))
{
// this error is final, no other error can override it:
result = info;
return true;
}
if (result == null || result.Severity == DiagnosticSeverity.Warning && info.Severity == DiagnosticSeverity.Error)
{
// there could be an error of higher-priority
result = info;
return false;
}
// we have a second low-pri error, continue looking for a higher priority one
return false;
}
/// <summary>
/// Reports specified use-site diagnostic to given diagnostic bag.
/// </summary>
/// <remarks>
/// This method should be the only method adding use-site diagnostics to a diagnostic bag.
/// It performs additional adjustments of the location for unification related diagnostics and
/// may be the place where to add more use-site location post-processing.
/// </remarks>
/// <returns>True if the diagnostic has error severity.</returns>
internal static bool ReportUseSiteDiagnostic(DiagnosticInfo info, DiagnosticBag diagnostics, Location location)
{
// Unlike VB the C# Dev11 compiler reports only a single unification error/warning.
// By dropping the location we effectively merge all unification use-site errors that have the same error code into a single error.
// The error message clearly explains how to fix the problem and reporting the error for each location wouldn't add much value.
if (info.Code == (int)ErrorCode.WRN_UnifyReferenceBldRev ||
info.Code == (int)ErrorCode.WRN_UnifyReferenceMajMin ||
info.Code == (int)ErrorCode.ERR_AssemblyMatchBadVersion)
{
location = NoLocation.Singleton;
}
diagnostics.Add(info, location);
return info.Severity == DiagnosticSeverity.Error;
}
/// <summary>
/// Derive error info from a type symbol.
/// </summary>
internal bool DeriveUseSiteDiagnosticFromType(ref DiagnosticInfo result, TypeSymbol type)
{
DiagnosticInfo info = type.GetUseSiteDiagnostic();
if (info != null)
{
if (info.Code == (int)ErrorCode.ERR_BogusType)
{
info = GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo() ?? info;