-
Notifications
You must be signed in to change notification settings - Fork 4k
/
CSharpSemanticModel.cs
5329 lines (4677 loc) · 273 KB
/
CSharpSemanticModel.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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Allows asking semantic questions about a tree of syntax nodes in a Compilation. Typically,
/// an instance is obtained by a call to <see cref="Compilation"/>.<see
/// cref="Compilation.GetSemanticModel(SyntaxTree, bool)"/>.
/// </summary>
/// <remarks>
/// <para>An instance of <see cref="CSharpSemanticModel"/> caches local symbols and semantic
/// information. Thus, it is much more efficient to use a single instance of <see
/// cref="CSharpSemanticModel"/> when asking multiple questions about a syntax tree, because
/// information from the first question may be reused. This also means that holding onto an
/// instance of SemanticModel for a long time may keep a significant amount of memory from being
/// garbage collected.
/// </para>
/// <para>
/// When an answer is a named symbol that is reachable by traversing from the root of the symbol
/// table, (that is, from an <see cref="AssemblySymbol"/> of the <see cref="Compilation"/>),
/// that symbol will be returned (i.e. the returned value will be reference-equal to one
/// reachable from the root of the symbol table). Symbols representing entities without names
/// (e.g. array-of-int) may or may not exhibit reference equality. However, some named symbols
/// (such as local variables) are not reachable from the root. These symbols are visible as
/// answers to semantic questions. When the same SemanticModel object is used, the answers
/// exhibit reference-equality.
/// </para>
/// </remarks>
internal abstract class CSharpSemanticModel : SemanticModel
{
/// <summary>
/// The compilation this object was obtained from.
/// </summary>
public new abstract CSharpCompilation Compilation { get; }
/// <summary>
/// The root node of the syntax tree that this binding is based on.
/// </summary>
internal new abstract CSharpSyntaxNode Root { get; }
// Is this node one that could be successfully interrogated by GetSymbolInfo/GetTypeInfo/GetMemberGroup/GetConstantValue?
// WARN: If isSpeculative is true, then don't look at .Parent - there might not be one.
internal static bool CanGetSemanticInfo(CSharpSyntaxNode node, bool allowNamedArgumentName = false, bool isSpeculative = false)
{
Debug.Assert(node != null);
if (!isSpeculative && IsInStructuredTriviaOtherThanCrefOrNameAttribute(node))
{
return false;
}
switch (node.Kind())
{
case SyntaxKind.CollectionInitializerExpression:
case SyntaxKind.ObjectInitializerExpression:
// new CollectionClass() { 1, 2, 3 }
// ~~~~~~~~~~~
// OR
//
// new ObjectClass() { field = 1, prop = 2 }
// ~~~~~~~~~~~~~~~~~~~~~~~
// CollectionInitializerExpression and ObjectInitializerExpression are not really expressions in the language sense.
// We do not allow getting the semantic info for these syntax nodes. However, we do allow getting semantic info
// for each of the individual initializer elements or member assignments.
return false;
case SyntaxKind.ComplexElementInitializerExpression:
// new Collection { 1, {2, 3} }
// ~~~~~~
// ComplexElementInitializerExpression are also not true expressions in the language sense, so we disallow getting the
// semantic info for it. However, we may be interested in getting the semantic info for the compiler generated Add
// method invoked with initializer expressions as arguments. Roslyn bug 11987 tracks this work item.
return false;
case SyntaxKind.IdentifierName:
// The alias of a using directive is a declaration, so there is no semantic info - use GetDeclaredSymbol instead.
if (!isSpeculative && node.Parent != null && node.Parent.Kind() == SyntaxKind.NameEquals && node.Parent.Parent.Kind() == SyntaxKind.UsingDirective)
{
return false;
}
goto default;
case SyntaxKind.OmittedTypeArgument:
case SyntaxKind.RefExpression:
case SyntaxKind.RefType:
// These are just placeholders and are not separately meaningful.
return false;
default:
// If we are being asked for binding info on a "missing" syntax node
// then there's no point in doing any work at all. For example, the user might
// have something like "class C { [] void M() {} }". The caller might obtain
// the attribute declaration syntax and then attempt to ask for type information
// about the contents of the attribute. But the parser has recovered from the
// missing attribute type and filled in a "missing" node in its place. There's
// nothing we can do with that, so let's not allow it.
if (node.IsMissing)
{
return false;
}
return
(node is ExpressionSyntax && (isSpeculative || allowNamedArgumentName || !SyntaxFacts.IsNamedArgumentName(node))) ||
(node is ConstructorInitializerSyntax) ||
(node is PrimaryConstructorBaseTypeSyntax) ||
(node is AttributeSyntax) ||
(node is CrefSyntax);
}
}
#region Abstract worker methods
/// <summary>
/// Gets symbol information about a syntax node. This is overridden by various specializations of SemanticModel.
/// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named
/// argument nodes have been handled.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="options">Options to control behavior.</param>
/// <param name="cancellationToken">The cancellation token.</param>
internal abstract SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets symbol information about the 'Add' method corresponding to an expression syntax <paramref name="node"/> within collection initializer.
/// This is the worker function that is overridden in various derived kinds of Semantic Models. It can assume that
/// CheckSyntaxNode has already been called and the <paramref name="node"/> is in the right place in the syntax tree.
/// </summary>
internal abstract SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets type information about a syntax node. This is overridden by various specializations of SemanticModel.
/// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named
/// argument nodes have been handled.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">The cancellation token.</param>
internal abstract CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Binds the provided expression in the given context.
/// </summary>
/// <param name="position">The position to bind at.</param>
/// <param name="expression">The expression to bind</param>
/// <param name="bindingOption">How to speculatively bind the given expression. If this is <see cref="SpeculativeBindingOption.BindAsTypeOrNamespace"/>
/// then the provided expression should be a <see cref="TypeSyntax"/>.</param>
/// <param name="binder">The binder that was used to bind the given syntax.</param>
/// <param name="crefSymbols">The symbols used in a cref. If this is not default, then the return is null.</param>
/// <returns>The expression that was bound. If <paramref name="crefSymbols"/> is not default, this is null.</returns>
internal abstract BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray<Symbol> crefSymbols);
/// <summary>
/// Gets a list of method or indexed property symbols for a syntax node. This is overridden by various specializations of SemanticModel.
/// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named
/// argument nodes have been handled.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="options"></param>
/// <param name="cancellationToken">The cancellation token.</param>
internal abstract ImmutableArray<Symbol> GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a list of indexer symbols for a syntax node. This is overridden by various specializations of SemanticModel.
/// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named
/// argument nodes have been handled.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="options"></param>
/// <param name="cancellationToken">The cancellation token.</param>
internal abstract ImmutableArray<IPropertySymbol> GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the constant value for a syntax node. This is overridden by various specializations of SemanticModel.
/// It can assume that CheckSyntaxNode and CanGetSemanticInfo have already been called, as well as that named
/// argument nodes have been handled.
/// </summary>
/// <param name="node">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">The cancellation token.</param>
internal abstract Optional<object> GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken));
#endregion Abstract worker methods
#region Helpers for speculative binding
internal Binder GetSpeculativeBinder(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption)
{
Debug.Assert(expression != null);
position = CheckAndAdjustPosition(position);
if (bindingOption == SpeculativeBindingOption.BindAsTypeOrNamespace)
{
if (!(expression is TypeSyntax))
{
return null;
}
}
Binder binder = this.GetEnclosingBinder(position);
if (binder == null)
{
return null;
}
if (bindingOption == SpeculativeBindingOption.BindAsTypeOrNamespace && IsInTypeofExpression(position))
{
// If position is within a typeof expression, GetEnclosingBinder may return a
// TypeofBinder. However, this TypeofBinder will have been constructed with the
// actual syntax of the typeof argument and we want to use the given syntax.
// Wrap the binder in another TypeofBinder to overrule its description of where
// unbound generic types are allowed.
//Debug.Assert(binder is TypeofBinder); // Expectation, not requirement.
binder = new TypeofBinder(expression, binder);
}
binder = new WithNullableContextBinder(SyntaxTree, position, binder);
return new ExecutableCodeBinder(expression, binder.ContainingMemberOrLambda, binder).GetBinder(expression);
}
private Binder GetSpeculativeBinderForAttribute(int position, AttributeSyntax attribute)
{
position = CheckAndAdjustPositionForSpeculativeAttribute(position);
var binder = this.GetEnclosingBinder(position);
if (binder == null)
{
return null;
}
return new ExecutableCodeBinder(attribute, binder.ContainingMemberOrLambda, binder).GetBinder(attribute);
}
private static BoundExpression GetSpeculativelyBoundExpressionHelper(Binder binder, ExpressionSyntax expression, SpeculativeBindingOption bindingOption)
{
Debug.Assert(binder != null);
Debug.Assert(binder.IsSemanticModelBinder);
Debug.Assert(expression != null);
Debug.Assert(bindingOption != SpeculativeBindingOption.BindAsTypeOrNamespace || expression is TypeSyntax);
BoundExpression boundNode;
if (bindingOption == SpeculativeBindingOption.BindAsTypeOrNamespace || binder.Flags.Includes(BinderFlags.CrefParameterOrReturnType))
{
boundNode = binder.BindNamespaceOrType(expression, BindingDiagnosticBag.Discarded);
}
else
{
Debug.Assert(bindingOption == SpeculativeBindingOption.BindAsExpression);
boundNode = binder.BindExpression(expression, BindingDiagnosticBag.Discarded);
}
return boundNode;
}
/// <summary>
/// Bind the given expression speculatively at the given position, and return back
/// the resulting bound node. May return null in some error cases.
/// </summary>
/// <remarks>
/// Keep in sync with Binder.BindCrefParameterOrReturnType.
/// </remarks>
protected BoundExpression GetSpeculativelyBoundExpressionWithoutNullability(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray<Symbol> crefSymbols)
{
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
crefSymbols = default(ImmutableArray<Symbol>);
expression = SyntaxFactory.GetStandaloneExpression(expression);
binder = this.GetSpeculativeBinder(position, expression, bindingOption);
if (binder == null)
{
return null;
}
if (binder.Flags.Includes(BinderFlags.CrefParameterOrReturnType))
{
crefSymbols = ImmutableArray.Create<Symbol>(binder.BindType(expression, BindingDiagnosticBag.Discarded).Type);
return null;
}
else if (binder.InCref)
{
if (expression.IsKind(SyntaxKind.QualifiedName))
{
var qualified = (QualifiedNameSyntax)expression;
var crefWrapper = SyntaxFactory.QualifiedCref(qualified.Left, SyntaxFactory.NameMemberCref(qualified.Right));
crefSymbols = BindCref(crefWrapper, binder);
}
else if (expression is TypeSyntax typeSyntax)
{
var crefWrapper = typeSyntax is PredefinedTypeSyntax ?
(CrefSyntax)SyntaxFactory.TypeCref(typeSyntax) :
SyntaxFactory.NameMemberCref(typeSyntax);
crefSymbols = BindCref(crefWrapper, binder);
}
return null;
}
var boundNode = GetSpeculativelyBoundExpressionHelper(binder, expression, bindingOption);
return boundNode;
}
internal static ImmutableArray<Symbol> BindCref(CrefSyntax crefSyntax, Binder binder)
{
Symbol unusedAmbiguityWinner;
var symbols = binder.BindCref(crefSyntax, out unusedAmbiguityWinner, BindingDiagnosticBag.Discarded);
return symbols;
}
internal SymbolInfo GetCrefSymbolInfo(int position, CrefSyntax crefSyntax, SymbolInfoOptions options, bool hasParameterList)
{
var binder = this.GetEnclosingBinder(position);
if (binder?.InCref == true)
{
ImmutableArray<Symbol> symbols = BindCref(crefSyntax, binder);
return GetCrefSymbolInfo(symbols, options, hasParameterList);
}
return SymbolInfo.None;
}
internal static bool HasParameterList(CrefSyntax crefSyntax)
{
while (crefSyntax.Kind() == SyntaxKind.QualifiedCref)
{
crefSyntax = ((QualifiedCrefSyntax)crefSyntax).Member;
}
switch (crefSyntax.Kind())
{
case SyntaxKind.NameMemberCref:
return ((NameMemberCrefSyntax)crefSyntax).Parameters != null;
case SyntaxKind.IndexerMemberCref:
return ((IndexerMemberCrefSyntax)crefSyntax).Parameters != null;
case SyntaxKind.OperatorMemberCref:
return ((OperatorMemberCrefSyntax)crefSyntax).Parameters != null;
case SyntaxKind.ConversionOperatorMemberCref:
return ((ConversionOperatorMemberCrefSyntax)crefSyntax).Parameters != null;
}
return false;
}
private static SymbolInfo GetCrefSymbolInfo(ImmutableArray<Symbol> symbols, SymbolInfoOptions options, bool hasParameterList)
{
switch (symbols.Length)
{
case 0:
return SymbolInfo.None;
case 1:
// Might have to expand an ExtendedErrorTypeSymbol into multiple candidates.
return GetSymbolInfoForSymbol(symbols[0], options);
default:
if ((options & SymbolInfoOptions.ResolveAliases) == SymbolInfoOptions.ResolveAliases)
{
symbols = UnwrapAliases(symbols);
}
LookupResultKind resultKind = LookupResultKind.Ambiguous;
// The boundary between Ambiguous and OverloadResolutionFailure is let clear-cut for crefs.
// We'll say that overload resolution failed if the syntax has a parameter list and if
// all of the candidates have the same kind.
SymbolKind firstCandidateKind = symbols[0].Kind;
if (hasParameterList && symbols.All(s => s.Kind == firstCandidateKind))
{
resultKind = LookupResultKind.OverloadResolutionFailure;
}
return SymbolInfoFactory.Create(symbols, resultKind, isDynamic: false);
}
}
/// <summary>
/// Bind the given attribute speculatively at the given position, and return back
/// the resulting bound node. May return null in some error cases.
/// </summary>
private BoundAttribute GetSpeculativelyBoundAttribute(int position, AttributeSyntax attribute, out Binder binder)
{
if (attribute == null)
{
throw new ArgumentNullException(nameof(attribute));
}
binder = this.GetSpeculativeBinderForAttribute(position, attribute);
if (binder == null)
{
return null;
}
AliasSymbol aliasOpt; // not needed.
NamedTypeSymbol attributeType = (NamedTypeSymbol)binder.BindType(attribute.Name, BindingDiagnosticBag.Discarded, out aliasOpt).Type;
var boundNode = new ExecutableCodeBinder(attribute, binder.ContainingMemberOrLambda, binder).BindAttribute(attribute, attributeType, BindingDiagnosticBag.Discarded);
return boundNode;
}
// When speculatively binding an attribute, we have to use the name lookup rules for an attribute,
// even if the position isn't within an attribute. For example:
// class C {
// class DAttribute: Attribute {}
// }
//
// If we speculatively bind the attribute "D" with position at the beginning of "class C", it should
// bind to DAttribute.
//
// But GetBinderForPosition won't do that; it only handles the case where position is inside an attribute.
// This function adds a special case: if the position (after first adjustment) is at the exact beginning
// of a type or method, the position is adjusted so the right binder is chosen to get the right things
// in scope.
private int CheckAndAdjustPositionForSpeculativeAttribute(int position)
{
position = CheckAndAdjustPosition(position);
SyntaxToken token = Root.FindToken(position);
if (position == 0 && position != token.SpanStart)
return position;
CSharpSyntaxNode node = (CSharpSyntaxNode)token.Parent;
if (position == node.SpanStart)
{
// There are two cases where the binder chosen for a position at the beginning of a symbol
// is incorrect for binding an attribute:
//
// For a type, the binder should be the one that is used for the interior of the type, where
// the types members (and type parameters) are in scope. We adjust the position to the "{" to get
// that binder.
//
// For a generic method, the binder should not include the type parameters. We adjust the position to
// the method name to get that binder.
if (node is BaseTypeDeclarationSyntax typeDecl)
{
// We're at the beginning of a type declaration. We want the members to be in scope for attributes,
// so use the open brace token.
position = typeDecl.OpenBraceToken.SpanStart;
}
var methodDecl = node.FirstAncestorOrSelf<MethodDeclarationSyntax>();
if (methodDecl?.SpanStart == position)
{
// We're at the beginning of a method declaration. We want the type parameters to NOT be in scope.
position = methodDecl.Identifier.SpanStart;
}
}
return position;
}
#endregion Helpers for speculative binding
protected override IOperation GetOperationCore(SyntaxNode node, CancellationToken cancellationToken)
{
var csnode = (CSharpSyntaxNode)node;
CheckSyntaxNode(csnode);
return this.GetOperationWorker(csnode, cancellationToken);
}
internal virtual IOperation GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken)
{
return null;
}
#region GetSymbolInfo
/// <summary>
/// Gets the semantic information for an ordering clause in an orderby query clause.
/// </summary>
public abstract SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the semantic information associated with a select or group clause.
/// </summary>
public abstract SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the SymbolInfo for the Deconstruct method used for a deconstruction pattern clause, if any.
/// </summary>
public SymbolInfo GetSymbolInfo(PositionalPatternClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(node);
return this.GetSymbolInfoWorker(node, SymbolInfoOptions.DefaultOptions, cancellationToken);
}
/// <summary>
/// Returns what symbol(s), if any, the given expression syntax bound to in the program.
///
/// An AliasSymbol will never be returned by this method. What the alias refers to will be
/// returned instead. To get information about aliases, call GetAliasInfo.
///
/// If binding the type name C in the expression "new C(...)" the actual constructor bound to
/// will be returned (or all constructor if overload resolution failed). This occurs as long as C
/// unambiguously binds to a single type that has a constructor. If C ambiguously binds to multiple
/// types, or C binds to a static class, then type(s) are returned.
/// </summary>
public SymbolInfo GetSymbolInfo(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(expression);
if (!CanGetSemanticInfo(expression, allowNamedArgumentName: true))
{
return SymbolInfo.None;
}
else if (SyntaxFacts.IsNamedArgumentName(expression))
{
// Named arguments handled in special way.
return this.GetNamedArgumentSymbolInfo((IdentifierNameSyntax)expression, cancellationToken);
}
else if (SyntaxFacts.IsDeclarationExpressionType(expression, out DeclarationExpressionSyntax parent))
{
switch (parent.Designation.Kind())
{
case SyntaxKind.SingleVariableDesignation:
return GetSymbolInfoFromSymbolOrNone(TypeFromVariable((SingleVariableDesignationSyntax)parent.Designation, cancellationToken).Type);
case SyntaxKind.DiscardDesignation:
return GetSymbolInfoFromSymbolOrNone(GetTypeInfoWorker(parent, cancellationToken).Type.GetPublicSymbol());
case SyntaxKind.ParenthesizedVariableDesignation:
if (((TypeSyntax)expression).IsVar)
{
return SymbolInfo.None;
}
break;
}
}
else if (expression is DeclarationExpressionSyntax declaration)
{
if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation)
{
return SymbolInfo.None;
}
var symbol = GetDeclaredSymbol((SingleVariableDesignationSyntax)declaration.Designation, cancellationToken);
if ((object)symbol == null)
{
return SymbolInfo.None;
}
return new SymbolInfo(symbol);
}
return this.GetSymbolInfoWorker(expression, SymbolInfoOptions.DefaultOptions, cancellationToken);
}
private static SymbolInfo GetSymbolInfoFromSymbolOrNone(ITypeSymbol type)
{
if (type?.Kind != SymbolKind.ErrorType)
{
return new SymbolInfo(type);
}
return SymbolInfo.None;
}
/// <summary>
/// Given a variable designation (typically in the left-hand-side of a deconstruction declaration statement),
/// figure out its type by looking at the declared symbol of the corresponding variable.
/// </summary>
private (ITypeSymbol Type, CodeAnalysis.NullableAnnotation Annotation) TypeFromVariable(SingleVariableDesignationSyntax variableDesignation, CancellationToken cancellationToken)
{
var variable = GetDeclaredSymbol(variableDesignation, cancellationToken);
switch (variable)
{
case ILocalSymbol local:
return (local.Type, local.NullableAnnotation);
case IFieldSymbol field:
return (field.Type, field.NullableAnnotation);
}
return default;
}
/// <summary>
/// Returns what 'Add' method symbol(s), if any, corresponds to the given expression syntax
/// within <see cref="BaseObjectCreationExpressionSyntax.Initializer"/>.
/// </summary>
public SymbolInfo GetCollectionInitializerSymbolInfo(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(expression);
if (expression.Parent != null && expression.Parent.Kind() == SyntaxKind.CollectionInitializerExpression)
{
// Find containing object creation expression
InitializerExpressionSyntax initializer = (InitializerExpressionSyntax)expression.Parent;
// Skip containing object initializers
while (initializer.Parent != null &&
initializer.Parent.Kind() == SyntaxKind.SimpleAssignmentExpression &&
((AssignmentExpressionSyntax)initializer.Parent).Right == initializer &&
initializer.Parent.Parent != null &&
initializer.Parent.Parent.Kind() == SyntaxKind.ObjectInitializerExpression)
{
initializer = (InitializerExpressionSyntax)initializer.Parent.Parent;
}
if (initializer.Parent is BaseObjectCreationExpressionSyntax objectCreation &&
objectCreation.Initializer == initializer &&
CanGetSemanticInfo(objectCreation, allowNamedArgumentName: false))
{
return GetCollectionInitializerSymbolInfoWorker((InitializerExpressionSyntax)expression.Parent, expression, cancellationToken);
}
}
return SymbolInfo.None;
}
/// <summary>
/// Returns what symbol(s), if any, the given constructor initializer syntax bound to in the program.
/// </summary>
/// <param name="constructorInitializer">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public SymbolInfo GetSymbolInfo(ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(constructorInitializer);
return CanGetSemanticInfo(constructorInitializer)
? GetSymbolInfoWorker(constructorInitializer, SymbolInfoOptions.DefaultOptions, cancellationToken)
: SymbolInfo.None;
}
/// <summary>
/// Returns what symbol(s), if any, the given constructor initializer syntax bound to in the program.
/// </summary>
/// <param name="constructorInitializer">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public SymbolInfo GetSymbolInfo(PrimaryConstructorBaseTypeSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(constructorInitializer);
return CanGetSemanticInfo(constructorInitializer)
? GetSymbolInfoWorker(constructorInitializer, SymbolInfoOptions.DefaultOptions, cancellationToken)
: SymbolInfo.None;
}
/// <summary>
/// Returns what symbol(s), if any, the given attribute syntax bound to in the program.
/// </summary>
/// <param name="attributeSyntax">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public SymbolInfo GetSymbolInfo(AttributeSyntax attributeSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(attributeSyntax);
return CanGetSemanticInfo(attributeSyntax)
? GetSymbolInfoWorker(attributeSyntax, SymbolInfoOptions.DefaultOptions, cancellationToken)
: SymbolInfo.None;
}
/// <summary>
/// Gets the semantic information associated with a documentation comment cref.
/// </summary>
public SymbolInfo GetSymbolInfo(CrefSyntax crefSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(crefSyntax);
return CanGetSemanticInfo(crefSyntax)
? GetSymbolInfoWorker(crefSyntax, SymbolInfoOptions.DefaultOptions, cancellationToken)
: SymbolInfo.None;
}
/// <summary>
/// Binds the expression in the context of the specified location and gets symbol information.
/// This method is used to get symbol information about an expression that did not actually
/// appear in the source code.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and
/// accessibility. This character position must be within the FullSpan of the Root syntax
/// node in this SemanticModel.
/// </param>
/// <param name="expression">A syntax node that represents a parsed expression. This syntax
/// node need not and typically does not appear in the source code referred to by the
/// SemanticModel instance.</param>
/// <param name="bindingOption">Indicates whether to binding the expression as a full expressions,
/// or as a type or namespace. If SpeculativeBindingOption.BindAsTypeOrNamespace is supplied, then
/// expression should derive from TypeSyntax.</param>
/// <returns>The symbol information for the topmost node of the expression.</returns>
/// <remarks>
/// The passed in expression is interpreted as a stand-alone expression, as if it
/// appeared by itself somewhere within the scope that encloses "position".
///
/// <paramref name="bindingOption"/> is ignored if <paramref name="position"/> is within a documentation
/// comment cref attribute value.
/// </remarks>
public SymbolInfo GetSpeculativeSymbolInfo(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption)
{
if (!CanGetSemanticInfo(expression, isSpeculative: true)) return SymbolInfo.None;
Binder binder;
ImmutableArray<Symbol> crefSymbols;
BoundNode boundNode = GetSpeculativelyBoundExpression(position, expression, bindingOption, out binder, out crefSymbols); //calls CheckAndAdjustPosition
Debug.Assert(boundNode == null || crefSymbols.IsDefault);
if (boundNode == null)
{
return crefSymbols.IsDefault ? SymbolInfo.None : GetCrefSymbolInfo(crefSymbols, SymbolInfoOptions.DefaultOptions, hasParameterList: false);
}
var symbolInfo = this.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, boundNode, boundNode, boundNodeForSyntacticParent: null, binderOpt: binder);
return symbolInfo;
}
/// <summary>
/// Bind the attribute in the context of the specified location and get semantic information
/// such as type, symbols and diagnostics. This method is used to get semantic information about an attribute
/// that did not actually appear in the source code.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and accessibility. This
/// character position must be within the FullSpan of the Root syntax node in this SemanticModel. In order to obtain
/// the correct scoping rules for the attribute, position should be the Start position of the Span of the symbol that
/// the attribute is being applied to.
/// </param>
/// <param name="attribute">A syntax node that represents a parsed attribute. This syntax node
/// need not and typically does not appear in the source code referred to SemanticModel instance.</param>
/// <returns>The semantic information for the topmost node of the attribute.</returns>
public SymbolInfo GetSpeculativeSymbolInfo(int position, AttributeSyntax attribute)
{
Debug.Assert(CanGetSemanticInfo(attribute, isSpeculative: true));
Binder binder;
BoundNode boundNode = GetSpeculativelyBoundAttribute(position, attribute, out binder); //calls CheckAndAdjustPosition
if (boundNode == null)
return SymbolInfo.None;
var symbolInfo = this.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, boundNode, boundNode, boundNodeForSyntacticParent: null, binderOpt: binder);
return symbolInfo;
}
/// <summary>
/// Bind the constructor initializer in the context of the specified location and get semantic information
/// such as type, symbols and diagnostics. This method is used to get semantic information about a constructor
/// initializer that did not actually appear in the source code.
///
/// NOTE: This will only work in locations where there is already a constructor initializer.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and accessibility. This
/// character position must be within the FullSpan of the Root syntax node in this SemanticModel.
/// Furthermore, it must be within the span of an existing constructor initializer.
/// </param>
/// <param name="constructorInitializer">A syntax node that represents a parsed constructor initializer. This syntax node
/// need not and typically does not appear in the source code referred to SemanticModel instance.</param>
/// <returns>The semantic information for the topmost node of the constructor initializer.</returns>
public SymbolInfo GetSpeculativeSymbolInfo(int position, ConstructorInitializerSyntax constructorInitializer)
{
Debug.Assert(CanGetSemanticInfo(constructorInitializer, isSpeculative: true));
position = CheckAndAdjustPosition(position);
if (constructorInitializer == null)
{
throw new ArgumentNullException(nameof(constructorInitializer));
}
// NOTE: since we're going to be depending on a MemberModel to do the binding for us,
// we need to find a constructor initializer in the tree of this semantic model.
// NOTE: This approach will not allow speculative binding of a constructor initializer
// on a constructor that didn't formerly have one.
// TODO: Should we support positions that are not in existing constructor initializers?
// If so, we will need to build up the context that would otherwise be built up by
// InitializerMemberModel.
var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<ConstructorInitializerSyntax>().FirstOrDefault();
if (existingConstructorInitializer == null)
{
return SymbolInfo.None;
}
MemberSemanticModel memberModel = GetMemberModel(existingConstructorInitializer);
if (memberModel == null)
{
return SymbolInfo.None;
}
var binder = memberModel.GetEnclosingBinder(position);
if (binder != null)
{
binder = new ExecutableCodeBinder(constructorInitializer, binder.ContainingMemberOrLambda, binder);
BoundExpressionStatement bnode = binder.BindConstructorInitializer(constructorInitializer, BindingDiagnosticBag.Discarded);
var binfo = GetSymbolInfoFromBoundConstructorInitializer(memberModel, binder, bnode);
return binfo;
}
else
{
return SymbolInfo.None;
}
}
private static SymbolInfo GetSymbolInfoFromBoundConstructorInitializer(MemberSemanticModel memberModel, Binder binder, BoundExpressionStatement bnode)
{
BoundExpression expression = bnode.Expression;
while (expression is BoundSequence sequence)
{
expression = sequence.Value;
}
return memberModel.GetSymbolInfoForNode(SymbolInfoOptions.DefaultOptions, expression, expression, boundNodeForSyntacticParent: null, binderOpt: binder);
}
/// <summary>
/// Bind the constructor initializer in the context of the specified location and get semantic information
/// about symbols. This method is used to get semantic information about a constructor
/// initializer that did not actually appear in the source code.
///
/// NOTE: This will only work in locations where there is already a constructor initializer.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and accessibility. This
/// character position must be within the span of an existing constructor initializer.
/// </param>
/// <param name="constructorInitializer">A syntax node that represents a parsed constructor initializer. This syntax node
/// need not and typically does not appear in the source code referred to SemanticModel instance.</param>
/// <returns>The semantic information for the topmost node of the constructor initializer.</returns>
public SymbolInfo GetSpeculativeSymbolInfo(int position, PrimaryConstructorBaseTypeSyntax constructorInitializer)
{
Debug.Assert(CanGetSemanticInfo(constructorInitializer, isSpeculative: true));
position = CheckAndAdjustPosition(position);
if (constructorInitializer == null)
{
throw new ArgumentNullException(nameof(constructorInitializer));
}
// NOTE: since we're going to be depending on a MemberModel to do the binding for us,
// we need to find a constructor initializer in the tree of this semantic model.
// NOTE: This approach will not allow speculative binding of a constructor initializer
// on a constructor that didn't formerly have one.
// TODO: Should we support positions that are not in existing constructor initializers?
// If so, we will need to build up the context that would otherwise be built up by
// InitializerMemberModel.
var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<PrimaryConstructorBaseTypeSyntax>().FirstOrDefault();
if (existingConstructorInitializer == null)
{
return SymbolInfo.None;
}
MemberSemanticModel memberModel = GetMemberModel(existingConstructorInitializer);
if (memberModel == null)
{
return SymbolInfo.None;
}
var argumentList = existingConstructorInitializer.ArgumentList;
var binder = memberModel.GetEnclosingBinder(LookupPosition.IsBetweenTokens(position, argumentList.OpenParenToken, argumentList.CloseParenToken) ? position : argumentList.OpenParenToken.SpanStart);
if (binder != null)
{
binder = new ExecutableCodeBinder(constructorInitializer, binder.ContainingMemberOrLambda, binder);
BoundExpressionStatement bnode = binder.BindConstructorInitializer(constructorInitializer, BindingDiagnosticBag.Discarded);
SymbolInfo binfo = GetSymbolInfoFromBoundConstructorInitializer(memberModel, binder, bnode);
return binfo;
}
else
{
return SymbolInfo.None;
}
}
/// <summary>
/// Bind the cref in the context of the specified location and get semantic information
/// such as type, symbols and diagnostics. This method is used to get semantic information about a cref
/// that did not actually appear in the source code.
/// </summary>
/// <param name="position">A character position used to identify a declaration scope and accessibility. This
/// character position must be within the FullSpan of the Root syntax node in this SemanticModel. In order to obtain
/// the correct scoping rules for the cref, position should be the Start position of the Span of the original cref.
/// </param>
/// <param name="cref">A syntax node that represents a parsed cref. This syntax node
/// need not and typically does not appear in the source code referred to SemanticModel instance.</param>
/// <param name="options">SymbolInfo options.</param>
/// <returns>The semantic information for the topmost node of the cref.</returns>
public SymbolInfo GetSpeculativeSymbolInfo(int position, CrefSyntax cref, SymbolInfoOptions options = SymbolInfoOptions.DefaultOptions)
{
Debug.Assert(CanGetSemanticInfo(cref, isSpeculative: true));
position = CheckAndAdjustPosition(position);
return this.GetCrefSymbolInfo(position, cref, options, HasParameterList(cref));
}
#endregion GetSymbolInfo
#region GetTypeInfo
/// <summary>
/// Gets type information about a constructor initializer.
/// </summary>
/// <param name="constructorInitializer">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public TypeInfo GetTypeInfo(ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(constructorInitializer);
return CanGetSemanticInfo(constructorInitializer)
? GetTypeInfoWorker(constructorInitializer, cancellationToken)
: CSharpTypeInfo.None;
}
public abstract TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken));
public TypeInfo GetTypeInfo(PatternSyntax pattern, CancellationToken cancellationToken = default(CancellationToken))
{
while (pattern is ParenthesizedPatternSyntax pp)
pattern = pp.Pattern;
CheckSyntaxNode(pattern);
return GetTypeInfoWorker(pattern, cancellationToken);
}
/// <summary>
/// Gets type information about an expression.
/// </summary>
/// <param name="expression">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public TypeInfo GetTypeInfo(ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(expression);
if (!CanGetSemanticInfo(expression))
{
return CSharpTypeInfo.None;
}
else if (SyntaxFacts.IsDeclarationExpressionType(expression, out DeclarationExpressionSyntax parent))
{
switch (parent.Designation.Kind())
{
case SyntaxKind.SingleVariableDesignation:
var (declarationType, annotation) = ((ITypeSymbol, CodeAnalysis.NullableAnnotation))TypeFromVariable((SingleVariableDesignationSyntax)parent.Designation, cancellationToken);
var declarationTypeSymbol = declarationType.GetSymbol();
var nullabilityInfo = annotation.ToNullabilityInfo(declarationTypeSymbol);
return new CSharpTypeInfo(declarationTypeSymbol, declarationTypeSymbol, nullabilityInfo, nullabilityInfo, Conversion.Identity);
case SyntaxKind.DiscardDesignation:
var declarationInfo = GetTypeInfoWorker(parent, cancellationToken);
return new CSharpTypeInfo(declarationInfo.Type, declarationInfo.Type, declarationInfo.Nullability, declarationInfo.Nullability, Conversion.Identity);
case SyntaxKind.ParenthesizedVariableDesignation:
if (((TypeSyntax)expression).IsVar)
{
return CSharpTypeInfo.None;
}
break;
}
}
return GetTypeInfoWorker(expression, cancellationToken);
}
/// <summary>
/// Gets type information about an attribute.
/// </summary>
/// <param name="attributeSyntax">The syntax node to get semantic information for.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public TypeInfo GetTypeInfo(AttributeSyntax attributeSyntax, CancellationToken cancellationToken = default(CancellationToken))
{
CheckSyntaxNode(attributeSyntax);
return CanGetSemanticInfo(attributeSyntax)
? GetTypeInfoWorker(attributeSyntax, cancellationToken)
: CSharpTypeInfo.None;
}
/// <summary>
/// Gets the conversion that occurred between the expression's type and type implied by the expression's context.
/// </summary>
public Conversion GetConversion(SyntaxNode expression, CancellationToken cancellationToken = default(CancellationToken))
{
var csnode = (CSharpSyntaxNode)expression;
CheckSyntaxNode(csnode);
var info = CanGetSemanticInfo(csnode)