diff --git a/DocGenerator.2017/DocGenerator.csproj b/DocGenerator.2017/DocGenerator.csproj
index b5a4c8ed..b4d3efe0 100644
--- a/DocGenerator.2017/DocGenerator.csproj
+++ b/DocGenerator.2017/DocGenerator.csproj
@@ -57,29 +57,29 @@
..\packages\ManagedEsent.1.9.4\lib\net40\Esent.Interop.dll
-
- ..\packages\Microsoft.CodeAnalysis.Common.2.0.0\lib\netstandard1.3\Microsoft.CodeAnalysis.dll
+
+ ..\packages\Microsoft.CodeAnalysis.Common.2.1.0\lib\netstandard1.3\Microsoft.CodeAnalysis.dll
-
- ..\packages\Microsoft.CodeAnalysis.CSharp.2.0.0\lib\netstandard1.3\Microsoft.CodeAnalysis.CSharp.dll
+
+ ..\packages\Microsoft.CodeAnalysis.CSharp.2.1.0\lib\netstandard1.3\Microsoft.CodeAnalysis.CSharp.dll
-
- ..\packages\Microsoft.CodeAnalysis.CSharp.Workspaces.2.0.0\lib\netstandard1.3\Microsoft.CodeAnalysis.CSharp.Workspaces.dll
+
+ ..\packages\Microsoft.CodeAnalysis.CSharp.Workspaces.2.1.0\lib\netstandard1.3\Microsoft.CodeAnalysis.CSharp.Workspaces.dll
..\packages\Microsoft.CodeAnalysis.Elfie.0.10.6\lib\net46\Microsoft.CodeAnalysis.Elfie.dll
-
- ..\packages\Microsoft.CodeAnalysis.VisualBasic.2.0.0\lib\netstandard1.3\Microsoft.CodeAnalysis.VisualBasic.dll
+
+ ..\packages\Microsoft.CodeAnalysis.VisualBasic.2.1.0\lib\netstandard1.3\Microsoft.CodeAnalysis.VisualBasic.dll
-
- ..\packages\Microsoft.CodeAnalysis.VisualBasic.Workspaces.2.0.0\lib\netstandard1.3\Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll
+
+ ..\packages\Microsoft.CodeAnalysis.VisualBasic.Workspaces.2.1.0\lib\netstandard1.3\Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll
-
- ..\packages\Microsoft.CodeAnalysis.Workspaces.Common.2.0.0\lib\net46\Microsoft.CodeAnalysis.Workspaces.dll
+
+ ..\packages\Microsoft.CodeAnalysis.Workspaces.Common.2.1.0\lib\net46\Microsoft.CodeAnalysis.Workspaces.dll
-
- ..\packages\Microsoft.CodeAnalysis.Workspaces.Common.2.0.0\lib\net46\Microsoft.CodeAnalysis.Workspaces.Desktop.dll
+
+ ..\packages\Microsoft.CodeAnalysis.Workspaces.Common.2.1.0\lib\net46\Microsoft.CodeAnalysis.Workspaces.Desktop.dll
diff --git a/DocGenerator.2017/packages.config b/DocGenerator.2017/packages.config
index 5b6cbc98..7749a9cc 100644
--- a/DocGenerator.2017/packages.config
+++ b/DocGenerator.2017/packages.config
@@ -2,13 +2,13 @@
-
-
-
+
+
+
-
-
-
+
+
+
diff --git a/README.md b/README.md
index ec359044..d08ec1ff 100644
--- a/README.md
+++ b/README.md
@@ -2,6 +2,8 @@
[![Join the chat at https://gitter.im/icsharpcode/RefactoringEssentials](https://badges.gitter.im/icsharpcode/RefactoringEssentials.svg)](https://gitter.im/icsharpcode/RefactoringEssentials?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+[![](https://codescene.io/projects/842/status.svg) Get more details at **codescene.io**.](https://codescene.io/projects/842/jobs/latest-successful/results)
+
[@vsrefactoring](https://twitter.com/vsrefactoring) | [vsrefactoringessentials.com](http://vsrefactoringessentials.com/)
Refactorings Essentials sports the following features:
@@ -27,4 +29,5 @@ makes them easier to maintain and contribute to.
Branch | Status 4.* (VS 2015) | Status 5.* (VS 2017)
--- | --- | ---
*master* (Development) | [![Build status](https://ci.appveyor.com/api/projects/status/5463mskexnsa0176/branch/master?svg=true)](https://ci.appveyor.com/project/icsharpcode/refactoringessentials/branch/master) | [![Build status](https://ci.appveyor.com/api/projects/status/r01wr5xdclj24y20/branch/master?svg=true)](https://ci.appveyor.com/project/icsharpcode/refactoringessentials-wgnsw/branch/master)
-*release* (Latest Release) | [![Build status](https://ci.appveyor.com/api/projects/status/5463mskexnsa0176/branch/release?svg=true)](https://ci.appveyor.com/project/icsharpcode/refactoringessentials/branch/release) | [![Build status](https://ci.appveyor.com/api/projects/status/r01wr5xdclj24y20/branch/release?svg=true)](https://ci.appveyor.com/project/icsharpcode/refactoringessentials-wgnsw/branch/release)
\ No newline at end of file
+*release* (Latest Release) | [![Build status](https://ci.appveyor.com/api/projects/status/5463mskexnsa0176/branch/release?svg=true)](https://ci.appveyor.com/project/icsharpcode/refactoringessentials/branch/release) | [![Build status](https://ci.appveyor.com/api/projects/status/r01wr5xdclj24y20/branch/release?svg=true)](https://ci.appveyor.com/project/icsharpcode/refactoringessentials-wgnsw/branch/release)
+k
diff --git a/RefactoringEssentials.2017/RefactoringEssentials.csproj b/RefactoringEssentials.2017/RefactoringEssentials.csproj
index 031822bd..69103b21 100644
--- a/RefactoringEssentials.2017/RefactoringEssentials.csproj
+++ b/RefactoringEssentials.2017/RefactoringEssentials.csproj
@@ -197,6 +197,9 @@
CSharp\CodeRefactorings\Synced\ConvertAutoPropertyToPropertyCodeRefactoringProvider.cs
+
+ CSharp\CodeRefactorings\Synced\ConvertAutoPropertyToPropertyManipulater.cs
+
CSharp\CodeRefactorings\Synced\ConvertCoalescingToConditionalExpressionCodeRefactoringProvider.cs
@@ -1331,6 +1334,18 @@
CSharp\SyntaxExtensions.cs
+
+ CSharp\CodeRefactoringStatementSyntax.cs
+
+
+ CSharp\DocumentManipulator.cs
+
+
+ CSharp\PropertyDeclarationContext.cs
+
+
+ CSharp\PropertyDeclarationContextFinder.cs
+
Samples\CSharp\SampleAnalyzer.cs
@@ -1694,10 +1709,10 @@
-
-
-
-
+
+
+
+
diff --git a/RefactoringEssentials/CSharp/CodeRefactoringStatementSyntax.cs b/RefactoringEssentials/CSharp/CodeRefactoringStatementSyntax.cs
new file mode 100644
index 00000000..f66298d2
--- /dev/null
+++ b/RefactoringEssentials/CSharp/CodeRefactoringStatementSyntax.cs
@@ -0,0 +1,26 @@
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+
+namespace RefactoringEssentials.CSharp
+{
+ public class CodeRefactoringStatementSyntax
+ {
+ StatementSyntax StatementSyntax { get; }
+
+ public CodeRefactoringStatementSyntax(StatementSyntax statementSyntax)
+ {
+ StatementSyntax = statementSyntax;
+ }
+
+ public CodeRefactoringStatementSyntax WithAdditionalAnnotations(params SyntaxAnnotation[] annotations)
+ {
+ return new CodeRefactoringStatementSyntax(StatementSyntax.WithAdditionalAnnotations(annotations));
+ }
+
+ public BlockSyntax WrapInBlock()
+ {
+ return SyntaxFactory.Block(StatementSyntax);
+ }
+ }
+}
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Custom/InitializeReadOnlyAutoPropertyFromConstructorParameterCodeRefactoringProvider.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Custom/InitializeReadOnlyAutoPropertyFromConstructorParameterCodeRefactoringProvider.cs
index cfa907b5..27c8e237 100644
--- a/RefactoringEssentials/CSharp/CodeRefactorings/Custom/InitializeReadOnlyAutoPropertyFromConstructorParameterCodeRefactoringProvider.cs
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Custom/InitializeReadOnlyAutoPropertyFromConstructorParameterCodeRefactoringProvider.cs
@@ -43,7 +43,7 @@ static Task CreateAndInitialiseReadOnlyAutoPropertyFromConstructorPara
nodeToAdd: CreateAutoProperty(
type: context.Type,
identifier: context.PropertyName,
- accessors: GetAccessor(),
+ accessors: GetAutoAccessor(),
accessibility: SyntaxKind.PublicKeyword));
var rootWithAssignmentAndProperty = AddStatementToConstructorBody(
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ContractEnsuresNotNullReturnRefactoringProvider.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ContractEnsuresNotNullReturnRefactoringProvider.cs
index f2a0c610..546e67e4 100644
--- a/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ContractEnsuresNotNullReturnRefactoringProvider.cs
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ContractEnsuresNotNullReturnRefactoringProvider.cs
@@ -99,18 +99,68 @@ static StatementSyntax CreateContractEnsuresCall(string returnType)
return SyntaxFactory.ParseStatement($"Contract.Ensures(Contract.Result<{returnType}>() != null);\r\n").WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation);
}
- static bool HasReturnContract(BlockSyntax bodyStatement, string returnType)
+ static bool ValidateContractAccess(MemberAccessExpressionSyntax access, string method, string genericTypeName)
{
- var workspace = new AdhocWorkspace();
+ if (access == null)
+ return false;
+
+ var className = access.Expression.GetRightmostName() as SimpleNameSyntax;
+ if (className == null || className.Identifier.ValueText != "Contract")
+ return false;
+
+ var ensures = access.GetRightmostName() as SimpleNameSyntax;
+ if (ensures == null || ensures.Identifier.ValueText != method)
+ return false;
+
+ if (genericTypeName!= null)
+ {
+ var generic = ensures as GenericNameSyntax;
+ if (generic == null || generic.Arity != 1)
+ return false;
+
+ var typeName = generic.TypeArgumentList.Arguments[0].GetRightmostName() as SimpleNameSyntax;
+ if (typeName == null || typeName.Identifier.ValueText != genericTypeName)
+ return false;
+ }
+ return true;
+ }
- var rhsEnsures = $"Contract.Ensures(Contract.Result<{returnType}>() != null);";
- var lhsEnsures = $"Contract.Ensures(null != Contract.Result<{returnType}>());";
+ static bool HasReturnContract(BlockSyntax bodyStatement, string returnType)
+ {
+ var rhsEnsures = SyntaxFactory.ParseStatement($"Contract.Ensures(Contract.Result<{returnType}>() != null);");
+ var lhsEnsures = SyntaxFactory.ParseStatement($"Contract.Ensures(null != Contract.Result<{returnType}>());");
foreach (var expression in bodyStatement.DescendantNodes().OfType())
{
- var formatted = Formatter.Format(expression, workspace).ToString();
+ var ies = expression.Expression as InvocationExpressionSyntax;
+ if (ies == null)
+ continue;
+
+ var access = ies.Expression as MemberAccessExpressionSyntax;
+ if (access == null)
+ continue;
+
+ if (!ValidateContractAccess(access, "Ensures", null))
+ continue;
- if (formatted == rhsEnsures || formatted == lhsEnsures)
- return true;
+ if (ies.ArgumentList.Arguments.Count != 1)
+ continue;
+
+ var arg = ies.ArgumentList.Arguments[0].Expression as BinaryExpressionSyntax;
+ if (arg == null || !arg.OperatorToken.IsKind(SyntaxKind.ExclamationEqualsToken))
+ continue;
+
+ if (arg.Left.IsKind(SyntaxKind.NullLiteralExpression))
+ {
+ ies = arg.Right as InvocationExpressionSyntax;
+ }
+ else if (arg.Right.IsKind(SyntaxKind.NullLiteralExpression))
+ {
+ ies = arg.Left as InvocationExpressionSyntax;
+ }
+ access = ies?.Expression as MemberAccessExpressionSyntax;
+ if (!ValidateContractAccess(access, "Result", returnType))
+ continue;
+ return true;
}
return false;
}
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertAutoPropertyToPropertyCodeRefactoringProvider.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertAutoPropertyToPropertyCodeRefactoringProvider.cs
index f103aebb..c987a849 100644
--- a/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertAutoPropertyToPropertyCodeRefactoringProvider.cs
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertAutoPropertyToPropertyCodeRefactoringProvider.cs
@@ -10,86 +10,33 @@
namespace RefactoringEssentials.CSharp.CodeRefactorings
{
- [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Convert auto-property to computed propertyy")]
+ [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Convert auto-property to computed property")]
public class ConvertAutoPropertyToPropertyCodeRefactoringProvider : CodeRefactoringProvider
{
+ readonly PropertyDeclarationContextFinder propertyDeclarationContextFinder;
+
+ public ConvertAutoPropertyToPropertyCodeRefactoringProvider()
+ {
+ this.propertyDeclarationContextFinder = new PropertyDeclarationContextFinder();
+ }
+
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
- var document = context.Document;
- if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
- return;
- var span = context.Span;
- if (!span.IsEmpty)
- return;
- var cancellationToken = context.CancellationToken;
- if (cancellationToken.IsCancellationRequested)
- return;
- var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- if (model.IsFromGeneratedCode(cancellationToken))
- return;
- var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
+ var propertyDeclarationContext = await propertyDeclarationContextFinder.Find(context);
- var property = root.FindNode(span) as PropertyDeclarationSyntax;
- if (property == null || !property.Identifier.Span.Contains(span))
- return;
- var enclosingTypeDeclaration = property.Ancestors().OfType().FirstOrDefault();
- if (enclosingTypeDeclaration == null || enclosingTypeDeclaration is InterfaceDeclarationSyntax)
- return;
- // ignore properties with >=1 accessor body
- if (property.AccessorList?.Accessors.Any(b => b.Body != null) != false)
+ if (propertyDeclarationContext == null) return;
+
+ // Auto properties don't have any accessors
+ if (propertyDeclarationContext.Property.AccessorList?.Accessors.Any(b => b.Body != null) != false)
return;
+
context.RegisterRefactoring(
CodeActionFactory.Create(
- property.Identifier.Span,
+ propertyDeclarationContext.Property.Identifier.Span,
DiagnosticSeverity.Info,
GettextCatalog.GetString("To computed property"),
- t2 =>
- {
- var getBody = SyntaxFactory.Block(
- SyntaxFactory.ThrowStatement(
- SyntaxFactory.ObjectCreationExpression(
- SyntaxFactory.QualifiedName(
- SyntaxFactory.IdentifierName(@"System"),
- SyntaxFactory.IdentifierName(@"NotImplementedException")
- ).WithoutAnnotations(Simplifier.Annotation)
- ).WithArgumentList(SyntaxFactory.ArgumentList())
- )
- );
-
- var getter = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getBody);
- var setter = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, getBody);
-
- var newProperty = property.WithAccessorList(SyntaxFactory.AccessorList(new SyntaxList().Add(getter).Add(setter)));
- newProperty = newProperty.WithAdditionalAnnotations(Formatter.Annotation);
- var newRoot = root.ReplaceNode((SyntaxNode)property, newProperty);
- return Task.FromResult(document.WithSyntaxRoot(newRoot));
- })
+ t2 => new ConvertAutoPropertyToPropertyManipulater(propertyDeclarationContext).Manipulate())
);
}
-
- public static string GetNameProposal(string name, SemanticModel model, SyntaxNode node)
- {
- string baseName = char.ToLower(name[0]) + name.Substring(1);
- var enclosingClass = node.AncestorsAndSelf().OfType().FirstOrDefault();
- if (enclosingClass == null)
- return baseName;
-
- INamedTypeSymbol typeSymbol = model.GetDeclaredSymbol(enclosingClass);
- IEnumerable members = typeSymbol.MemberNames;
-
- string proposedName = null;
- int number = 0;
- do
- {
- proposedName = baseName;
- if (number != 0)
- {
- proposedName = baseName + number.ToString();
- }
- number++;
- } while (members.Contains(proposedName));
- return proposedName;
- }
}
}
-
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertAutoPropertyToPropertyManipulater.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertAutoPropertyToPropertyManipulater.cs
new file mode 100644
index 00000000..a986208b
--- /dev/null
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertAutoPropertyToPropertyManipulater.cs
@@ -0,0 +1,30 @@
+using Microsoft.CodeAnalysis;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static RefactoringEssentials.CSharp.Manipulations;
+using RefactoringEssentials.CSharp;
+using System.Diagnostics.Contracts;
+
+internal class ConvertAutoPropertyToPropertyManipulater : DocumentManipulator
+{
+ readonly PropertyDeclarationSyntax property;
+
+ public ConvertAutoPropertyToPropertyManipulater(PropertyDeclarationContext context) : base(context.Document, context.Root)
+ {
+ Contract.Requires(context != null);
+ Contract.Requires(context.Property != null);
+
+ this.property = context.Property;
+ }
+
+ public Task Manipulate()
+ {
+ var newProperty = PropertyWithReplacedAccessors(
+ property,
+ GetAccessor(ThrowNotImplementedExceptionBlock),
+ SetAccessor(ThrowNotImplementedExceptionBlock));
+
+ return DocumentWithReplacedNode(property, newProperty);
+ }
+
+}
\ No newline at end of file
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertExpressionBodyToStatementBodyCodeRefactoringProvider.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertExpressionBodyToStatementBodyCodeRefactoringProvider.cs
index a5f71a42..c3321d54 100644
--- a/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertExpressionBodyToStatementBodyCodeRefactoringProvider.cs
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertExpressionBodyToStatementBodyCodeRefactoringProvider.cs
@@ -16,6 +16,9 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte
var document = context.Document;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
return;
+ var options = document.Project.ParseOptions as CSharpParseOptions;
+ if (options != null && options.LanguageVersion < LanguageVersion.CSharp6)
+ return;
var span = context.Span;
if (!span.IsEmpty)
return;
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertStatementBodyToExpressionBodyCodeRefactoringProvider.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertStatementBodyToExpressionBodyCodeRefactoringProvider.cs
index f7205fa3..90c49577 100644
--- a/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertStatementBodyToExpressionBodyCodeRefactoringProvider.cs
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Synced/ConvertStatementBodyToExpressionBodyCodeRefactoringProvider.cs
@@ -16,6 +16,9 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte
var document = context.Document;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
return;
+ var options = document.Project.ParseOptions as CSharpParseOptions;
+ if (options != null && options.LanguageVersion < LanguageVersion.CSharp6)
+ return;
var span = context.Span;
if (!span.IsEmpty)
return;
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Synced/InitializeAutoPropertyFromConstructorParameterCodeRefactoringProvider.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Synced/InitializeAutoPropertyFromConstructorParameterCodeRefactoringProvider.cs
index c7c57438..68827f94 100644
--- a/RefactoringEssentials/CSharp/CodeRefactorings/Synced/InitializeAutoPropertyFromConstructorParameterCodeRefactoringProvider.cs
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Synced/InitializeAutoPropertyFromConstructorParameterCodeRefactoringProvider.cs
@@ -47,7 +47,7 @@ static Task CreateAndInitialiseAutoPropertyFromConstructorParameter(Co
nodeToAdd: CreateAutoProperty(
type: context.Type,
identifier: context.PropertyName,
- accessors: GetAndSetAccessors(),
+ accessors: GetAndSetAutoAccessors(),
accessibility: SyntaxKind.PublicKeyword));
var rootWithAssignmentAndProperty = AddStatementToConstructorBody(
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/ChangeAccessModifierAction.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/ChangeAccessModifierAction.cs
index 368be4af..3b4f986b 100644
--- a/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/ChangeAccessModifierAction.cs
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/ChangeAccessModifierAction.cs
@@ -39,29 +39,29 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte
node = node.Parent;
if (node == null || node.IsKind(SyntaxKind.InterfaceDeclaration, SyntaxKind.EnumMemberDeclaration))
return;
-
+
ISymbol symbol = null;
var field = node as FieldDeclarationSyntax;
- if(field != null)
+ if (field != null)
symbol = model.GetDeclaredSymbol(field.Declaration.Variables.First(), cancellationToken);
else
{
var member = node as MemberDeclarationSyntax;
- if(member != null)
+ if (member != null)
symbol = model.GetDeclaredSymbol(member, cancellationToken);
else
{
var accessor = node as AccessorDeclarationSyntax;
- if(accessor != null)
+ if (accessor != null)
symbol = model.GetDeclaredSymbol(accessor, cancellationToken);
}
}
if (!symbol.AccessibilityChangeable())
return;
-
+
foreach (var accessibility in GetPossibleAccessibilities(model, symbol, node, cancellationToken))
{
- var modifiers = GetAccessibilityModifiers(accessibility);
+ var modifiers = GetAccessibilityModifiers(accessibility, node.GetModifiers());
context.RegisterRefactoring(CodeActionFactory.Create(
token.Span,
DiagnosticSeverity.Info,
@@ -84,13 +84,13 @@ static IEnumerable GetPossibleAccessibilities(SemanticModel model
if (containingType == null)
{
if (member.IsPublic())
- result = new [] { Accessibility.Internal };
+ result = new[] { Accessibility.Internal };
- result = new [] { Accessibility.Public };
+ result = new[] { Accessibility.Public };
}
else if (containingType.IsValueType)
{
- result = new []
+ result = new[]
{
Accessibility.Private,
Accessibility.Internal,
@@ -118,11 +118,11 @@ static IEnumerable GetPossibleAccessibilities(SemanticModel model
}
}
-
+
return result.Where(a => a != member.DeclaredAccessibility);
}
- public static SyntaxTokenList GetAccessibilityModifiers(Accessibility accessibility)
+ public static SyntaxTokenList GetAccessibilityModifiers(Accessibility accessibility, SyntaxTokenList oldList)
{
var tokenList = new List();
switch (accessibility)
@@ -148,6 +148,17 @@ public static SyntaxTokenList GetAccessibilityModifiers(Accessibility accessibil
tokenList.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
break;
}
+
+ foreach (var token in oldList)
+ {
+ if (token.IsKind(SyntaxKind.PrivateKeyword) ||
+ token.IsKind(SyntaxKind.ProtectedKeyword) ||
+ token.IsKind(SyntaxKind.InternalKeyword) ||
+ token.IsKind(SyntaxKind.PublicKeyword))
+ continue;
+ tokenList.Add(token);
+ }
+
return SyntaxFactory.TokenList(tokenList.Select(t => t.WithTrailingTrivia(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "))));
}
}
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/CreateIndexerAction.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/CreateIndexerAction.cs
index 69582a24..b71f4ed9 100644
--- a/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/CreateIndexerAction.cs
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/CreateIndexerAction.cs
@@ -1,87 +1,87 @@
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using Microsoft.CodeAnalysis;
-using System.Threading.Tasks;
+//using Microsoft.CodeAnalysis.CodeRefactorings;
+//using Microsoft.CodeAnalysis;
+//using System.Threading.Tasks;
-namespace RefactoringEssentials.CSharp.CodeRefactorings
-{
- [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Create indexer")]
- [NotPortedYet]
- public class CreateIndexerAction : CodeRefactoringProvider
- {
- public override Task ComputeRefactoringsAsync(CodeRefactoringContext context)
- {
- //var document = context.Document;
- //var span = context.Span;
- //var cancellationToken = context.CancellationToken;
- //var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- //if (model.IsFromGeneratedCode(cancellationToken))
- // return;
- //var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
- return Task.FromResult(0);
- }
- // public async Task ComputeRefactoringsAsync(Document document, TextSpan span, CancellationToken cancellationToken)
- // {
- // var indexer = context.GetNode();
- // if (indexer == null)
- // yield break;
- // if (!(context.Resolve(indexer).IsError))
- // yield break;
- //
- // var state = context.GetResolverStateBefore(indexer);
- // if (state.CurrentTypeDefinition == null)
- // yield break;
- // var guessedType = TypeGuessing.GuessAstType(context, indexer);
- //
- // bool createInOtherType = false;
- // ResolveResult targetResolveResult = null;
- // targetResolveResult = context.Resolve(indexer.Target);
- // createInOtherType = !state.CurrentTypeDefinition.Equals(targetResolveResult.Type.GetDefinition());
- //
- // bool isStatic;
- // if (createInOtherType) {
- // if (targetResolveResult.Type.GetDefinition() == null || targetResolveResult.Type.GetDefinition().Region.IsEmpty)
- // yield break;
- // isStatic = targetResolveResult is TypeResolveResult;
- // if (isStatic && targetResolveResult.Type.Kind == TypeKind.Interface || targetResolveResult.Type.Kind == TypeKind.Enum)
- // yield break;
- // } else {
- // isStatic = indexer.Target is IdentifierExpression && state.CurrentMember.IsStatic;
- // }
- //
- // yield return new CodeAction(context.TranslateString("Create indexer"), script => {
- // var decl = new IndexerDeclaration() {
- // ReturnType = guessedType,
- // Getter = new Accessor() {
- // Body = new BlockStatement() {
- // new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
- // }
- // },
- // Setter = new Accessor() {
- // Body = new BlockStatement() {
- // new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
- // }
- // },
- // };
- // decl.Parameters.AddRange(CreateMethodDeclarationAction.GenerateParameters(context, indexer.Arguments));
- // if (isStatic)
- // decl.Modifiers |= Modifiers.Static;
- //
- // if (createInOtherType) {
- // if (targetResolveResult.Type.Kind == TypeKind.Interface) {
- // decl.Getter.Body = null;
- // decl.Setter.Body = null;
- // decl.Modifiers = Modifiers.None;
- // } else {
- // decl.Modifiers |= Modifiers.Public;
- // }
- //
- // script.InsertWithCursor(context.TranslateString("Create indexer"), targetResolveResult.Type.GetDefinition(), (s, c) => decl);
- // return;
- // }
- //
- // script.InsertWithCursor(context.TranslateString("Create indexer"), Script.InsertPosition.Before, decl);
- // }, indexer) { Severity = RefactoringEssentials.Refactoring.Severity.Error };
- // }
+//namespace RefactoringEssentials.CSharp.CodeRefactorings
+//{
+// [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Create indexer")]
+// [NotPortedYet]
+// public class CreateIndexerAction : CodeRefactoringProvider
+// {
+// public override Task ComputeRefactoringsAsync(CodeRefactoringContext context)
+// {
+// //var document = context.Document;
+// //var span = context.Span;
+// //var cancellationToken = context.CancellationToken;
+// //var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
+// //if (model.IsFromGeneratedCode(cancellationToken))
+// // return;
+// //var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
+// return Task.FromResult(0);
+// }
+// // public async Task ComputeRefactoringsAsync(Document document, TextSpan span, CancellationToken cancellationToken)
+// // {
+// // var indexer = context.GetNode();
+// // if (indexer == null)
+// // yield break;
+// // if (!(context.Resolve(indexer).IsError))
+// // yield break;
+// //
+// // var state = context.GetResolverStateBefore(indexer);
+// // if (state.CurrentTypeDefinition == null)
+// // yield break;
+// // var guessedType = TypeGuessing.GuessAstType(context, indexer);
+// //
+// // bool createInOtherType = false;
+// // ResolveResult targetResolveResult = null;
+// // targetResolveResult = context.Resolve(indexer.Target);
+// // createInOtherType = !state.CurrentTypeDefinition.Equals(targetResolveResult.Type.GetDefinition());
+// //
+// // bool isStatic;
+// // if (createInOtherType) {
+// // if (targetResolveResult.Type.GetDefinition() == null || targetResolveResult.Type.GetDefinition().Region.IsEmpty)
+// // yield break;
+// // isStatic = targetResolveResult is TypeResolveResult;
+// // if (isStatic && targetResolveResult.Type.Kind == TypeKind.Interface || targetResolveResult.Type.Kind == TypeKind.Enum)
+// // yield break;
+// // } else {
+// // isStatic = indexer.Target is IdentifierExpression && state.CurrentMember.IsStatic;
+// // }
+// //
+// // yield return new CodeAction(context.TranslateString("Create indexer"), script => {
+// // var decl = new IndexerDeclaration() {
+// // ReturnType = guessedType,
+// // Getter = new Accessor() {
+// // Body = new BlockStatement() {
+// // new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
+// // }
+// // },
+// // Setter = new Accessor() {
+// // Body = new BlockStatement() {
+// // new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
+// // }
+// // },
+// // };
+// // decl.Parameters.AddRange(CreateMethodDeclarationAction.GenerateParameters(context, indexer.Arguments));
+// // if (isStatic)
+// // decl.Modifiers |= Modifiers.Static;
+// //
+// // if (createInOtherType) {
+// // if (targetResolveResult.Type.Kind == TypeKind.Interface) {
+// // decl.Getter.Body = null;
+// // decl.Setter.Body = null;
+// // decl.Modifiers = Modifiers.None;
+// // } else {
+// // decl.Modifiers |= Modifiers.Public;
+// // }
+// //
+// // script.InsertWithCursor(context.TranslateString("Create indexer"), targetResolveResult.Type.GetDefinition(), (s, c) => decl);
+// // return;
+// // }
+// //
+// // script.InsertWithCursor(context.TranslateString("Create indexer"), Script.InsertPosition.Before, decl);
+// // }, indexer) { Severity = RefactoringEssentials.Refactoring.Severity.Error };
+// // }
- }
-}
\ No newline at end of file
+// }
+//}
\ No newline at end of file
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/IntroduceConstantAction.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/IntroduceConstantAction.cs
index c9276b5c..af610a66 100644
--- a/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/IntroduceConstantAction.cs
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/IntroduceConstantAction.cs
@@ -1,139 +1,139 @@
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using Microsoft.CodeAnalysis;
-using System.Threading.Tasks;
+//using Microsoft.CodeAnalysis.CodeRefactorings;
+//using Microsoft.CodeAnalysis;
+//using System.Threading.Tasks;
-namespace RefactoringEssentials.CSharp.CodeRefactorings
-{
- [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Introduce constant")]
- [NotPortedYet]
- public class IntroduceConstantAction : CodeRefactoringProvider
- {
- public override Task ComputeRefactoringsAsync(CodeRefactoringContext context)
- {
- //var document = context.Document;
- //var span = context.Span;
- //var cancellationToken = context.CancellationToken;
- //var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- //if (model.IsFromGeneratedCode(cancellationToken))
- // return;
- //var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
- return Task.FromResult(0);
- }
- // public async Task ComputeRefactoringsAsync(Document document, TextSpan span, CancellationToken cancellationToken)
- // {
- // var pexpr = context.GetNode();
- // if (pexpr == null)
- // yield break;
- //
- // var visitor = new DeclareLocalVariableAction.SearchNodeVisitior(pexpr);
- //
- // if (pexpr.Parent is VariableInitializer) {
- // var varDec = pexpr.Parent.Parent as VariableDeclarationStatement;
- // if (varDec != null && (varDec.Modifiers & Modifiers.Const) != 0)
- // yield break;
- // var fieldDecl = pexpr.Parent.Parent as FieldDeclaration;
- // if (fieldDecl != null && (fieldDecl.Modifiers & Modifiers.Const) != 0)
- // yield break;
- // }
- //
- // var node = context.GetNode ();
- // if (node != null)
- // node.AcceptVisitor(visitor);
- //
- // var resolveResult = context.Resolve(pexpr);
- // var statement = context.GetNode();
- // if (statement != null) {
- // yield return new CodeAction(context.TranslateString("Create local constant"), script => {
- // string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
- // var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
- // if (service != null)
- // name = service.CheckName(context, name, AffectedEntity.LocalConstant);
- //
- // var initializer = new VariableInitializer(name, pexpr.Clone());
- // var decl = new VariableDeclarationStatement() {
- // Type = context.CreateShortType(resolveResult.Type),
- // Modifiers = Modifiers.Const,
- // Variables = { initializer }
- // };
- //
- // script.InsertBefore(statement, decl);
- // var variableUsage = new IdentifierExpression(name);
- // script.Replace(pexpr, variableUsage);
- // script.Link(initializer.NameToken, variableUsage);
- // }, pexpr);
- // }
- //
- // yield return new CodeAction(context.TranslateString("Create constant field"), script => {
- // string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
- // var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
- // if (service != null)
- // name = service.CheckName(context, name, AffectedEntity.ConstantField);
- //
- // var initializer = new VariableInitializer(name, pexpr.Clone());
- //
- // var decl = new FieldDeclaration() {
- // ReturnType = context.CreateShortType(resolveResult.Type),
- // Modifiers = Modifiers.Const,
- // Variables = { initializer }
- // };
- //
- // var variableUsage = new IdentifierExpression(name);
- // script.Replace(pexpr, variableUsage);
- // // script.Link(initializer.NameToken, variableUsage);
- // script.InsertWithCursor(context.TranslateString("Create constant"), Script.InsertPosition.Before, decl);
- // }, pexpr);
- //
- // if (visitor.Matches.Count > 1) {
- // yield return new CodeAction(string.Format(context.TranslateString("Create local constant (replace '{0}' occurrences)"), visitor.Matches.Count), script => {
- // string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
- // var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
- // if (service != null)
- // name = service.CheckName(context, name, AffectedEntity.LocalConstant);
- //
- // var initializer = new VariableInitializer(name, pexpr.Clone());
- // var decl = new VariableDeclarationStatement() {
- // Type = context.CreateShortType(resolveResult.Type),
- // Modifiers = Modifiers.Const,
- // Variables = { initializer }
- // };
- //
- // script.InsertBefore(statement, decl);
- //
- // var linkedNodes = new List();
- // linkedNodes.Add(initializer.NameToken);
- // for (int i = 0; i < visitor.Matches.Count; i++) {
- // var identifierExpression = new IdentifierExpression(name);
- // linkedNodes.Add(identifierExpression);
- // script.Replace(visitor.Matches [i], identifierExpression);
- // }
- // script.Link(linkedNodes.ToArray ());
- // }, pexpr);
- //
- // yield return new CodeAction(string.Format(context.TranslateString("Create constant field (replace '{0}' occurrences)"), visitor.Matches.Count), script => {
- // string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
- // var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
- // if (service != null)
- // name = service.CheckName(context, name, AffectedEntity.ConstantField);
- //
- // var initializer = new VariableInitializer(name, pexpr.Clone());
- //
- // var decl = new FieldDeclaration() {
- // ReturnType = context.CreateShortType(resolveResult.Type),
- // Modifiers = Modifiers.Const,
- // Variables = { initializer }
- // };
- //
- // var linkedNodes = new List();
- // linkedNodes.Add(initializer.NameToken);
- // for (int i = 0; i < visitor.Matches.Count; i++) {
- // var identifierExpression = new IdentifierExpression(name);
- // linkedNodes.Add(identifierExpression);
- // script.Replace(visitor.Matches [i], identifierExpression);
- // }
- // script.InsertWithCursor(context.TranslateString("Create constant"), Script.InsertPosition.Before, decl);
- // }, pexpr);
- // }
- // }
- }
-}
+//namespace RefactoringEssentials.CSharp.CodeRefactorings
+//{
+// [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Introduce constant")]
+// [NotPortedYet]
+// public class IntroduceConstantAction : CodeRefactoringProvider
+// {
+// public override Task ComputeRefactoringsAsync(CodeRefactoringContext context)
+// {
+// //var document = context.Document;
+// //var span = context.Span;
+// //var cancellationToken = context.CancellationToken;
+// //var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
+// //if (model.IsFromGeneratedCode(cancellationToken))
+// // return;
+// //var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
+// return Task.FromResult(0);
+// }
+// // public async Task ComputeRefactoringsAsync(Document document, TextSpan span, CancellationToken cancellationToken)
+// // {
+// // var pexpr = context.GetNode();
+// // if (pexpr == null)
+// // yield break;
+// //
+// // var visitor = new DeclareLocalVariableAction.SearchNodeVisitior(pexpr);
+// //
+// // if (pexpr.Parent is VariableInitializer) {
+// // var varDec = pexpr.Parent.Parent as VariableDeclarationStatement;
+// // if (varDec != null && (varDec.Modifiers & Modifiers.Const) != 0)
+// // yield break;
+// // var fieldDecl = pexpr.Parent.Parent as FieldDeclaration;
+// // if (fieldDecl != null && (fieldDecl.Modifiers & Modifiers.Const) != 0)
+// // yield break;
+// // }
+// //
+// // var node = context.GetNode ();
+// // if (node != null)
+// // node.AcceptVisitor(visitor);
+// //
+// // var resolveResult = context.Resolve(pexpr);
+// // var statement = context.GetNode();
+// // if (statement != null) {
+// // yield return new CodeAction(context.TranslateString("Create local constant"), script => {
+// // string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
+// // var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
+// // if (service != null)
+// // name = service.CheckName(context, name, AffectedEntity.LocalConstant);
+// //
+// // var initializer = new VariableInitializer(name, pexpr.Clone());
+// // var decl = new VariableDeclarationStatement() {
+// // Type = context.CreateShortType(resolveResult.Type),
+// // Modifiers = Modifiers.Const,
+// // Variables = { initializer }
+// // };
+// //
+// // script.InsertBefore(statement, decl);
+// // var variableUsage = new IdentifierExpression(name);
+// // script.Replace(pexpr, variableUsage);
+// // script.Link(initializer.NameToken, variableUsage);
+// // }, pexpr);
+// // }
+// //
+// // yield return new CodeAction(context.TranslateString("Create constant field"), script => {
+// // string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
+// // var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
+// // if (service != null)
+// // name = service.CheckName(context, name, AffectedEntity.ConstantField);
+// //
+// // var initializer = new VariableInitializer(name, pexpr.Clone());
+// //
+// // var decl = new FieldDeclaration() {
+// // ReturnType = context.CreateShortType(resolveResult.Type),
+// // Modifiers = Modifiers.Const,
+// // Variables = { initializer }
+// // };
+// //
+// // var variableUsage = new IdentifierExpression(name);
+// // script.Replace(pexpr, variableUsage);
+// // // script.Link(initializer.NameToken, variableUsage);
+// // script.InsertWithCursor(context.TranslateString("Create constant"), Script.InsertPosition.Before, decl);
+// // }, pexpr);
+// //
+// // if (visitor.Matches.Count > 1) {
+// // yield return new CodeAction(string.Format(context.TranslateString("Create local constant (replace '{0}' occurrences)"), visitor.Matches.Count), script => {
+// // string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
+// // var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
+// // if (service != null)
+// // name = service.CheckName(context, name, AffectedEntity.LocalConstant);
+// //
+// // var initializer = new VariableInitializer(name, pexpr.Clone());
+// // var decl = new VariableDeclarationStatement() {
+// // Type = context.CreateShortType(resolveResult.Type),
+// // Modifiers = Modifiers.Const,
+// // Variables = { initializer }
+// // };
+// //
+// // script.InsertBefore(statement, decl);
+// //
+// // var linkedNodes = new List();
+// // linkedNodes.Add(initializer.NameToken);
+// // for (int i = 0; i < visitor.Matches.Count; i++) {
+// // var identifierExpression = new IdentifierExpression(name);
+// // linkedNodes.Add(identifierExpression);
+// // script.Replace(visitor.Matches [i], identifierExpression);
+// // }
+// // script.Link(linkedNodes.ToArray ());
+// // }, pexpr);
+// //
+// // yield return new CodeAction(string.Format(context.TranslateString("Create constant field (replace '{0}' occurrences)"), visitor.Matches.Count), script => {
+// // string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
+// // var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
+// // if (service != null)
+// // name = service.CheckName(context, name, AffectedEntity.ConstantField);
+// //
+// // var initializer = new VariableInitializer(name, pexpr.Clone());
+// //
+// // var decl = new FieldDeclaration() {
+// // ReturnType = context.CreateShortType(resolveResult.Type),
+// // Modifiers = Modifiers.Const,
+// // Variables = { initializer }
+// // };
+// //
+// // var linkedNodes = new List();
+// // linkedNodes.Add(initializer.NameToken);
+// // for (int i = 0; i < visitor.Matches.Count; i++) {
+// // var identifierExpression = new IdentifierExpression(name);
+// // linkedNodes.Add(identifierExpression);
+// // script.Replace(visitor.Matches [i], identifierExpression);
+// // }
+// // script.InsertWithCursor(context.TranslateString("Create constant"), Script.InsertPosition.Before, decl);
+// // }, pexpr);
+// // }
+// // }
+// }
+//}
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/LinqFluentToQueryAction.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/LinqFluentToQueryAction.cs
index 68a9e6f1..458481ac 100644
--- a/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/LinqFluentToQueryAction.cs
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/LinqFluentToQueryAction.cs
@@ -1,117 +1,117 @@
-using System.Threading;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
+//using System.Threading;
+//using System.Collections.Generic;
+//using Microsoft.CodeAnalysis.CodeRefactorings;
+//using Microsoft.CodeAnalysis;
+//using Microsoft.CodeAnalysis.CodeActions;
+//using Microsoft.CodeAnalysis.Text;
+//using Microsoft.CodeAnalysis.CSharp.Syntax;
-namespace RefactoringEssentials.CSharp.CodeRefactorings
-{
- [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Convert LINQ query to fluent syntax")]
- [NotPortedYet]
- public class LinqFluentToQueryAction : SpecializedCodeRefactoringProvider
- {
- // static readonly List LinqQueryMethods = new List() {
- // "Select", "SelectMany", "GroupBy",
- // "OrderBy", "OrderByDescending", "ThenBy", "ThenByDescending",
- // "Where", "Cast",
- // "Join", "GroupJoin"
- // };
- //
- protected override IEnumerable GetActions(Document document, SemanticModel semanticModel, SyntaxNode root, TextSpan span, InvocationExpressionSyntax node, CancellationToken cancellationToken)
- {
- yield break;
- }
- // protected override CodeAction GetAction(SemanticModel context, InvocationExpression node)
- // {
- // if (!IsLinqMethodInvocation(node)) {
- // return null;
- // }
- //
- // while (node.Parent is MemberReferenceExpression) {
- // var parentInvocation = ((MemberReferenceExpression)node.Parent).Parent;
- // if (!IsLinqMethodInvocation(parentInvocation)) {
- // break;
- // }
- // node = (InvocationExpression) parentInvocation;
- // }
- //
- // IntroduceQueryExpressions queryExpressionIntroducer = new IntroduceQueryExpressions();
- // CombineQueryExpressions queryExpressionCombiner = new CombineQueryExpressions();
- // Expression newNode = queryExpressionIntroducer.ConvertFluentToQuery(node);
- //
- // queryExpressionCombiner.CombineQuery(newNode);
- //
- // if (!(newNode is QueryExpression)) {
- // return null;
- // }
- //
- // return new CodeAction(context.TranslateString("Convert to query syntax"), script => {
- // List newNames = new List();
- // var identifiers = newNode.Descendants.OfType().ToList();
- // foreach (var identifier in identifiers.Where(id => id.Name.StartsWith("<>")))
- // {
- // int nameId = int.Parse(identifier.Name.Substring(2)) - 1;
- // while (newNames.Count <= nameId) {
- // //Find new name
- //
- // //This might skip some legitimate names, but that's not a real problem.
- // var topMostBlock = node.AncestorsAndSelf.OfType().Last();
- // var variableDeclarations = topMostBlock.Descendants.OfType();
- // var declaredNames = variableDeclarations.SelectMany(variableDeclaration => variableDeclaration.Variables).Select(variable => variable.Name).ToList();
- //
- // int currentId = 1;
- // while (identifiers.Any(id => id.Name == "_" + currentId) || declaredNames.Contains("_" + currentId)) {
- // ++currentId;
- // }
- //
- // newNames.Add("_" + currentId);
- // }
- //
- // identifier.Name = newNames[nameId];
- // }
- //
- // if (NeedsParenthesis(node)) {
- // newNode = new ParenthesizedExpression(newNode);
- // }
- //
- // script.Replace(node, newNode);
- // }, node);
- // }
- //
- // bool NeedsParenthesis(AstNode node)
- // {
- // AstNode parent = node.Parent;
- // if (parent is BinaryOperatorExpression)
- // return true;
- //
- // UnaryOperatorExpression unaryExpression = parent as UnaryOperatorExpression;
- // if (unaryExpression != null) {
- // return unaryExpression.Operator == UnaryOperatorType.PostIncrement ||
- // unaryExpression.Operator == UnaryOperatorType.PostDecrement;
- // }
- //
- // return parent is MemberReferenceExpression ||
- // parent is InvocationExpression;
- // }
- //
- // bool IsLinqMethodInvocation(AstNode node)
- // {
- // var invocation = node as InvocationExpression;
- // return invocation != null && IsLinqMethodInvocation(invocation);
- // }
- //
- // bool IsLinqMethodInvocation(InvocationExpression node)
- // {
- // var target = node.Target as MemberReferenceExpression;
- // return target != null && IsLinqMethod(target);
- // }
- //
- // bool IsLinqMethod(MemberReferenceExpression node)
- // {
- // return LinqQueryMethods.Contains(node.MemberName);
- // }
- }
-}
+//namespace RefactoringEssentials.CSharp.CodeRefactorings
+//{
+// [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Convert LINQ query to fluent syntax")]
+// [NotPortedYet]
+// public class LinqFluentToQueryAction : SpecializedCodeRefactoringProvider
+// {
+// // static readonly List LinqQueryMethods = new List() {
+// // "Select", "SelectMany", "GroupBy",
+// // "OrderBy", "OrderByDescending", "ThenBy", "ThenByDescending",
+// // "Where", "Cast",
+// // "Join", "GroupJoin"
+// // };
+// //
+// protected override IEnumerable GetActions(Document document, SemanticModel semanticModel, SyntaxNode root, TextSpan span, InvocationExpressionSyntax node, CancellationToken cancellationToken)
+// {
+// yield break;
+// }
+// // protected override CodeAction GetAction(SemanticModel context, InvocationExpression node)
+// // {
+// // if (!IsLinqMethodInvocation(node)) {
+// // return null;
+// // }
+// //
+// // while (node.Parent is MemberReferenceExpression) {
+// // var parentInvocation = ((MemberReferenceExpression)node.Parent).Parent;
+// // if (!IsLinqMethodInvocation(parentInvocation)) {
+// // break;
+// // }
+// // node = (InvocationExpression) parentInvocation;
+// // }
+// //
+// // IntroduceQueryExpressions queryExpressionIntroducer = new IntroduceQueryExpressions();
+// // CombineQueryExpressions queryExpressionCombiner = new CombineQueryExpressions();
+// // Expression newNode = queryExpressionIntroducer.ConvertFluentToQuery(node);
+// //
+// // queryExpressionCombiner.CombineQuery(newNode);
+// //
+// // if (!(newNode is QueryExpression)) {
+// // return null;
+// // }
+// //
+// // return new CodeAction(context.TranslateString("Convert to query syntax"), script => {
+// // List newNames = new List();
+// // var identifiers = newNode.Descendants.OfType().ToList();
+// // foreach (var identifier in identifiers.Where(id => id.Name.StartsWith("<>")))
+// // {
+// // int nameId = int.Parse(identifier.Name.Substring(2)) - 1;
+// // while (newNames.Count <= nameId) {
+// // //Find new name
+// //
+// // //This might skip some legitimate names, but that's not a real problem.
+// // var topMostBlock = node.AncestorsAndSelf.OfType().Last();
+// // var variableDeclarations = topMostBlock.Descendants.OfType();
+// // var declaredNames = variableDeclarations.SelectMany(variableDeclaration => variableDeclaration.Variables).Select(variable => variable.Name).ToList();
+// //
+// // int currentId = 1;
+// // while (identifiers.Any(id => id.Name == "_" + currentId) || declaredNames.Contains("_" + currentId)) {
+// // ++currentId;
+// // }
+// //
+// // newNames.Add("_" + currentId);
+// // }
+// //
+// // identifier.Name = newNames[nameId];
+// // }
+// //
+// // if (NeedsParenthesis(node)) {
+// // newNode = new ParenthesizedExpression(newNode);
+// // }
+// //
+// // script.Replace(node, newNode);
+// // }, node);
+// // }
+// //
+// // bool NeedsParenthesis(AstNode node)
+// // {
+// // AstNode parent = node.Parent;
+// // if (parent is BinaryOperatorExpression)
+// // return true;
+// //
+// // UnaryOperatorExpression unaryExpression = parent as UnaryOperatorExpression;
+// // if (unaryExpression != null) {
+// // return unaryExpression.Operator == UnaryOperatorType.PostIncrement ||
+// // unaryExpression.Operator == UnaryOperatorType.PostDecrement;
+// // }
+// //
+// // return parent is MemberReferenceExpression ||
+// // parent is InvocationExpression;
+// // }
+// //
+// // bool IsLinqMethodInvocation(AstNode node)
+// // {
+// // var invocation = node as InvocationExpression;
+// // return invocation != null && IsLinqMethodInvocation(invocation);
+// // }
+// //
+// // bool IsLinqMethodInvocation(InvocationExpression node)
+// // {
+// // var target = node.Target as MemberReferenceExpression;
+// // return target != null && IsLinqMethod(target);
+// // }
+// //
+// // bool IsLinqMethod(MemberReferenceExpression node)
+// // {
+// // return LinqQueryMethods.Contains(node.MemberName);
+// // }
+// }
+//}
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/LinqQueryToFluentAction.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/LinqQueryToFluentAction.cs
index 245d9840..dba2a260 100644
--- a/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/LinqQueryToFluentAction.cs
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/LinqQueryToFluentAction.cs
@@ -1,99 +1,99 @@
-using System.Threading;
-using System.Collections.Generic;
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
+//using System.Threading;
+//using System.Collections.Generic;
+//using Microsoft.CodeAnalysis.CodeRefactorings;
+//using Microsoft.CodeAnalysis;
+//using Microsoft.CodeAnalysis.CodeActions;
+//using Microsoft.CodeAnalysis.Text;
+//using Microsoft.CodeAnalysis.CSharp.Syntax;
-namespace RefactoringEssentials.CSharp.CodeRefactorings
-{
- [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Convert LINQ query to fluent syntax")]
- [NotPortedYet]
- public class LinqQueryToFluentAction : SpecializedCodeRefactoringProvider
- {
- protected override IEnumerable GetActions(Document document, SemanticModel semanticModel, SyntaxNode root, TextSpan span, QueryExpressionSyntax node, CancellationToken cancellationToken)
- {
- yield break;
- }
- // protected override CodeAction GetAction(SemanticModel context, QueryExpression node)
- // {
- // AstNode currentNode = node;
- // for (;;) {
- // QueryContinuationClause continuationParent = currentNode.Parent as QueryContinuationClause;
- // if (continuationParent != null) {
- // currentNode = continuationParent;
- // continue;
- // }
- // QueryExpression exprParent = currentNode.Parent as QueryExpression;
- // if (exprParent != null) {
- // currentNode = exprParent;
- // continue;
- // }
- //
- // break;
- // }
- //
- // node = (QueryExpression)currentNode;
- //
- // return new CodeAction(context.TranslateString("Convert LINQ query to fluent syntax"),
- // script => ConvertQueryToFluent(context, script, node),
- // node);
- // }
- //
- // static void ConvertQueryToFluent(SemanticModel context, Script script, QueryExpression query) {
- // IEnumerable underscoreIdentifiers = GetNameProposals (context, query, "_");
- // Expression newExpression = GetFluentFromQuery(query, underscoreIdentifiers);
- // script.Replace (query, newExpression);
- // }
- //
- // static IEnumerable GetNameProposals(SemanticModel context, QueryExpression query, string baseName)
- // {
- // var resolver = context.GetResolverStateBefore(query);
- // int current = -1;
- // string nameProposal;
- // for (;;) {
- // do {
- // ++current;
- // nameProposal = baseName + (current == 0 ? string.Empty : current.ToString());
- // } while (IsNameUsed (resolver, query, nameProposal));
- //
- // yield return nameProposal;
- // }
- // }
- //
- // static bool IsNameUsed(CSharpResolver resolver, QueryExpression query, string name)
- // {
- // if (resolver.ResolveSimpleName(name, new List()) is LocalResolveResult) {
- // return true;
- // }
- //
- // if (query.Ancestors.OfType ().Any(variable => variable.Name == name)) {
- // return true;
- // }
- //
- // if (query.Ancestors.OfType ()
- // .Any(blockStatement => DeclaresLocalVariable(blockStatement, name))) {
- //
- // return true;
- // }
- //
- // return query.Descendants.OfType ().Any (identifier => identifier.Name == name);
- // }
- //
- // static bool DeclaresLocalVariable(BlockStatement blockStatement, string name) {
- // return blockStatement.Descendants.OfType ()
- // .Any(variable => variable.Name == name &&
- // variable.Ancestors.OfType().First() == blockStatement);
- // }
- //
- // static Expression GetFluentFromQuery (QueryExpression query, IEnumerable underscoreIdentifiers)
- // {
- // var queryExpander = new QueryExpressionExpander();
- // var expandResult = queryExpander.ExpandQueryExpressions(query, underscoreIdentifiers);
- //
- // return (Expression) expandResult.AstNode;
- // }
- }
-}
+//namespace RefactoringEssentials.CSharp.CodeRefactorings
+//{
+// [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Convert LINQ query to fluent syntax")]
+// [NotPortedYet]
+// public class LinqQueryToFluentAction : SpecializedCodeRefactoringProvider
+// {
+// protected override IEnumerable GetActions(Document document, SemanticModel semanticModel, SyntaxNode root, TextSpan span, QueryExpressionSyntax node, CancellationToken cancellationToken)
+// {
+// yield break;
+// }
+// // protected override CodeAction GetAction(SemanticModel context, QueryExpression node)
+// // {
+// // AstNode currentNode = node;
+// // for (;;) {
+// // QueryContinuationClause continuationParent = currentNode.Parent as QueryContinuationClause;
+// // if (continuationParent != null) {
+// // currentNode = continuationParent;
+// // continue;
+// // }
+// // QueryExpression exprParent = currentNode.Parent as QueryExpression;
+// // if (exprParent != null) {
+// // currentNode = exprParent;
+// // continue;
+// // }
+// //
+// // break;
+// // }
+// //
+// // node = (QueryExpression)currentNode;
+// //
+// // return new CodeAction(context.TranslateString("Convert LINQ query to fluent syntax"),
+// // script => ConvertQueryToFluent(context, script, node),
+// // node);
+// // }
+// //
+// // static void ConvertQueryToFluent(SemanticModel context, Script script, QueryExpression query) {
+// // IEnumerable underscoreIdentifiers = GetNameProposals (context, query, "_");
+// // Expression newExpression = GetFluentFromQuery(query, underscoreIdentifiers);
+// // script.Replace (query, newExpression);
+// // }
+// //
+// // static IEnumerable GetNameProposals(SemanticModel context, QueryExpression query, string baseName)
+// // {
+// // var resolver = context.GetResolverStateBefore(query);
+// // int current = -1;
+// // string nameProposal;
+// // for (;;) {
+// // do {
+// // ++current;
+// // nameProposal = baseName + (current == 0 ? string.Empty : current.ToString());
+// // } while (IsNameUsed (resolver, query, nameProposal));
+// //
+// // yield return nameProposal;
+// // }
+// // }
+// //
+// // static bool IsNameUsed(CSharpResolver resolver, QueryExpression query, string name)
+// // {
+// // if (resolver.ResolveSimpleName(name, new List()) is LocalResolveResult) {
+// // return true;
+// // }
+// //
+// // if (query.Ancestors.OfType ().Any(variable => variable.Name == name)) {
+// // return true;
+// // }
+// //
+// // if (query.Ancestors.OfType ()
+// // .Any(blockStatement => DeclaresLocalVariable(blockStatement, name))) {
+// //
+// // return true;
+// // }
+// //
+// // return query.Descendants.OfType ().Any (identifier => identifier.Name == name);
+// // }
+// //
+// // static bool DeclaresLocalVariable(BlockStatement blockStatement, string name) {
+// // return blockStatement.Descendants.OfType ()
+// // .Any(variable => variable.Name == name &&
+// // variable.Ancestors.OfType().First() == blockStatement);
+// // }
+// //
+// // static Expression GetFluentFromQuery (QueryExpression query, IEnumerable underscoreIdentifiers)
+// // {
+// // var queryExpander = new QueryExpressionExpander();
+// // var expandResult = queryExpander.ExpandQueryExpressions(query, underscoreIdentifiers);
+// //
+// // return (Expression) expandResult.AstNode;
+// // }
+// }
+//}
diff --git a/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/MoveToOuterScopeAction.cs b/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/MoveToOuterScopeAction.cs
index bef755b3..e1d6451a 100644
--- a/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/MoveToOuterScopeAction.cs
+++ b/RefactoringEssentials/CSharp/CodeRefactorings/Uncategorized/MoveToOuterScopeAction.cs
@@ -1,134 +1,134 @@
-using Microsoft.CodeAnalysis.CodeRefactorings;
-using Microsoft.CodeAnalysis;
-using System.Threading.Tasks;
+//using Microsoft.CodeAnalysis.CodeRefactorings;
+//using Microsoft.CodeAnalysis;
+//using System.Threading.Tasks;
-namespace RefactoringEssentials.CSharp.CodeRefactorings
-{
- [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Move to outer scope")]
- [NotPortedYet]
- public class MoveToOuterScopeAction : CodeRefactoringProvider
- {
- public override Task ComputeRefactoringsAsync(CodeRefactoringContext context)
- {
- //var document = context.Document;
- //var span = context.Span;
- //var cancellationToken = context.CancellationToken;
- //var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- //if (model.IsFromGeneratedCode(cancellationToken))
- // return;
- //var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
- return Task.FromResult(0);
- }
- // public async Task ComputeRefactoringsAsync(Document document, TextSpan span, CancellationToken cancellationToken)
- // {
- // var variableDeclaration = context.GetNode();
- // if (variableDeclaration == null)
- // yield break;
- // var entryNode = FindCurrentScopeEntryNode(variableDeclaration);
- // if (entryNode == null)
- // yield break;
- // var selectedInitializer = context.GetNode();
- // if (selectedInitializer != null) {
- // if (!selectedInitializer.NameToken.Contains(context.Location))
- // yield break;
- // if (HasDependency(context, entryNode, selectedInitializer)) {
- // yield return MoveDeclarationAction(context, entryNode, variableDeclaration, selectedInitializer);
- // } else {
- // yield return MoveInitializerAction(context, entryNode, variableDeclaration, selectedInitializer);
- // }
- // } else {
- // if (!variableDeclaration.Type.Contains(context.Location) || variableDeclaration.Variables.Count <= 1)
- // yield break;
- // yield return new CodeAction(context.TranslateString("Move declaration to outer scope"), script => {
- // script.Remove(variableDeclaration);
- // script.InsertBefore(entryNode, variableDeclaration.Clone());
- // }, variableDeclaration);
- // }
- // }
- //
- // static CodeAction MoveInitializerAction(SemanticModel context, AstNode insertAnchor,
- // VariableDeclarationStatement declaration, VariableInitializer initializer)
- // {
- // var type = declaration.Type.Clone();
- // var name = initializer.Name;
- // return new CodeAction(context.TranslateString("Move initializer to outer scope"), script => {
- // if (declaration.Variables.Count != 1) {
- // var innerDeclaration = RemoveInitializer(declaration, initializer);
- // script.InsertBefore(declaration, innerDeclaration);
- // }
- // script.Remove(declaration);
- // var outerDeclaration = new VariableDeclarationStatement(type, name, initializer.Initializer.Clone());
- // script.InsertBefore(insertAnchor, outerDeclaration);
- // }, initializer.NameToken);
- // }
- //
- // static CodeAction MoveDeclarationAction(SemanticModel context, AstNode insertAnchor,
- // VariableDeclarationStatement declarationStatement, VariableInitializer initializer)
- // {
- // var type = declarationStatement.Type.Clone();
- // var name = initializer.Name;
- //
- // return new CodeAction(context.TranslateString("Move declaration to outer scope"), script => {
- // script.InsertBefore(declarationStatement, new ExpressionStatement {
- // Expression = new AssignmentExpression(new IdentifierExpression(name), initializer.Initializer.Clone())
- // });
- // script.Remove(declarationStatement);
- // script.InsertBefore(insertAnchor, new VariableDeclarationStatement(type, name, Expression.Null));
- // }, initializer.NameToken);
- // }
- //
- // bool HasDependency(SemanticModel context, AstNode firstSearchNode, AstNode targetNode)
- // {
- // var referenceFinder = new FindReferences();
- // var identifiers = targetNode.Descendants
- // .Where(n => n is IdentifierExpression)
- // .Select(node => (IdentifierExpression)node);
- // foreach (var identifier in identifiers) {
- // var resolveResult = context.Resolve(identifier);
- // var localResolveResult = resolveResult as LocalResolveResult;
- // if (localResolveResult == null)
- // continue;
- // bool referenceFound = false;
- //// var variable = localResolveResult.Variable;
- // var syntaxTree = context.RootNode as SyntaxTree;
- // referenceFinder.FindLocalReferences(localResolveResult.Variable, context.UnresolvedFile, syntaxTree,
- // context.Compilation, (node, nodeResolveResult) => {
- // if (node.StartLocation > firstSearchNode.StartLocation && node.EndLocation < targetNode.StartLocation)
- // referenceFound = true;
- // }, CancellationToken.None);
- // if (referenceFound)
- // return true;
- // }
- // return false;
- // }
- //
- // static VariableDeclarationStatement RemoveInitializer(VariableDeclarationStatement variableDeclarationStatement, VariableInitializer selectedVariableInitializer)
- // {
- // var newVariableDeclarationStatement = new VariableDeclarationStatement() {
- // Type = variableDeclarationStatement.Type.Clone()
- // };
- // foreach (var variableInitializer in variableDeclarationStatement.Variables) {
- // if (variableInitializer != selectedVariableInitializer) {
- // newVariableDeclarationStatement.AddChild((VariableInitializer)variableInitializer.Clone(), Roles.Variable);
- // }
- // }
- // return newVariableDeclarationStatement;
- // }
- //
- // AstNode FindCurrentScopeEntryNode(Statement startNode)
- // {
- // // Start one node up in the tree, otherwise we may stop at the BlockStatement
- // // of the current scope instead of moving up to the enclosing scope
- // var currentNode = startNode.Parent;
- // AstNode lastNode;
- // do {
- // lastNode = currentNode;
- // currentNode = currentNode.Parent;
- // if (currentNode == null)
- // return null;
- // } while (!(currentNode is BlockStatement));
- // return lastNode;
- // }
- }
-}
+//namespace RefactoringEssentials.CSharp.CodeRefactorings
+//{
+// [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Move to outer scope")]
+// [NotPortedYet]
+// public class MoveToOuterScopeAction : CodeRefactoringProvider
+// {
+// public override Task ComputeRefactoringsAsync(CodeRefactoringContext context)
+// {
+// //var document = context.Document;
+// //var span = context.Span;
+// //var cancellationToken = context.CancellationToken;
+// //var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
+// //if (model.IsFromGeneratedCode(cancellationToken))
+// // return;
+// //var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
+// return Task.FromResult(0);
+// }
+// // public async Task ComputeRefactoringsAsync(Document document, TextSpan span, CancellationToken cancellationToken)
+// // {
+// // var variableDeclaration = context.GetNode();
+// // if (variableDeclaration == null)
+// // yield break;
+// // var entryNode = FindCurrentScopeEntryNode(variableDeclaration);
+// // if (entryNode == null)
+// // yield break;
+// // var selectedInitializer = context.GetNode();
+// // if (selectedInitializer != null) {
+// // if (!selectedInitializer.NameToken.Contains(context.Location))
+// // yield break;
+// // if (HasDependency(context, entryNode, selectedInitializer)) {
+// // yield return MoveDeclarationAction(context, entryNode, variableDeclaration, selectedInitializer);
+// // } else {
+// // yield return MoveInitializerAction(context, entryNode, variableDeclaration, selectedInitializer);
+// // }
+// // } else {
+// // if (!variableDeclaration.Type.Contains(context.Location) || variableDeclaration.Variables.Count <= 1)
+// // yield break;
+// // yield return new CodeAction(context.TranslateString("Move declaration to outer scope"), script => {
+// // script.Remove(variableDeclaration);
+// // script.InsertBefore(entryNode, variableDeclaration.Clone());
+// // }, variableDeclaration);
+// // }
+// // }
+// //
+// // static CodeAction MoveInitializerAction(SemanticModel context, AstNode insertAnchor,
+// // VariableDeclarationStatement declaration, VariableInitializer initializer)
+// // {
+// // var type = declaration.Type.Clone();
+// // var name = initializer.Name;
+// // return new CodeAction(context.TranslateString("Move initializer to outer scope"), script => {
+// // if (declaration.Variables.Count != 1) {
+// // var innerDeclaration = RemoveInitializer(declaration, initializer);
+// // script.InsertBefore(declaration, innerDeclaration);
+// // }
+// // script.Remove(declaration);
+// // var outerDeclaration = new VariableDeclarationStatement(type, name, initializer.Initializer.Clone());
+// // script.InsertBefore(insertAnchor, outerDeclaration);
+// // }, initializer.NameToken);
+// // }
+// //
+// // static CodeAction MoveDeclarationAction(SemanticModel context, AstNode insertAnchor,
+// // VariableDeclarationStatement declarationStatement, VariableInitializer initializer)
+// // {
+// // var type = declarationStatement.Type.Clone();
+// // var name = initializer.Name;
+// //
+// // return new CodeAction(context.TranslateString("Move declaration to outer scope"), script => {
+// // script.InsertBefore(declarationStatement, new ExpressionStatement {
+// // Expression = new AssignmentExpression(new IdentifierExpression(name), initializer.Initializer.Clone())
+// // });
+// // script.Remove(declarationStatement);
+// // script.InsertBefore(insertAnchor, new VariableDeclarationStatement(type, name, Expression.Null));
+// // }, initializer.NameToken);
+// // }
+// //
+// // bool HasDependency(SemanticModel context, AstNode firstSearchNode, AstNode targetNode)
+// // {
+// // var referenceFinder = new FindReferences();
+// // var identifiers = targetNode.Descendants
+// // .Where(n => n is IdentifierExpression)
+// // .Select(node => (IdentifierExpression)node);
+// // foreach (var identifier in identifiers) {
+// // var resolveResult = context.Resolve(identifier);
+// // var localResolveResult = resolveResult as LocalResolveResult;
+// // if (localResolveResult == null)
+// // continue;
+// // bool referenceFound = false;
+// //// var variable = localResolveResult.Variable;
+// // var syntaxTree = context.RootNode as SyntaxTree;
+// // referenceFinder.FindLocalReferences(localResolveResult.Variable, context.UnresolvedFile, syntaxTree,
+// // context.Compilation, (node, nodeResolveResult) => {
+// // if (node.StartLocation > firstSearchNode.StartLocation && node.EndLocation < targetNode.StartLocation)
+// // referenceFound = true;
+// // }, CancellationToken.None);
+// // if (referenceFound)
+// // return true;
+// // }
+// // return false;
+// // }
+// //
+// // static VariableDeclarationStatement RemoveInitializer(VariableDeclarationStatement variableDeclarationStatement, VariableInitializer selectedVariableInitializer)
+// // {
+// // var newVariableDeclarationStatement = new VariableDeclarationStatement() {
+// // Type = variableDeclarationStatement.Type.Clone()
+// // };
+// // foreach (var variableInitializer in variableDeclarationStatement.Variables) {
+// // if (variableInitializer != selectedVariableInitializer) {
+// // newVariableDeclarationStatement.AddChild((VariableInitializer)variableInitializer.Clone(), Roles.Variable);
+// // }
+// // }
+// // return newVariableDeclarationStatement;
+// // }
+// //
+// // AstNode FindCurrentScopeEntryNode(Statement startNode)
+// // {
+// // // Start one node up in the tree, otherwise we may stop at the BlockStatement
+// // // of the current scope instead of moving up to the enclosing scope
+// // var currentNode = startNode.Parent;
+// // AstNode lastNode;
+// // do {
+// // lastNode = currentNode;
+// // currentNode = currentNode.Parent;
+// // if (currentNode == null)
+// // return null;
+// // } while (!(currentNode is BlockStatement));
+// // return lastNode;
+// // }
+// }
+//}
diff --git a/RefactoringEssentials/CSharp/ConstructorParameterContextFinder.cs b/RefactoringEssentials/CSharp/ConstructorParameterContextFinder.cs
index 044ccebf..bc8e515c 100644
--- a/RefactoringEssentials/CSharp/ConstructorParameterContextFinder.cs
+++ b/RefactoringEssentials/CSharp/ConstructorParameterContextFinder.cs
@@ -3,7 +3,7 @@
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
-using System.Linq;
+using System.Diagnostics.Contracts;
using System.Text;
using System.Threading.Tasks;
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Custom/AdditionalOfTypeAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Custom/AdditionalOfTypeAnalyzer.cs
index 5ea68aff..c5eecffd 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Custom/AdditionalOfTypeAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Custom/AdditionalOfTypeAnalyzer.cs
@@ -1,105 +1,105 @@
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Diagnostics;
-using System.Collections.Immutable;
+//using Microsoft.CodeAnalysis;
+//using Microsoft.CodeAnalysis.Diagnostics;
+//using System.Collections.Immutable;
-namespace RefactoringEssentials.CSharp.Diagnostics
-{
- [DiagnosticAnalyzer(LanguageNames.CSharp)]
- [NotPortedYet]
- public class AdditionalOfTypeAnalyzer : DiagnosticAnalyzer
- {
- // static readonly AstNode whereSimpleCase =
- // new InvocationExpression(
- // new MemberReferenceExpression(new AnyNode("target"), "Where"),
- // new NamedNode("lambda",
- // new LambdaExpression {
- // Parameters = { PatternHelper.NamedParameter("param1", PatternHelper.AnyType("paramType", true), Pattern.AnyString) },
- // Body = PatternHelper.OptionalParentheses(
- // new IsExpression(PatternHelper.OptionalParentheses(new NamedNode("expr1", new IdentifierExpression(Pattern.AnyString))), new AnyNode("type"))
- // )
- // }
- // )
- // );
+//namespace RefactoringEssentials.CSharp.Diagnostics
+//{
+// [DiagnosticAnalyzer(LanguageNames.CSharp)]
+// [NotPortedYet]
+// public class AdditionalOfTypeAnalyzer : DiagnosticAnalyzer
+// {
+// // static readonly AstNode whereSimpleCase =
+// // new InvocationExpression(
+// // new MemberReferenceExpression(new AnyNode("target"), "Where"),
+// // new NamedNode("lambda",
+// // new LambdaExpression {
+// // Parameters = { PatternHelper.NamedParameter("param1", PatternHelper.AnyType("paramType", true), Pattern.AnyString) },
+// // Body = PatternHelper.OptionalParentheses(
+// // new IsExpression(PatternHelper.OptionalParentheses(new NamedNode("expr1", new IdentifierExpression(Pattern.AnyString))), new AnyNode("type"))
+// // )
+// // }
+// // )
+// // );
- static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
- CSharpDiagnosticIDs.AdditionalOfTypeAnalyzerID,
- GettextCatalog.GetString("Replace with call to OfType (extended cases)"),
- GettextCatalog.GetString("Replace with 'OfType'"),
- DiagnosticAnalyzerCategories.PracticesAndImprovements,
- DiagnosticSeverity.Warning,
- isEnabledByDefault: true,
- helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.AdditionalOfTypeAnalyzerID)
- );
+// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
+// CSharpDiagnosticIDs.AdditionalOfTypeAnalyzerID,
+// GettextCatalog.GetString("Replace with call to OfType (extended cases)"),
+// GettextCatalog.GetString("Replace with 'OfType'"),
+// DiagnosticAnalyzerCategories.PracticesAndImprovements,
+// DiagnosticSeverity.Warning,
+// isEnabledByDefault: true,
+// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.AdditionalOfTypeAnalyzerID)
+// );
- public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
+// public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
- public override void Initialize(AnalysisContext context)
- {
- context.EnableConcurrentExecution();
- context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
- //context.RegisterSyntaxNodeAction(
- // (nodeContext) => {
- // Diagnostic diagnostic;
- // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
- // nodeContext.ReportDiagnostic(diagnostic);
- // }
- // },
- // new SyntaxKind[] { SyntaxKind.None }
- //);
- }
+// public override void Initialize(AnalysisContext context)
+// {
+// context.EnableConcurrentExecution();
+// context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
+// //context.RegisterSyntaxNodeAction(
+// // (nodeContext) => {
+// // Diagnostic diagnostic;
+// // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
+// // nodeContext.ReportDiagnostic(diagnostic);
+// // }
+// // },
+// // new SyntaxKind[] { SyntaxKind.None }
+// //);
+// }
- static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
- {
- diagnostic = default(Diagnostic);
- //var node = nodeContext.Node as ;
- //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
- //return true;
- return false;
- }
+// static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
+// {
+// diagnostic = default(Diagnostic);
+// //var node = nodeContext.Node as ;
+// //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
+// //return true;
+// return false;
+// }
- // class GatherVisitor : GatherVisitorBase
- // {
- // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
- // : base(semanticModel, addDiagnostic, cancellationToken)
- // {
- // }
+// // class GatherVisitor : GatherVisitorBase
+// // {
+// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
+// // : base(semanticModel, addDiagnostic, cancellationToken)
+// // {
+// // }
- //// public override void VisitInvocationExpression (InvocationExpression anyInvoke)
- //// {
- //// var match = ReplaceWithOfTypeAnalyzer.selectNotNullPattern.Match (anyInvoke);
- //// if (match.Success)
- //// return;
- ////
- //// match = ReplaceWithOfTypeAnalyzer.wherePatternCase1.Match (anyInvoke);
- //// if (match.Success)
- //// return;
- ////
- //// match = ReplaceWithOfTypeAnalyzer.wherePatternCase2.Match (anyInvoke);
- //// if (match.Success)
- //// return;
- ////
- //// // Warning: The simple case is not 100% equal in semantic, but it's one common code smell
- //// match = whereSimpleCase.Match (anyInvoke);
- //// if (!match.Success)
- //// return;
- //// var lambda = match.Get("lambda").Single();
- //// var expr = match.Get("expr1").Single();
- //// if (lambda.Parameters.Count != 1)
- //// return;
- //// if (expr.Identifier != lambda.Parameters.Single().Name)
- //// return;
- //// AddDiagnosticAnalyzer (new CodeIssue(
- //// anyInvoke,
- // // ctx.TranslateString("Replace with OfType"),
- //// ctx.TranslateString("Replace with call to OfType"),
- //// script => {
- //// var target = match.Get("target").Single().Clone ();
- //// var type = match.Get("type").Single().Clone();
- //// script.Replace(anyInvoke, new InvocationExpression(new MemberReferenceExpression(target, "OfType", type)));
- //// }
- //// ));
- //// }
- // }
- }
+// //// public override void VisitInvocationExpression (InvocationExpression anyInvoke)
+// //// {
+// //// var match = ReplaceWithOfTypeAnalyzer.selectNotNullPattern.Match (anyInvoke);
+// //// if (match.Success)
+// //// return;
+// ////
+// //// match = ReplaceWithOfTypeAnalyzer.wherePatternCase1.Match (anyInvoke);
+// //// if (match.Success)
+// //// return;
+// ////
+// //// match = ReplaceWithOfTypeAnalyzer.wherePatternCase2.Match (anyInvoke);
+// //// if (match.Success)
+// //// return;
+// ////
+// //// // Warning: The simple case is not 100% equal in semantic, but it's one common code smell
+// //// match = whereSimpleCase.Match (anyInvoke);
+// //// if (!match.Success)
+// //// return;
+// //// var lambda = match.Get("lambda").Single();
+// //// var expr = match.Get("expr1").Single();
+// //// if (lambda.Parameters.Count != 1)
+// //// return;
+// //// if (expr.Identifier != lambda.Parameters.Single().Name)
+// //// return;
+// //// AddDiagnosticAnalyzer (new CodeIssue(
+// //// anyInvoke,
+// // // ctx.TranslateString("Replace with OfType"),
+// //// ctx.TranslateString("Replace with call to OfType"),
+// //// script => {
+// //// var target = match.Get("target").Single().Clone ();
+// //// var type = match.Get("type").Single().Clone();
+// //// script.Replace(anyInvoke, new InvocationExpression(new MemberReferenceExpression(target, "OfType", type)));
+// //// }
+// //// ));
+// //// }
+// // }
+// }
-}
\ No newline at end of file
+//}
\ No newline at end of file
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Custom/CheckNamespaceAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Custom/CheckNamespaceAnalyzer.cs
index dae445ab..65c98a39 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Custom/CheckNamespaceAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Custom/CheckNamespaceAnalyzer.cs
@@ -1,89 +1,89 @@
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Diagnostics;
-using System.Collections.Immutable;
+//using Microsoft.CodeAnalysis;
+//using Microsoft.CodeAnalysis.Diagnostics;
+//using System.Collections.Immutable;
-namespace RefactoringEssentials.CSharp.Diagnostics
-{
- [DiagnosticAnalyzer(LanguageNames.CSharp)]
- [NotPortedYet]
- public class CheckNamespaceAnalyzer : DiagnosticAnalyzer
- {
- static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
- CSharpDiagnosticIDs.CheckNamespaceAnalyzerID,
- GettextCatalog.GetString("Check if a namespace corresponds to a file location"),
- "{0}",
- DiagnosticAnalyzerCategories.CodeQualityIssues,
- DiagnosticSeverity.Warning,
- isEnabledByDefault: true,
- helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.CheckNamespaceAnalyzerID)
- );
+//namespace RefactoringEssentials.CSharp.Diagnostics
+//{
+// [DiagnosticAnalyzer(LanguageNames.CSharp)]
+// [NotPortedYet]
+// public class CheckNamespaceAnalyzer : DiagnosticAnalyzer
+// {
+// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
+// CSharpDiagnosticIDs.CheckNamespaceAnalyzerID,
+// GettextCatalog.GetString("Check if a namespace corresponds to a file location"),
+// "{0}",
+// DiagnosticAnalyzerCategories.CodeQualityIssues,
+// DiagnosticSeverity.Warning,
+// isEnabledByDefault: true,
+// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.CheckNamespaceAnalyzerID)
+// );
- public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
+// public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
- public override void Initialize(AnalysisContext context)
- {
- context.EnableConcurrentExecution();
- context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
- //context.RegisterSyntaxNodeAction(
- // (nodeContext) => {
- // Diagnostic diagnostic;
- // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
- // nodeContext.ReportDiagnostic(diagnostic);
- // }
- // },
- // new SyntaxKind[] { SyntaxKind.None }
- //);
- }
+// public override void Initialize(AnalysisContext context)
+// {
+// context.EnableConcurrentExecution();
+// context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
+// //context.RegisterSyntaxNodeAction(
+// // (nodeContext) => {
+// // Diagnostic diagnostic;
+// // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
+// // nodeContext.ReportDiagnostic(diagnostic);
+// // }
+// // },
+// // new SyntaxKind[] { SyntaxKind.None }
+// //);
+// }
- static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
- {
- diagnostic = default(Diagnostic);
- //var node = nodeContext.Node as ;
- //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
- //return true;
- return false;
- }
+// static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
+// {
+// diagnostic = default(Diagnostic);
+// //var node = nodeContext.Node as ;
+// //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
+// //return true;
+// return false;
+// }
- // class GatherVisitor : GatherVisitorBase
- // {
- // //readonly string defaultNamespace;
+// // class GatherVisitor : GatherVisitorBase
+// // {
+// // //readonly string defaultNamespace;
- // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
- // : base(semanticModel, addDiagnostic, cancellationToken)
- // {
- // }
+// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
+// // : base(semanticModel, addDiagnostic, cancellationToken)
+// // {
+// // }
- //// public override void VisitSyntaxTree(SyntaxTree syntaxTree)
- //// {
- //// if (string.IsNullOrEmpty(defaultNamespace))
- //// return;
- //// base.VisitSyntaxTree(syntaxTree);
- //// }
- ////
- //// public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
- //// {
- //// base.VisitNamespaceDeclaration(namespaceDeclaration);
- //// // only check top level namespaces
- //// if (namespaceDeclaration.Parent is NamespaceDeclaration ||
- //// namespaceDeclaration.FullName == defaultNamespace)
- //// return;
- //// AddDiagnosticAnalyzer(new CodeIssue(
- //// namespaceDeclaration.NamespaceName,
- //// string.Format(ctx.TranslateString("Namespace does not correspond to file location, should be: '{0}'"), ctx.DefaultNamespace)
- //// ));
- //// }
- ////
- //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
- //// {
- //// var ns = typeDeclaration.Parent as NamespaceDeclaration;
- //// if (ns == null) {
- //// AddDiagnosticAnalyzer(new CodeIssue(
- //// typeDeclaration.NameToken,
- //// string.Format(ctx.TranslateString("Type should be declared inside the namespace '{0}'"), ctx.DefaultNamespace)
- //// ));
- //// }
- //// // skip children
- //// }
- // }
- }
-}
\ No newline at end of file
+// //// public override void VisitSyntaxTree(SyntaxTree syntaxTree)
+// //// {
+// //// if (string.IsNullOrEmpty(defaultNamespace))
+// //// return;
+// //// base.VisitSyntaxTree(syntaxTree);
+// //// }
+// ////
+// //// public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
+// //// {
+// //// base.VisitNamespaceDeclaration(namespaceDeclaration);
+// //// // only check top level namespaces
+// //// if (namespaceDeclaration.Parent is NamespaceDeclaration ||
+// //// namespaceDeclaration.FullName == defaultNamespace)
+// //// return;
+// //// AddDiagnosticAnalyzer(new CodeIssue(
+// //// namespaceDeclaration.NamespaceName,
+// //// string.Format(ctx.TranslateString("Namespace does not correspond to file location, should be: '{0}'"), ctx.DefaultNamespace)
+// //// ));
+// //// }
+// ////
+// //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
+// //// {
+// //// var ns = typeDeclaration.Parent as NamespaceDeclaration;
+// //// if (ns == null) {
+// //// AddDiagnosticAnalyzer(new CodeIssue(
+// //// typeDeclaration.NameToken,
+// //// string.Format(ctx.TranslateString("Type should be declared inside the namespace '{0}'"), ctx.DefaultNamespace)
+// //// ));
+// //// }
+// //// // skip children
+// //// }
+// // }
+// }
+//}
\ No newline at end of file
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Custom/LockThisAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Custom/LockThisAnalyzer.cs
index 7543e2b4..f7f76136 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Custom/LockThisAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Custom/LockThisAnalyzer.cs
@@ -1,386 +1,386 @@
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Diagnostics;
-using System.Collections.Immutable;
+//using Microsoft.CodeAnalysis;
+//using Microsoft.CodeAnalysis.Diagnostics;
+//using System.Collections.Immutable;
-namespace RefactoringEssentials.CSharp.Diagnostics
-{
- [DiagnosticAnalyzer(LanguageNames.CSharp)]
- [NotPortedYet]
- public class LockThisAnalyzer : DiagnosticAnalyzer
- {
- static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
- CSharpDiagnosticIDs.LockThisAnalyzerID,
- GettextCatalog.GetString("Warns about using lock (this) or MethodImplOptions.Synchronized"),
- "{0}",
- DiagnosticAnalyzerCategories.CodeQualityIssues,
- DiagnosticSeverity.Warning,
- isEnabledByDefault: true,
- helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.LockThisAnalyzerID)
- );
+//namespace RefactoringEssentials.CSharp.Diagnostics
+//{
+// [DiagnosticAnalyzer(LanguageNames.CSharp)]
+// [NotPortedYet]
+// public class LockThisAnalyzer : DiagnosticAnalyzer
+// {
+// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
+// CSharpDiagnosticIDs.LockThisAnalyzerID,
+// GettextCatalog.GetString("Warns about using lock (this) or MethodImplOptions.Synchronized"),
+// "{0}",
+// DiagnosticAnalyzerCategories.CodeQualityIssues,
+// DiagnosticSeverity.Warning,
+// isEnabledByDefault: true,
+// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.LockThisAnalyzerID)
+// );
- public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
+// public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
- public override void Initialize(AnalysisContext context)
- {
- context.EnableConcurrentExecution();
- context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
- //context.RegisterSyntaxNodeAction(
- // (nodeContext) => {
- // Diagnostic diagnostic;
- // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
- // nodeContext.ReportDiagnostic(diagnostic);
- // }
- // },
- // new SyntaxKind[] { SyntaxKind.None }
- //);
- }
+// public override void Initialize(AnalysisContext context)
+// {
+// context.EnableConcurrentExecution();
+// context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
+// //context.RegisterSyntaxNodeAction(
+// // (nodeContext) => {
+// // Diagnostic diagnostic;
+// // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
+// // nodeContext.ReportDiagnostic(diagnostic);
+// // }
+// // },
+// // new SyntaxKind[] { SyntaxKind.None }
+// //);
+// }
- static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
- {
- diagnostic = default(Diagnostic);
- //var node = nodeContext.Node as ;
- //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
- //return true;
- return false;
- }
+// static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
+// {
+// diagnostic = default(Diagnostic);
+// //var node = nodeContext.Node as ;
+// //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
+// //return true;
+// return false;
+// }
- // class GatherVisitor : GatherVisitorBase
- // {
- // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
- // : base(semanticModel, addDiagnostic, cancellationToken)
- // {
- // }
+// // class GatherVisitor : GatherVisitorBase
+// // {
+// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
+// // : base(semanticModel, addDiagnostic, cancellationToken)
+// // {
+// // }
- //// public override void VisitAttribute(Attribute attribute)
- //// {
- //// base.VisitAttribute(attribute);
- ////
- //// if (IsMethodSynchronizedAttribute(attribute)) {
- //// var fixAction = new CodeAction(ctx.TranslateString("Create private locker field"), script => {
- //// var containerEntity = GetParentMethodOrProperty(attribute);
- //// var containerType = containerEntity.GetParent();
- ////
- //// FixLockThisIssue(script, containerEntity, containerType);
- //// }, attribute);
- ////
- //// AddDiagnosticAnalyzer(new CodeIssue(attribute, ctx.TranslateString("Found [MethodImpl(MethodImplOptions.Synchronized)]"), fixAction));
- //// }
- //// }
- ////
- //// static EntityDeclaration GetParentMethodOrProperty(AstNode node)
- //// {
- //// var containerEntity = node.GetParent();
- //// if (containerEntity is Accessor) {
- //// containerEntity = containerEntity.GetParent();
- //// }
- ////
- //// return containerEntity;
- //// }
- ////
- //// public override void VisitLockStatement(LockStatement lockStatement)
- //// {
- //// base.VisitLockStatement(lockStatement);
- ////
- //// var expression = lockStatement.Expression;
- ////
- //// if (IsThisReference(expression)) {
- //// var fixAction = new CodeAction(ctx.TranslateString("Create private locker field"), script => {
- //// var containerEntity = GetParentMethodOrProperty(lockStatement);
- ////
- //// var containerType = containerEntity.GetParent();
- ////
- //// FixLockThisIssue(script, containerEntity, containerType);
- ////
- //// }, lockStatement);
- ////
- //// AddDiagnosticAnalyzer(new CodeIssue(lockStatement.LockToken.StartLocation,
- //// lockStatement.RParToken.EndLocation, ctx.TranslateString("Found lock (this)"), fixAction));
- //// }
- //// }
- ////
- //// static bool IsEntityStatic(EntityDeclaration containerEntity)
- //// {
- //// return containerEntity.Modifiers.HasFlag(Modifiers.Static);
- //// }
- ////
- //// void FixLockThisIssue(Script script, EntityDeclaration containerEntity, TypeDeclaration containerType)
- //// {
- //// bool isStatic = IsEntityStatic(containerEntity);
- ////
- //// List synchronizedStatements = FixMethodsWithMethodImplAttribute(script, containerType, isStatic).ToList();
- ////
- //// List linkNodes = new List();
- ////
- //// var locksToModify = LocksToModify(containerType, synchronizedStatements);
- //// List nodeContexts = new List(locksToModify);
- ////
- //// foreach (var synchronizedStatement in synchronizedStatements) {
- //// if (synchronizedStatement.Statements.Count > 0) {
- //// nodeContexts.Add(synchronizedStatement.Statements.First());
- ////
- //// if (!isStatic) {
- //// foreach (var childLock in synchronizedStatement.Descendants.OfType()) {
- //// if (IsThisReference(childLock.Expression)) {
- //// nodeContexts.Add(childLock);
- //// }
- //// }
- //// }
- //// }
- //// }
- ////
- //// string proposedName = GetNameProposal(nodeContexts, "locker");
- ////
- //// if (!isStatic) {
- //// foreach (var lockToModify in locksToModify) {
- //// var identifier = new IdentifierExpression (proposedName);
- //// script.Replace(lockToModify.Expression, identifier);
- ////
- //// linkNodes.Add(identifier);
- //// }
- //// }
- ////
- //// foreach (var synchronizedStatement in synchronizedStatements) {
- //// if (synchronizedStatement.Statements.Count > 0) {
- //// var newBody = synchronizedStatement.Clone();
- ////
- //// var outerLock = new LockStatement();
- //// var outerLockIdentifier = new IdentifierExpression (proposedName);
- //// outerLock.Expression = outerLockIdentifier;
- //// outerLock.EmbeddedStatement = newBody;
- ////
- //// linkNodes.Add(outerLockIdentifier);
- ////
- //// if (!isStatic) {
- //// foreach (var childLock in newBody.Descendants.OfType()) {
- //// if (IsThisReference(childLock.Expression)) {
- //// var identifier = new IdentifierExpression (proposedName);
- //// childLock.Expression.ReplaceWith(identifier);
- ////
- //// linkNodes.Add(identifier);
- //// }
- //// }
- //// }
- ////
- //// script.InsertBefore(synchronizedStatement.Statements.First(), outerLock);
- ////
- //// foreach (var stmt in synchronizedStatement.Statements) {
- //// script.Remove(stmt);
- //// }
- //// }
- //// }
- ////
- //// if (linkNodes.Any()) {
- //// var objectType = new PrimitiveType("object");
- ////
- //// var lockerFieldDeclaration = new FieldDeclaration() {
- //// Modifiers = isStatic ? Modifiers.Static : Modifiers.None,
- //// ReturnType = objectType.Clone()
- //// };
- ////
- //// var lockerVariable = new VariableInitializer(proposedName, new ObjectCreateExpression(objectType.Clone()));
- //// lockerFieldDeclaration.Variables.Add(lockerVariable);
- //// script.InsertBefore(containerEntity, lockerFieldDeclaration);
- ////
- //// linkNodes.Add(lockerVariable.NameToken);
- ////
- //// script.Link(linkNodes.ToArray());
- //// }
- //// }
- ////
- //// string GetNameProposal(List nodeContexts, string baseName)
- //// {
- //// var resolverStates = nodeContexts.Select(ctx.GetResolverStateBefore).ToList();
- //// string nameProposal;
- //// int n = 0;
- //// do {
- //// nameProposal = baseName + (n == 0 ? string.Empty : n.ToString());
- //// n++;
- //// } while (IdentifierNameExists(resolverStates, nameProposal));
- //// return nameProposal;
- //// }
- ////
- //// static bool IdentifierNameExists(List resolverStates, string nameProposal)
- //// {
- //// return resolverStates.Any(resolverState => {
- //// ResolveResult result = resolverState.LookupSimpleNameOrTypeName(nameProposal, new List(), NameLookupMode.Expression);
- //// return !result.IsError;
- //// });
- //// }
- ////
- //// IEnumerable LocksToModify(TypeDeclaration containerType, IEnumerable synchronizedStatements)
- //// {
- //// foreach (var lockToModify in LocksInType(containerType)) {
- //// if (lockToModify.Ancestors.OfType()
- //// .Any(ancestor => synchronizedStatements.Contains(ancestor))) {
- ////
- //// //These will be modified separately
- //// continue;
- //// }
- ////
- //// if (!IsThisReference (lockToModify.Expression)) {
- //// continue;
- //// }
- ////
- //// yield return lockToModify;
- //// }
- //// }
- ////
- //// IEnumerable FixMethodsWithMethodImplAttribute(Script script, TypeDeclaration containerType, bool isStatic)
- //// {
- //// var bodies = new List();
- ////
- //// foreach (var entityDeclarationToModify in EntitiesInType(containerType)) {
- //// var methodDeclaration = entityDeclarationToModify as MethodDeclaration;
- //// var accessor = entityDeclarationToModify as Accessor;
- //// if (methodDeclaration == null && accessor == null) {
- //// continue;
- //// }
- ////
- //// if ((methodDeclaration != null && IsEntityStatic(methodDeclaration) != isStatic) ||
- //// (accessor != null && IsEntityStatic(accessor.GetParent()) != isStatic)) {
- //// //These will need a separate lock and therefore will not be changed.
- //// continue;
- //// }
- ////
- //// var attributes = entityDeclarationToModify.Attributes.SelectMany(attributeSection => attributeSection.Attributes);
- //// var methodSynchronizedAttribute = attributes.FirstOrDefault(IsMethodSynchronizedAttribute);
- //// if (methodSynchronizedAttribute != null) {
- //// short methodImplValue = GetMethodImplValue(methodSynchronizedAttribute);
- //// short newValue = (short)(methodImplValue & ~((short)MethodImplOptions.Synchronized));
- //// if (newValue != 0) {
- //// InsertNewAttribute(script, methodSynchronizedAttribute, newValue);
- //// } else {
- //// var section = methodSynchronizedAttribute.GetParent();
- //// if (section.Attributes.Count == 1) {
- //// script.Remove(section);
- //// } else {
- //// script.Remove(methodSynchronizedAttribute);
- //// }
- //// }
- ////
- //// bool isAbstract = entityDeclarationToModify.Modifiers.HasFlag(Modifiers.Abstract);
- //// if (!isAbstract) {
- //// var body = methodDeclaration == null ? accessor.Body : methodDeclaration.Body;
- //// bodies.Add(body);
- //// }
- //// }
- //// }
- ////
- //// return bodies;
- //// }
- ////
- //// void InsertNewAttribute(Script script, Attribute attribute, short newValue) {
- //// var availableValues = (MethodImplOptions[]) Enum.GetValues(typeof(MethodImplOptions));
- //// var activeValues = availableValues.Where(value => (newValue & (short)value) != 0).ToList();
- ////
- //// var astBuilder = ctx.CreateTypeSystemAstBuilder(attribute);
- //// var methodImplOptionsType = astBuilder.ConvertType(new FullTypeName(typeof(MethodImplOptions).FullName));
- ////
- //// Expression expression = CreateMethodImplReferenceNode(activeValues[0], methodImplOptionsType);
- //// for (int optionIndex = 1; optionIndex < activeValues.Count; ++optionIndex) {
- //// expression = new BinaryOperatorExpression(expression,
- //// BinaryOperatorType.BitwiseOr,
- //// CreateMethodImplReferenceNode(activeValues [optionIndex], methodImplOptionsType));
- //// }
- ////
- //// var newAttribute = new Attribute();
- //// newAttribute.Type = attribute.Type.Clone();
- //// newAttribute.Arguments.Add(expression);
- ////
- //// script.Replace(attribute, newAttribute);
- //// }
- ////
- //// static MemberReferenceExpression CreateMethodImplReferenceNode(MethodImplOptions option, AstType methodImplOptionsType)
- //// {
- //// return methodImplOptionsType.Clone().Member(Enum.GetName(typeof(MethodImplOptions), option));
- //// }
- ////
- //// bool IsMethodSynchronizedAttribute(Attribute attribute)
- //// {
- //// var unresolvedType = attribute.Type;
- //// var resolvedType = ctx.ResolveType(unresolvedType);
- ////
- //// if (resolvedType.FullName != typeof(MethodImplAttribute).FullName) {
- //// return false;
- //// }
- ////
- //// short methodImpl = GetMethodImplValue(attribute);
- ////
- //// return (methodImpl & (short) MethodImplOptions.Synchronized) != 0;
- //// }
- ////
- //// short GetMethodImplValue(Attribute attribute)
- //// {
- //// short methodImpl = 0;
- //// foreach (var argument in attribute.Arguments) {
- //// var namedExpression = argument as NamedExpression;
- ////
- //// if (namedExpression == null) {
- //// short? implValue = GetMethodImplOptionsAsShort(argument);
- ////
- //// if (implValue != null) {
- //// methodImpl = (short)implValue;
- //// }
- ////
- //// } else if (namedExpression.Name == "Value") {
- //// short? implValue = GetMethodImplOptionsAsShort(namedExpression.Expression);
- ////
- //// if (implValue != null) {
- //// methodImpl = (short)implValue;
- //// }
- //// }
- //// }
- ////
- //// return methodImpl;
- //// }
- ////
- //// short? GetMethodImplOptionsAsShort(AstNode argument)
- //// {
- //// //Returns null if the value could not be guessed
- ////
- //// var result = ctx.Resolve(argument);
- //// if (!result.IsCompileTimeConstant) {
- //// return null;
- //// }
- ////
- //// if (result.Type.FullName == typeof(MethodImplOptions).FullName) {
- //// return (short)(MethodImplOptions)result.ConstantValue;
- //// }
- ////
- //// return null;
- //// }
- ////
- //// static IEnumerable EntitiesInType(TypeDeclaration containerType)
- //// {
- //// return containerType.Descendants.OfType().Where(entityDeclaration => {
- //// var childContainerType = entityDeclaration.GetParent();
- ////
- //// return childContainerType == containerType;
- //// });
- //// }
- ////
- //// static IEnumerable LocksInType(TypeDeclaration containerType)
- //// {
- //// return containerType.Descendants.OfType().Where(lockStatement => {
- //// var childContainerType = lockStatement.GetParent();
- ////
- //// return childContainerType == containerType;
- //// });
- //// }
- ////
- //// static bool IsThisReference (Expression expression)
- //// {
- //// if (expression is ThisReferenceExpression) {
- //// return true;
- //// }
- ////
- //// var parenthesizedExpression = expression as ParenthesizedExpression;
- //// if (parenthesizedExpression != null) {
- //// return IsThisReference(parenthesizedExpression.Expression);
- //// }
- ////
- //// return false;
- //// }
- // }
- }
-}
\ No newline at end of file
+// //// public override void VisitAttribute(Attribute attribute)
+// //// {
+// //// base.VisitAttribute(attribute);
+// ////
+// //// if (IsMethodSynchronizedAttribute(attribute)) {
+// //// var fixAction = new CodeAction(ctx.TranslateString("Create private locker field"), script => {
+// //// var containerEntity = GetParentMethodOrProperty(attribute);
+// //// var containerType = containerEntity.GetParent();
+// ////
+// //// FixLockThisIssue(script, containerEntity, containerType);
+// //// }, attribute);
+// ////
+// //// AddDiagnosticAnalyzer(new CodeIssue(attribute, ctx.TranslateString("Found [MethodImpl(MethodImplOptions.Synchronized)]"), fixAction));
+// //// }
+// //// }
+// ////
+// //// static EntityDeclaration GetParentMethodOrProperty(AstNode node)
+// //// {
+// //// var containerEntity = node.GetParent();
+// //// if (containerEntity is Accessor) {
+// //// containerEntity = containerEntity.GetParent();
+// //// }
+// ////
+// //// return containerEntity;
+// //// }
+// ////
+// //// public override void VisitLockStatement(LockStatement lockStatement)
+// //// {
+// //// base.VisitLockStatement(lockStatement);
+// ////
+// //// var expression = lockStatement.Expression;
+// ////
+// //// if (IsThisReference(expression)) {
+// //// var fixAction = new CodeAction(ctx.TranslateString("Create private locker field"), script => {
+// //// var containerEntity = GetParentMethodOrProperty(lockStatement);
+// ////
+// //// var containerType = containerEntity.GetParent();
+// ////
+// //// FixLockThisIssue(script, containerEntity, containerType);
+// ////
+// //// }, lockStatement);
+// ////
+// //// AddDiagnosticAnalyzer(new CodeIssue(lockStatement.LockToken.StartLocation,
+// //// lockStatement.RParToken.EndLocation, ctx.TranslateString("Found lock (this)"), fixAction));
+// //// }
+// //// }
+// ////
+// //// static bool IsEntityStatic(EntityDeclaration containerEntity)
+// //// {
+// //// return containerEntity.Modifiers.HasFlag(Modifiers.Static);
+// //// }
+// ////
+// //// void FixLockThisIssue(Script script, EntityDeclaration containerEntity, TypeDeclaration containerType)
+// //// {
+// //// bool isStatic = IsEntityStatic(containerEntity);
+// ////
+// //// List synchronizedStatements = FixMethodsWithMethodImplAttribute(script, containerType, isStatic).ToList();
+// ////
+// //// List linkNodes = new List();
+// ////
+// //// var locksToModify = LocksToModify(containerType, synchronizedStatements);
+// //// List nodeContexts = new List(locksToModify);
+// ////
+// //// foreach (var synchronizedStatement in synchronizedStatements) {
+// //// if (synchronizedStatement.Statements.Count > 0) {
+// //// nodeContexts.Add(synchronizedStatement.Statements.First());
+// ////
+// //// if (!isStatic) {
+// //// foreach (var childLock in synchronizedStatement.Descendants.OfType()) {
+// //// if (IsThisReference(childLock.Expression)) {
+// //// nodeContexts.Add(childLock);
+// //// }
+// //// }
+// //// }
+// //// }
+// //// }
+// ////
+// //// string proposedName = GetNameProposal(nodeContexts, "locker");
+// ////
+// //// if (!isStatic) {
+// //// foreach (var lockToModify in locksToModify) {
+// //// var identifier = new IdentifierExpression (proposedName);
+// //// script.Replace(lockToModify.Expression, identifier);
+// ////
+// //// linkNodes.Add(identifier);
+// //// }
+// //// }
+// ////
+// //// foreach (var synchronizedStatement in synchronizedStatements) {
+// //// if (synchronizedStatement.Statements.Count > 0) {
+// //// var newBody = synchronizedStatement.Clone();
+// ////
+// //// var outerLock = new LockStatement();
+// //// var outerLockIdentifier = new IdentifierExpression (proposedName);
+// //// outerLock.Expression = outerLockIdentifier;
+// //// outerLock.EmbeddedStatement = newBody;
+// ////
+// //// linkNodes.Add(outerLockIdentifier);
+// ////
+// //// if (!isStatic) {
+// //// foreach (var childLock in newBody.Descendants.OfType()) {
+// //// if (IsThisReference(childLock.Expression)) {
+// //// var identifier = new IdentifierExpression (proposedName);
+// //// childLock.Expression.ReplaceWith(identifier);
+// ////
+// //// linkNodes.Add(identifier);
+// //// }
+// //// }
+// //// }
+// ////
+// //// script.InsertBefore(synchronizedStatement.Statements.First(), outerLock);
+// ////
+// //// foreach (var stmt in synchronizedStatement.Statements) {
+// //// script.Remove(stmt);
+// //// }
+// //// }
+// //// }
+// ////
+// //// if (linkNodes.Any()) {
+// //// var objectType = new PrimitiveType("object");
+// ////
+// //// var lockerFieldDeclaration = new FieldDeclaration() {
+// //// Modifiers = isStatic ? Modifiers.Static : Modifiers.None,
+// //// ReturnType = objectType.Clone()
+// //// };
+// ////
+// //// var lockerVariable = new VariableInitializer(proposedName, new ObjectCreateExpression(objectType.Clone()));
+// //// lockerFieldDeclaration.Variables.Add(lockerVariable);
+// //// script.InsertBefore(containerEntity, lockerFieldDeclaration);
+// ////
+// //// linkNodes.Add(lockerVariable.NameToken);
+// ////
+// //// script.Link(linkNodes.ToArray());
+// //// }
+// //// }
+// ////
+// //// string GetNameProposal(List nodeContexts, string baseName)
+// //// {
+// //// var resolverStates = nodeContexts.Select(ctx.GetResolverStateBefore).ToList();
+// //// string nameProposal;
+// //// int n = 0;
+// //// do {
+// //// nameProposal = baseName + (n == 0 ? string.Empty : n.ToString());
+// //// n++;
+// //// } while (IdentifierNameExists(resolverStates, nameProposal));
+// //// return nameProposal;
+// //// }
+// ////
+// //// static bool IdentifierNameExists(List resolverStates, string nameProposal)
+// //// {
+// //// return resolverStates.Any(resolverState => {
+// //// ResolveResult result = resolverState.LookupSimpleNameOrTypeName(nameProposal, new List(), NameLookupMode.Expression);
+// //// return !result.IsError;
+// //// });
+// //// }
+// ////
+// //// IEnumerable LocksToModify(TypeDeclaration containerType, IEnumerable synchronizedStatements)
+// //// {
+// //// foreach (var lockToModify in LocksInType(containerType)) {
+// //// if (lockToModify.Ancestors.OfType()
+// //// .Any(ancestor => synchronizedStatements.Contains(ancestor))) {
+// ////
+// //// //These will be modified separately
+// //// continue;
+// //// }
+// ////
+// //// if (!IsThisReference (lockToModify.Expression)) {
+// //// continue;
+// //// }
+// ////
+// //// yield return lockToModify;
+// //// }
+// //// }
+// ////
+// //// IEnumerable FixMethodsWithMethodImplAttribute(Script script, TypeDeclaration containerType, bool isStatic)
+// //// {
+// //// var bodies = new List();
+// ////
+// //// foreach (var entityDeclarationToModify in EntitiesInType(containerType)) {
+// //// var methodDeclaration = entityDeclarationToModify as MethodDeclaration;
+// //// var accessor = entityDeclarationToModify as Accessor;
+// //// if (methodDeclaration == null && accessor == null) {
+// //// continue;
+// //// }
+// ////
+// //// if ((methodDeclaration != null && IsEntityStatic(methodDeclaration) != isStatic) ||
+// //// (accessor != null && IsEntityStatic(accessor.GetParent()) != isStatic)) {
+// //// //These will need a separate lock and therefore will not be changed.
+// //// continue;
+// //// }
+// ////
+// //// var attributes = entityDeclarationToModify.Attributes.SelectMany(attributeSection => attributeSection.Attributes);
+// //// var methodSynchronizedAttribute = attributes.FirstOrDefault(IsMethodSynchronizedAttribute);
+// //// if (methodSynchronizedAttribute != null) {
+// //// short methodImplValue = GetMethodImplValue(methodSynchronizedAttribute);
+// //// short newValue = (short)(methodImplValue & ~((short)MethodImplOptions.Synchronized));
+// //// if (newValue != 0) {
+// //// InsertNewAttribute(script, methodSynchronizedAttribute, newValue);
+// //// } else {
+// //// var section = methodSynchronizedAttribute.GetParent();
+// //// if (section.Attributes.Count == 1) {
+// //// script.Remove(section);
+// //// } else {
+// //// script.Remove(methodSynchronizedAttribute);
+// //// }
+// //// }
+// ////
+// //// bool isAbstract = entityDeclarationToModify.Modifiers.HasFlag(Modifiers.Abstract);
+// //// if (!isAbstract) {
+// //// var body = methodDeclaration == null ? accessor.Body : methodDeclaration.Body;
+// //// bodies.Add(body);
+// //// }
+// //// }
+// //// }
+// ////
+// //// return bodies;
+// //// }
+// ////
+// //// void InsertNewAttribute(Script script, Attribute attribute, short newValue) {
+// //// var availableValues = (MethodImplOptions[]) Enum.GetValues(typeof(MethodImplOptions));
+// //// var activeValues = availableValues.Where(value => (newValue & (short)value) != 0).ToList();
+// ////
+// //// var astBuilder = ctx.CreateTypeSystemAstBuilder(attribute);
+// //// var methodImplOptionsType = astBuilder.ConvertType(new FullTypeName(typeof(MethodImplOptions).FullName));
+// ////
+// //// Expression expression = CreateMethodImplReferenceNode(activeValues[0], methodImplOptionsType);
+// //// for (int optionIndex = 1; optionIndex < activeValues.Count; ++optionIndex) {
+// //// expression = new BinaryOperatorExpression(expression,
+// //// BinaryOperatorType.BitwiseOr,
+// //// CreateMethodImplReferenceNode(activeValues [optionIndex], methodImplOptionsType));
+// //// }
+// ////
+// //// var newAttribute = new Attribute();
+// //// newAttribute.Type = attribute.Type.Clone();
+// //// newAttribute.Arguments.Add(expression);
+// ////
+// //// script.Replace(attribute, newAttribute);
+// //// }
+// ////
+// //// static MemberReferenceExpression CreateMethodImplReferenceNode(MethodImplOptions option, AstType methodImplOptionsType)
+// //// {
+// //// return methodImplOptionsType.Clone().Member(Enum.GetName(typeof(MethodImplOptions), option));
+// //// }
+// ////
+// //// bool IsMethodSynchronizedAttribute(Attribute attribute)
+// //// {
+// //// var unresolvedType = attribute.Type;
+// //// var resolvedType = ctx.ResolveType(unresolvedType);
+// ////
+// //// if (resolvedType.FullName != typeof(MethodImplAttribute).FullName) {
+// //// return false;
+// //// }
+// ////
+// //// short methodImpl = GetMethodImplValue(attribute);
+// ////
+// //// return (methodImpl & (short) MethodImplOptions.Synchronized) != 0;
+// //// }
+// ////
+// //// short GetMethodImplValue(Attribute attribute)
+// //// {
+// //// short methodImpl = 0;
+// //// foreach (var argument in attribute.Arguments) {
+// //// var namedExpression = argument as NamedExpression;
+// ////
+// //// if (namedExpression == null) {
+// //// short? implValue = GetMethodImplOptionsAsShort(argument);
+// ////
+// //// if (implValue != null) {
+// //// methodImpl = (short)implValue;
+// //// }
+// ////
+// //// } else if (namedExpression.Name == "Value") {
+// //// short? implValue = GetMethodImplOptionsAsShort(namedExpression.Expression);
+// ////
+// //// if (implValue != null) {
+// //// methodImpl = (short)implValue;
+// //// }
+// //// }
+// //// }
+// ////
+// //// return methodImpl;
+// //// }
+// ////
+// //// short? GetMethodImplOptionsAsShort(AstNode argument)
+// //// {
+// //// //Returns null if the value could not be guessed
+// ////
+// //// var result = ctx.Resolve(argument);
+// //// if (!result.IsCompileTimeConstant) {
+// //// return null;
+// //// }
+// ////
+// //// if (result.Type.FullName == typeof(MethodImplOptions).FullName) {
+// //// return (short)(MethodImplOptions)result.ConstantValue;
+// //// }
+// ////
+// //// return null;
+// //// }
+// ////
+// //// static IEnumerable EntitiesInType(TypeDeclaration containerType)
+// //// {
+// //// return containerType.Descendants.OfType().Where(entityDeclaration => {
+// //// var childContainerType = entityDeclaration.GetParent();
+// ////
+// //// return childContainerType == containerType;
+// //// });
+// //// }
+// ////
+// //// static IEnumerable LocksInType(TypeDeclaration containerType)
+// //// {
+// //// return containerType.Descendants.OfType().Where(lockStatement => {
+// //// var childContainerType = lockStatement.GetParent();
+// ////
+// //// return childContainerType == containerType;
+// //// });
+// //// }
+// ////
+// //// static bool IsThisReference (Expression expression)
+// //// {
+// //// if (expression is ThisReferenceExpression) {
+// //// return true;
+// //// }
+// ////
+// //// var parenthesizedExpression = expression as ParenthesizedExpression;
+// //// if (parenthesizedExpression != null) {
+// //// return IsThisReference(parenthesizedExpression.Expression);
+// //// }
+// ////
+// //// return false;
+// //// }
+// // }
+// }
+//}
\ No newline at end of file
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Custom/NameOfSuggestionAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Custom/NameOfSuggestionAnalyzer.cs
index 9d70bba0..54a24210 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Custom/NameOfSuggestionAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Custom/NameOfSuggestionAnalyzer.cs
@@ -63,13 +63,33 @@ static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnost
return true;
}
+ static SyntaxToken? GetTypeName (TypeSyntax syntax)
+ {
+ if (syntax is SimpleNameSyntax sns)
+ {
+ // sns.GetRightmostName ?
+ return sns.Identifier;
+ }
+ if (syntax is QualifiedNameSyntax qns)
+ {
+ return GetTypeName(qns.Right);
+ }
+ if (syntax is AliasQualifiedNameSyntax aqns)
+ {
+ return GetTypeName(aqns.Name);
+ }
+ return null;
+ }
+
internal static bool CheckExceptionType(SemanticModel model, ObjectCreationExpressionSyntax objectCreateExpression, out ExpressionSyntax paramNode)
{
paramNode = null;
- var type = model.GetTypeInfo(objectCreateExpression).Type;
- if (type == null)
+
+ var typeName = GetTypeName (objectCreateExpression.Type)?.Text;
+ if (typeName == null)
return false;
- if (type.Name == typeof(ArgumentException).Name)
+
+ if (typeName == nameof(ArgumentException))
{
if (objectCreateExpression.ArgumentList.Arguments.Count >= 2)
{
@@ -77,9 +97,9 @@ internal static bool CheckExceptionType(SemanticModel model, ObjectCreationExpre
}
return paramNode != null;
}
- if (type.Name == typeof(ArgumentNullException).Name ||
- type.Name == typeof(ArgumentOutOfRangeException).Name ||
- type.Name == "DuplicateWaitObjectException")
+ if (typeName == nameof(ArgumentNullException) ||
+ typeName == nameof(ArgumentOutOfRangeException) ||
+ typeName == "DuplicateWaitObjectException")
{
if (objectCreateExpression.ArgumentList.Arguments.Count >= 1)
{
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Custom/NegativeRelationalExpressionAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Custom/NegativeRelationalExpressionAnalyzer.cs
index 7f11e907..d2676265 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Custom/NegativeRelationalExpressionAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Custom/NegativeRelationalExpressionAnalyzer.cs
@@ -1,110 +1,110 @@
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Diagnostics;
-using System.Collections.Immutable;
+//using Microsoft.CodeAnalysis;
+//using Microsoft.CodeAnalysis.Diagnostics;
+//using System.Collections.Immutable;
-namespace RefactoringEssentials.CSharp.Diagnostics
-{
- [DiagnosticAnalyzer(LanguageNames.CSharp)]
- [NotPortedYet]
- public class NegativeRelationalExpressionAnalyzer : DiagnosticAnalyzer
- {
- static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
- CSharpDiagnosticIDs.NegativeRelationalExpressionAnalyzerID,
- GettextCatalog.GetString("Simplify negative relational expression"),
- GettextCatalog.GetString("Simplify negative relational expression"),
- DiagnosticAnalyzerCategories.PracticesAndImprovements,
- DiagnosticSeverity.Info,
- isEnabledByDefault: true,
- helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.NegativeRelationalExpressionAnalyzerID)
- );
+//namespace RefactoringEssentials.CSharp.Diagnostics
+//{
+// [DiagnosticAnalyzer(LanguageNames.CSharp)]
+// [NotPortedYet]
+// public class NegativeRelationalExpressionAnalyzer : DiagnosticAnalyzer
+// {
+// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
+// CSharpDiagnosticIDs.NegativeRelationalExpressionAnalyzerID,
+// GettextCatalog.GetString("Simplify negative relational expression"),
+// GettextCatalog.GetString("Simplify negative relational expression"),
+// DiagnosticAnalyzerCategories.PracticesAndImprovements,
+// DiagnosticSeverity.Info,
+// isEnabledByDefault: true,
+// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.NegativeRelationalExpressionAnalyzerID)
+// );
- public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
+// public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
- public override void Initialize(AnalysisContext context)
- {
- context.EnableConcurrentExecution();
- context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
- //context.RegisterSyntaxNodeAction(
- // (nodeContext) => {
- // Diagnostic diagnostic;
- // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
- // nodeContext.ReportDiagnostic(diagnostic);
- // }
- // },
- // new SyntaxKind[] { SyntaxKind.None }
- //);
- }
+// public override void Initialize(AnalysisContext context)
+// {
+// context.EnableConcurrentExecution();
+// context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
+// //context.RegisterSyntaxNodeAction(
+// // (nodeContext) => {
+// // Diagnostic diagnostic;
+// // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
+// // nodeContext.ReportDiagnostic(diagnostic);
+// // }
+// // },
+// // new SyntaxKind[] { SyntaxKind.None }
+// //);
+// }
- static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
- {
- diagnostic = default(Diagnostic);
- //var node = nodeContext.Node as ;
- //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
- //return true;
- return false;
- }
+// static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
+// {
+// diagnostic = default(Diagnostic);
+// //var node = nodeContext.Node as ;
+// //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
+// //return true;
+// return false;
+// }
- // class GatherVisitor : GatherVisitorBase
- // {
- // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
- // : base(semanticModel, addDiagnostic, cancellationToken)
- // {
- // }
+// // class GatherVisitor : GatherVisitorBase
+// // {
+// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
+// // : base(semanticModel, addDiagnostic, cancellationToken)
+// // {
+// // }
- //// bool IsFloatingPoint (AstNode node)
- //// {
- //// var typeDef = ctx.Resolve (node).Type.GetDefinition ();
- //// return typeDef != null &&
- //// (typeDef.KnownTypeCode == KnownTypeCode.Single || typeDef.KnownTypeCode == KnownTypeCode.Double);
- //// }
- ////
- //// public override void VisitUnaryOperatorExpression (UnaryOperatorExpression unaryOperatorExpression)
- //// {
- //// base.VisitUnaryOperatorExpression (unaryOperatorExpression);
- ////
- //// if (unaryOperatorExpression.Operator != UnaryOperatorType.Not)
- //// return;
- ////
- //// var expr = unaryOperatorExpression.Expression;
- //// while (expr != null && expr is ParenthesizedExpression)
- //// expr = ((ParenthesizedExpression)expr).Expression;
- ////
- //// var binaryOperatorExpr = expr as BinaryOperatorExpression;
- //// if (binaryOperatorExpr == null)
- //// return;
- //// switch (binaryOperatorExpr.Operator) {
- //// case BinaryOperatorType.BitwiseAnd:
- //// case BinaryOperatorType.BitwiseOr:
- //// case BinaryOperatorType.ConditionalAnd:
- //// case BinaryOperatorType.ConditionalOr:
- //// case BinaryOperatorType.ExclusiveOr:
- //// return;
- //// }
- ////
- //// var negatedOp = CSharpUtil.NegateRelationalOperator(binaryOperatorExpr.Operator);
- //// if (negatedOp == BinaryOperatorType.Any)
- //// return;
- ////
- //// if (IsFloatingPoint (binaryOperatorExpr.Left) || IsFloatingPoint (binaryOperatorExpr.Right)) {
- //// if (negatedOp != BinaryOperatorType.Equality && negatedOp != BinaryOperatorType.InEquality)
- //// return;
- //// }
- ////
- // // AddDiagnosticAnalyzer (new CodeIssue(unaryOperatorExpression, ctx.TranslateString ("Simplify negative relational expression"), ctx.TranslateString ("Simplify negative relational expression"),
- //// script => script.Replace (unaryOperatorExpression,
- //// new BinaryOperatorExpression (binaryOperatorExpr.Left.Clone (), negatedOp,
- //// binaryOperatorExpr.Right.Clone ()))));
- //// }
- ////
- //// public override void VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
- //// {
- //// if (operatorDeclaration.OperatorType.IsComparisonOperator()) {
- //// // Ignore operator declaration; within them it's common to define one operator
- //// // by negating another.
- //// return;
- //// }
- //// base.VisitOperatorDeclaration(operatorDeclaration);
- //// }
- // }
- }
-}
\ No newline at end of file
+// //// bool IsFloatingPoint (AstNode node)
+// //// {
+// //// var typeDef = ctx.Resolve (node).Type.GetDefinition ();
+// //// return typeDef != null &&
+// //// (typeDef.KnownTypeCode == KnownTypeCode.Single || typeDef.KnownTypeCode == KnownTypeCode.Double);
+// //// }
+// ////
+// //// public override void VisitUnaryOperatorExpression (UnaryOperatorExpression unaryOperatorExpression)
+// //// {
+// //// base.VisitUnaryOperatorExpression (unaryOperatorExpression);
+// ////
+// //// if (unaryOperatorExpression.Operator != UnaryOperatorType.Not)
+// //// return;
+// ////
+// //// var expr = unaryOperatorExpression.Expression;
+// //// while (expr != null && expr is ParenthesizedExpression)
+// //// expr = ((ParenthesizedExpression)expr).Expression;
+// ////
+// //// var binaryOperatorExpr = expr as BinaryOperatorExpression;
+// //// if (binaryOperatorExpr == null)
+// //// return;
+// //// switch (binaryOperatorExpr.Operator) {
+// //// case BinaryOperatorType.BitwiseAnd:
+// //// case BinaryOperatorType.BitwiseOr:
+// //// case BinaryOperatorType.ConditionalAnd:
+// //// case BinaryOperatorType.ConditionalOr:
+// //// case BinaryOperatorType.ExclusiveOr:
+// //// return;
+// //// }
+// ////
+// //// var negatedOp = CSharpUtil.NegateRelationalOperator(binaryOperatorExpr.Operator);
+// //// if (negatedOp == BinaryOperatorType.Any)
+// //// return;
+// ////
+// //// if (IsFloatingPoint (binaryOperatorExpr.Left) || IsFloatingPoint (binaryOperatorExpr.Right)) {
+// //// if (negatedOp != BinaryOperatorType.Equality && negatedOp != BinaryOperatorType.InEquality)
+// //// return;
+// //// }
+// ////
+// // // AddDiagnosticAnalyzer (new CodeIssue(unaryOperatorExpression, ctx.TranslateString ("Simplify negative relational expression"), ctx.TranslateString ("Simplify negative relational expression"),
+// //// script => script.Replace (unaryOperatorExpression,
+// //// new BinaryOperatorExpression (binaryOperatorExpr.Left.Clone (), negatedOp,
+// //// binaryOperatorExpr.Right.Clone ()))));
+// //// }
+// ////
+// //// public override void VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
+// //// {
+// //// if (operatorDeclaration.OperatorType.IsComparisonOperator()) {
+// //// // Ignore operator declaration; within them it's common to define one operator
+// //// // by negating another.
+// //// return;
+// //// }
+// //// base.VisitOperatorDeclaration(operatorDeclaration);
+// //// }
+// // }
+// }
+//}
\ No newline at end of file
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Custom/ParameterOnlyAssignedAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Custom/ParameterOnlyAssignedAnalyzer.cs
index 70da8a45..81039e66 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Custom/ParameterOnlyAssignedAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Custom/ParameterOnlyAssignedAnalyzer.cs
@@ -27,56 +27,48 @@ public override void Initialize(AnalysisContext context)
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterSyntaxNodeAction(
- (nodeContext) =>
- {
- Diagnostic diagnostic;
- if (TryGetDiagnostic(nodeContext, out diagnostic))
- {
- nodeContext.ReportDiagnostic(diagnostic);
- }
- },
- SyntaxKind.Parameter
- );
+ AnalyzeParameterList,
+ SyntaxKind.ParameterList
+ );
}
- private static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
+ private static void AnalyzeParameterList(SyntaxNodeAnalysisContext nodeContext)
{
- diagnostic = default(Diagnostic);
+ var parameterList = nodeContext.Node as ParameterListSyntax;
+ if (parameterList == null)
+ return;
- var parameter = nodeContext.Node as ParameterSyntax;
- if (parameter == null)
- return false;
-
- if (parameter.Modifiers.Any(SyntaxKind.OutKeyword) || parameter.Modifiers.Any(SyntaxKind.RefKeyword))
- return false;
-
- var localParamSymbol = nodeContext.SemanticModel.GetDeclaredSymbol(parameter);
- if (localParamSymbol == null)
- return false;
-
- var method = parameter.Parent.Parent as MethodDeclarationSyntax;
+ var method = parameterList.Parent as MethodDeclarationSyntax;
if (method == null || method.Body == null)
- return false;
+ return;
- var dataFlow = nodeContext.SemanticModel.AnalyzeDataFlow(method.Body);
- if (dataFlow.AlwaysAssigned.Except(dataFlow.ReadInside).Contains(localParamSymbol))
+ var dataFlow = new System.Lazy(() => nodeContext.SemanticModel.AnalyzeDataFlow(method.Body));
+ foreach (var parameter in parameterList.Parameters)
{
- var statements = method.Body.Statements;
- foreach (var statement in statements)
+ if (parameter.Modifiers.Any(SyntaxKind.OutKeyword) || parameter.Modifiers.Any(SyntaxKind.RefKeyword))
+ continue;
+
+ var localParamSymbol = nodeContext.SemanticModel.GetDeclaredSymbol(parameter);
+ if (localParamSymbol == null)
+ continue;
+
+ if (dataFlow.Value.AlwaysAssigned.Except(dataFlow.Value.ReadInside).Contains(localParamSymbol))
{
- var expression = statement as ExpressionStatementSyntax;
- var assignment = expression?.Expression as AssignmentExpressionSyntax;
- if (assignment == null)
- continue;
- var symbol = nodeContext.SemanticModel.GetSymbolInfo(assignment.Left).Symbol as IParameterSymbol;
- if (localParamSymbol.Equals(symbol))
+ var statements = method.Body.Statements;
+ foreach (var statement in statements)
{
- diagnostic = Diagnostic.Create(descriptor, assignment.GetLocation());
- return true;
+ var expression = statement as ExpressionStatementSyntax;
+ var assignment = expression?.Expression as AssignmentExpressionSyntax;
+ if (assignment == null)
+ continue;
+ var symbol = nodeContext.SemanticModel.GetSymbolInfo(assignment.Left).Symbol as IParameterSymbol;
+ if (localParamSymbol.Equals(symbol))
+ {
+ nodeContext.ReportDiagnostic (Diagnostic.Create(descriptor, assignment.GetLocation()));
+ }
}
}
}
- return false;
}
}
}
\ No newline at end of file
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Custom/RedundantAssignmentAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Custom/RedundantAssignmentAnalyzer.cs
index 678c197b..18820334 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Custom/RedundantAssignmentAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Custom/RedundantAssignmentAnalyzer.cs
@@ -1,481 +1,481 @@
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Diagnostics;
-using System.Collections.Immutable;
+//using Microsoft.CodeAnalysis;
+//using Microsoft.CodeAnalysis.Diagnostics;
+//using System.Collections.Immutable;
-namespace RefactoringEssentials.CSharp.Diagnostics
-{
- [DiagnosticAnalyzer(LanguageNames.CSharp)]
- [NotPortedYet]
- public class RedundantAssignmentAnalyzer : DiagnosticAnalyzer
- {
- static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
- CSharpDiagnosticIDs.RedundantAssignmentAnalyzerID,
- GettextCatalog.GetString("Value assigned to a variable or parameter is not used in all execution path"),
- GettextCatalog.GetString("Assignment is redundant"),
- DiagnosticAnalyzerCategories.RedundanciesInCode,
- DiagnosticSeverity.Warning,
- isEnabledByDefault: true,
- helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantAssignmentAnalyzerID),
- customTags: DiagnosticCustomTags.Unnecessary
- );
+//namespace RefactoringEssentials.CSharp.Diagnostics
+//{
+// [DiagnosticAnalyzer(LanguageNames.CSharp)]
+// [NotPortedYet]
+// public class RedundantAssignmentAnalyzer : DiagnosticAnalyzer
+// {
+// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
+// CSharpDiagnosticIDs.RedundantAssignmentAnalyzerID,
+// GettextCatalog.GetString("Value assigned to a variable or parameter is not used in all execution path"),
+// GettextCatalog.GetString("Assignment is redundant"),
+// DiagnosticAnalyzerCategories.RedundanciesInCode,
+// DiagnosticSeverity.Warning,
+// isEnabledByDefault: true,
+// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantAssignmentAnalyzerID),
+// customTags: DiagnosticCustomTags.Unnecessary
+// );
- public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
+// public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
- public override void Initialize(AnalysisContext context)
- {
- context.EnableConcurrentExecution();
- context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
- //context.RegisterSyntaxNodeAction(
- // (nodeContext) => {
- // Diagnostic diagnostic;
- // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
- // nodeContext.ReportDiagnostic(diagnostic);
- // }
- // },
- // new SyntaxKind[] { SyntaxKind.None }
- //);
- }
+// public override void Initialize(AnalysisContext context)
+// {
+// context.EnableConcurrentExecution();
+// context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
+// //context.RegisterSyntaxNodeAction(
+// // (nodeContext) => {
+// // Diagnostic diagnostic;
+// // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
+// // nodeContext.ReportDiagnostic(diagnostic);
+// // }
+// // },
+// // new SyntaxKind[] { SyntaxKind.None }
+// //);
+// }
- static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
- {
- diagnostic = default(Diagnostic);
- //var node = nodeContext.Node as ;
- //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
- //return true;
- return false;
- }
+// static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
+// {
+// diagnostic = default(Diagnostic);
+// //var node = nodeContext.Node as ;
+// //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
+// //return true;
+// return false;
+// }
- // class GatherVisitor : GatherVisitorBase
- // {
- // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
- // : base(semanticModel, addDiagnostic, cancellationToken)
- // {
- // }
- ////
- //// public override void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
- //// {
- //// base.VisitParameterDeclaration(parameterDeclaration);
- //// if (parameterDeclaration.ParameterModifier == ParameterModifier.Out ||
- //// parameterDeclaration.ParameterModifier == ParameterModifier.Ref)
- //// return;
- ////
- //// var resolveResult = ctx.Resolve(parameterDeclaration) as LocalResolveResult;
- //// BlockStatement rootStatement = null;
- //// if (parameterDeclaration.Parent is MethodDeclaration) {
- //// rootStatement = ((MethodDeclaration)parameterDeclaration.Parent).Body;
- //// } else if (parameterDeclaration.Parent is AnonymousMethodExpression) {
- //// rootStatement = ((AnonymousMethodExpression)parameterDeclaration.Parent).Body;
- //// } else if (parameterDeclaration.Parent is LambdaExpression) {
- //// rootStatement = ((LambdaExpression)parameterDeclaration.Parent).Body as BlockStatement;
- //// }
- //// CollectIssues(parameterDeclaration, rootStatement, resolveResult);
- //// }
- ////
- //// public override void VisitVariableInitializer(VariableInitializer variableInitializer)
- //// {
- //// base.VisitVariableInitializer(variableInitializer);
- //// if (!inUsingStatementResourceAcquisition) {
- //// var resolveResult = ctx.Resolve(variableInitializer) as LocalResolveResult;
- //// CollectIssues(variableInitializer, variableInitializer.GetParent(), resolveResult);
- //// }
- //// }
- ////
- //// bool inUsingStatementResourceAcquisition;
- ////
- //// public override void VisitUsingStatement(UsingStatement usingStatement)
- //// {
- //// inUsingStatementResourceAcquisition = true;
- //// usingStatement.ResourceAcquisition.AcceptVisitor(this);
- //// inUsingStatementResourceAcquisition = false;
- //// usingStatement.EmbeddedStatement.AcceptVisitor(this);
- //// }
- ////
- //// void CollectIssues(AstNode variableDecl, BlockStatement rootStatement, LocalResolveResult resolveResult)
- //// {
- //// if (rootStatement == null || resolveResult == null)
- //// return;
- ////
- //// var references = new HashSet();
- //// var refStatements = new HashSet();
- //// var usedInLambda = false;
- //// var results = ctx.FindReferences(rootStatement, resolveResult.Variable);
- //// foreach (var result in results) {
- //// var node = result.Node;
- //// if (node == variableDecl)
- //// continue;
- ////
- //// var parent = node.Parent;
- //// while (!(parent == null || parent is Statement || parent is LambdaExpression || parent is QueryExpression))
- //// parent = parent.Parent;
- //// if (parent == null)
- //// continue;
- ////
- //// var statement = parent as Statement;
- //// if (statement != null) {
- //// references.Add(node);
- //// refStatements.Add(statement);
- //// }
- ////
- //// while (parent != null && parent != rootStatement) {
- //// if (parent is LambdaExpression || parent is AnonymousMethodExpression || parent is QueryExpression) {
- //// usedInLambda = true;
- //// break;
- //// }
- //// parent = parent.Parent;
- //// }
- //// if (usedInLambda) {
- //// break;
- //// }
- //// }
- ////
- //// // stop analyzing if the variable is used in any lambda expression or anonymous method
- //// if (usedInLambda)
- //// return;
- ////
- //// var startNode = new VariableReferenceGraphBuilder(ctx).Build(rootStatement, references, refStatements, ctx);
- //// var variableInitializer = variableDecl as VariableInitializer;
- //// if (variableInitializer != null && !variableInitializer.Initializer.IsNull)
- //// startNode.References.Insert(0, variableInitializer);
- ////
- //// ProcessNodes(startNode);
- //// }
- ////
- //// class SearchInvocationsVisitor : DepthFirstAstVisitor
- //// {
- //// bool foundInvocations;
- ////
- //// public bool ContainsInvocations(AstNode node)
- //// {
- //// foundInvocations = false;
- //// node.AcceptVisitor(this);
- //// return foundInvocations;
- //// }
- ////
- //// protected override void VisitChildren(AstNode node)
- //// {
- //// AstNode next;
- //// for (var child = node.FirstChild; child != null && !foundInvocations; child = next) {
- //// next = child.NextSibling;
- //// child.AcceptVisitor(this);
- //// }
- //// }
- ////
- //// public override void VisitInvocationExpression(InvocationExpression invocationExpression)
- //// {
- //// foundInvocations = true;
- //// }
- //// }
- ////
- //// private class SearchRefOrOutVisitor : DepthFirstAstVisitor
- //// {
- //// private bool foundInvocations;
- //// private string _varName;
- ////
- //// public bool ContainsRefOrOut(VariableInitializer variableInitializer)
- //// {
- //// var node = variableInitializer.Parent.Parent;
- //// foundInvocations = false;
- //// _varName = variableInitializer.Name;
- //// node.AcceptVisitor(this);
- //// return foundInvocations;
- //// }
- ////
- //// protected override void VisitChildren(AstNode node)
- //// {
- //// AstNode next;
- //// for (var child = node.FirstChild; child != null && !foundInvocations; child = next) {
- //// next = child.NextSibling;
- //// child.AcceptVisitor(this);
- //// }
- //// }
- ////
- //// public override void VisitInvocationExpression(InvocationExpression methodDeclaration)
- //// {
- //// if (foundInvocations)
- //// return;
- //// if (methodDeclaration.Arguments.Count == 0)
- //// return;
- //// foreach (var argument in methodDeclaration.Arguments) {
- //// var directionExpression = argument as DirectionExpression;
- //// if (directionExpression == null)
- //// continue;
- ////
- //// if (directionExpression.FieldDirection != FieldDirection.Out && directionExpression.FieldDirection != FieldDirection.Ref)
- //// continue;
- //// var idExpression = (directionExpression.Expression) as IdentifierExpression;
- //// if (idExpression == null)
- //// continue;
- //// foundInvocations = (idExpression.Identifier == _varName);
- ////
- //// foundInvocations = true;
- //// }
- //// }
- //// }
- ////
- //// class SearchAssignmentForVarVisitor : DepthFirstAstVisitor
- //// {
- //// bool _foundInvocations;
- //// private VariableInitializer _variableInitializer;
- ////
- //// public bool ContainsLaterAssignments(VariableInitializer variableInitializer)
- //// {
- //// _foundInvocations = false;
- //// _variableInitializer = variableInitializer;
- //// variableInitializer.Parent.Parent.AcceptVisitor(this);
- //// return _foundInvocations;
- //// }
- ////
- //// protected override void VisitChildren(AstNode node)
- //// {
- //// AstNode next;
- //// for (var child = node.FirstChild; child != null && !_foundInvocations; child = next) {
- //// next = child.NextSibling;
- //// child.AcceptVisitor(this);
- //// }
- //// }
- ////
- //// public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression)
- //// {
- //// if (_foundInvocations)
- //// return;
- //// base.VisitAssignmentExpression(assignmentExpression);
- //// if (assignmentExpression.Left.ToString() == _variableInitializer.Name
- //// && assignmentExpression.StartLocation > _variableInitializer.StartLocation) {
- //// _foundInvocations = true;
- //// }
- //// }
- //// }
- ////
- //// bool ContainsOtherAssignments(AstNode parent)
- //// {
- //// int count = 0;
- //// foreach (var child in parent.Children.OfType()) {
- //// count++;
- //// if (count > 1)
- //// return true;
- //// }
- //// return false;
- //// }
- ////
- //// void AddDiagnosticAnalyzer(AstNode node)
- //// {
- //// var issueDescription = ctx.TranslateString("");
- //// var actionDescription = ctx.TranslateString("Remove redundant assignment");
- ////
- //// var variableInitializer = node as VariableInitializer;
- //// if (variableInitializer != null) {
- //// var containsInvocations =
- //// new SearchInvocationsVisitor().ContainsInvocations(variableInitializer.Initializer);
- ////
- //// var varDecl = node.Parent as VariableDeclarationStatement;
- ////
- //// var isDeclareStatement = varDecl != null;
- //// var isUsingVar = isDeclareStatement && varDecl.Type.IsVar();
- ////
- //// var expressionType = ctx.Resolve(node).Type;
- ////
- //// var containsLaterAssignments = false;
- //// if (isDeclareStatement) {
- //// //if it is used later, the redundant removal should remove the assignment
- //// //but not the variable
- //// containsLaterAssignments =
- //// new SearchAssignmentForVarVisitor().ContainsLaterAssignments(variableInitializer);
- //// }
- ////
- //// AstNode grayOutNode;
- //// var containsRefOrOut = new SearchRefOrOutVisitor().ContainsRefOrOut(variableInitializer);
- //// if (containsInvocations && isDeclareStatement) {
- //// grayOutNode = variableInitializer.AssignToken;
- //// } else {
- //// if (isDeclareStatement && !containsRefOrOut && !containsLaterAssignments && !ContainsOtherAssignments(variableInitializer.Parent)) {
- //// grayOutNode = variableInitializer.Parent;
- //// } else {
- //// grayOutNode = variableInitializer.Initializer;
- //// }
- //// }
- ////
- //// AddDiagnosticAnalyzer(new CodeIssue(grayOutNode, issueDescription, actionDescription, script => {
- //// var variableNode = (VariableInitializer)node;
- //// if (containsInvocations && isDeclareStatement) {
- //// //add the column ';' that will be removed after the next line replacement
- //// var expression = (Statement)variableNode.Initializer.Clone();
- //// if (containsLaterAssignments && varDecl != null) {
- //// var clonedDefinition = (VariableDeclarationStatement)varDecl.Clone();
- ////
- //// var shortExpressionType = CreateShortType(ctx, expressionType, node);
- //// clonedDefinition.Type = shortExpressionType;
- //// var variableNodeClone = clonedDefinition.GetVariable(variableNode.Name);
- //// variableNodeClone.Initializer = null;
- //// script.InsertBefore(node.Parent, clonedDefinition);
- //// }
- //// script.Replace(node.Parent, expression);
- //// return;
- //// }
- //// if (isDeclareStatement && !containsRefOrOut && !containsLaterAssignments&& !ContainsOtherAssignments(variableInitializer.Parent)) {
- //// script.Remove(node.Parent);
- //// return;
- //// }
- //// var replacement = (VariableInitializer)variableNode.Clone();
- //// replacement.Initializer = Expression.Null;
- //// if (isUsingVar) {
- //// var shortExpressionType = CreateShortType(ctx, expressionType, node);
- //// script.Replace(varDecl.Type, shortExpressionType);
- //// }
- //// script.Replace(node, replacement);
- //// }) { IssueMarker = IssueMarker.GrayOut });
- //// }
- ////
- //// var assignmentExpr = node.Parent as AssignmentExpression;
- //// if (assignmentExpr == null)
- //// return;
- //// if (assignmentExpr.Parent is ExpressionStatement) {
- //// AddDiagnosticAnalyzer(new CodeIssue(assignmentExpr.Parent, issueDescription, actionDescription, script => script.Remove(assignmentExpr.Parent)) { IssueMarker = IssueMarker.GrayOut });
- //// } else {
- //// AddDiagnosticAnalyzer(new CodeIssue(assignmentExpr.Left.StartLocation, assignmentExpr.OperatorToken.EndLocation, issueDescription, actionDescription,
- //// script => script.Replace(assignmentExpr, assignmentExpr.Right.Clone())) { IssueMarker = IssueMarker.GrayOut });
- //// }
- //// }
- ////
- //// private static AstType CreateShortType(BaseSemanticModel SemanticModel, IType expressionType, AstNode node)
- //// {
- ////
- //// var csResolver = SemanticModel.Resolver.GetResolverStateBefore(node);
- //// var builder = new TypeSystemAstBuilder(csResolver);
- //// return builder.ConvertType(expressionType);
- //// }
- ////
- //// static bool IsAssignment(AstNode node)
- //// {
- //// if (node is VariableInitializer)
- //// return true;
- ////
- //// var assignmentExpr = node.Parent as AssignmentExpression;
- //// if (assignmentExpr != null)
- //// return assignmentExpr.Left == node && assignmentExpr.Operator == AssignmentOperatorType.Assign;
- ////
- //// var direction = node.Parent as DirectionExpression;
- //// if (direction != null)
- //// return direction.FieldDirection == FieldDirection.Out && direction.Expression == node;
- ////
- //// return false;
- //// }
- ////
- //// static bool IsInsideTryOrCatchBlock(AstNode node)
- //// {
- //// var tryCatchStatement = node.GetParent();
- //// if (tryCatchStatement != null) {
- //// if (tryCatchStatement.TryBlock.Contains(node.StartLocation))
- //// return true;
- //// foreach (var catchBlock in tryCatchStatement.CatchClauses)
- //// if (catchBlock.Body.Contains(node.StartLocation))
- //// return true;
- //// }
- //// return false;
- //// }
- ////
- //// enum NodeState
- //// {
- //// None,
- //// UsageReachable,
- //// UsageUnreachable,
- //// Processing,
- //// }
- ////
- //// void ProcessNodes(VariableReferenceNode startNode)
- //// {
- //// // node state of a node indicates whether it is possible for an upstream node to reach any usage via
- //// // the node
- //// var nodeStates = new Dictionary();
- //// var assignments = new List();
- ////
- //// // dfs to preprocess all nodes and find nodes which end with assignment
- //// var stack = new Stack();
- //// stack.Push(startNode);
- //// while (stack.Count > 0) {
- //// var node = stack.Pop();
- //// if (node == null)
- //// continue;
- //// if (node.References.Count > 0) {
- //// nodeStates [node] = IsAssignment(node.References [0]) ?
- //// NodeState.UsageUnreachable : NodeState.UsageReachable;
- //// } else {
- //// nodeStates [node] = NodeState.None;
- //// }
- ////
- //// // find indices of all assignments in node.References
- //// var assignmentIndices = new List();
- //// for (int i = 0; i < node.References.Count; i++) {
- //// if (IsAssignment(node.References [i]))
- //// assignmentIndices.Add(i);
- //// }
- //// // for two consecutive assignments, the first one is redundant
- //// for (int i = 0; i < assignmentIndices.Count - 1; i++) {
- //// var index1 = assignmentIndices [i];
- //// var index2 = assignmentIndices [i + 1];
- //// if (index1 + 1 == index2)
- //// AddDiagnosticAnalyzer(node.References [index1]);
- //// }
- //// // if the node ends with an assignment, add it to assignments so as to check if it is redundant
- //// // later
- //// if (assignmentIndices.Count > 0 &&
- //// assignmentIndices [assignmentIndices.Count - 1] == node.References.Count - 1)
- //// assignments.Add(node);
- ////
- //// foreach (var nextNode in node.NextNodes) {
- //// if (!nodeStates.ContainsKey(nextNode))
- //// stack.Push(nextNode);
- //// }
- //// }
- ////
- //// foreach (var node in assignments) {
- //// // we do not analyze an assignment inside a try block as it can jump to any catch block or finally block
- //// if (IsInsideTryOrCatchBlock(node.References [0]))
- //// continue;
- //// ProcessNode(node, true, nodeStates);
- //// }
- //// }
- ////
- //// void ProcessNode(VariableReferenceNode node, bool addIssue,
- //// IDictionary nodeStates)
- //// {
- //// if (nodeStates [node] == NodeState.None)
- //// nodeStates [node] = NodeState.Processing;
- ////
- //// bool? reachable = false;
- //// foreach (var nextNode in node.NextNodes) {
- //// if (nodeStates [nextNode] == NodeState.None)
- //// ProcessNode(nextNode, false, nodeStates);
- ////
- //// if (nodeStates [nextNode] == NodeState.UsageReachable) {
- //// reachable = true;
- //// break;
- //// }
- //// // downstream nodes are not fully processed (e.g. due to loop), there is no enough info to
- //// // determine the node state
- //// if (nodeStates [nextNode] != NodeState.UsageUnreachable)
- //// reachable = null;
- //// }
- ////
- //// // add issue if it is not possible to reach any usage via NextNodes
- //// if (addIssue && reachable == false)
- //// AddDiagnosticAnalyzer(node.References [node.References.Count - 1]);
- ////
- //// if (nodeStates [node] != NodeState.Processing)
- //// return;
- ////
- //// switch (reachable) {
- //// case null:
- //// nodeStates [node] = NodeState.None;
- //// break;
- //// case true:
- //// nodeStates [node] = NodeState.UsageReachable;
- //// break;
- //// case false:
- //// nodeStates [node] = NodeState.UsageUnreachable;
- //// break;
- //// }
- //// }
- // }
- }
+// // class GatherVisitor : GatherVisitorBase
+// // {
+// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
+// // : base(semanticModel, addDiagnostic, cancellationToken)
+// // {
+// // }
+// ////
+// //// public override void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
+// //// {
+// //// base.VisitParameterDeclaration(parameterDeclaration);
+// //// if (parameterDeclaration.ParameterModifier == ParameterModifier.Out ||
+// //// parameterDeclaration.ParameterModifier == ParameterModifier.Ref)
+// //// return;
+// ////
+// //// var resolveResult = ctx.Resolve(parameterDeclaration) as LocalResolveResult;
+// //// BlockStatement rootStatement = null;
+// //// if (parameterDeclaration.Parent is MethodDeclaration) {
+// //// rootStatement = ((MethodDeclaration)parameterDeclaration.Parent).Body;
+// //// } else if (parameterDeclaration.Parent is AnonymousMethodExpression) {
+// //// rootStatement = ((AnonymousMethodExpression)parameterDeclaration.Parent).Body;
+// //// } else if (parameterDeclaration.Parent is LambdaExpression) {
+// //// rootStatement = ((LambdaExpression)parameterDeclaration.Parent).Body as BlockStatement;
+// //// }
+// //// CollectIssues(parameterDeclaration, rootStatement, resolveResult);
+// //// }
+// ////
+// //// public override void VisitVariableInitializer(VariableInitializer variableInitializer)
+// //// {
+// //// base.VisitVariableInitializer(variableInitializer);
+// //// if (!inUsingStatementResourceAcquisition) {
+// //// var resolveResult = ctx.Resolve(variableInitializer) as LocalResolveResult;
+// //// CollectIssues(variableInitializer, variableInitializer.GetParent(), resolveResult);
+// //// }
+// //// }
+// ////
+// //// bool inUsingStatementResourceAcquisition;
+// ////
+// //// public override void VisitUsingStatement(UsingStatement usingStatement)
+// //// {
+// //// inUsingStatementResourceAcquisition = true;
+// //// usingStatement.ResourceAcquisition.AcceptVisitor(this);
+// //// inUsingStatementResourceAcquisition = false;
+// //// usingStatement.EmbeddedStatement.AcceptVisitor(this);
+// //// }
+// ////
+// //// void CollectIssues(AstNode variableDecl, BlockStatement rootStatement, LocalResolveResult resolveResult)
+// //// {
+// //// if (rootStatement == null || resolveResult == null)
+// //// return;
+// ////
+// //// var references = new HashSet();
+// //// var refStatements = new HashSet();
+// //// var usedInLambda = false;
+// //// var results = ctx.FindReferences(rootStatement, resolveResult.Variable);
+// //// foreach (var result in results) {
+// //// var node = result.Node;
+// //// if (node == variableDecl)
+// //// continue;
+// ////
+// //// var parent = node.Parent;
+// //// while (!(parent == null || parent is Statement || parent is LambdaExpression || parent is QueryExpression))
+// //// parent = parent.Parent;
+// //// if (parent == null)
+// //// continue;
+// ////
+// //// var statement = parent as Statement;
+// //// if (statement != null) {
+// //// references.Add(node);
+// //// refStatements.Add(statement);
+// //// }
+// ////
+// //// while (parent != null && parent != rootStatement) {
+// //// if (parent is LambdaExpression || parent is AnonymousMethodExpression || parent is QueryExpression) {
+// //// usedInLambda = true;
+// //// break;
+// //// }
+// //// parent = parent.Parent;
+// //// }
+// //// if (usedInLambda) {
+// //// break;
+// //// }
+// //// }
+// ////
+// //// // stop analyzing if the variable is used in any lambda expression or anonymous method
+// //// if (usedInLambda)
+// //// return;
+// ////
+// //// var startNode = new VariableReferenceGraphBuilder(ctx).Build(rootStatement, references, refStatements, ctx);
+// //// var variableInitializer = variableDecl as VariableInitializer;
+// //// if (variableInitializer != null && !variableInitializer.Initializer.IsNull)
+// //// startNode.References.Insert(0, variableInitializer);
+// ////
+// //// ProcessNodes(startNode);
+// //// }
+// ////
+// //// class SearchInvocationsVisitor : DepthFirstAstVisitor
+// //// {
+// //// bool foundInvocations;
+// ////
+// //// public bool ContainsInvocations(AstNode node)
+// //// {
+// //// foundInvocations = false;
+// //// node.AcceptVisitor(this);
+// //// return foundInvocations;
+// //// }
+// ////
+// //// protected override void VisitChildren(AstNode node)
+// //// {
+// //// AstNode next;
+// //// for (var child = node.FirstChild; child != null && !foundInvocations; child = next) {
+// //// next = child.NextSibling;
+// //// child.AcceptVisitor(this);
+// //// }
+// //// }
+// ////
+// //// public override void VisitInvocationExpression(InvocationExpression invocationExpression)
+// //// {
+// //// foundInvocations = true;
+// //// }
+// //// }
+// ////
+// //// private class SearchRefOrOutVisitor : DepthFirstAstVisitor
+// //// {
+// //// private bool foundInvocations;
+// //// private string _varName;
+// ////
+// //// public bool ContainsRefOrOut(VariableInitializer variableInitializer)
+// //// {
+// //// var node = variableInitializer.Parent.Parent;
+// //// foundInvocations = false;
+// //// _varName = variableInitializer.Name;
+// //// node.AcceptVisitor(this);
+// //// return foundInvocations;
+// //// }
+// ////
+// //// protected override void VisitChildren(AstNode node)
+// //// {
+// //// AstNode next;
+// //// for (var child = node.FirstChild; child != null && !foundInvocations; child = next) {
+// //// next = child.NextSibling;
+// //// child.AcceptVisitor(this);
+// //// }
+// //// }
+// ////
+// //// public override void VisitInvocationExpression(InvocationExpression methodDeclaration)
+// //// {
+// //// if (foundInvocations)
+// //// return;
+// //// if (methodDeclaration.Arguments.Count == 0)
+// //// return;
+// //// foreach (var argument in methodDeclaration.Arguments) {
+// //// var directionExpression = argument as DirectionExpression;
+// //// if (directionExpression == null)
+// //// continue;
+// ////
+// //// if (directionExpression.FieldDirection != FieldDirection.Out && directionExpression.FieldDirection != FieldDirection.Ref)
+// //// continue;
+// //// var idExpression = (directionExpression.Expression) as IdentifierExpression;
+// //// if (idExpression == null)
+// //// continue;
+// //// foundInvocations = (idExpression.Identifier == _varName);
+// ////
+// //// foundInvocations = true;
+// //// }
+// //// }
+// //// }
+// ////
+// //// class SearchAssignmentForVarVisitor : DepthFirstAstVisitor
+// //// {
+// //// bool _foundInvocations;
+// //// private VariableInitializer _variableInitializer;
+// ////
+// //// public bool ContainsLaterAssignments(VariableInitializer variableInitializer)
+// //// {
+// //// _foundInvocations = false;
+// //// _variableInitializer = variableInitializer;
+// //// variableInitializer.Parent.Parent.AcceptVisitor(this);
+// //// return _foundInvocations;
+// //// }
+// ////
+// //// protected override void VisitChildren(AstNode node)
+// //// {
+// //// AstNode next;
+// //// for (var child = node.FirstChild; child != null && !_foundInvocations; child = next) {
+// //// next = child.NextSibling;
+// //// child.AcceptVisitor(this);
+// //// }
+// //// }
+// ////
+// //// public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression)
+// //// {
+// //// if (_foundInvocations)
+// //// return;
+// //// base.VisitAssignmentExpression(assignmentExpression);
+// //// if (assignmentExpression.Left.ToString() == _variableInitializer.Name
+// //// && assignmentExpression.StartLocation > _variableInitializer.StartLocation) {
+// //// _foundInvocations = true;
+// //// }
+// //// }
+// //// }
+// ////
+// //// bool ContainsOtherAssignments(AstNode parent)
+// //// {
+// //// int count = 0;
+// //// foreach (var child in parent.Children.OfType()) {
+// //// count++;
+// //// if (count > 1)
+// //// return true;
+// //// }
+// //// return false;
+// //// }
+// ////
+// //// void AddDiagnosticAnalyzer(AstNode node)
+// //// {
+// //// var issueDescription = ctx.TranslateString("");
+// //// var actionDescription = ctx.TranslateString("Remove redundant assignment");
+// ////
+// //// var variableInitializer = node as VariableInitializer;
+// //// if (variableInitializer != null) {
+// //// var containsInvocations =
+// //// new SearchInvocationsVisitor().ContainsInvocations(variableInitializer.Initializer);
+// ////
+// //// var varDecl = node.Parent as VariableDeclarationStatement;
+// ////
+// //// var isDeclareStatement = varDecl != null;
+// //// var isUsingVar = isDeclareStatement && varDecl.Type.IsVar();
+// ////
+// //// var expressionType = ctx.Resolve(node).Type;
+// ////
+// //// var containsLaterAssignments = false;
+// //// if (isDeclareStatement) {
+// //// //if it is used later, the redundant removal should remove the assignment
+// //// //but not the variable
+// //// containsLaterAssignments =
+// //// new SearchAssignmentForVarVisitor().ContainsLaterAssignments(variableInitializer);
+// //// }
+// ////
+// //// AstNode grayOutNode;
+// //// var containsRefOrOut = new SearchRefOrOutVisitor().ContainsRefOrOut(variableInitializer);
+// //// if (containsInvocations && isDeclareStatement) {
+// //// grayOutNode = variableInitializer.AssignToken;
+// //// } else {
+// //// if (isDeclareStatement && !containsRefOrOut && !containsLaterAssignments && !ContainsOtherAssignments(variableInitializer.Parent)) {
+// //// grayOutNode = variableInitializer.Parent;
+// //// } else {
+// //// grayOutNode = variableInitializer.Initializer;
+// //// }
+// //// }
+// ////
+// //// AddDiagnosticAnalyzer(new CodeIssue(grayOutNode, issueDescription, actionDescription, script => {
+// //// var variableNode = (VariableInitializer)node;
+// //// if (containsInvocations && isDeclareStatement) {
+// //// //add the column ';' that will be removed after the next line replacement
+// //// var expression = (Statement)variableNode.Initializer.Clone();
+// //// if (containsLaterAssignments && varDecl != null) {
+// //// var clonedDefinition = (VariableDeclarationStatement)varDecl.Clone();
+// ////
+// //// var shortExpressionType = CreateShortType(ctx, expressionType, node);
+// //// clonedDefinition.Type = shortExpressionType;
+// //// var variableNodeClone = clonedDefinition.GetVariable(variableNode.Name);
+// //// variableNodeClone.Initializer = null;
+// //// script.InsertBefore(node.Parent, clonedDefinition);
+// //// }
+// //// script.Replace(node.Parent, expression);
+// //// return;
+// //// }
+// //// if (isDeclareStatement && !containsRefOrOut && !containsLaterAssignments&& !ContainsOtherAssignments(variableInitializer.Parent)) {
+// //// script.Remove(node.Parent);
+// //// return;
+// //// }
+// //// var replacement = (VariableInitializer)variableNode.Clone();
+// //// replacement.Initializer = Expression.Null;
+// //// if (isUsingVar) {
+// //// var shortExpressionType = CreateShortType(ctx, expressionType, node);
+// //// script.Replace(varDecl.Type, shortExpressionType);
+// //// }
+// //// script.Replace(node, replacement);
+// //// }) { IssueMarker = IssueMarker.GrayOut });
+// //// }
+// ////
+// //// var assignmentExpr = node.Parent as AssignmentExpression;
+// //// if (assignmentExpr == null)
+// //// return;
+// //// if (assignmentExpr.Parent is ExpressionStatement) {
+// //// AddDiagnosticAnalyzer(new CodeIssue(assignmentExpr.Parent, issueDescription, actionDescription, script => script.Remove(assignmentExpr.Parent)) { IssueMarker = IssueMarker.GrayOut });
+// //// } else {
+// //// AddDiagnosticAnalyzer(new CodeIssue(assignmentExpr.Left.StartLocation, assignmentExpr.OperatorToken.EndLocation, issueDescription, actionDescription,
+// //// script => script.Replace(assignmentExpr, assignmentExpr.Right.Clone())) { IssueMarker = IssueMarker.GrayOut });
+// //// }
+// //// }
+// ////
+// //// private static AstType CreateShortType(BaseSemanticModel SemanticModel, IType expressionType, AstNode node)
+// //// {
+// ////
+// //// var csResolver = SemanticModel.Resolver.GetResolverStateBefore(node);
+// //// var builder = new TypeSystemAstBuilder(csResolver);
+// //// return builder.ConvertType(expressionType);
+// //// }
+// ////
+// //// static bool IsAssignment(AstNode node)
+// //// {
+// //// if (node is VariableInitializer)
+// //// return true;
+// ////
+// //// var assignmentExpr = node.Parent as AssignmentExpression;
+// //// if (assignmentExpr != null)
+// //// return assignmentExpr.Left == node && assignmentExpr.Operator == AssignmentOperatorType.Assign;
+// ////
+// //// var direction = node.Parent as DirectionExpression;
+// //// if (direction != null)
+// //// return direction.FieldDirection == FieldDirection.Out && direction.Expression == node;
+// ////
+// //// return false;
+// //// }
+// ////
+// //// static bool IsInsideTryOrCatchBlock(AstNode node)
+// //// {
+// //// var tryCatchStatement = node.GetParent();
+// //// if (tryCatchStatement != null) {
+// //// if (tryCatchStatement.TryBlock.Contains(node.StartLocation))
+// //// return true;
+// //// foreach (var catchBlock in tryCatchStatement.CatchClauses)
+// //// if (catchBlock.Body.Contains(node.StartLocation))
+// //// return true;
+// //// }
+// //// return false;
+// //// }
+// ////
+// //// enum NodeState
+// //// {
+// //// None,
+// //// UsageReachable,
+// //// UsageUnreachable,
+// //// Processing,
+// //// }
+// ////
+// //// void ProcessNodes(VariableReferenceNode startNode)
+// //// {
+// //// // node state of a node indicates whether it is possible for an upstream node to reach any usage via
+// //// // the node
+// //// var nodeStates = new Dictionary();
+// //// var assignments = new List();
+// ////
+// //// // dfs to preprocess all nodes and find nodes which end with assignment
+// //// var stack = new Stack();
+// //// stack.Push(startNode);
+// //// while (stack.Count > 0) {
+// //// var node = stack.Pop();
+// //// if (node == null)
+// //// continue;
+// //// if (node.References.Count > 0) {
+// //// nodeStates [node] = IsAssignment(node.References [0]) ?
+// //// NodeState.UsageUnreachable : NodeState.UsageReachable;
+// //// } else {
+// //// nodeStates [node] = NodeState.None;
+// //// }
+// ////
+// //// // find indices of all assignments in node.References
+// //// var assignmentIndices = new List();
+// //// for (int i = 0; i < node.References.Count; i++) {
+// //// if (IsAssignment(node.References [i]))
+// //// assignmentIndices.Add(i);
+// //// }
+// //// // for two consecutive assignments, the first one is redundant
+// //// for (int i = 0; i < assignmentIndices.Count - 1; i++) {
+// //// var index1 = assignmentIndices [i];
+// //// var index2 = assignmentIndices [i + 1];
+// //// if (index1 + 1 == index2)
+// //// AddDiagnosticAnalyzer(node.References [index1]);
+// //// }
+// //// // if the node ends with an assignment, add it to assignments so as to check if it is redundant
+// //// // later
+// //// if (assignmentIndices.Count > 0 &&
+// //// assignmentIndices [assignmentIndices.Count - 1] == node.References.Count - 1)
+// //// assignments.Add(node);
+// ////
+// //// foreach (var nextNode in node.NextNodes) {
+// //// if (!nodeStates.ContainsKey(nextNode))
+// //// stack.Push(nextNode);
+// //// }
+// //// }
+// ////
+// //// foreach (var node in assignments) {
+// //// // we do not analyze an assignment inside a try block as it can jump to any catch block or finally block
+// //// if (IsInsideTryOrCatchBlock(node.References [0]))
+// //// continue;
+// //// ProcessNode(node, true, nodeStates);
+// //// }
+// //// }
+// ////
+// //// void ProcessNode(VariableReferenceNode node, bool addIssue,
+// //// IDictionary nodeStates)
+// //// {
+// //// if (nodeStates [node] == NodeState.None)
+// //// nodeStates [node] = NodeState.Processing;
+// ////
+// //// bool? reachable = false;
+// //// foreach (var nextNode in node.NextNodes) {
+// //// if (nodeStates [nextNode] == NodeState.None)
+// //// ProcessNode(nextNode, false, nodeStates);
+// ////
+// //// if (nodeStates [nextNode] == NodeState.UsageReachable) {
+// //// reachable = true;
+// //// break;
+// //// }
+// //// // downstream nodes are not fully processed (e.g. due to loop), there is no enough info to
+// //// // determine the node state
+// //// if (nodeStates [nextNode] != NodeState.UsageUnreachable)
+// //// reachable = null;
+// //// }
+// ////
+// //// // add issue if it is not possible to reach any usage via NextNodes
+// //// if (addIssue && reachable == false)
+// //// AddDiagnosticAnalyzer(node.References [node.References.Count - 1]);
+// ////
+// //// if (nodeStates [node] != NodeState.Processing)
+// //// return;
+// ////
+// //// switch (reachable) {
+// //// case null:
+// //// nodeStates [node] = NodeState.None;
+// //// break;
+// //// case true:
+// //// nodeStates [node] = NodeState.UsageReachable;
+// //// break;
+// //// case false:
+// //// nodeStates [node] = NodeState.UsageUnreachable;
+// //// break;
+// //// }
+// //// }
+// // }
+// }
-}
\ No newline at end of file
+//}
\ No newline at end of file
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Custom/StaticEventSubscriptionAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Custom/StaticEventSubscriptionAnalyzer.cs
index b87c5286..d6b445b4 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Custom/StaticEventSubscriptionAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Custom/StaticEventSubscriptionAnalyzer.cs
@@ -1,145 +1,145 @@
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Diagnostics;
-using System.Collections.Immutable;
+//using Microsoft.CodeAnalysis;
+//using Microsoft.CodeAnalysis.Diagnostics;
+//using System.Collections.Immutable;
-namespace RefactoringEssentials.CSharp.Diagnostics
-{
- [DiagnosticAnalyzer(LanguageNames.CSharp)]
- [NotPortedYet]
- public class StaticEventSubscriptionAnalyzer : DiagnosticAnalyzer
- {
- static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
- CSharpDiagnosticIDs.StaticEventSubscriptionAnalyzerID,
- GettextCatalog.GetString("Checks if static events are removed"),
- GettextCatalog.GetString("Subscription to static events without unsubscription may cause memory leaks"),
- DiagnosticAnalyzerCategories.CodeQualityIssues,
- DiagnosticSeverity.Warning,
- isEnabledByDefault: true,
- helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.StaticEventSubscriptionAnalyzerID)
- );
+//namespace RefactoringEssentials.CSharp.Diagnostics
+//{
+// [DiagnosticAnalyzer(LanguageNames.CSharp)]
+// [NotPortedYet]
+// public class StaticEventSubscriptionAnalyzer : DiagnosticAnalyzer
+// {
+// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
+// CSharpDiagnosticIDs.StaticEventSubscriptionAnalyzerID,
+// GettextCatalog.GetString("Checks if static events are removed"),
+// GettextCatalog.GetString("Subscription to static events without unsubscription may cause memory leaks"),
+// DiagnosticAnalyzerCategories.CodeQualityIssues,
+// DiagnosticSeverity.Warning,
+// isEnabledByDefault: true,
+// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.StaticEventSubscriptionAnalyzerID)
+// );
- public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
+// public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
- public override void Initialize(AnalysisContext context)
- {
- context.EnableConcurrentExecution();
- context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
- //context.RegisterSyntaxNodeAction(
- // (nodeContext) => {
- // Diagnostic diagnostic;
- // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
- // nodeContext.ReportDiagnostic(diagnostic);
- // }
- // },
- // new SyntaxKind[] { SyntaxKind.None }
- //);
- }
+// public override void Initialize(AnalysisContext context)
+// {
+// context.EnableConcurrentExecution();
+// context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
+// //context.RegisterSyntaxNodeAction(
+// // (nodeContext) => {
+// // Diagnostic diagnostic;
+// // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
+// // nodeContext.ReportDiagnostic(diagnostic);
+// // }
+// // },
+// // new SyntaxKind[] { SyntaxKind.None }
+// //);
+// }
- static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
- {
- diagnostic = default(Diagnostic);
- //var node = nodeContext.Node as ;
- //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
- //return true;
- return false;
- }
+// static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
+// {
+// diagnostic = default(Diagnostic);
+// //var node = nodeContext.Node as ;
+// //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
+// //return true;
+// return false;
+// }
- // class GatherVisitor : GatherVisitorBase
- // {
- // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
- // : base(semanticModel, addDiagnostic, cancellationToken)
- // {
- // }
+// // class GatherVisitor : GatherVisitorBase
+// // {
+// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
+// // : base(semanticModel, addDiagnostic, cancellationToken)
+// // {
+// // }
- //// public override void VisitSyntaxTree(SyntaxTree syntaxTree)
- //// {
- //// base.VisitSyntaxTree(syntaxTree);
- ////
- //// foreach (var assignedEvent in assignedEvents) {
- //// addedEvents.Remove(assignedEvent);
- //// }
- ////
- //// foreach (var hs in removedEvents) {
- //// HashSet> h;
- //// if (!addedEvents.TryGetValue(hs.Key, out h))
- //// continue;
- //// foreach (var evt in hs.Value) {
- //// restart:
- //// foreach (var m in h) {
- //// if (m.Item1 == evt) {
- //// h.Remove(m);
- //// goto restart;
- //// }
- //// }
- //// }
- //// }
- ////
- //// foreach (var added in addedEvents) {
- //// foreach (var usage in added.Value) {
- //// AddDiagnosticAnalyzer(new CodeIssue(usage.Item2.OperatorToken,
- // // ctx.TranslateString("Subscription to static events without unsubscription may cause memory leaks.")));
- //// }
- //// }
- //// }
- ////
- //// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
- //// {
- //// if (methodDeclaration.HasModifier(Modifiers.Static))
- //// return;
- ////
- //// base.VisitMethodDeclaration(methodDeclaration);
- //// }
- ////
- //// public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
- //// {
- //// if (constructorDeclaration.HasModifier(Modifiers.Static))
- //// return;
- //// base.VisitConstructorDeclaration(constructorDeclaration);
- //// }
- //// readonly Dictionary>> addedEvents = new Dictionary>>();
- //// readonly Dictionary> removedEvents = new Dictionary>();
- //// readonly HashSet assignedEvents = new HashSet ();
- ////
- //// public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression)
- //// {
- //// base.VisitAssignmentExpression(assignmentExpression);
- ////
- //// if (assignmentExpression.Operator == AssignmentOperatorType.Add) {
- //// var left = ctx.Resolve(assignmentExpression.Left) as MemberResolveResult;
- //// if (left == null || left.Member.SymbolKind != SymbolKind.Event || !left.Member.IsStatic)
- //// return;
- ////
- //// if (assignmentExpression.Right is AnonymousMethodExpression || assignmentExpression.Right is LambdaExpression) {
- //// AddDiagnosticAnalyzer(new CodeIssue(assignmentExpression.OperatorToken,
- //// ctx.TranslateString("Subscription to static events with an anonymous method may cause memory leaks.")));
- //// }
- ////
- ////
- //// var right = ctx.Resolve(assignmentExpression.Right) as MethodGroupResolveResult;
- //// if (right == null || right.Methods.Count() != 1)
- //// return;
- //// HashSet> hs;
- //// if (!addedEvents.TryGetValue(left.Member, out hs))
- //// addedEvents[left.Member] = hs = new HashSet>();
- //// hs.Add(Tuple.Create((IMember)right.Methods.First(), assignmentExpression));
- //// } else if (assignmentExpression.Operator == AssignmentOperatorType.Subtract) {
- //// var left = ctx.Resolve(assignmentExpression.Left) as MemberResolveResult;
- //// if (left == null || left.Member.SymbolKind != SymbolKind.Event || !left.Member.IsStatic)
- //// return;
- //// var right = ctx.Resolve(assignmentExpression.Right) as MethodGroupResolveResult;
- //// if (right == null || right.Methods.Count() != 1)
- //// return;
- //// HashSet hs;
- //// if (!removedEvents.TryGetValue(left.Member, out hs))
- //// removedEvents[left.Member] = hs = new HashSet();
- //// hs.Add(right.Methods.First());
- //// } else if (assignmentExpression.Operator == AssignmentOperatorType.Assign) {
- //// var left = ctx.Resolve(assignmentExpression.Left) as MemberResolveResult;
- //// if (left == null || left.Member.SymbolKind != SymbolKind.Event || !left.Member.IsStatic)
- //// return;
- //// assignedEvents.Add(left.Member);
- //// }
- //// }
- // }
- }
-}
\ No newline at end of file
+// //// public override void VisitSyntaxTree(SyntaxTree syntaxTree)
+// //// {
+// //// base.VisitSyntaxTree(syntaxTree);
+// ////
+// //// foreach (var assignedEvent in assignedEvents) {
+// //// addedEvents.Remove(assignedEvent);
+// //// }
+// ////
+// //// foreach (var hs in removedEvents) {
+// //// HashSet> h;
+// //// if (!addedEvents.TryGetValue(hs.Key, out h))
+// //// continue;
+// //// foreach (var evt in hs.Value) {
+// //// restart:
+// //// foreach (var m in h) {
+// //// if (m.Item1 == evt) {
+// //// h.Remove(m);
+// //// goto restart;
+// //// }
+// //// }
+// //// }
+// //// }
+// ////
+// //// foreach (var added in addedEvents) {
+// //// foreach (var usage in added.Value) {
+// //// AddDiagnosticAnalyzer(new CodeIssue(usage.Item2.OperatorToken,
+// // // ctx.TranslateString("Subscription to static events without unsubscription may cause memory leaks.")));
+// //// }
+// //// }
+// //// }
+// ////
+// //// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
+// //// {
+// //// if (methodDeclaration.HasModifier(Modifiers.Static))
+// //// return;
+// ////
+// //// base.VisitMethodDeclaration(methodDeclaration);
+// //// }
+// ////
+// //// public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
+// //// {
+// //// if (constructorDeclaration.HasModifier(Modifiers.Static))
+// //// return;
+// //// base.VisitConstructorDeclaration(constructorDeclaration);
+// //// }
+// //// readonly Dictionary>> addedEvents = new Dictionary>>();
+// //// readonly Dictionary> removedEvents = new Dictionary>();
+// //// readonly HashSet assignedEvents = new HashSet ();
+// ////
+// //// public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression)
+// //// {
+// //// base.VisitAssignmentExpression(assignmentExpression);
+// ////
+// //// if (assignmentExpression.Operator == AssignmentOperatorType.Add) {
+// //// var left = ctx.Resolve(assignmentExpression.Left) as MemberResolveResult;
+// //// if (left == null || left.Member.SymbolKind != SymbolKind.Event || !left.Member.IsStatic)
+// //// return;
+// ////
+// //// if (assignmentExpression.Right is AnonymousMethodExpression || assignmentExpression.Right is LambdaExpression) {
+// //// AddDiagnosticAnalyzer(new CodeIssue(assignmentExpression.OperatorToken,
+// //// ctx.TranslateString("Subscription to static events with an anonymous method may cause memory leaks.")));
+// //// }
+// ////
+// ////
+// //// var right = ctx.Resolve(assignmentExpression.Right) as MethodGroupResolveResult;
+// //// if (right == null || right.Methods.Count() != 1)
+// //// return;
+// //// HashSet> hs;
+// //// if (!addedEvents.TryGetValue(left.Member, out hs))
+// //// addedEvents[left.Member] = hs = new HashSet>();
+// //// hs.Add(Tuple.Create((IMember)right.Methods.First(), assignmentExpression));
+// //// } else if (assignmentExpression.Operator == AssignmentOperatorType.Subtract) {
+// //// var left = ctx.Resolve(assignmentExpression.Left) as MemberResolveResult;
+// //// if (left == null || left.Member.SymbolKind != SymbolKind.Event || !left.Member.IsStatic)
+// //// return;
+// //// var right = ctx.Resolve(assignmentExpression.Right) as MethodGroupResolveResult;
+// //// if (right == null || right.Methods.Count() != 1)
+// //// return;
+// //// HashSet hs;
+// //// if (!removedEvents.TryGetValue(left.Member, out hs))
+// //// removedEvents[left.Member] = hs = new HashSet();
+// //// hs.Add(right.Methods.First());
+// //// } else if (assignmentExpression.Operator == AssignmentOperatorType.Assign) {
+// //// var left = ctx.Resolve(assignmentExpression.Left) as MemberResolveResult;
+// //// if (left == null || left.Member.SymbolKind != SymbolKind.Event || !left.Member.IsStatic)
+// //// return;
+// //// assignedEvents.Add(left.Member);
+// //// }
+// //// }
+// // }
+// }
+//}
\ No newline at end of file
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/EqualExpressionComparisonAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/EqualExpressionComparisonAnalyzer.cs
index 1eb112f7..bacc4065 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/EqualExpressionComparisonAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/EqualExpressionComparisonAnalyzer.cs
@@ -77,39 +77,52 @@ static bool TryGetDiagnosticFromEqualsInvocation(SyntaxNodeAnalysisContext nodeC
diagnostic = default(Diagnostic);
var node = nodeContext.Node as InvocationExpressionSyntax;
- var info = nodeContext.SemanticModel.GetSymbolInfo(node);
+ SimpleNameSyntax methodName;
+ if (node.Expression is MemberAccessExpressionSyntax maes)
+ methodName = maes.Name;
+ else if (node.Expression is IdentifierNameSyntax ins)
+ methodName = ins;
+ else
+ return false;
+
+ if (methodName.Identifier.ValueText != "Equals")
+ return false;
- if (info.Symbol == null || !info.Symbol.IsKind(SymbolKind.Method) || info.Symbol.Name != "Equals" || info.Symbol.GetReturnType().SpecialType != SpecialType.System_Boolean)
+ var info = nodeContext.SemanticModel.GetSymbolInfo(node);
+ if (info.Symbol == null || !info.Symbol.IsKind(SymbolKind.Method) || info.Symbol.GetReturnType().SpecialType != SpecialType.System_Boolean)
return false;
var method = info.Symbol as IMethodSymbol;
if (method.IsStatic) {
if (method.Parameters.Length != 2 || node.ArgumentList.Arguments.Count != 2)
return false;
- if (CSharpUtil.AreConditionsEqual(node.ArgumentList.Arguments[0].Expression, node.ArgumentList.Arguments[1].Expression)) {
- if (node.Parent.IsKind(SyntaxKind.LogicalNotExpression)) {
- diagnostic = Diagnostic.Create(descriptor, node.Parent.GetLocation(), "false");
- } else {
- diagnostic = Diagnostic.Create(descriptor, node.GetLocation(), "true");
- }
+ if (AreConditionsEquivalent(node, node.ArgumentList.Arguments[0].Expression, node.ArgumentList.Arguments[1].Expression, out diagnostic))
return true;
- }
} else {
if (method.Parameters.Length != 1 || node.ArgumentList.Arguments.Count != 1)
return false;
var target = node.Expression as MemberAccessExpressionSyntax;
if (target == null)
return false;
- if (CSharpUtil.AreConditionsEqual(node.ArgumentList.Arguments[0].Expression, target.Expression)) {
- if (node.Parent.IsKind(SyntaxKind.LogicalNotExpression)) {
- diagnostic = Diagnostic.Create(descriptor, node.Parent.GetLocation(), "false");
- } else {
- diagnostic = Diagnostic.Create(descriptor, node.GetLocation(), "true");
- }
+
+ if (AreConditionsEquivalent(node, node.ArgumentList.Arguments[0].Expression, target.Expression, out diagnostic))
return true;
- }
}
return false;
}
+
+ static bool AreConditionsEquivalent (ExpressionSyntax node, ExpressionSyntax arg1, ExpressionSyntax arg2, out Diagnostic diagnostic)
+ {
+ if (CSharpUtil.AreConditionsEqual(arg1, arg2))
+ {
+ if (node.Parent.IsKind(SyntaxKind.LogicalNotExpression))
+ diagnostic = Diagnostic.Create(descriptor, node.Parent.GetLocation(), "false");
+ else
+ diagnostic = Diagnostic.Create(descriptor, node.GetLocation(), "true");
+ return true;
+ }
+ diagnostic = default(Diagnostic);
+ return false;
+ }
}
}
\ No newline at end of file
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/ForControlVariableIsNeverModifiedAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/ForControlVariableIsNeverModifiedAnalyzer.cs
index f6dc49d9..d881c814 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/ForControlVariableIsNeverModifiedAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/ForControlVariableIsNeverModifiedAnalyzer.cs
@@ -43,6 +43,8 @@ void AnalyzeForStatement(SyntaxNodeAnalysisContext nodeContext)
return;
if ((node.Condition == null) || !node.Condition.DescendantNodesAndSelf().OfType().Any(n => n.Identifier.ValueText == local.Name))
continue;
+ if (!IsLoopVariable(node.Condition, local.Name))
+ continue;
bool wasModified = false;
foreach (var identifier in node.DescendantNodesAndSelf().OfType()) {
if (identifier.Identifier.ValueText != local.Name)
@@ -63,6 +65,20 @@ void AnalyzeForStatement(SyntaxNodeAnalysisContext nodeContext)
}
}
+ bool IsLoopVariable (ExpressionSyntax condition, string name)
+ {
+ foreach (var n in condition.DescendantNodesAndSelf ()) {
+ var binOp = n as BinaryExpressionSyntax;
+ if (binOp != null && binOp.Left.DescendantNodesAndSelf ().OfType ().Any (i => i.Identifier.ValueText == name))
+ return true;
+ if (n is PrefixUnaryExpressionSyntax || n is PostfixUnaryExpressionSyntax) {
+ if (n.DescendantNodesAndSelf ().OfType ().Any (i => i.Identifier.ValueText == name))
+ return true;
+ }
+ }
+ return false;
+ }
+
bool IsModified(IdentifierNameSyntax identifier)
{
if (identifier.Parent.IsKind(SyntaxKind.PreDecrementExpression) ||
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/FunctionNeverReturnsAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/FunctionNeverReturnsAnalyzer.cs
index 7e0f05c0..8308a4e6 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/FunctionNeverReturnsAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/FunctionNeverReturnsAnalyzer.cs
@@ -6,7 +6,7 @@
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using RefactoringEssentials.Util.Analysis;
-
+/*
namespace RefactoringEssentials.CSharp.Diagnostics
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
@@ -294,4 +294,4 @@ bool CheckRecursion(SyntaxNode node)
}
}
}
-}
\ No newline at end of file
+}*/
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/LocalVariableHidesMemberAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/LocalVariableHidesMemberAnalyzer.cs
index 869d712a..741fdd2f 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/LocalVariableHidesMemberAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/LocalVariableHidesMemberAnalyzer.cs
@@ -74,8 +74,8 @@ static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnost
var member = node.AncestorsAndSelf().FirstOrDefault(n => n is MemberDeclarationSyntax);
if (member == null)
return false;
- var symbols = nodeContext.SemanticModel.LookupSymbols(member.SpanStart);
var memberSymbol = nodeContext.SemanticModel.GetDeclaredSymbol(member);
+ var symbols = nodeContext.SemanticModel.LookupSymbols(member.SpanStart, memberSymbol.GetContainingTypeOrThis());
foreach (var variable in node.Declaration.Variables)
{
@@ -109,8 +109,8 @@ static bool TryGetDiagnosticFromForeach(SyntaxNodeAnalysisContext nodeContext, o
var member = node.AncestorsAndSelf().FirstOrDefault(n => n is MemberDeclarationSyntax);
if (member == null)
return false;
- var symbols = nodeContext.SemanticModel.LookupSymbols(member.SpanStart);
var memberSymbol = nodeContext.SemanticModel.GetDeclaredSymbol(member);
+ var symbols = nodeContext.SemanticModel.LookupSymbols(member.SpanStart, memberSymbol.GetContainingTypeOrThis());
var hidingMember = symbols.FirstOrDefault(v => v.Name == node.Identifier.ValueText && ((memberSymbol.IsStatic && v.IsStatic) || !memberSymbol.IsStatic) && !v.IsKind(SymbolKind.Local) && !v.IsKind(SymbolKind.Parameter));
if (hidingMember == null)
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/OptionalParameterHierarchyMismatchAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/OptionalParameterHierarchyMismatchAnalyzer.cs
index f5eaf0db..6cf117d2 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/OptionalParameterHierarchyMismatchAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/OptionalParameterHierarchyMismatchAnalyzer.cs
@@ -1,155 +1,155 @@
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Diagnostics;
-using System.Collections.Immutable;
+//using Microsoft.CodeAnalysis;
+//using Microsoft.CodeAnalysis.Diagnostics;
+//using System.Collections.Immutable;
-namespace RefactoringEssentials.CSharp.Diagnostics
-{
- [DiagnosticAnalyzer(LanguageNames.CSharp)]
- [NotPortedYet]
- public class OptionalParameterHierarchyMismatchAnalyzer : DiagnosticAnalyzer
- {
- static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
- CSharpDiagnosticIDs.OptionalParameterHierarchyMismatchAnalyzerID,
- GettextCatalog.GetString("The value of an optional parameter in a method does not match the base method"),
- GettextCatalog.GetString("Optional parameter value {0} differs from base {1} '{2}'"),
- DiagnosticAnalyzerCategories.CodeQualityIssues,
- DiagnosticSeverity.Warning,
- isEnabledByDefault: true,
- helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.OptionalParameterHierarchyMismatchAnalyzerID)
- );
+//namespace RefactoringEssentials.CSharp.Diagnostics
+//{
+// [DiagnosticAnalyzer(LanguageNames.CSharp)]
+// [NotPortedYet]
+// public class OptionalParameterHierarchyMismatchAnalyzer : DiagnosticAnalyzer
+// {
+// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
+// CSharpDiagnosticIDs.OptionalParameterHierarchyMismatchAnalyzerID,
+// GettextCatalog.GetString("The value of an optional parameter in a method does not match the base method"),
+// GettextCatalog.GetString("Optional parameter value {0} differs from base {1} '{2}'"),
+// DiagnosticAnalyzerCategories.CodeQualityIssues,
+// DiagnosticSeverity.Warning,
+// isEnabledByDefault: true,
+// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.OptionalParameterHierarchyMismatchAnalyzerID)
+// );
- public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
+// public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
- public override void Initialize(AnalysisContext context)
- {
- context.EnableConcurrentExecution();
- context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
- //context.RegisterSyntaxNodeAction(
- // (nodeContext) => {
- // Diagnostic diagnostic;
- // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
- // nodeContext.ReportDiagnostic(diagnostic);
- // }
- // },
- // new SyntaxKind[] { SyntaxKind.None }
- //);
- }
+// public override void Initialize(AnalysisContext context)
+// {
+// context.EnableConcurrentExecution();
+// context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
+// //context.RegisterSyntaxNodeAction(
+// // (nodeContext) => {
+// // Diagnostic diagnostic;
+// // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
+// // nodeContext.ReportDiagnostic(diagnostic);
+// // }
+// // },
+// // new SyntaxKind[] { SyntaxKind.None }
+// //);
+// }
- static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
- {
- diagnostic = default(Diagnostic);
- //var node = nodeContext.Node as ;
- //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
- //return true;
- return false;
- }
+// static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
+// {
+// diagnostic = default(Diagnostic);
+// //var node = nodeContext.Node as ;
+// //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
+// //return true;
+// return false;
+// }
- // class GatherVisitor : GatherVisitorBase
- // {
- // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
- // : base (semanticModel, addDiagnostic, cancellationToken)
- // {
- // }
- ////
- //// //Delegate declarations are not visited even though they can have optional
- //// //parameters because they can not be overriden.
- ////
- //// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
- //// {
- //// VisitParameterizedEntityDeclaration("method", methodDeclaration, methodDeclaration.Parameters);
- //// }
- ////
- //// void VisitParameterizedEntityDeclaration(string memberType, EntityDeclaration entityDeclaration, AstNodeCollection parameters)
- //// {
- //// // Ignore explicit interface implementations (those should have no optional parameters as there can't be any direct calls)
- //// if (!entityDeclaration.GetChildByRole(EntityDeclaration.PrivateImplementationTypeRole).IsNull)
- //// return;
- //// //Override is not strictly necessary because methodDeclaration
- //// //might still implement an interface member
- //// var memberResolveResult = ctx.Resolve(entityDeclaration) as MemberResolveResult;
- //// if (memberResolveResult == null) {
- //// return;
- //// }
- //// var member = (IParameterizedMember)memberResolveResult.Member;
- //// var baseMembers = InheritanceHelper.GetBaseMembers(member, true).ToList();
- //// foreach (IParameterizedMember baseMember in baseMembers) {
- //// if (baseMember.IsOverride || baseMember.DeclaringType.Kind == TypeKind.Interface)
- //// continue;
- //// CompareMethods(memberType, parameters, member, baseMember);
- //// return;
- //// }
- //// // only check 1 interface method -> multiple interface implementations could lead to deault value conflicts
- //// // possible other solutions: Skip the interface check entirely
- //// var interfaceBaseMethods = baseMembers.Where(b => b.DeclaringType.Kind == TypeKind.Interface).ToList();
- //// if (interfaceBaseMethods.Count == 1) {
- //// foreach (IParameterizedMember baseMember in interfaceBaseMethods) {
- //// if (baseMember.DeclaringType.Kind == TypeKind.Interface) {
- //// CompareMethods(memberType, parameters, member, baseMember);
- //// }
- //// }
- //// }
- //// }
- ////
- //// static Expression CreateDefaultValueExpression(BaseSemanticModel ctx, AstNode node, IType type, object constantValue)
- //// {
- //// var astBuilder = ctx.CreateTypeSystemAstBuilder(node);
- //// return astBuilder.ConvertConstantValue(type, constantValue);
- //// }
- ////
- //// void CompareMethods(string memberType, AstNodeCollection parameters, IParameterizedMember overridenMethod, IParameterizedMember baseMethod)
- //// {
- //// var parameterEnumerator = parameters.GetEnumerator();
- //// for (int parameterIndex = 0; parameterIndex < overridenMethod.Parameters.Count; parameterIndex++) {
- //// parameterEnumerator.MoveNext();
- ////
- //// var baseParameter = baseMethod.Parameters [parameterIndex];
- ////
- //// var overridenParameter = overridenMethod.Parameters [parameterIndex];
- ////
- //// string parameterName = overridenParameter.Name;
- //// var parameterDeclaration = parameterEnumerator.Current;
- ////
- //// if (overridenParameter.IsOptional) {
- //// if (!baseParameter.IsOptional) {
- //// AddDiagnosticAnalyzer(new CodeIssue(parameterDeclaration,
- //// string.Format(ctx.TranslateString("Optional parameter value {0} differs from base " + memberType + " '{1}'"), parameterName, baseMethod.DeclaringType.FullName),
- //// ctx.TranslateString("Remove parameter default value"),
- //// script => {
- //// script.Remove(parameterDeclaration.AssignToken);
- //// script.Remove(parameterDeclaration.DefaultExpression);
- //// script.FormatText(parameterDeclaration);
- //// }));
- //// } else if (!object.Equals(overridenParameter.ConstantValue, baseParameter.ConstantValue)) {
- //// AddDiagnosticAnalyzer(new CodeIssue(parameterDeclaration,
- //// string.Format(ctx.TranslateString("Optional parameter value {0} differs from base " + memberType + " '{1}'"), parameterName, baseMethod.DeclaringType.FullName),
- //// string.Format(ctx.TranslateString("Change default value to {0}"), baseParameter.ConstantValue),
- //// script => script.Replace(parameterDeclaration.DefaultExpression, CreateDefaultValueExpression(ctx, parameterDeclaration, baseParameter.Type, baseParameter.ConstantValue))));
- //// }
- //// } else {
- //// if (!baseParameter.IsOptional)
- //// continue;
- //// AddDiagnosticAnalyzer(new CodeIssue(parameterDeclaration,
- //// string.Format(ctx.TranslateString("Parameter {0} has default value in base method '{1}'"), parameterName, baseMethod.FullName),
- //// string.Format(ctx.TranslateString("Add default value from base '{0}'"), CreateDefaultValueExpression(ctx, parameterDeclaration, baseParameter.Type, baseParameter.ConstantValue)),
- //// script => {
- //// var newParameter = (ParameterDeclaration)parameterDeclaration.Clone();
- //// newParameter.DefaultExpression = CreateDefaultValueExpression(ctx, parameterDeclaration, baseParameter.Type, baseParameter.ConstantValue);
- //// script.Replace(parameterDeclaration, newParameter);
- //// }
- //// ));
- //// }
- //// }
- //// }
- ////
- //// public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
- //// {
- //// VisitParameterizedEntityDeclaration("indexer", indexerDeclaration, indexerDeclaration.Parameters);
- //// }
- ////
- //// public override void VisitBlockStatement(BlockStatement blockStatement)
- //// {
- //// //No need to visit statements
- //// }
- // }
- }
-}
\ No newline at end of file
+// // class GatherVisitor : GatherVisitorBase
+// // {
+// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
+// // : base (semanticModel, addDiagnostic, cancellationToken)
+// // {
+// // }
+// ////
+// //// //Delegate declarations are not visited even though they can have optional
+// //// //parameters because they can not be overriden.
+// ////
+// //// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
+// //// {
+// //// VisitParameterizedEntityDeclaration("method", methodDeclaration, methodDeclaration.Parameters);
+// //// }
+// ////
+// //// void VisitParameterizedEntityDeclaration(string memberType, EntityDeclaration entityDeclaration, AstNodeCollection parameters)
+// //// {
+// //// // Ignore explicit interface implementations (those should have no optional parameters as there can't be any direct calls)
+// //// if (!entityDeclaration.GetChildByRole(EntityDeclaration.PrivateImplementationTypeRole).IsNull)
+// //// return;
+// //// //Override is not strictly necessary because methodDeclaration
+// //// //might still implement an interface member
+// //// var memberResolveResult = ctx.Resolve(entityDeclaration) as MemberResolveResult;
+// //// if (memberResolveResult == null) {
+// //// return;
+// //// }
+// //// var member = (IParameterizedMember)memberResolveResult.Member;
+// //// var baseMembers = InheritanceHelper.GetBaseMembers(member, true).ToList();
+// //// foreach (IParameterizedMember baseMember in baseMembers) {
+// //// if (baseMember.IsOverride || baseMember.DeclaringType.Kind == TypeKind.Interface)
+// //// continue;
+// //// CompareMethods(memberType, parameters, member, baseMember);
+// //// return;
+// //// }
+// //// // only check 1 interface method -> multiple interface implementations could lead to deault value conflicts
+// //// // possible other solutions: Skip the interface check entirely
+// //// var interfaceBaseMethods = baseMembers.Where(b => b.DeclaringType.Kind == TypeKind.Interface).ToList();
+// //// if (interfaceBaseMethods.Count == 1) {
+// //// foreach (IParameterizedMember baseMember in interfaceBaseMethods) {
+// //// if (baseMember.DeclaringType.Kind == TypeKind.Interface) {
+// //// CompareMethods(memberType, parameters, member, baseMember);
+// //// }
+// //// }
+// //// }
+// //// }
+// ////
+// //// static Expression CreateDefaultValueExpression(BaseSemanticModel ctx, AstNode node, IType type, object constantValue)
+// //// {
+// //// var astBuilder = ctx.CreateTypeSystemAstBuilder(node);
+// //// return astBuilder.ConvertConstantValue(type, constantValue);
+// //// }
+// ////
+// //// void CompareMethods(string memberType, AstNodeCollection parameters, IParameterizedMember overridenMethod, IParameterizedMember baseMethod)
+// //// {
+// //// var parameterEnumerator = parameters.GetEnumerator();
+// //// for (int parameterIndex = 0; parameterIndex < overridenMethod.Parameters.Count; parameterIndex++) {
+// //// parameterEnumerator.MoveNext();
+// ////
+// //// var baseParameter = baseMethod.Parameters [parameterIndex];
+// ////
+// //// var overridenParameter = overridenMethod.Parameters [parameterIndex];
+// ////
+// //// string parameterName = overridenParameter.Name;
+// //// var parameterDeclaration = parameterEnumerator.Current;
+// ////
+// //// if (overridenParameter.IsOptional) {
+// //// if (!baseParameter.IsOptional) {
+// //// AddDiagnosticAnalyzer(new CodeIssue(parameterDeclaration,
+// //// string.Format(ctx.TranslateString("Optional parameter value {0} differs from base " + memberType + " '{1}'"), parameterName, baseMethod.DeclaringType.FullName),
+// //// ctx.TranslateString("Remove parameter default value"),
+// //// script => {
+// //// script.Remove(parameterDeclaration.AssignToken);
+// //// script.Remove(parameterDeclaration.DefaultExpression);
+// //// script.FormatText(parameterDeclaration);
+// //// }));
+// //// } else if (!object.Equals(overridenParameter.ConstantValue, baseParameter.ConstantValue)) {
+// //// AddDiagnosticAnalyzer(new CodeIssue(parameterDeclaration,
+// //// string.Format(ctx.TranslateString("Optional parameter value {0} differs from base " + memberType + " '{1}'"), parameterName, baseMethod.DeclaringType.FullName),
+// //// string.Format(ctx.TranslateString("Change default value to {0}"), baseParameter.ConstantValue),
+// //// script => script.Replace(parameterDeclaration.DefaultExpression, CreateDefaultValueExpression(ctx, parameterDeclaration, baseParameter.Type, baseParameter.ConstantValue))));
+// //// }
+// //// } else {
+// //// if (!baseParameter.IsOptional)
+// //// continue;
+// //// AddDiagnosticAnalyzer(new CodeIssue(parameterDeclaration,
+// //// string.Format(ctx.TranslateString("Parameter {0} has default value in base method '{1}'"), parameterName, baseMethod.FullName),
+// //// string.Format(ctx.TranslateString("Add default value from base '{0}'"), CreateDefaultValueExpression(ctx, parameterDeclaration, baseParameter.Type, baseParameter.ConstantValue)),
+// //// script => {
+// //// var newParameter = (ParameterDeclaration)parameterDeclaration.Clone();
+// //// newParameter.DefaultExpression = CreateDefaultValueExpression(ctx, parameterDeclaration, baseParameter.Type, baseParameter.ConstantValue);
+// //// script.Replace(parameterDeclaration, newParameter);
+// //// }
+// //// ));
+// //// }
+// //// }
+// //// }
+// ////
+// //// public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
+// //// {
+// //// VisitParameterizedEntityDeclaration("indexer", indexerDeclaration, indexerDeclaration.Parameters);
+// //// }
+// ////
+// //// public override void VisitBlockStatement(BlockStatement blockStatement)
+// //// {
+// //// //No need to visit statements
+// //// }
+// // }
+// }
+//}
\ No newline at end of file
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/ParameterHidesMemberAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/ParameterHidesMemberAnalyzer.cs
index 7f925aa8..78a68418 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/ParameterHidesMemberAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/ParameterHidesMemberAnalyzer.cs
@@ -37,7 +37,6 @@ static void AnalyzeParameterList(SyntaxNodeAnalysisContext nodeContext)
if (member == null)
return;
- var symbols = nodeContext.SemanticModel.LookupSymbols(node.SpanStart);
var memberSymbol = nodeContext.SemanticModel.GetDeclaredSymbol(member);
if (memberSymbol == null)
return;
@@ -45,6 +44,8 @@ static void AnalyzeParameterList(SyntaxNodeAnalysisContext nodeContext)
return;
if (memberSymbol is IMethodSymbol && ((IMethodSymbol)memberSymbol).MethodKind == MethodKind.Constructor || memberSymbol.ExplicitInterfaceImplementations().Length > 0)
return;
+
+ var symbols = nodeContext.SemanticModel.LookupSymbols(node.SpanStart, memberSymbol.GetContainingTypeOrThis ());
foreach (var param in node.Parameters)
{
var hidingMember = symbols.FirstOrDefault(v => v.Name == param.Identifier.ValueText && ((memberSymbol.IsStatic && v.IsStatic) || !memberSymbol.IsStatic) && !v.IsKind(SymbolKind.Local) && !v.IsKind(SymbolKind.Parameter));
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/PolymorphicFieldLikeEventInvocationAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/PolymorphicFieldLikeEventInvocationAnalyzer.cs
index b47e0fa3..af1cb3e0 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/PolymorphicFieldLikeEventInvocationAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/PolymorphicFieldLikeEventInvocationAnalyzer.cs
@@ -1,76 +1,76 @@
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Diagnostics;
-using System.Collections.Immutable;
+//using Microsoft.CodeAnalysis;
+//using Microsoft.CodeAnalysis.Diagnostics;
+//using System.Collections.Immutable;
-namespace RefactoringEssentials.CSharp.Diagnostics
-{
- [DiagnosticAnalyzer(LanguageNames.CSharp)]
- [NotPortedYet]
- public class PolymorphicFieldLikeEventInvocationAnalyzer : DiagnosticAnalyzer
- {
- static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
- CSharpDiagnosticIDs.PolymorphicFieldLikeEventInvocationAnalyzerID,
- GettextCatalog.GetString("Invocation of polymorphic field event leads to unpredictable result since invocation lists are not virtual"),
- GettextCatalog.GetString("The event `{0}' can only appear on the left hand side of `+=' or `-=' operator"),
- DiagnosticAnalyzerCategories.CodeQualityIssues,
- DiagnosticSeverity.Warning,
- isEnabledByDefault: true,
- helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.PolymorphicFieldLikeEventInvocationAnalyzerID)
- );
+//namespace RefactoringEssentials.CSharp.Diagnostics
+//{
+// [DiagnosticAnalyzer(LanguageNames.CSharp)]
+// [NotPortedYet]
+// public class PolymorphicFieldLikeEventInvocationAnalyzer : DiagnosticAnalyzer
+// {
+// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
+// CSharpDiagnosticIDs.PolymorphicFieldLikeEventInvocationAnalyzerID,
+// GettextCatalog.GetString("Invocation of polymorphic field event leads to unpredictable result since invocation lists are not virtual"),
+// GettextCatalog.GetString("The event `{0}' can only appear on the left hand side of `+=' or `-=' operator"),
+// DiagnosticAnalyzerCategories.CodeQualityIssues,
+// DiagnosticSeverity.Warning,
+// isEnabledByDefault: true,
+// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.PolymorphicFieldLikeEventInvocationAnalyzerID)
+// );
- public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
+// public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
- public override void Initialize(AnalysisContext context)
- {
- context.EnableConcurrentExecution();
- context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
- //context.RegisterSyntaxNodeAction(
- // (nodeContext) => {
- // Diagnostic diagnostic;
- // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
- // nodeContext.ReportDiagnostic(diagnostic);
- // }
- // },
- // new SyntaxKind[] { SyntaxKind.None }
- //);
- }
+// public override void Initialize(AnalysisContext context)
+// {
+// context.EnableConcurrentExecution();
+// context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
+// //context.RegisterSyntaxNodeAction(
+// // (nodeContext) => {
+// // Diagnostic diagnostic;
+// // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
+// // nodeContext.ReportDiagnostic(diagnostic);
+// // }
+// // },
+// // new SyntaxKind[] { SyntaxKind.None }
+// //);
+// }
- static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
- {
- diagnostic = default(Diagnostic);
- //var node = nodeContext.Node as ;
- //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
- //return true;
- return false;
- }
+// static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
+// {
+// diagnostic = default(Diagnostic);
+// //var node = nodeContext.Node as ;
+// //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
+// //return true;
+// return false;
+// }
- // class GatherVisitor : GatherVisitorBase
- // {
- // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
- // : base (semanticModel, addDiagnostic, cancellationToken)
- // {
- // }
+// // class GatherVisitor : GatherVisitorBase
+// // {
+// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
+// // : base (semanticModel, addDiagnostic, cancellationToken)
+// // {
+// // }
- //// public override void VisitInvocationExpression(InvocationExpression invocationExpression)
- //// {
- //// base.VisitInvocationExpression(invocationExpression);
- //// var rr = ctx.Resolve(invocationExpression.Target) as MemberResolveResult;
- //// if (rr == null || rr.IsError)
- //// return;
- //// var evt = rr.Member as IEvent;
- //// if (evt == null || !evt.IsOverride)
- //// return;
- //// if (evt.AddAccessor.HasBody) {
- //// AddDiagnosticAnalyzer(new CodeIssue(
- //// invocationExpression.Target,
- // // string.Format(ctx.TranslateString("The event `{0}' can only appear on the left hand side of `+=' or `-=' operator"), evt.Name)
- //// ));
- //// return;
- //// }
- //// AddDiagnosticAnalyzer(new CodeIssue(
- //// invocationExpression,
- //// ctx.TranslateString("Invocation of polymorphic field like event")));
- //// }
- // }
- }
-}
\ No newline at end of file
+// //// public override void VisitInvocationExpression(InvocationExpression invocationExpression)
+// //// {
+// //// base.VisitInvocationExpression(invocationExpression);
+// //// var rr = ctx.Resolve(invocationExpression.Target) as MemberResolveResult;
+// //// if (rr == null || rr.IsError)
+// //// return;
+// //// var evt = rr.Member as IEvent;
+// //// if (evt == null || !evt.IsOverride)
+// //// return;
+// //// if (evt.AddAccessor.HasBody) {
+// //// AddDiagnosticAnalyzer(new CodeIssue(
+// //// invocationExpression.Target,
+// // // string.Format(ctx.TranslateString("The event `{0}' can only appear on the left hand side of `+=' or `-=' operator"), evt.Name)
+// //// ));
+// //// return;
+// //// }
+// //// AddDiagnosticAnalyzer(new CodeIssue(
+// //// invocationExpression,
+// //// ctx.TranslateString("Invocation of polymorphic field like event")));
+// //// }
+// // }
+// }
+//}
\ No newline at end of file
diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/PossibleAssignmentToReadonlyFieldAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/PossibleAssignmentToReadonlyFieldAnalyzer.cs
index 4501a435..b0f19495 100644
--- a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/PossibleAssignmentToReadonlyFieldAnalyzer.cs
+++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/PossibleAssignmentToReadonlyFieldAnalyzer.cs
@@ -1,120 +1,120 @@
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Diagnostics;
-using System.Collections.Immutable;
+//using Microsoft.CodeAnalysis;
+//using Microsoft.CodeAnalysis.Diagnostics;
+//using System.Collections.Immutable;
-namespace RefactoringEssentials.CSharp.Diagnostics
-{
- [DiagnosticAnalyzer(LanguageNames.CSharp)]
- [NotPortedYet]
- public class PossibleAssignmentToReadonlyFieldAnalyzer : DiagnosticAnalyzer
- {
- static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
- CSharpDiagnosticIDs.PossibleAssignmentToReadonlyFieldAnalyzerID,
- GettextCatalog.GetString("Check if a readonly field is used as assignment target"),
- "{0}",
- DiagnosticAnalyzerCategories.CodeQualityIssues,
- DiagnosticSeverity.Warning,
- isEnabledByDefault: true,
- helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.PossibleAssignmentToReadonlyFieldAnalyzerID)
- );
+//namespace RefactoringEssentials.CSharp.Diagnostics
+//{
+// [DiagnosticAnalyzer(LanguageNames.CSharp)]
+// [NotPortedYet]
+// public class PossibleAssignmentToReadonlyFieldAnalyzer : DiagnosticAnalyzer
+// {
+// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(
+// CSharpDiagnosticIDs.PossibleAssignmentToReadonlyFieldAnalyzerID,
+// GettextCatalog.GetString("Check if a readonly field is used as assignment target"),
+// "{0}",
+// DiagnosticAnalyzerCategories.CodeQualityIssues,
+// DiagnosticSeverity.Warning,
+// isEnabledByDefault: true,
+// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.PossibleAssignmentToReadonlyFieldAnalyzerID)
+// );
- public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
+// public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor);
- public override void Initialize(AnalysisContext context)
- {
- context.EnableConcurrentExecution();
- context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
- //context.RegisterSyntaxNodeAction(
- // (nodeContext) => {
- // Diagnostic diagnostic;
- // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
- // nodeContext.ReportDiagnostic(diagnostic);
- // }
- // },
- // new SyntaxKind[] { SyntaxKind.None }
- //);
- }
+// public override void Initialize(AnalysisContext context)
+// {
+// context.EnableConcurrentExecution();
+// context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
+// //context.RegisterSyntaxNodeAction(
+// // (nodeContext) => {
+// // Diagnostic diagnostic;
+// // if (TryGetDiagnostic (nodeContext, out diagnostic)) {
+// // nodeContext.ReportDiagnostic(diagnostic);
+// // }
+// // },
+// // new SyntaxKind[] { SyntaxKind.None }
+// //);
+// }
- static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
- {
- diagnostic = default(Diagnostic);
- //var node = nodeContext.Node as ;
- //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
- //return true;
- return false;
- }
+// static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
+// {
+// diagnostic = default(Diagnostic);
+// //var node = nodeContext.Node as ;
+// //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
+// //return true;
+// return false;
+// }
- // class GatherVisitor : GatherVisitorBase
- // {
- // //bool inConstructor;
+// // class GatherVisitor : GatherVisitorBase
+// // {
+// // //bool inConstructor;
- // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken)
- // : base (semanticModel, addDiagnostic, cancellationToken)
- // {
- // }
- ////
- //// public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
- //// {
- //// inConstructor = true;
- //// base.VisitConstructorDeclaration(constructorDeclaration);
- //// inConstructor = false;
- //// }
- ////
- //// void Check(Expression expr)
- //// {
- //// var mr = expr as MemberReferenceExpression;
- //// if (mr != null) {
- //// if (inConstructor && mr.Descendants.Any(d => d.Parent is MemberReferenceExpression && d is ThisReferenceExpression))
- //// return;
- //// Check(mr.Target);
- //// }
- //// if (inConstructor && expr is IdentifierExpression)
- //// return;
- ////
- //// var rr = ctx.Resolve(expr) as MemberResolveResult;
- ////
- //// if (rr == null || rr.IsError)
- //// return;
- //// var field = rr.Member as IField;
- ////
- //// if (field == null || !field.IsReadOnly)
- //// return;
- ////
- //// if (field.Type.Kind == TypeKind.TypeParameter) {
- //// var param = (ITypeParameter)field.Type;
- //// if (param.HasReferenceTypeConstraint)
- //// return;
- //// // TODO: Add resolve actions: Add class constraint + remove readonly modifier
- //// AddDiagnosticAnalyzer(new CodeIssue(expr,
- //// ctx.TranslateString("Assignment to a property of a readonly field can be useless. Type parameter is not known to be a reference type.")));
- //// return;
- //// }
- //// if (field.Type.Kind == TypeKind.Struct) {
- //// // TODO: Add resolve actions: Remove readonly modifier
- //// AddDiagnosticAnalyzer(new CodeIssue(expr, ctx.TranslateString("Readonly field can not be used as assignment target.")));
- //// }
- //// }
- ////
- //// public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression)
- //// {
- //// base.VisitAssignmentExpression (assignmentExpression);
- //// Check(assignmentExpression.Left);
- //// }
- ////
- //// public override void VisitDirectionExpression(DirectionExpression directionExpression)
- //// {
- //// base.VisitDirectionExpression (directionExpression);
- //// Check(directionExpression.Expression);
- //// }
- ////
- //// public override void VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
- //// {
- //// base.VisitUnaryOperatorExpression (unaryOperatorExpression);
- //// if (unaryOperatorExpression.Operator == UnaryOperatorType.Increment || unaryOperatorExpression.Operator == UnaryOperatorType.Decrement ||
- //// unaryOperatorExpression.Operator == UnaryOperatorType.PostIncrement || unaryOperatorExpression.Operator == UnaryOperatorType.PostDecrement) {
- //// Check(unaryOperatorExpression.Expression);
- //// }
- //// }
- // }
- }
-}
\ No newline at end of file
+// // public GatherVisitor(SemanticModel semanticModel, Action