-
Notifications
You must be signed in to change notification settings - Fork 4k
/
CSharpSemanticFactsService.cs
405 lines (332 loc) · 19.5 KB
/
CSharpSemanticFactsService.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
// 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.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal class CSharpSemanticFactsService : AbstractSemanticFactsService, ISemanticFactsService
{
internal static readonly CSharpSemanticFactsService Instance = new CSharpSemanticFactsService();
protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance;
private CSharpSemanticFactsService()
{
}
protected override SyntaxToken ToIdentifierToken(string identifier)
=> identifier.ToIdentifierToken();
protected override IEnumerable<ISymbol> GetCollidableSymbols(SemanticModel semanticModel, SyntaxNode location, SyntaxNode container, CancellationToken cancellationToken)
{
// Get all the symbols visible to the current location.
var visibleSymbols = semanticModel.LookupSymbols(location.SpanStart);
// Some symbols in the enclosing block could cause conflicts even if they are not available at the location.
// E.g. symbols inside if statements / try catch statements.
var symbolsInBlock = semanticModel.GetExistingSymbols(container, cancellationToken,
descendInto: n => ShouldDescendInto(n));
return symbolsInBlock.Concat(visibleSymbols);
// Walk through the enclosing block symbols, but avoid exploring local functions
// a) Visible symbols from the local function would be returned by LookupSymbols
// (e.g. location is inside a local function, the local function method name).
// b) Symbols declared inside the local function do not cause collisions with symbols declared outside them, so avoid considering those symbols.
// Exclude lambdas as well when the language version is C# 8 or higher because symbols declared inside no longer collide with outer variables.
bool ShouldDescendInto(SyntaxNode node)
{
var isLanguageVersionGreaterOrEqualToCSharp8 = (semanticModel.Compilation as CSharpCompilation)?.LanguageVersion >= LanguageVersion.CSharp8;
return isLanguageVersionGreaterOrEqualToCSharp8 ? !SyntaxFacts.IsAnonymousOrLocalFunction(node) : !SyntaxFacts.IsLocalFunctionStatement(node);
}
}
public bool SupportsImplicitInterfaceImplementation => true;
public bool ExposesAnonymousFunctionParameterNames => false;
public bool IsExpressionContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsExpressionContext(
position,
semanticModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken),
attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel);
}
public bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol expressionTypeOpt, CancellationToken cancellationToken)
=> node.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken);
public bool IsStatementContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsStatementContext(
position, semanticModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken), cancellationToken);
}
public bool IsTypeContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.SyntaxTree.IsTypeContext(position, cancellationToken, semanticModel);
public bool IsNamespaceContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.SyntaxTree.IsNamespaceContext(position, cancellationToken, semanticModel);
public bool IsNamespaceDeclarationNameContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.SyntaxTree.IsNamespaceDeclarationNameContext(position, cancellationToken);
public bool IsTypeDeclarationContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsTypeDeclarationContext(
position, semanticModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken), cancellationToken);
}
public bool IsMemberDeclarationContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsMemberDeclarationContext(
position, semanticModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken));
}
public bool IsPreProcessorDirectiveContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.SyntaxTree.IsPreProcessorDirectiveContext(
position, semanticModel.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken);
}
public bool IsGlobalStatementContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.SyntaxTree.IsGlobalStatementContext(position, cancellationToken);
public bool IsLabelContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.SyntaxTree.IsLabelContext(position, cancellationToken);
public bool IsAttributeNameContext(SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.SyntaxTree.IsAttributeNameContext(position, cancellationToken);
public bool IsWrittenTo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
=> (node as ExpressionSyntax).IsWrittenTo();
public bool IsOnlyWrittenTo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
=> (node as ExpressionSyntax).IsOnlyWrittenTo();
public bool IsInOutContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
=> (node as ExpressionSyntax).IsInOutContext();
public bool IsInRefContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
=> (node as ExpressionSyntax).IsInRefContext();
public bool IsInInContext(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
=> (node as ExpressionSyntax).IsInInContext();
public bool CanReplaceWithRValue(SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken)
=> (expression as ExpressionSyntax).CanReplaceWithRValue(semanticModel, cancellationToken);
public string GenerateNameForExpression(SemanticModel semanticModel, SyntaxNode expression, bool capitalize, CancellationToken cancellationToken)
=> semanticModel.GenerateNameForExpression((ExpressionSyntax)expression, capitalize, cancellationToken);
public ISymbol GetDeclaredSymbol(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
{
var location = token.GetLocation();
foreach (var ancestor in token.GetAncestors<SyntaxNode>())
{
var symbol = semanticModel.GetDeclaredSymbol(ancestor, cancellationToken);
if (symbol != null)
{
if (symbol.Locations.Contains(location))
{
return symbol;
}
// We found some symbol, but it defined something else. We're not going to have a higher node defining _another_ symbol with this token, so we can stop now.
return null;
}
// If we hit an executable statement syntax and didn't find anything yet, we can just stop now -- anything higher would be a member declaration which won't be defined by something inside a statement.
if (SyntaxFacts.IsExecutableStatement(ancestor))
{
return null;
}
}
return null;
}
public bool LastEnumValueHasInitializer(INamedTypeSymbol namedTypeSymbol)
{
var enumDecl = namedTypeSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).OfType<EnumDeclarationSyntax>().FirstOrDefault();
if (enumDecl != null)
{
var lastMember = enumDecl.Members.LastOrDefault();
if (lastMember != null)
{
return lastMember.EqualsValue != null;
}
}
return false;
}
public bool SupportsParameterizedProperties => false;
public bool TryGetSpeculativeSemanticModel(SemanticModel oldSemanticModel, SyntaxNode oldNode, SyntaxNode newNode, out SemanticModel speculativeModel)
{
Debug.Assert(oldNode.Kind() == newNode.Kind());
var model = oldSemanticModel;
if (!(oldNode is BaseMethodDeclarationSyntax oldMethod) || !(newNode is BaseMethodDeclarationSyntax newMethod) || oldMethod.Body == null)
{
speculativeModel = null;
return false;
}
var success = model.TryGetSpeculativeSemanticModelForMethodBody(oldMethod.Body.OpenBraceToken.Span.End, newMethod, out var csharpModel);
speculativeModel = csharpModel;
return success;
}
public ImmutableHashSet<string> GetAliasNameSet(SemanticModel model, CancellationToken cancellationToken)
{
var original = model.GetOriginalSemanticModel();
if (!original.SyntaxTree.HasCompilationUnitRoot)
{
return ImmutableHashSet.Create<string>();
}
var root = original.SyntaxTree.GetCompilationUnitRoot(cancellationToken);
var builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.Ordinal);
AppendAliasNames(root.Usings, builder);
AppendAliasNames(root.Members.OfType<NamespaceDeclarationSyntax>(), builder, cancellationToken);
return builder.ToImmutable();
}
private static void AppendAliasNames(SyntaxList<UsingDirectiveSyntax> usings, ImmutableHashSet<string>.Builder builder)
{
foreach (var @using in usings)
{
if (@using.Alias == null || @using.Alias.Name == null)
{
continue;
}
@using.Alias.Name.Identifier.ValueText.AppendToAliasNameSet(builder);
}
}
private void AppendAliasNames(IEnumerable<NamespaceDeclarationSyntax> namespaces, ImmutableHashSet<string>.Builder builder, CancellationToken cancellationToken)
{
foreach (var @namespace in namespaces)
{
cancellationToken.ThrowIfCancellationRequested();
AppendAliasNames(@namespace.Usings, builder);
AppendAliasNames(@namespace.Members.OfType<NamespaceDeclarationSyntax>(), builder, cancellationToken);
}
}
public ForEachSymbols GetForEachSymbols(SemanticModel semanticModel, SyntaxNode forEachStatement)
{
if (forEachStatement is CommonForEachStatementSyntax csforEachStatement)
{
var info = semanticModel.GetForEachStatementInfo(csforEachStatement);
return new ForEachSymbols(
info.GetEnumeratorMethod,
info.MoveNextMethod,
info.CurrentProperty,
info.DisposeMethod,
info.ElementType);
}
else
{
return default;
}
}
public IMethodSymbol GetGetAwaiterMethod(SemanticModel semanticModel, SyntaxNode node)
{
if (node is AwaitExpressionSyntax awaitExpression)
{
var info = semanticModel.GetAwaitExpressionInfo(awaitExpression);
return info.GetAwaiterMethod;
}
return null;
}
public ImmutableArray<IMethodSymbol> GetDeconstructionAssignmentMethods(SemanticModel semanticModel, SyntaxNode node)
{
if (node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction())
{
var builder = ArrayBuilder<IMethodSymbol>.GetInstance();
FlattenDeconstructionMethods(semanticModel.GetDeconstructionInfo(assignment), builder);
return builder.ToImmutableAndFree();
}
return ImmutableArray<IMethodSymbol>.Empty;
}
public ImmutableArray<IMethodSymbol> GetDeconstructionForEachMethods(SemanticModel semanticModel, SyntaxNode node)
{
if (node is ForEachVariableStatementSyntax @foreach)
{
var builder = ArrayBuilder<IMethodSymbol>.GetInstance();
FlattenDeconstructionMethods(semanticModel.GetDeconstructionInfo(@foreach), builder);
return builder.ToImmutableAndFree();
}
return ImmutableArray<IMethodSymbol>.Empty;
}
private static void FlattenDeconstructionMethods(DeconstructionInfo deconstruction, ArrayBuilder<IMethodSymbol> builder)
{
var method = deconstruction.Method;
if (method != null)
{
builder.Add(method);
}
foreach (var nested in deconstruction.Nested)
{
FlattenDeconstructionMethods(nested, builder);
}
}
public bool IsPartial(ITypeSymbol typeSymbol, CancellationToken cancellationToken)
{
var syntaxRefs = typeSymbol.DeclaringSyntaxReferences;
return syntaxRefs.Any(n => ((BaseTypeDeclarationSyntax)n.GetSyntax(cancellationToken)).Modifiers.Any(SyntaxKind.PartialKeyword));
}
public IEnumerable<ISymbol> GetDeclaredSymbols(
SemanticModel semanticModel, SyntaxNode memberDeclaration, CancellationToken cancellationToken)
{
if (memberDeclaration is FieldDeclarationSyntax field)
{
return field.Declaration.Variables.Select(
v => semanticModel.GetDeclaredSymbol(v, cancellationToken));
}
return SpecializedCollections.SingletonEnumerable(
semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken));
}
public IParameterSymbol FindParameterForArgument(SemanticModel semanticModel, SyntaxNode argumentNode, CancellationToken cancellationToken)
=> ((ArgumentSyntax)argumentNode).DetermineParameter(semanticModel, allowParams: false, cancellationToken);
public ImmutableArray<ISymbol> GetBestOrAllSymbols(SemanticModel semanticModel, SyntaxNode node, SyntaxToken token, CancellationToken cancellationToken)
{
if (node == null)
return ImmutableArray<ISymbol>.Empty;
return node switch
{
AssignmentExpressionSyntax _ when token.Kind() == SyntaxKind.EqualsToken => GetDeconstructionAssignmentMethods(semanticModel, node).As<ISymbol>(),
ForEachVariableStatementSyntax _ when token.Kind() == SyntaxKind.InKeyword => GetDeconstructionForEachMethods(semanticModel, node).As<ISymbol>(),
_ => GetSymbolInfo(semanticModel, node, token, cancellationToken).GetBestOrAllSymbols(),
};
}
private static SymbolInfo GetSymbolInfo(SemanticModel semanticModel, SyntaxNode node, SyntaxToken token, CancellationToken cancellationToken)
{
switch (node)
{
case OrderByClauseSyntax orderByClauseSyntax:
if (token.Kind() == SyntaxKind.CommaToken)
{
// Returning SymbolInfo for a comma token is the last resort
// in an order by clause if no other tokens to bind to a are present.
// See also the proposal at https://github.com/dotnet/roslyn/issues/23394
var separators = orderByClauseSyntax.Orderings.GetSeparators().ToImmutableList();
var index = separators.IndexOf(token);
if (index >= 0 && (index + 1) < orderByClauseSyntax.Orderings.Count)
{
var ordering = orderByClauseSyntax.Orderings[index + 1];
if (ordering.AscendingOrDescendingKeyword.Kind() == SyntaxKind.None)
{
return semanticModel.GetSymbolInfo(ordering, cancellationToken);
}
}
}
else if (orderByClauseSyntax.Orderings[0].AscendingOrDescendingKeyword.Kind() == SyntaxKind.None)
{
// The first ordering is displayed on the "orderby" keyword itself if there isn't a
// ascending/descending keyword.
return semanticModel.GetSymbolInfo(orderByClauseSyntax.Orderings[0], cancellationToken);
}
return default;
case QueryClauseSyntax queryClauseSyntax:
var queryInfo = semanticModel.GetQueryClauseInfo(queryClauseSyntax, cancellationToken);
var hasCastInfo = queryInfo.CastInfo.Symbol != null;
var hasOperationInfo = queryInfo.OperationInfo.Symbol != null;
if (hasCastInfo && hasOperationInfo)
{
// In some cases a single clause binds to more than one method. In those cases
// the tokens in the clause determine which of the two SymbolInfos are returned.
// See also the proposal at https://github.com/dotnet/roslyn/issues/23394
return token.IsKind(SyntaxKind.InKeyword) ? queryInfo.CastInfo : queryInfo.OperationInfo;
}
if (hasCastInfo)
{
return queryInfo.CastInfo;
}
return queryInfo.OperationInfo;
}
//Only in the orderby clause a comma can bind to a symbol.
if (token.IsKind(SyntaxKind.CommaToken))
{
return default;
}
return semanticModel.GetSymbolInfo(node, cancellationToken);
}
public bool IsInsideNameOfExpression(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken)
=> (node as ExpressionSyntax).IsInsideNameOfExpression(semanticModel, cancellationToken);
}
}