/
SetPositionAndRotation.cs
213 lines (151 loc) · 7.01 KB
/
SetPositionAndRotation.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
/*--------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*-------------------------------------------------------------------------------------------*/
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.Unity.Analyzers.Resources;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace Microsoft.Unity.Analyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SetPositionAndRotationAnalyzer : DiagnosticAnalyzer
{
internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
id: "UNT0022",
title: Strings.SetPositionAndRotationDiagnosticTitle,
messageFormat: Strings.SetPositionAndRotationDiagnosticMessageFormat,
category: DiagnosticCategory.Performance,
defaultSeverity: DiagnosticSeverity.Info,
isEnabledByDefault: true,
description: Strings.SetPositionAndRotationDiagnosticDescription);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
internal const string position = "position";
internal const string rotation = "rotation";
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterSyntaxNodeAction(AnalyzeAssignment, SyntaxKind.SimpleAssignmentExpression);
}
private static void AnalyzeAssignment(SyntaxNodeAnalysisContext context)
{
if (!(context.Node is AssignmentExpressionSyntax assignmentExpression))
return;
if (!IsSetPositionOrRotation(assignmentExpression, context.SemanticModel))
return;
if (context.Node.FirstAncestorOrSelf<BlockSyntax>() == null)
return;
if (context.Node.FirstAncestorOrSelf<ExpressionStatementSyntax>() == null)
return;
var block = context.Node.FirstAncestorOrSelf<BlockSyntax>();
var siblingsAndSelf = block.ChildNodes().ToImmutableArray();
var expression = context.Node.FirstAncestorOrSelf<ExpressionStatementSyntax>();
if (siblingsAndSelf.LastIndexOf(expression) == -1)
return;
var currentIndex = siblingsAndSelf.LastIndexOf(expression);
var nextIndex = currentIndex + 1;
if (nextIndex == siblingsAndSelf.Length)
return;
var statement = siblingsAndSelf[nextIndex];
if (!(statement is ExpressionStatementSyntax expressionStatement))
return;
if (!(expressionStatement.Expression is AssignmentExpressionSyntax nextAssignmentExpression))
return;
if (!IsSetPositionOrRotation(nextAssignmentExpression, context.SemanticModel))
return;
var property = GetProperty(assignmentExpression);
var nextProperty = GetProperty(nextAssignmentExpression);
if (property == nextProperty)
return;
context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation()));
}
internal static string GetProperty(AssignmentExpressionSyntax assignmentExpression)
{
if (!(assignmentExpression.Left is MemberAccessExpressionSyntax left))
return string.Empty;
return left.Name.ToString();
}
private static bool IsSetPositionOrRotation(AssignmentExpressionSyntax assignmentExpression, SemanticModel model)
{
if (!(assignmentExpression.Left is MemberAccessExpressionSyntax left))
return false;
var property = GetProperty(assignmentExpression);
if (property != position && property != rotation)
return false;
var leftSymbol = model.GetSymbolInfo(left);
if (leftSymbol.Symbol == null)
return false;
if (!(leftSymbol.Symbol is IPropertySymbol))
return false;
var leftExpressionTypeInfo = model.GetTypeInfo(left.Expression);
if (leftExpressionTypeInfo.Type == null)
return false;
return leftExpressionTypeInfo.Type.Extends(typeof(UnityEngine.Transform));
}
}
[ExportCodeFixProvider(LanguageNames.CSharp)]
public class SetPositionAndRotationCodeFix : CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(SetPositionAndRotationAnalyzer.Rule.Id);
public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
if (!(root?.FindNode(context.Span) is AssignmentExpressionSyntax expression))
return;
context.RegisterCodeFix(
CodeAction.Create(
Strings.SetPositionAndRotationCodeFixTitle,
ct => ReplaceWithInvocationAsync(context.Document, expression, "transform", "SetPositionAndRotation", ct),
expression.ToFullString()),
context.Diagnostics);
}
private static async Task<Document> ReplaceWithInvocationAsync(Document document, AssignmentExpressionSyntax assignmentExpression, string identifierName, string methodName, CancellationToken cancellationToken)
{
if (assignmentExpression.FirstAncestorOrSelf<BlockSyntax>() == null)
return document;
var block = assignmentExpression.FirstAncestorOrSelf<BlockSyntax>();
if (assignmentExpression.FirstAncestorOrSelf<ExpressionStatementSyntax>() == null)
return document;
var expression = assignmentExpression.FirstAncestorOrSelf<ExpressionStatementSyntax>();
var siblingsAndSelf = block.ChildNodes().ToImmutableArray();
if (siblingsAndSelf.LastIndexOf(expression) == -1)
return document;
var currentIndex = siblingsAndSelf.LastIndexOf(expression);
var nextIndex = currentIndex + 1;
if (nextIndex == siblingsAndSelf.Length)
return document;
var statement = siblingsAndSelf[nextIndex];
if (!(statement is ExpressionStatementSyntax expressionStatement))
return document;
if (!(expressionStatement.Expression is AssignmentExpressionSyntax nextAssignmentExpression))
return null;
var property = SetPositionAndRotationAnalyzer.GetProperty(assignmentExpression);
var arguments = new[] {Argument(assignmentExpression.Right), Argument(nextAssignmentExpression.Right)};
if (property != SetPositionAndRotationAnalyzer.position)
Array.Reverse(arguments);
var argList = ArgumentList()
.AddArguments(arguments);
var invocation = InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(identifierName),
IdentifierName(methodName)))
.WithArgumentList(argList);
var documentEditor = await DocumentEditor.CreateAsync(document, cancellationToken);
documentEditor.RemoveNode(statement);
documentEditor.ReplaceNode(assignmentExpression, invocation);
return documentEditor.GetChangedDocument();
}
}
}