-
Notifications
You must be signed in to change notification settings - Fork 4k
/
ISymbolExtensions.cs
1110 lines (953 loc) · 44.4 KB
/
ISymbolExtensions.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
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class ISymbolExtensions
{
public static string ToNameDisplayString(this ISymbol symbol)
{
return symbol.ToDisplayString(SymbolDisplayFormats.NameFormat);
}
public static string ToSignatureDisplayString(this ISymbol symbol)
{
return symbol.ToDisplayString(SymbolDisplayFormats.SignatureFormat);
}
public static SymbolVisibility GetResultantVisibility(this ISymbol symbol)
{
// Start by assuming it's visible.
var visibility = SymbolVisibility.Public;
switch (symbol.Kind)
{
case SymbolKind.Alias:
// Aliases are uber private. They're only visible in the same file that they
// were declared in.
return SymbolVisibility.Private;
case SymbolKind.Parameter:
// Parameters are only as visible as their containing symbol
return GetResultantVisibility(symbol.ContainingSymbol);
case SymbolKind.TypeParameter:
// Type Parameters are private.
return SymbolVisibility.Private;
}
while (symbol != null && symbol.Kind != SymbolKind.Namespace)
{
switch (symbol.DeclaredAccessibility)
{
// If we see anything private, then the symbol is private.
case Accessibility.NotApplicable:
case Accessibility.Private:
return SymbolVisibility.Private;
// If we see anything internal, then knock it down from public to
// internal.
case Accessibility.Internal:
case Accessibility.ProtectedAndInternal:
visibility = SymbolVisibility.Internal;
break;
// For anything else (Public, Protected, ProtectedOrInternal), the
// symbol stays at the level we've gotten so far.
}
symbol = symbol.ContainingSymbol;
}
return visibility;
}
public static ISymbol OverriddenMember(this ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Event:
return ((IEventSymbol)symbol).OverriddenEvent;
case SymbolKind.Method:
return ((IMethodSymbol)symbol).OverriddenMethod;
case SymbolKind.Property:
return ((IPropertySymbol)symbol).OverriddenProperty;
}
return null;
}
public static ImmutableArray<ISymbol> ExplicitInterfaceImplementations(this ISymbol symbol)
{
return symbol.TypeSwitch(
(IEventSymbol @event) => @event.ExplicitInterfaceImplementations.As<ISymbol>(),
(IMethodSymbol method) => method.ExplicitInterfaceImplementations.As<ISymbol>(),
(IPropertySymbol property) => property.ExplicitInterfaceImplementations.As<ISymbol>(),
_ => ImmutableArray.Create<ISymbol>());
}
public static bool IsOverridable(this ISymbol symbol)
{
return
symbol != null &&
symbol.ContainingType != null &&
symbol.ContainingType.TypeKind == TypeKind.Class &&
(symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride) &&
!symbol.IsSealed;
}
public static bool IsImplementable(this ISymbol symbol)
{
if (symbol != null &&
symbol.ContainingType != null &&
symbol.ContainingType.TypeKind == TypeKind.Interface)
{
if (symbol.Kind == SymbolKind.Event)
{
return true;
}
if (symbol.Kind == SymbolKind.Property)
{
return true;
}
if (symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.Ordinary)
{
return true;
}
}
return false;
}
public static INamedTypeSymbol GetContainingTypeOrThis(this ISymbol symbol)
{
if (symbol is INamedTypeSymbol)
{
return (INamedTypeSymbol)symbol;
}
return symbol.ContainingType;
}
public static bool IsPointerType(this ISymbol symbol)
{
return symbol is IPointerTypeSymbol;
}
public static bool IsErrorType(this ISymbol symbol)
{
return
symbol is ITypeSymbol &&
((ITypeSymbol)symbol).TypeKind == TypeKind.Error;
}
public static bool IsModuleType(this ISymbol symbol)
{
return
symbol is ITypeSymbol &&
((ITypeSymbol)symbol).TypeKind == TypeKind.Module;
}
public static bool IsInterfaceType(this ISymbol symbol)
{
return
symbol is ITypeSymbol &&
((ITypeSymbol)symbol).TypeKind == TypeKind.Interface;
}
public static bool IsArrayType(this ISymbol symbol)
{
return
symbol != null &&
symbol.Kind == SymbolKind.ArrayType;
}
public static bool IsAnonymousFunction(this ISymbol symbol)
{
return symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.AnonymousFunction;
}
public static bool IsKind(this ISymbol symbol, SymbolKind kind)
{
return symbol.MatchesKind(kind);
}
public static bool MatchesKind(this ISymbol symbol, SymbolKind kind)
{
return symbol != null
&& symbol.Kind == kind;
}
public static bool MatchesKind(this ISymbol symbol, SymbolKind kind1, SymbolKind kind2)
{
return symbol != null
&& (symbol.Kind == kind1 || symbol.Kind == kind2);
}
public static bool MatchesKind(this ISymbol symbol, SymbolKind kind1, SymbolKind kind2, SymbolKind kind3)
{
return symbol != null
&& (symbol.Kind == kind1 || symbol.Kind == kind2 || symbol.Kind == kind3);
}
public static bool MatchesKind(this ISymbol symbol, params SymbolKind[] kinds)
{
return symbol != null
&& kinds.Contains(symbol.Kind);
}
public static bool IsReducedExtension(this ISymbol symbol)
{
return symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.ReducedExtension;
}
public static bool IsExtensionMethod(this ISymbol symbol)
{
return symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsExtensionMethod;
}
public static bool IsModuleMember(this ISymbol symbol)
{
return symbol != null && symbol.ContainingSymbol is INamedTypeSymbol && symbol.ContainingType.TypeKind == TypeKind.Module;
}
public static bool IsConstructor(this ISymbol symbol)
{
return symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.Constructor;
}
public static bool IsStaticConstructor(this ISymbol symbol)
{
return symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.StaticConstructor;
}
public static bool IsDestructor(this ISymbol symbol)
{
return symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.Destructor;
}
public static bool IsUserDefinedOperator(this ISymbol symbol)
{
return symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.UserDefinedOperator;
}
public static bool IsConversion(this ISymbol symbol)
{
return symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.Conversion;
}
public static bool IsOrdinaryMethod(this ISymbol symbol)
{
return symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.Ordinary;
}
public static bool IsDelegateType(this ISymbol symbol)
{
return symbol is ITypeSymbol && ((ITypeSymbol)symbol).TypeKind == TypeKind.Delegate;
}
public static bool IsAnonymousType(this ISymbol symbol)
{
return symbol is INamedTypeSymbol && ((INamedTypeSymbol)symbol).IsAnonymousType;
}
public static bool IsNormalAnonymousType(this ISymbol symbol)
{
return symbol.IsAnonymousType() && !symbol.IsDelegateType();
}
public static bool IsAnonymousDelegateType(this ISymbol symbol)
{
return symbol.IsAnonymousType() && symbol.IsDelegateType();
}
public static bool IsAnonymousTypeProperty(this ISymbol symbol)
{
return symbol is IPropertySymbol && symbol.ContainingType.IsNormalAnonymousType();
}
public static bool IsIndexer(this ISymbol symbol)
{
return symbol is IPropertySymbol && ((IPropertySymbol)symbol).IsIndexer;
}
public static bool IsWriteableFieldOrProperty(this ISymbol symbol)
{
var fieldSymbol = symbol as IFieldSymbol;
if (fieldSymbol != null)
{
return !fieldSymbol.IsReadOnly
&& !fieldSymbol.IsConst;
}
var propertySymbol = symbol as IPropertySymbol;
if (propertySymbol != null)
{
return !propertySymbol.IsReadOnly;
}
return false;
}
public static ITypeSymbol GetMemberType(this ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Field:
return ((IFieldSymbol)symbol).Type;
case SymbolKind.Property:
return ((IPropertySymbol)symbol).Type;
case SymbolKind.Method:
return ((IMethodSymbol)symbol).ReturnType;
case SymbolKind.Event:
return ((IEventSymbol)symbol).Type;
}
return null;
}
public static int GetArity(this ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.NamedType:
return ((INamedTypeSymbol)symbol).Arity;
case SymbolKind.Method:
return ((IMethodSymbol)symbol).Arity;
default:
return 0;
}
}
public static ISymbol GetOriginalUnreducedDefinition(this ISymbol symbol)
{
if (symbol.IsReducedExtension())
{
// note: ReducedFrom is only a method definition and includes no type arguments.
symbol = ((IMethodSymbol)symbol).GetConstructedReducedFrom();
}
if (symbol.IsFunctionValue())
{
var method = symbol.ContainingSymbol as IMethodSymbol;
if (method != null)
{
symbol = method;
if (method.AssociatedSymbol != null)
{
symbol = method.AssociatedSymbol;
}
}
}
if (symbol.IsNormalAnonymousType() || symbol.IsAnonymousTypeProperty())
{
return symbol;
}
if (symbol is IParameterSymbol)
{
var parameter = (IParameterSymbol)symbol;
if (parameter.ContainingSymbol is IMethodSymbol)
{
var method = (IMethodSymbol)parameter.ContainingSymbol;
if (method.IsReducedExtension())
{
symbol = method.GetConstructedReducedFrom().Parameters[parameter.Ordinal + 1];
}
}
}
return symbol == null ? null : symbol.OriginalDefinition;
}
public static bool IsFunctionValue(this ISymbol symbol)
{
return symbol is ILocalSymbol && ((ILocalSymbol)symbol).IsFunctionValue;
}
public static bool IsThisParameter(this ISymbol symbol)
{
return symbol != null && symbol.Kind == SymbolKind.Parameter && ((IParameterSymbol)symbol).IsThis;
}
public static ISymbol ConvertThisParameterToType(this ISymbol symbol)
{
if (symbol.IsThisParameter())
{
return ((IParameterSymbol)symbol).Type;
}
return symbol;
}
public static bool IsParams(this ISymbol symbol)
{
var parameters = symbol.GetParameters();
return parameters.Length > 0 && parameters.Last().IsParams;
}
public static ImmutableArray<IParameterSymbol> GetParameters(this ISymbol symbol)
{
return symbol.TypeSwitch(
(IMethodSymbol m) => m.Parameters,
(IPropertySymbol p) => p.Parameters,
_ => ImmutableArray.Create<IParameterSymbol>());
}
#if false
public static ImmutableArray<ITypeParameterSymbol> GetTypeParameters(this ISymbol symbol)
{
return symbol.TypeSwitch(
(IMethodSymbol m) => m.TypeParameters,
(INamedTypeSymbol nt) => nt.TypeParameters,
_ => ImmutableArray.Create<ITypeParameterSymbol>());
}
#endif
public static ImmutableArray<ITypeSymbol> GetTypeArguments(this ISymbol symbol)
{
return symbol.TypeSwitch(
(IMethodSymbol m) => m.TypeArguments,
(INamedTypeSymbol nt) => nt.TypeArguments,
_ => ImmutableArray.Create<ITypeSymbol>());
}
public static ImmutableArray<ITypeSymbol> GetAllTypeArguments(this ISymbol symbol)
{
var results = new List<ITypeSymbol>(symbol.GetTypeArguments());
var containingType = symbol.ContainingType;
while (containingType != null)
{
results.AddRange(containingType.GetTypeArguments());
containingType = containingType.ContainingType;
}
return results.AsImmutable();
}
public static bool IsAttribute(this ISymbol symbol)
{
var typeSymbol = symbol as ITypeSymbol;
return typeSymbol != null
? typeSymbol.IsAttribute()
: false;
}
/// <summary>
/// Returns true if this symbol contains anything unsafe within it. for example
/// List<int*[]> is unsafe, as it "int* Foo { get; }"
/// </summary>
public static bool IsUnsafe(this ISymbol member)
{
// TODO(cyrusn): Defer to compiler code to handle this once it can.
return member != null && member.Accept(new IsUnsafeVisitor());
}
public static ITypeSymbol ConvertToType(
this ISymbol symbol,
Compilation compilation,
bool extensionUsedAsInstance = false)
{
if (symbol is ITypeSymbol)
{
return (ITypeSymbol)symbol;
}
else if (symbol is IMethodSymbol)
{
// Convert the symbol to Func<...> or Action<...>
var method = (IMethodSymbol)symbol;
if (!method.Parameters.Any(p => p.RefKind != RefKind.None))
{
if (method.ReturnsVoid)
{
var count = extensionUsedAsInstance ? method.Parameters.Length - 1 : method.Parameters.Length;
var skip = extensionUsedAsInstance ? 1 : 0;
count = Math.Max(0, count);
if (count == 0)
{
// Action
return compilation.ActionType();
}
else
{
// Action<TArg1, ..., TArgN>
var actionName = "System.Action`" + count;
var actionType = compilation.GetTypeByMetadataName(actionName);
if (actionType != null)
{
var types = method.Parameters
.Skip(skip)
.Select(p =>
(object)p.Type == null ?
compilation.GetSpecialType(SpecialType.System_Object) :
p.Type)
.ToArray();
return actionType.Construct(types);
}
}
}
else
{
// Func<TArg1,...,TArgN,TReturn>
//
// +1 for the return type.
var count = extensionUsedAsInstance ? method.Parameters.Length - 1 : method.Parameters.Length;
var skip = extensionUsedAsInstance ? 1 : 0;
var functionName = "System.Func`" + (count + 1);
var functionType = compilation.GetTypeByMetadataName(functionName);
if (functionType != null)
{
var types = method.Parameters
.Skip(skip)
.Select(p => p.Type)
.Concat(method.ReturnType)
.Select(t =>
(object)t == null ?
compilation.GetSpecialType(SpecialType.System_Object) :
t)
.ToArray();
return functionType.Construct(types);
}
}
}
}
// Otherwise, just default to object.
return compilation.ObjectType;
}
public static bool IsDeprecated(this ISymbol symbol)
{
// TODO(cyrusn): Implement this
return false;
}
public static bool IsStaticType(this ISymbol symbol)
{
return symbol != null && symbol.Kind == SymbolKind.NamedType && symbol.IsStatic;
}
public static bool IsNamespace(this ISymbol symbol)
{
return symbol != null && symbol.Kind == SymbolKind.Namespace;
}
public static bool IsOrContainsAccessibleAttribute(this ISymbol symbol, ISymbol withinType, IAssemblySymbol withinAssembly)
{
var alias = symbol as IAliasSymbol;
if (alias != null)
{
symbol = alias.Target;
}
var namespaceOrType = symbol as INamespaceOrTypeSymbol;
if (namespaceOrType == null)
{
return false;
}
if (namespaceOrType.IsAttribute() && namespaceOrType.IsAccessibleWithin(withinType ?? withinAssembly))
{
return true;
}
return namespaceOrType.GetMembers().Any(nt => nt.IsOrContainsAccessibleAttribute(withinType, withinAssembly));
}
public static IEnumerable<IPropertySymbol> GetValidAnonymousTypeProperties(this ISymbol symbol)
{
Contract.ThrowIfFalse(symbol.IsNormalAnonymousType());
return ((INamedTypeSymbol)symbol).GetMembers().OfType<IPropertySymbol>().Where(p => p.CanBeReferencedByName);
}
public static Accessibility ComputeResultantAccessibility(this ISymbol symbol, ITypeSymbol finalDestination)
{
if (symbol == null)
{
return Accessibility.Private;
}
switch (symbol.DeclaredAccessibility)
{
default:
return symbol.DeclaredAccessibility;
case Accessibility.ProtectedAndInternal:
return symbol.ContainingAssembly.GivesAccessTo(finalDestination.ContainingAssembly)
? Accessibility.ProtectedAndInternal
: Accessibility.Internal;
case Accessibility.ProtectedOrInternal:
return symbol.ContainingAssembly.GivesAccessTo(finalDestination.ContainingAssembly)
? Accessibility.ProtectedOrInternal
: Accessibility.Protected;
}
}
/// <returns>
/// Returns true if symbol is a local variable and its declaring syntax node is
/// after the current position, false otherwise (including for non-local symbols)
/// </returns>
public static bool IsInaccessibleLocal(this ISymbol symbol, int position)
{
if (symbol.Kind != SymbolKind.Local)
{
return false;
}
// Implicitly declared locals (with Option Explicit Off in VB) are scoped to the entire
// method and should always be considered accessible from within the same method.
if (symbol.IsImplicitlyDeclared)
{
return false;
}
var declarationSyntax = symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).FirstOrDefault();
return declarationSyntax != null && position < declarationSyntax.SpanStart;
}
/// <summary>
/// Checks a given symbol for browsability based on its declaration location, attributes
/// explicitly limiting browsability, and whether showing of advanced members is enabled.
/// The optional attribute constructor parameters may be used to specify the symbols of the
/// constructors of the various browsability limiting attributes because finding these
/// repeatedly over a large list of symbols can be slow. If providing these constructor
/// symbols, they should be in the format provided by
/// EditorBrowsableHelpers.GetSpecial*AttributeConstructor(). If these are not provided,
/// they will be found in the compilation.
/// </summary>
public static bool IsEditorBrowsable(
this ISymbol symbol,
bool hideAdvancedMembers,
Compilation compilation,
IMethodSymbol editorBrowsableAttributeConstructor = null,
List<IMethodSymbol> typeLibTypeAttributeConstructors = null,
List<IMethodSymbol> typeLibFuncAttributeConstructors = null,
List<IMethodSymbol> typeLibVarAttributeConstructors = null,
INamedTypeSymbol hideModuleNameAttribute = null)
{
// Namespaces can't have attributes, so just return true here. This also saves us a
// costly check if this namespace has any locations in source (since a merged namespace
// needs to go collect all the locations).
if (symbol.Kind == SymbolKind.Namespace)
{
return true;
}
// check for IsImplicitlyDeclared so we don't spend time examining VB's embedded types.
// This saves a few percent in typing scenarios. An implicitly declared symbol can't
// have attributes, so it can't be hidden by them.
if (symbol.IsImplicitlyDeclared)
{
return true;
}
// Ignore browsability limiting attributes if the symbol is declared in source.
// Check all locations since some of VB's embedded My symbols are declared in
// both source and the MyTemplateLocation.
if (symbol.Locations.All(loc => loc.IsInSource))
{
// The HideModuleNameAttribute still applies to Modules defined in source
return !IsBrowsingProhibitedByHideModuleNameAttribute(symbol, compilation, hideModuleNameAttribute);
}
return !IsBrowsingProhibited(
symbol,
hideAdvancedMembers,
compilation,
editorBrowsableAttributeConstructor,
typeLibTypeAttributeConstructors,
typeLibFuncAttributeConstructors,
typeLibVarAttributeConstructors,
hideModuleNameAttribute);
}
private static bool IsBrowsingProhibited(
ISymbol symbol,
bool hideAdvancedMembers,
Compilation compilation,
IMethodSymbol editorBrowsableAttributeConstructor,
List<IMethodSymbol> typeLibTypeAttributeConstructors,
List<IMethodSymbol> typeLibFuncAttributeConstructors,
List<IMethodSymbol> typeLibVarAttributeConstructors,
INamedTypeSymbol hideModuleNameAttribute)
{
var attributes = symbol.GetAttributes();
if (attributes.Length == 0)
{
return false;
}
return IsBrowsingProhibitedByEditorBrowsableAttribute(symbol, attributes, hideAdvancedMembers, compilation, editorBrowsableAttributeConstructor)
|| IsBrowsingProhibitedByTypeLibTypeAttribute(symbol, attributes, compilation, typeLibTypeAttributeConstructors)
|| IsBrowsingProhibitedByTypeLibFuncAttribute(symbol, attributes, compilation, typeLibFuncAttributeConstructors)
|| IsBrowsingProhibitedByTypeLibVarAttribute(symbol, attributes, compilation, typeLibVarAttributeConstructors)
|| IsBrowsingProhibitedByHideModuleNameAttribute(symbol, compilation, hideModuleNameAttribute, attributes);
}
private static bool IsBrowsingProhibitedByHideModuleNameAttribute(
ISymbol symbol, Compilation compilation, INamedTypeSymbol hideModuleNameAttribute, ImmutableArray<AttributeData> attributes = default(ImmutableArray<AttributeData>))
{
if (!symbol.IsModuleType())
{
return false;
}
attributes = attributes.IsDefault ? symbol.GetAttributes() : attributes;
hideModuleNameAttribute = hideModuleNameAttribute ?? compilation.HideModuleNameAttribute();
foreach (var attribute in attributes)
{
if (attribute.AttributeClass == hideModuleNameAttribute)
{
return true;
}
}
return false;
}
private static bool IsBrowsingProhibitedByEditorBrowsableAttribute(
ISymbol symbol, ImmutableArray<AttributeData> attributes, bool hideAdvancedMembers, Compilation compilation, IMethodSymbol constructor)
{
constructor = constructor ?? EditorBrowsableHelpers.GetSpecialEditorBrowsableAttributeConstructor(compilation);
if (constructor == null)
{
return false;
}
foreach (var attribute in attributes)
{
if (attribute.AttributeConstructor == constructor &&
attribute.ConstructorArguments.Length == 1 &&
attribute.ConstructorArguments.First().Value is int)
{
var state = (EditorBrowsableState)attribute.ConstructorArguments.First().Value;
if (EditorBrowsableState.Never == state ||
(hideAdvancedMembers && EditorBrowsableState.Advanced == state))
{
return true;
}
}
}
return false;
}
private static bool IsBrowsingProhibitedByTypeLibTypeAttribute(
ISymbol symbol, ImmutableArray<AttributeData> attributes, Compilation compilation, List<IMethodSymbol> constructors)
{
return IsBrowsingProhibitedByTypeLibAttributeWorker(
symbol,
attributes,
constructors ?? EditorBrowsableHelpers.GetSpecialTypeLibTypeAttributeConstructors(compilation),
TypeLibTypeFlagsFHidden);
}
private static bool IsBrowsingProhibitedByTypeLibFuncAttribute(
ISymbol symbol, ImmutableArray<AttributeData> attributes, Compilation compilation, List<IMethodSymbol> constructors)
{
return IsBrowsingProhibitedByTypeLibAttributeWorker(
symbol,
attributes,
constructors ?? EditorBrowsableHelpers.GetSpecialTypeLibFuncAttributeConstructors(compilation),
TypeLibFuncFlagsFHidden);
}
private static bool IsBrowsingProhibitedByTypeLibVarAttribute(
ISymbol symbol, ImmutableArray<AttributeData> attributes, Compilation compilation, List<IMethodSymbol> constructors)
{
return IsBrowsingProhibitedByTypeLibAttributeWorker(
symbol,
attributes,
constructors ?? EditorBrowsableHelpers.GetSpecialTypeLibVarAttributeConstructors(compilation),
TypeLibVarFlagsFHidden);
}
private const int TypeLibTypeFlagsFHidden = 0x0010;
private const int TypeLibFuncFlagsFHidden = 0x0040;
private const int TypeLibVarFlagsFHidden = 0x0040;
private static bool IsBrowsingProhibitedByTypeLibAttributeWorker(
ISymbol symbol, ImmutableArray<AttributeData> attributes, List<IMethodSymbol> attributeConstructors, int hiddenFlag)
{
foreach (var attribute in attributes)
{
if (attribute.ConstructorArguments.Length == 1)
{
foreach (var constructor in attributeConstructors)
{
if (attribute.AttributeConstructor == constructor)
{
var actualFlags = 0;
// Check for both constructor signatures. The constructor that takes a TypeLib*Flags reports an int argument.
var argumentValue = attribute.ConstructorArguments.First().Value;
if (argumentValue is int)
{
actualFlags = (int)argumentValue;
}
else if (argumentValue is short)
{
actualFlags = (short)argumentValue;
}
else
{
continue;
}
if ((actualFlags & hiddenFlag) == hiddenFlag)
{
return true;
}
}
}
}
}
return false;
}
public static bool IsAccessor(this ISymbol symbol)
{
return symbol.IsPropertyAccessor() || symbol.IsEventAccessor();
}
public static bool IsPropertyAccessor(this ISymbol symbol)
{
var method = symbol as IMethodSymbol;
return method != null && method.MethodKind.IsPropertyAccessor();
}
public static bool IsEventAccessor(this ISymbol symbol)
{
var method = symbol as IMethodSymbol;
return method != null &&
(method.MethodKind == MethodKind.EventAdd ||
method.MethodKind == MethodKind.EventRaise ||
method.MethodKind == MethodKind.EventRemove);
}
public static DeclarationModifiers GetSymbolModifiers(this ISymbol symbol)
{
return new DeclarationModifiers(
isStatic: symbol.IsStatic,
isAbstract: symbol.IsAbstract,
isUnsafe: symbol.IsUnsafe(),
isVirtual: symbol.IsVirtual,
isOverride: symbol.IsOverride,
isSealed: symbol.IsSealed);
}
public static ITypeSymbol GetSymbolType(this ISymbol symbol)
{
var localSymbol = symbol as ILocalSymbol;
if (localSymbol != null)
{
return localSymbol.Type;
}
var fieldSymbol = symbol as IFieldSymbol;
if (fieldSymbol != null)
{
return fieldSymbol.Type;
}
var propertySymbol = symbol as IPropertySymbol;
if (propertySymbol != null)
{
return propertySymbol.Type;
}
var parameterSymbol = symbol as IParameterSymbol;
if (parameterSymbol != null)
{
return parameterSymbol.Type;
}
var aliasSymbol = symbol as IAliasSymbol;
if (aliasSymbol != null)
{
return aliasSymbol.Target as ITypeSymbol;
}
return symbol as ITypeSymbol;
}
public static DocumentationComment GetDocumentationComment(this ISymbol symbol, CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken))
{
string xmlText = symbol.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken);
return string.IsNullOrEmpty(xmlText) ? DocumentationComment.Empty : DocumentationComment.FromXmlFragment(xmlText);
}
/// <summary>
/// If the <paramref name="symbol"/> is a method symbol, returns True if the method's return type is "awaitable".
/// If the <paramref name="symbol"/> is a type symbol, returns True if that type is "awaitable".
/// An "awaitable" is any type that exposes a GetAwaiter method which returns a valid "awaiter". This GetAwaiter method may be an instance method or an extension method.
/// </summary>
public static bool IsAwaitable(this ISymbol symbol, SemanticModel semanticModel, int position)
{
IMethodSymbol methodSymbol = symbol as IMethodSymbol;
ITypeSymbol typeSymbol = null;
if (methodSymbol == null)
{
typeSymbol = symbol as ITypeSymbol;
if (typeSymbol == null)
{
return false;
}
}
else
{
if (methodSymbol.ReturnType == null)
{
return false;
}
// dynamic
if (methodSymbol.ReturnType.TypeKind == TypeKind.Dynamic &&
methodSymbol.MethodKind != MethodKind.BuiltinOperator)
{
return true;
}
}
// otherwise: needs valid GetAwaiter
var potentialGetAwaiters = semanticModel.LookupSymbols(position,
container: typeSymbol ?? methodSymbol.ReturnType.OriginalDefinition,
name: WellKnownMemberNames.GetAwaiter,
includeReducedExtensionMethods: true);
var getAwaiters = potentialGetAwaiters.OfType<IMethodSymbol>().Where(x => !x.Parameters.Any());
return getAwaiters.Any(VerifyGetAwaiter);
}
private static bool VerifyGetAwaiter(IMethodSymbol getAwaiter)
{
var returnType = getAwaiter.ReturnType;
if (returnType == null)
{
return false;
}
// bool IsCompleted { get }
if (!returnType.GetMembers().OfType<IPropertySymbol>().Any(p => p.Name == WellKnownMemberNames.IsCompleted && p.Type.SpecialType == SpecialType.System_Boolean && p.GetMethod != null))
{
return false;
}
var methods = returnType.GetMembers().OfType<IMethodSymbol>();
// NOTE: (vladres) The current version of C# Spec, §7.7.7.3 'Runtime evaluation of await expressions', requires that
// NOTE: the interface method INotifyCompletion.OnCompleted or ICriticalNotifyCompletion.UnsafeOnCompleted is invoked
// NOTE: (rather than any OnCompleted method conforming to a certain pattern).
// NOTE: Should this code be updated to match the spec?
// void OnCompleted(Action)
// Actions are delegates, so we'll just check for delegates.
if (!methods.Any(x => x.Name == WellKnownMemberNames.OnCompleted && x.ReturnsVoid && x.Parameters.Length == 1 && x.Parameters.First().Type.TypeKind == TypeKind.Delegate))
{
return false;
}
// void GetResult() || T GetResult()
return methods.Any(m => m.Name == WellKnownMemberNames.GetResult && !m.Parameters.Any());
}
public static IList<SymbolDisplayPart> ToAwaitableParts(this ISymbol symbol, string awaitKeyword, string initializedVariableName, SemanticModel semanticModel, int position)
{
var spacePart = new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, " ");
var parts = new List<SymbolDisplayPart>();
parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, "\r\nUsage:\r\n "));
var returnType = symbol.InferAwaitableReturnType(semanticModel, position);
returnType = returnType != null && returnType.SpecialType != SpecialType.System_Void ? returnType : null;
if (returnType != null)
{
if (semanticModel.Language == "C#")
{
parts.AddRange(returnType.ToMinimalDisplayParts(semanticModel, position));
parts.Add(spacePart);
parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.LocalName, null, initializedVariableName));
}
else
{
parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "Dim"));
parts.Add(spacePart);
parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.LocalName, null, initializedVariableName));
parts.Add(spacePart);
parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "as"));