This repository was archived by the owner on Sep 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 273
Expand file tree
/
Copy pathUsingHelper.cs
More file actions
221 lines (196 loc) · 7.79 KB
/
UsingHelper.cs
File metadata and controls
221 lines (196 loc) · 7.79 KB
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
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.Semantics;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
/// <summary>
/// Helper methods for managing using declarations.
/// </summary>
public class UsingHelper
{
/// <summary>
/// Inserts 'using ns;' in the current scope, and then removes all explicit
/// usages of ns that were made redundant by the new using.
/// </summary>
public static void InsertUsingAndRemoveRedundantNamespaceUsage(RefactoringContext context, Script script, string ns)
{
InsertUsing(context, script, new UsingDeclaration(ns));
// TODO: remove the usages that were made redundant
}
/// <summary>
/// Inserts 'newUsing' in the current scope.
/// This method will try to insert new usings in the correct position (depending on
/// where the existing usings are; and maintaining the sort order).
/// </summary>
public static void InsertUsing(RefactoringContext context, Script script, AstNode newUsing)
{
UsingInfo newUsingInfo = new UsingInfo(newUsing, context, script);
AstNode enclosingNamespace = context.GetNode<NamespaceDeclaration>() ?? context.RootNode;
// Find nearest enclosing parent that has usings:
AstNode usingParent = enclosingNamespace;
while (usingParent != null && !usingParent.Children.OfType<UsingDeclaration>().Any())
usingParent = usingParent.Parent;
if (usingParent == null) {
// No existing usings at all -> use the default location
if (script.FormattingOptions.UsingPlacement == UsingPlacement.TopOfFile) {
usingParent = context.RootNode;
} else {
usingParent = enclosingNamespace;
}
}
// Find the main block of using declarations in the chosen scope:
AstNode blockStart = usingParent.Children.FirstOrDefault(IsUsingDeclaration);
AstNode insertionPoint;
bool insertAfter = false;
if (blockStart == null) {
// no using declarations in the file
Debug.Assert(SyntaxTree.MemberRole == NamespaceDeclaration.MemberRole);
insertionPoint = usingParent.GetChildrenByRole(SyntaxTree.MemberRole).SkipWhile(CanAppearBeforeUsings).FirstOrDefault();
} else {
insertionPoint = blockStart;
while (IsUsingFollowing (ref insertionPoint) && newUsingInfo.CompareTo(new UsingInfo(insertionPoint, context, script)) > 0)
insertionPoint = insertionPoint.NextSibling;
if (!IsUsingDeclaration(insertionPoint)) {
// Insert after last using instead of before next node
// This affects where empty lines get placed.
insertionPoint = insertionPoint.PrevSibling;
insertAfter = true;
}
}
if (insertionPoint != null) {
if (insertAfter)
script.InsertAfter(insertionPoint, newUsing);
else
script.InsertBefore(insertionPoint, newUsing);
}
}
static bool IsUsingFollowing(ref AstNode insertionPoint)
{
var node = insertionPoint;
while (node != null && node.Role == Roles.NewLine)
node = node.NextSibling;
if (IsUsingDeclaration(node)) {
insertionPoint = node;
return true;
}
return false;
}
static bool IsUsingDeclaration(AstNode node)
{
return node is UsingDeclaration || node is UsingAliasDeclaration;
}
static bool CanAppearBeforeUsings(AstNode node)
{
if (node is ExternAliasDeclaration)
return true;
if (node is PreProcessorDirective)
return true;
if (node is NewLineNode)
return true;
Comment c = node as Comment;
if (c != null)
return !c.IsDocumentation;
return false;
}
/// <summary>
/// Sorts the specified usings.
/// </summary>
public static IEnumerable<AstNode> SortUsingBlock(IEnumerable<AstNode> nodes, BaseRefactoringContext context, Script script)
{
var infos = nodes.Select(_ => new UsingInfo(_, context, script));
var orderedInfos = infos.OrderBy(_ => _);
var orderedNodes = orderedInfos.Select(_ => _.Node);
return orderedNodes;
}
private sealed class UsingInfo : IComparable<UsingInfo>
{
public AstNode Node;
public string Alias;
public string Name;
public bool IsAlias;
public bool HasTypesFromOtherAssemblies;
public bool IsSystem;
public bool IsSimpleAlphabeticalCompare;
public UsingInfo(AstNode node, BaseRefactoringContext context, Script script)
{
var importAndAlias = GetImportAndAlias(node);
Node = node;
Alias = importAndAlias.Item2;
Name = importAndAlias.Item1.ToString();
IsAlias = Alias != null;
IsSimpleAlphabeticalCompare = script.FormattingOptions.AlphabeticalSortUsing;
ResolveResult rr;
if (node.Ancestors.Contains(context.RootNode)) {
rr = context.Resolve(importAndAlias.Item1);
} else {
// It's possible that we're looking at a new using that
// isn't part of the AST.
var resolver = new CSharpAstResolver(new CSharpResolver(context.Compilation), node);
rr = resolver.Resolve(importAndAlias.Item1);
}
var nrr = rr as NamespaceResolveResult;
HasTypesFromOtherAssemblies = nrr != null && nrr.Namespace.ContributingAssemblies.Any(a => !a.IsMainAssembly);
IsSystem = HasTypesFromOtherAssemblies && (Name == "System" || Name.StartsWith("System.", StringComparison.Ordinal));
}
private static Tuple<AstType, string> GetImportAndAlias(AstNode node)
{
var plainUsing = node as UsingDeclaration;
if (plainUsing != null)
return Tuple.Create(plainUsing.Import, (string)null);
var aliasUsing = node as UsingAliasDeclaration;
if (aliasUsing != null)
return Tuple.Create(aliasUsing.Import, aliasUsing.Alias);
throw new InvalidOperationException(string.Format("Invalid using node: {0}", node));
}
public int CompareTo(UsingInfo y)
{
UsingInfo x = this;
if (IsSimpleAlphabeticalCompare)
{
return AlphabeticalCompare(y);
}
else
{
if (x.IsAlias != y.IsAlias)
return x.IsAlias ? 1 : -1;
else if (x.HasTypesFromOtherAssemblies != y.HasTypesFromOtherAssemblies)
return x.HasTypesFromOtherAssemblies ? -1 : 1;
else if (x.IsSystem != y.IsSystem)
return x.IsSystem ? -1 : 1;
else
return AlphabeticalCompare(y);
}
}
private int AlphabeticalCompare(UsingInfo y)
{
UsingInfo x = this;
if (x.Alias != y.Alias)
return StringComparer.Ordinal.Compare(x.Alias, y.Alias);
else if (x.Name != y.Name)
return StringComparer.Ordinal.Compare(x.Name, y.Name);
else
return 0;
}
}
}
}