/
AddUsingStaticDirectiveRefactoring.cs
85 lines (66 loc) · 3.23 KB
/
AddUsingStaticDirectiveRefactoring.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
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Roslynator.CSharp.Refactorings
{
internal static class AddUsingStaticDirectiveRefactoring
{
public static async Task ComputeRefactoringsAsync(RefactoringContext context, MemberAccessExpressionSyntax memberAccess)
{
if (memberAccess.Expression?.IsMissing != false)
return;
if (memberAccess.Name?.IsMissing != false)
return;
if (context.Span.IsBetweenSpans(memberAccess))
{
if (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))
memberAccess = (MemberAccessExpressionSyntax)memberAccess.Parent;
}
if (!context.Span.IsBetweenSpans(memberAccess.Expression))
{
return;
}
SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);
if (semanticModel.GetSymbol(memberAccess.Expression, context.CancellationToken) is not INamedTypeSymbol typeSymbol)
{
return;
}
if (typeSymbol.TypeKind != TypeKind.Class
&& typeSymbol.TypeKind != TypeKind.Struct)
{
return;
}
if (!typeSymbol.DeclaredAccessibility.Is(Accessibility.Public, Accessibility.Internal))
return;
if (semanticModel.GetSymbol(memberAccess.Name, context.CancellationToken)?.IsStatic != true)
return;
if (CSharpUtility.IsStaticClassInScope(memberAccess, typeSymbol, semanticModel, context.CancellationToken))
return;
context.RegisterRefactoring(
$"using static {typeSymbol};",
ct => RefactorAsync(context.Document, typeSymbol.ToString(), memberAccess, ct),
RefactoringDescriptors.AddUsingStaticDirective);
}
private static async Task<Document> RefactorAsync(
Document document,
string name,
MemberAccessExpressionSyntax memberAccess,
CancellationToken cancellationToken = default)
{
SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
SimpleNameSyntax newNode = memberAccess.Name.WithTriviaFrom(memberAccess);
SyntaxNode newRoot = oldRoot.ReplaceNode(memberAccess, newNode);
newRoot = ((CompilationUnitSyntax)newRoot).AddUsings(CSharpFactory.UsingStaticDirective(SyntaxFactory.ParseName(name)));
return document.WithSyntaxRoot(newRoot);
}
private static MemberAccessExpressionSyntax GetTopmostMemberAccessExpression(MemberAccessExpressionSyntax memberAccess)
{
while (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))
memberAccess = (MemberAccessExpressionSyntax)memberAccess.Parent;
return memberAccess;
}
}
}