-
Notifications
You must be signed in to change notification settings - Fork 4k
/
CSharpSimplificationService.cs
232 lines (199 loc) · 9.86 KB
/
CSharpSimplificationService.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
// 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.Composition;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
[ExportLanguageService(typeof(ISimplificationService), LanguageNames.CSharp), Shared]
internal partial class CSharpSimplificationService : AbstractSimplificationService<ExpressionSyntax, StatementSyntax, CrefSyntax>
{
// 1. the cast simplifier should run earlier then everything else to minimize the type expressions
// 2. Extension method reducer may insert parentheses. So run it before the parentheses remover.
private static readonly ImmutableArray<AbstractReducer> s_reducers =
ImmutableArray.Create<AbstractReducer>(
new CSharpVarReducer(),
new CSharpNameReducer(),
new CSharpNullableAnnotationReducer(),
new CSharpCastReducer(),
new CSharpExtensionMethodReducer(),
new CSharpParenthesizedExpressionReducer(),
new CSharpParenthesizedPatternReducer(),
new CSharpEscapingReducer(),
new CSharpMiscellaneousReducer(),
new CSharpInferredMemberNameReducer(),
new CSharpDefaultExpressionReducer());
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpSimplificationService() : base(s_reducers)
{
}
public override SimplifierOptions DefaultOptions
=> CSharpSimplifierOptions.Default;
public override SimplifierOptions GetSimplifierOptions(AnalyzerConfigOptions options, SimplifierOptions? fallbackOptions)
=> options.GetCSharpSimplifierOptions((CSharpSimplifierOptions?)fallbackOptions);
public override SyntaxNode Expand(SyntaxNode node, SemanticModel semanticModel, SyntaxAnnotation? annotationForReplacedAliasIdentifier, Func<SyntaxNode, bool>? expandInsideNode, bool expandParameter, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Simplifier_ExpandNode, cancellationToken))
{
if (node is AttributeSyntax or
AttributeArgumentSyntax or
ConstructorInitializerSyntax or
ExpressionSyntax or
FieldDeclarationSyntax or
StatementSyntax or
CrefSyntax or
XmlNameAttributeSyntax or
TypeConstraintSyntax or
BaseTypeSyntax)
{
var rewriter = new Expander(semanticModel, expandInsideNode, expandParameter, cancellationToken, annotationForReplacedAliasIdentifier);
return rewriter.Visit(node);
}
else
{
throw new ArgumentException(CSharpWorkspaceResources.Only_attributes_constructor_initializers_expressions_or_statements_can_be_made_explicit, nameof(node));
}
}
}
public override SyntaxToken Expand(SyntaxToken token, SemanticModel semanticModel, Func<SyntaxNode, bool>? expandInsideNode, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(token.Parent);
using (Logger.LogBlock(FunctionId.Simplifier_ExpandToken, cancellationToken))
{
var rewriter = new Expander(semanticModel, expandInsideNode, false, cancellationToken);
var rewrittenToken = TryEscapeIdentifierToken(rewriter.VisitToken(token), token.Parent).WithAdditionalAnnotations(Simplifier.Annotation);
if (TryAddLeadingElasticTriviaIfNecessary(rewrittenToken, token, out var rewrittenTokenWithElasticTrivia))
{
return rewrittenTokenWithElasticTrivia;
}
return rewrittenToken;
}
}
public static SyntaxToken TryEscapeIdentifierToken(SyntaxToken syntaxToken, SyntaxNode parentOfToken)
{
// do not escape an already escaped identifier
if (syntaxToken.IsVerbatimIdentifier())
{
return syntaxToken;
}
if (SyntaxFacts.GetKeywordKind(syntaxToken.ValueText) == SyntaxKind.None && SyntaxFacts.GetContextualKeywordKind(syntaxToken.ValueText) == SyntaxKind.None)
{
return syntaxToken;
}
if (SyntaxFacts.GetContextualKeywordKind(syntaxToken.ValueText) == SyntaxKind.UnderscoreToken)
{
return syntaxToken;
}
var parent = parentOfToken.Parent;
if (parentOfToken is SimpleNameSyntax && parent.IsKind(SyntaxKind.XmlNameAttribute))
{
// do not try to escape XML name attributes
return syntaxToken;
}
// do not escape global in a namespace qualified name
if (parent.IsKind(SyntaxKind.AliasQualifiedName) &&
syntaxToken.ValueText == "global")
{
return syntaxToken;
}
// safe to escape identifier
return syntaxToken.CopyAnnotationsTo(
SyntaxFactory.VerbatimIdentifier(
syntaxToken.LeadingTrivia,
syntaxToken.ToString(),
syntaxToken.ValueText,
syntaxToken.TrailingTrivia))
.WithAdditionalAnnotations(Simplifier.Annotation);
}
public static T AppendElasticTriviaIfNecessary<T>(T rewrittenNode, T originalNode) where T : SyntaxNode
{
var firstRewrittenToken = rewrittenNode.GetFirstToken(true, false, true, true);
var firstOriginalToken = originalNode.GetFirstToken(true, false, true, true);
if (TryAddLeadingElasticTriviaIfNecessary(firstRewrittenToken, firstOriginalToken, out var rewrittenTokenWithLeadingElasticTrivia))
{
return rewrittenNode.ReplaceToken(firstRewrittenToken, rewrittenTokenWithLeadingElasticTrivia);
}
return rewrittenNode;
}
private static bool TryAddLeadingElasticTriviaIfNecessary(SyntaxToken token, SyntaxToken originalToken, out SyntaxToken tokenWithLeadingWhitespace)
{
tokenWithLeadingWhitespace = default;
if (token.HasLeadingTrivia)
{
return false;
}
var previousToken = originalToken.GetPreviousToken();
if (previousToken.HasTrailingTrivia)
{
return false;
}
tokenWithLeadingWhitespace = token.WithLeadingTrivia(SyntaxFactory.ElasticMarker).WithAdditionalAnnotations(Formatter.Annotation);
return true;
}
protected override SemanticModel GetSpeculativeSemanticModel(ref SyntaxNode nodeToSpeculate, SemanticModel originalSemanticModel, SyntaxNode originalNode)
{
var syntaxNodeToSpeculate = nodeToSpeculate;
Contract.ThrowIfNull(syntaxNodeToSpeculate);
Contract.ThrowIfFalse(SpeculationAnalyzer.CanSpeculateOnNode(nodeToSpeculate));
return SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(originalNode, syntaxNodeToSpeculate, originalSemanticModel);
}
protected override ImmutableArray<NodeOrTokenToReduce> GetNodesAndTokensToReduce(SyntaxNode root, Func<SyntaxNodeOrToken, bool> isNodeOrTokenOutsideSimplifySpans)
=> NodesAndTokensToReduceComputer.Compute(root, isNodeOrTokenOutsideSimplifySpans);
protected override bool NodeRequiresNonSpeculativeSemanticModel(SyntaxNode node)
=> false;
private const string s_CS8019_UnusedUsingDirective = "CS8019";
protected override void GetUnusedNamespaceImports(SemanticModel model, HashSet<SyntaxNode> namespaceImports, CancellationToken cancellationToken)
{
var root = model.SyntaxTree.GetRoot(cancellationToken);
var diagnostics = model.GetDiagnostics(cancellationToken: cancellationToken);
foreach (var diagnostic in diagnostics)
{
if (diagnostic.Id == s_CS8019_UnusedUsingDirective)
{
if (root.FindNode(diagnostic.Location.SourceSpan) is UsingDirectiveSyntax node)
{
namespaceImports.Add(node);
}
}
}
}
// Is the tuple on either side of a deconstruction (top-level or nested)?
private static bool IsTupleInDeconstruction(SyntaxNode tuple)
{
Debug.Assert(tuple.IsKind(SyntaxKind.TupleExpression));
var currentTuple = tuple;
do
{
var parent = currentTuple.Parent;
if (parent.IsKind(SyntaxKind.SimpleAssignmentExpression))
{
return true;
}
if (!parent.IsKind(SyntaxKind.Argument))
{
return false;
}
var grandParent = parent.Parent;
if (!grandParent.IsKind(SyntaxKind.TupleExpression))
{
return false;
}
currentTuple = grandParent;
}
while (true);
}
}
}