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 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 diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/PossibleMultipleEnumerationAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/PossibleMultipleEnumerationAnalyzer.cs index ba130725..a0c32e67 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/PossibleMultipleEnumerationAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/CodeQuality/PossibleMultipleEnumerationAnalyzer.cs @@ -1,415 +1,415 @@ -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 PossibleMultipleEnumerationAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.PossibleMultipleEnumerationAnalyzerID, - GettextCatalog.GetString("Possible multiple enumeration of IEnumerable"), - GettextCatalog.GetString("Possible multiple enumeration of IEnumerable"), - DiagnosticAnalyzerCategories.CodeQualityIssues, - DiagnosticSeverity.Warning, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.PossibleMultipleEnumerationAnalyzerID) - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class PossibleMultipleEnumerationAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.PossibleMultipleEnumerationAnalyzerID, +// GettextCatalog.GetString("Possible multiple enumeration of IEnumerable"), +// GettextCatalog.GetString("Possible multiple enumeration of IEnumerable"), +// DiagnosticAnalyzerCategories.CodeQualityIssues, +// DiagnosticSeverity.Warning, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.PossibleMultipleEnumerationAnalyzerID) +// ); - 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 AnalysisStatementCollector : DepthFirstAstVisitor - // { - // List statements; - // AstNode variableDecl; - // - // AnalysisStatementCollector (AstNode variableDecl) - // { - // this.variableDecl = variableDecl; - // } - // - // IList GetStatements () - // { - // if (statements != null) - // return statements; - // - // statements = new List (); - // var parent = variableDecl.Parent; - // while (parent != null) { - // if (parent is BlockStatement || parent is MethodDeclaration || - // parent is AnonymousMethodExpression || parent is LambdaExpression) { - // parent.AcceptVisitor (this); - // if (parent is BlockStatement) - // statements.Add ((BlockStatement)parent); - // break; - // } - // parent = parent.Parent; - // } - // return statements; - // } - // - // public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) - // { - // statements.Add (methodDeclaration.Body); - // - // base.VisitMethodDeclaration (methodDeclaration); - // } - // - // public override void VisitAnonymousMethodExpression (AnonymousMethodExpression anonymousMethodExpression) - // { - // statements.Add (anonymousMethodExpression.Body); - // - // base.VisitAnonymousMethodExpression (anonymousMethodExpression); - // } - // - // public override void VisitLambdaExpression (LambdaExpression lambdaExpression) - // { - // var body = lambdaExpression.Body as BlockStatement; - // if (body != null) - // statements.Add (body); - // - // base.VisitLambdaExpression (lambdaExpression); - // } - // - // public static IList Collect (AstNode variableDecl) - // { - // return new AnalysisStatementCollector (variableDecl).GetStatements (); - // } - // } +// // class AnalysisStatementCollector : DepthFirstAstVisitor +// // { +// // List statements; +// // AstNode variableDecl; +// // +// // AnalysisStatementCollector (AstNode variableDecl) +// // { +// // this.variableDecl = variableDecl; +// // } +// // +// // IList GetStatements () +// // { +// // if (statements != null) +// // return statements; +// // +// // statements = new List (); +// // var parent = variableDecl.Parent; +// // while (parent != null) { +// // if (parent is BlockStatement || parent is MethodDeclaration || +// // parent is AnonymousMethodExpression || parent is LambdaExpression) { +// // parent.AcceptVisitor (this); +// // if (parent is BlockStatement) +// // statements.Add ((BlockStatement)parent); +// // break; +// // } +// // parent = parent.Parent; +// // } +// // return statements; +// // } +// // +// // public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) +// // { +// // statements.Add (methodDeclaration.Body); +// // +// // base.VisitMethodDeclaration (methodDeclaration); +// // } +// // +// // public override void VisitAnonymousMethodExpression (AnonymousMethodExpression anonymousMethodExpression) +// // { +// // statements.Add (anonymousMethodExpression.Body); +// // +// // base.VisitAnonymousMethodExpression (anonymousMethodExpression); +// // } +// // +// // public override void VisitLambdaExpression (LambdaExpression lambdaExpression) +// // { +// // var body = lambdaExpression.Body as BlockStatement; +// // if (body != null) +// // statements.Add (body); +// // +// // base.VisitLambdaExpression (lambdaExpression); +// // } +// // +// // public static IList Collect (AstNode variableDecl) +// // { +// // return new AnalysisStatementCollector (variableDecl).GetStatements (); +// // } +// // } - // class GatherVisitor : GatherVisitorBase - // { - // //HashSet collectedAstNodes; +// // class GatherVisitor : GatherVisitorBase +// // { +// // //HashSet collectedAstNodes; - // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) - // : base (semanticModel, addDiagnostic, cancellationToken) - // { - // //this.collectedAstNodes = new HashSet (); - // } +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // //this.collectedAstNodes = new HashSet (); +// // } - //// void ResolveIssue(Script s, AstNode node, Func type, string methodCall) - //// { - //// var rr = ctx.Resolve(node) as LocalResolveResult; - //// if (rr == null || rr.IsError) - //// return; - //// var refs = ctx.FindReferences(ctx.RootNode, rr.Variable); - //// var nodes = refs.Select(r => r.Node).Where(IsEnumeration).OfType().ToList(); - //// if (nodes.Count == 0) - //// return; - //// var first = nodes.First().GetParent(); - //// var varName = ctx.GetNameProposal("enumerable", first.StartLocation); - //// var astBuilder = ctx.CreateTypeSystemAstBuilder(first); - //// - //// var links = new List(); - //// var varDec = new VariableDeclarationStatement(new PrimitiveType("var"), varName, new BinaryOperatorExpression(new AsExpression((Expression)node.Clone(), type (astBuilder)), BinaryOperatorType.NullCoalescing, new InvocationExpression(new MemberReferenceExpression((Expression)node.Clone(), methodCall)))); - //// - //// links.Add(varDec.Variables.First().NameToken); - //// s.InsertBefore(first, varDec); - //// foreach (var n in nodes) { - //// var id = new IdentifierExpression(varName); - //// links.Add(id); - //// s.Replace(n, id); - //// } - //// s.Link(links); - //// } - //// - //// void AddDiagnosticAnalyzer (AstNode node, IType elementType, IList nodes) - //// { - //// if (collectedAstNodes.Add(node)) { - //// var actions = new List(); - //// actions.Add( - //// new CodeAction( - //// ctx.TranslateString("Enumerate to array"), - //// s => ResolveIssue(s, node, ab => new ComposedType { BaseType = ab.ConvertType(elementType), ArraySpecifiers = { new ArraySpecifier() } }, "ToArray"), - //// node - //// ) - //// ); - //// - //// actions.Add( - //// new CodeAction( - //// ctx.TranslateString("Enumerate to list"), - //// s => { - //// var listType = ctx.Compilation.FindType(typeof(IList<>)); - //// ResolveIssue(s, node, ab => ab.ConvertType(new ParameterizedType(listType.GetDefinition(), new IType[]{ elementType })), "ToList"); - //// }, - //// node - //// ) - //// ); - //// - //// AddDiagnosticAnalyzer(new CodeIssue(node, ctx.TranslateString("Possible multiple enumeration of IEnumerable"), actions)); - //// } - //// } - //// - //// void AddDiagnosticAnalyzers (IList nodes) - //// { - //// if (nodes.Count == 0) - //// return; - //// var rr = ctx.Resolve(nodes[0]); - //// var elementType = TypeGuessing.GetElementType(ctx.Resolver, rr.Type); - //// - //// foreach (var node in nodes) - //// AddDiagnosticAnalyzer (node, elementType, nodes); - //// } - //// - //// public override void VisitParameterDeclaration (ParameterDeclaration parameterDeclaration) - //// { - //// base.VisitParameterDeclaration (parameterDeclaration); - //// - //// var resolveResult = ctx.Resolve (parameterDeclaration) as LocalResolveResult; - //// CollectIssues (parameterDeclaration, parameterDeclaration.Parent, resolveResult); - //// } - //// - //// public override void VisitVariableInitializer (VariableInitializer variableInitializer) - //// { - //// base.VisitVariableInitializer (variableInitializer); - //// - //// var resolveResult = ctx.Resolve (variableInitializer) as LocalResolveResult; - //// CollectIssues (variableInitializer, variableInitializer.Parent.Parent, resolveResult); - //// } - //// - //// static bool IsAssignment (AstNode node) - //// { - //// var assignment = node.Parent as AssignmentExpression; - //// if (assignment != null) - //// return assignment.Left == node; - //// - //// var direction = node.Parent as DirectionExpression; - //// if (direction != null) - //// return direction.FieldDirection == FieldDirection.Out && direction.Expression == node; - //// - //// return false; - //// } - //// - //// bool IsEnumeration (AstNode node) - //// { - //// var foreachStatement = node.Parent as ForeachStatement; - //// if (foreachStatement != null && foreachStatement.InExpression == node) { - //// return true; - //// } - //// - //// var memberRef = node.Parent as MemberReferenceExpression; - //// if (memberRef != null && memberRef.Target == node) { - //// var invocation = memberRef.Parent as InvocationExpression; - //// if (invocation == null || invocation.Target != memberRef) - //// return false; - //// - //// var methodGroup = ctx.Resolve (memberRef) as MethodGroupResolveResult; - //// if (methodGroup == null) - //// return false; - //// - //// var method = methodGroup.Methods.FirstOrDefault (); - //// if (method != null) { - //// var declaringTypeDef = method.DeclaringTypeDefinition; - //// if (declaringTypeDef != null && declaringTypeDef.KnownTypeCode == KnownTypeCode.Object) - //// return false; - //// } - //// return true; - //// } - //// - //// return false; - //// } - //// - //// HashSet references; - //// HashSet refStatements; - //// HashSet lambdaExpressions; - //// - //// HashSet visitedNodes; - //// HashSet collectedNodes; - //// Dictionary nodeDegree; // number of enumerations a node can reach - //// - //// void FindReferences (AstNode variableDecl, AstNode rootNode, IVariable variable) - //// { - //// references = new HashSet (); - //// refStatements = new HashSet (); - //// lambdaExpressions = new HashSet (); - //// - //// foreach (var result in ctx.FindReferences (rootNode, variable)) { - //// var astNode = result.Node; - //// if (astNode == variableDecl) - //// continue; - //// - //// var parent = astNode.Parent; - //// while (!(parent == null || parent is Statement || parent is LambdaExpression)) - //// parent = parent.Parent; - //// if (parent == null) - //// continue; - //// - //// // lambda expression with expression body, should be analyzed separately - //// var expr = parent as LambdaExpression; - //// if (expr != null) { - //// if (IsAssignment (astNode) || IsEnumeration (astNode)) { - //// references.Add (astNode); - //// lambdaExpressions.Add (expr); - //// } - //// continue; - //// } - //// - //// if (IsAssignment (astNode) || IsEnumeration (astNode)) { - //// references.Add (astNode); - //// var statement = (Statement)parent; - //// refStatements.Add (statement); - //// } - //// } - //// } - //// - //// void CollectIssues (AstNode variableDecl, AstNode rootNode, LocalResolveResult resolveResult) - //// { - //// if (resolveResult == null) - //// return; - //// var type = resolveResult.Type; - //// var typeDef = type.GetDefinition (); - //// if (typeDef == null || - //// (typeDef.KnownTypeCode != KnownTypeCode.IEnumerable && - //// typeDef.KnownTypeCode != KnownTypeCode.IEnumerableOfT)) - //// return; - //// - //// FindReferences (variableDecl, rootNode, resolveResult.Variable); - //// - //// var statements = AnalysisStatementCollector.Collect (variableDecl); - //// var builder = new VariableReferenceGraphBuilder (ctx); - //// foreach (var statement in statements) { - //// var vrNode = builder.Build (statement, references, refStatements, ctx); - //// FindMultipleEnumeration (vrNode); - //// } - //// foreach (var lambda in lambdaExpressions) { - //// var vrNode = builder.Build (references, ctx.Resolver, (Expression)lambda.Body); - //// FindMultipleEnumeration (vrNode); - //// } - //// } - //// - //// /// - //// /// split references in the specified node into sub nodes according to the value they uses - //// /// - //// /// node to split - //// /// list of sub nodes - //// static IList SplitNode (VariableReferenceNode node) - //// { - //// var subNodes = new List (); - //// // find indices of all assignments in node and use them to split references - //// var assignmentIndices = new List { -1 }; - //// for (int i = 0; i < node.References.Count; i++) { - //// if (IsAssignment (node.References [i])) - //// assignmentIndices.Add (i); - //// } - //// assignmentIndices.Add (node.References.Count); - //// for (int i = 0; i < assignmentIndices.Count - 1; i++) { - //// var index1 = assignmentIndices [i]; - //// var index2 = assignmentIndices [i + 1]; - //// if (index1 + 1 >= index2) - //// continue; - //// var subNode = new VariableReferenceNode (); - //// for (int refIndex = index1 + 1; refIndex < index2; refIndex++) - //// subNode.References.Add (node.References [refIndex]); - //// subNodes.Add (subNode); - //// } - //// if (subNodes.Count == 0) - //// subNodes.Add (new VariableReferenceNode ()); - //// - //// var firstNode = subNodes [0]; - //// foreach (var prevNode in node.PreviousNodes) { - //// prevNode.NextNodes.Remove (node); - //// // connect two nodes if the first ref is not an assignment - //// if (firstNode.References.FirstOrDefault () == node.References.FirstOrDefault ()) - //// prevNode.NextNodes.Add (firstNode); - //// } - //// - //// var lastNode = subNodes [subNodes.Count - 1]; - //// foreach (var nextNode in node.NextNodes) { - //// nextNode.PreviousNodes.Remove (node); - //// lastNode.AddNextNode (nextNode); - //// } - //// - //// return subNodes; - //// } - //// - //// /// - //// /// convert a variable reference graph starting from the specified node to an assignment usage graph, - //// /// in which nodes are connect if and only if they contains references using the same assigned value - //// /// - //// /// starting node of the variable reference graph - //// /// - //// /// list of VariableReferenceNode, each of which is a starting node of a sub-graph in which references all - //// /// use the same assigned value - //// /// - //// static IEnumerable GetAssignmentUsageGraph (VariableReferenceNode startNode) - //// { - //// var graph = new List (); - //// var visited = new HashSet (); - //// var stack = new Stack (); - //// stack.Push (startNode); - //// while (stack.Count > 0) { - //// var node = stack.Pop (); - //// if (!visited.Add (node)) - //// continue; - //// - //// var nodes = SplitNode (node); - //// graph.AddRange (nodes); - //// foreach (var addedNode in nodes) - //// visited.Add (addedNode); - //// - //// foreach (var nextNode in nodes.Last ().NextNodes) - //// stack.Push (nextNode); - //// } - //// return graph; - //// } - //// - //// void FindMultipleEnumeration (VariableReferenceNode startNode) - //// { - //// var vrg = GetAssignmentUsageGraph (startNode); - //// visitedNodes = new HashSet (); - //// collectedNodes = new HashSet (); - //// - //// // degree of a node is the number of references that can be reached by the node - //// nodeDegree = new Dictionary (); - //// - //// foreach (var node in vrg) { - //// if (node.References.Count == 0 || !visitedNodes.Add (node)) - //// continue; - //// ProcessNode (node); - //// if (nodeDegree [node] > 1) - //// collectedNodes.Add (node); - //// } - //// foreach (var node in collectedNodes) - //// AddDiagnosticAnalyzers (node.References); - //// } - //// - //// void ProcessNode (VariableReferenceNode node) - //// { - //// var degree = nodeDegree [node] = 0; - //// foreach (var nextNode in node.NextNodes) { - //// collectedNodes.Add (nextNode); - //// if (visitedNodes.Add (nextNode)) - //// ProcessNode (nextNode); - //// degree = Math.Max (degree, nodeDegree [nextNode]); - //// } - //// nodeDegree [node] = degree + node.References.Count; - //// } - // } - } -} \ No newline at end of file +// //// void ResolveIssue(Script s, AstNode node, Func type, string methodCall) +// //// { +// //// var rr = ctx.Resolve(node) as LocalResolveResult; +// //// if (rr == null || rr.IsError) +// //// return; +// //// var refs = ctx.FindReferences(ctx.RootNode, rr.Variable); +// //// var nodes = refs.Select(r => r.Node).Where(IsEnumeration).OfType().ToList(); +// //// if (nodes.Count == 0) +// //// return; +// //// var first = nodes.First().GetParent(); +// //// var varName = ctx.GetNameProposal("enumerable", first.StartLocation); +// //// var astBuilder = ctx.CreateTypeSystemAstBuilder(first); +// //// +// //// var links = new List(); +// //// var varDec = new VariableDeclarationStatement(new PrimitiveType("var"), varName, new BinaryOperatorExpression(new AsExpression((Expression)node.Clone(), type (astBuilder)), BinaryOperatorType.NullCoalescing, new InvocationExpression(new MemberReferenceExpression((Expression)node.Clone(), methodCall)))); +// //// +// //// links.Add(varDec.Variables.First().NameToken); +// //// s.InsertBefore(first, varDec); +// //// foreach (var n in nodes) { +// //// var id = new IdentifierExpression(varName); +// //// links.Add(id); +// //// s.Replace(n, id); +// //// } +// //// s.Link(links); +// //// } +// //// +// //// void AddDiagnosticAnalyzer (AstNode node, IType elementType, IList nodes) +// //// { +// //// if (collectedAstNodes.Add(node)) { +// //// var actions = new List(); +// //// actions.Add( +// //// new CodeAction( +// //// ctx.TranslateString("Enumerate to array"), +// //// s => ResolveIssue(s, node, ab => new ComposedType { BaseType = ab.ConvertType(elementType), ArraySpecifiers = { new ArraySpecifier() } }, "ToArray"), +// //// node +// //// ) +// //// ); +// //// +// //// actions.Add( +// //// new CodeAction( +// //// ctx.TranslateString("Enumerate to list"), +// //// s => { +// //// var listType = ctx.Compilation.FindType(typeof(IList<>)); +// //// ResolveIssue(s, node, ab => ab.ConvertType(new ParameterizedType(listType.GetDefinition(), new IType[]{ elementType })), "ToList"); +// //// }, +// //// node +// //// ) +// //// ); +// //// +// //// AddDiagnosticAnalyzer(new CodeIssue(node, ctx.TranslateString("Possible multiple enumeration of IEnumerable"), actions)); +// //// } +// //// } +// //// +// //// void AddDiagnosticAnalyzers (IList nodes) +// //// { +// //// if (nodes.Count == 0) +// //// return; +// //// var rr = ctx.Resolve(nodes[0]); +// //// var elementType = TypeGuessing.GetElementType(ctx.Resolver, rr.Type); +// //// +// //// foreach (var node in nodes) +// //// AddDiagnosticAnalyzer (node, elementType, nodes); +// //// } +// //// +// //// public override void VisitParameterDeclaration (ParameterDeclaration parameterDeclaration) +// //// { +// //// base.VisitParameterDeclaration (parameterDeclaration); +// //// +// //// var resolveResult = ctx.Resolve (parameterDeclaration) as LocalResolveResult; +// //// CollectIssues (parameterDeclaration, parameterDeclaration.Parent, resolveResult); +// //// } +// //// +// //// public override void VisitVariableInitializer (VariableInitializer variableInitializer) +// //// { +// //// base.VisitVariableInitializer (variableInitializer); +// //// +// //// var resolveResult = ctx.Resolve (variableInitializer) as LocalResolveResult; +// //// CollectIssues (variableInitializer, variableInitializer.Parent.Parent, resolveResult); +// //// } +// //// +// //// static bool IsAssignment (AstNode node) +// //// { +// //// var assignment = node.Parent as AssignmentExpression; +// //// if (assignment != null) +// //// return assignment.Left == node; +// //// +// //// var direction = node.Parent as DirectionExpression; +// //// if (direction != null) +// //// return direction.FieldDirection == FieldDirection.Out && direction.Expression == node; +// //// +// //// return false; +// //// } +// //// +// //// bool IsEnumeration (AstNode node) +// //// { +// //// var foreachStatement = node.Parent as ForeachStatement; +// //// if (foreachStatement != null && foreachStatement.InExpression == node) { +// //// return true; +// //// } +// //// +// //// var memberRef = node.Parent as MemberReferenceExpression; +// //// if (memberRef != null && memberRef.Target == node) { +// //// var invocation = memberRef.Parent as InvocationExpression; +// //// if (invocation == null || invocation.Target != memberRef) +// //// return false; +// //// +// //// var methodGroup = ctx.Resolve (memberRef) as MethodGroupResolveResult; +// //// if (methodGroup == null) +// //// return false; +// //// +// //// var method = methodGroup.Methods.FirstOrDefault (); +// //// if (method != null) { +// //// var declaringTypeDef = method.DeclaringTypeDefinition; +// //// if (declaringTypeDef != null && declaringTypeDef.KnownTypeCode == KnownTypeCode.Object) +// //// return false; +// //// } +// //// return true; +// //// } +// //// +// //// return false; +// //// } +// //// +// //// HashSet references; +// //// HashSet refStatements; +// //// HashSet lambdaExpressions; +// //// +// //// HashSet visitedNodes; +// //// HashSet collectedNodes; +// //// Dictionary nodeDegree; // number of enumerations a node can reach +// //// +// //// void FindReferences (AstNode variableDecl, AstNode rootNode, IVariable variable) +// //// { +// //// references = new HashSet (); +// //// refStatements = new HashSet (); +// //// lambdaExpressions = new HashSet (); +// //// +// //// foreach (var result in ctx.FindReferences (rootNode, variable)) { +// //// var astNode = result.Node; +// //// if (astNode == variableDecl) +// //// continue; +// //// +// //// var parent = astNode.Parent; +// //// while (!(parent == null || parent is Statement || parent is LambdaExpression)) +// //// parent = parent.Parent; +// //// if (parent == null) +// //// continue; +// //// +// //// // lambda expression with expression body, should be analyzed separately +// //// var expr = parent as LambdaExpression; +// //// if (expr != null) { +// //// if (IsAssignment (astNode) || IsEnumeration (astNode)) { +// //// references.Add (astNode); +// //// lambdaExpressions.Add (expr); +// //// } +// //// continue; +// //// } +// //// +// //// if (IsAssignment (astNode) || IsEnumeration (astNode)) { +// //// references.Add (astNode); +// //// var statement = (Statement)parent; +// //// refStatements.Add (statement); +// //// } +// //// } +// //// } +// //// +// //// void CollectIssues (AstNode variableDecl, AstNode rootNode, LocalResolveResult resolveResult) +// //// { +// //// if (resolveResult == null) +// //// return; +// //// var type = resolveResult.Type; +// //// var typeDef = type.GetDefinition (); +// //// if (typeDef == null || +// //// (typeDef.KnownTypeCode != KnownTypeCode.IEnumerable && +// //// typeDef.KnownTypeCode != KnownTypeCode.IEnumerableOfT)) +// //// return; +// //// +// //// FindReferences (variableDecl, rootNode, resolveResult.Variable); +// //// +// //// var statements = AnalysisStatementCollector.Collect (variableDecl); +// //// var builder = new VariableReferenceGraphBuilder (ctx); +// //// foreach (var statement in statements) { +// //// var vrNode = builder.Build (statement, references, refStatements, ctx); +// //// FindMultipleEnumeration (vrNode); +// //// } +// //// foreach (var lambda in lambdaExpressions) { +// //// var vrNode = builder.Build (references, ctx.Resolver, (Expression)lambda.Body); +// //// FindMultipleEnumeration (vrNode); +// //// } +// //// } +// //// +// //// /// +// //// /// split references in the specified node into sub nodes according to the value they uses +// //// /// +// //// /// node to split +// //// /// list of sub nodes +// //// static IList SplitNode (VariableReferenceNode node) +// //// { +// //// var subNodes = new List (); +// //// // find indices of all assignments in node and use them to split references +// //// var assignmentIndices = new List { -1 }; +// //// for (int i = 0; i < node.References.Count; i++) { +// //// if (IsAssignment (node.References [i])) +// //// assignmentIndices.Add (i); +// //// } +// //// assignmentIndices.Add (node.References.Count); +// //// for (int i = 0; i < assignmentIndices.Count - 1; i++) { +// //// var index1 = assignmentIndices [i]; +// //// var index2 = assignmentIndices [i + 1]; +// //// if (index1 + 1 >= index2) +// //// continue; +// //// var subNode = new VariableReferenceNode (); +// //// for (int refIndex = index1 + 1; refIndex < index2; refIndex++) +// //// subNode.References.Add (node.References [refIndex]); +// //// subNodes.Add (subNode); +// //// } +// //// if (subNodes.Count == 0) +// //// subNodes.Add (new VariableReferenceNode ()); +// //// +// //// var firstNode = subNodes [0]; +// //// foreach (var prevNode in node.PreviousNodes) { +// //// prevNode.NextNodes.Remove (node); +// //// // connect two nodes if the first ref is not an assignment +// //// if (firstNode.References.FirstOrDefault () == node.References.FirstOrDefault ()) +// //// prevNode.NextNodes.Add (firstNode); +// //// } +// //// +// //// var lastNode = subNodes [subNodes.Count - 1]; +// //// foreach (var nextNode in node.NextNodes) { +// //// nextNode.PreviousNodes.Remove (node); +// //// lastNode.AddNextNode (nextNode); +// //// } +// //// +// //// return subNodes; +// //// } +// //// +// //// /// +// //// /// convert a variable reference graph starting from the specified node to an assignment usage graph, +// //// /// in which nodes are connect if and only if they contains references using the same assigned value +// //// /// +// //// /// starting node of the variable reference graph +// //// /// +// //// /// list of VariableReferenceNode, each of which is a starting node of a sub-graph in which references all +// //// /// use the same assigned value +// //// /// +// //// static IEnumerable GetAssignmentUsageGraph (VariableReferenceNode startNode) +// //// { +// //// var graph = new List (); +// //// var visited = new HashSet (); +// //// var stack = new Stack (); +// //// stack.Push (startNode); +// //// while (stack.Count > 0) { +// //// var node = stack.Pop (); +// //// if (!visited.Add (node)) +// //// continue; +// //// +// //// var nodes = SplitNode (node); +// //// graph.AddRange (nodes); +// //// foreach (var addedNode in nodes) +// //// visited.Add (addedNode); +// //// +// //// foreach (var nextNode in nodes.Last ().NextNodes) +// //// stack.Push (nextNode); +// //// } +// //// return graph; +// //// } +// //// +// //// void FindMultipleEnumeration (VariableReferenceNode startNode) +// //// { +// //// var vrg = GetAssignmentUsageGraph (startNode); +// //// visitedNodes = new HashSet (); +// //// collectedNodes = new HashSet (); +// //// +// //// // degree of a node is the number of references that can be reached by the node +// //// nodeDegree = new Dictionary (); +// //// +// //// foreach (var node in vrg) { +// //// if (node.References.Count == 0 || !visitedNodes.Add (node)) +// //// continue; +// //// ProcessNode (node); +// //// if (nodeDegree [node] > 1) +// //// collectedNodes.Add (node); +// //// } +// //// foreach (var node in collectedNodes) +// //// AddDiagnosticAnalyzers (node.References); +// //// } +// //// +// //// void ProcessNode (VariableReferenceNode node) +// //// { +// //// var degree = nodeDegree [node] = 0; +// //// foreach (var nextNode in node.NextNodes) { +// //// collectedNodes.Add (nextNode); +// //// if (visitedNodes.Add (nextNode)) +// //// ProcessNode (nextNode); +// //// degree = Math.Max (degree, nodeDegree [nextNode]); +// //// } +// //// nodeDegree [node] = degree + node.References.Count; +// //// } +// // } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/CompilerWarnings/CS1573ParameterHasNoMatchingParamTagAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/CompilerWarnings/CS1573ParameterHasNoMatchingParamTagAnalyzer.cs index ebc2f076..ccafe20d 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/CompilerWarnings/CS1573ParameterHasNoMatchingParamTagAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/CompilerWarnings/CS1573ParameterHasNoMatchingParamTagAnalyzer.cs @@ -1,314 +1,314 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis.CodeFixes; -using System.Threading.Tasks; -using System.Linq; +//using Microsoft.CodeAnalysis; +//using Microsoft.CodeAnalysis.Diagnostics; +//using System.Collections.Immutable; +//using Microsoft.CodeAnalysis.CodeFixes; +//using System.Threading.Tasks; +//using System.Linq; -namespace RefactoringEssentials.CSharp.Diagnostics -{ - //[DiagnosticAnalyzer(LanguageNames.CSharp)] - [NotPortedYet] - public class CS1573ParameterHasNoMatchingParamTagAnalyzer : DiagnosticAnalyzer - { - internal const string DiagnosticId = "CS1573ParameterHasNoMatchingParamTagAnalyzer"; - const string Description = "Parameter has no matching param tag in the XML comment"; - const string MessageFormat = ""; - const string Category = DiagnosticAnalyzerCategories.CompilerWarnings; +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// //[DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class CS1573ParameterHasNoMatchingParamTagAnalyzer : DiagnosticAnalyzer +// { +// internal const string DiagnosticId = "CS1573ParameterHasNoMatchingParamTagAnalyzer"; +// const string Description = "Parameter has no matching param tag in the XML comment"; +// const string MessageFormat = ""; +// const string Category = DiagnosticAnalyzerCategories.CompilerWarnings; - static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning, true, "Parameter has no matching param tag in the XML comment"); +// static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning, true, "Parameter has no matching param tag in the XML comment"); - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(Rule); - } - } +// public override ImmutableArray SupportedDiagnostics +// { +// get +// { +// return ImmutableArray.Create(Rule); +// } +// } - 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 List storedXmlComment = new List(); +// // class GatherVisitor : GatherVisitorBase +// // { +// // //readonly List storedXmlComment = new List(); - // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) - // : base (semanticModel, addDiagnostic, cancellationToken) - // { - // } - //// - //// void InvalideXmlComments() - //// { - //// storedXmlComment.Clear(); - //// } - //// - //// public override void VisitComment(Comment comment) - //// { - //// base.VisitComment(comment); - //// if (comment.CommentType == CommentType.Documentation) - //// storedXmlComment.Add(comment); - //// } - //// - //// public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration) - //// { - //// InvalideXmlComments(); - //// base.VisitNamespaceDeclaration(namespaceDeclaration); - //// } - //// - //// public override void VisitUsingDeclaration(UsingDeclaration usingDeclaration) - //// { - //// InvalideXmlComments(); - //// base.VisitUsingDeclaration(usingDeclaration); - //// } - //// - //// public override void VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration) - //// { - //// InvalideXmlComments(); - //// base.VisitUsingAliasDeclaration(usingDeclaration); - //// } - //// - //// public override void VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration) - //// { - //// InvalideXmlComments(); - //// base.VisitExternAliasDeclaration(externAliasDeclaration); - //// } - //// - //// void AddXmlIssue(int line, int col, int length, string str) - //// { - //// var cmt = storedXmlComment [Math.Max(0, Math.Min(storedXmlComment.Count - 1, line))]; - //// - //// AddDiagnosticAnalyzer(new CodeIssue(new TextLocation(cmt.StartLocation.Line, cmt.StartLocation.Column + 3 + col), - //// new TextLocation(cmt.StartLocation.Line, cmt.StartLocation.Column + 3 + col + length), - //// str)); - //// } - //// - //// int SearchAttributeColumn(int x, int line) - //// { - //// var comment = storedXmlComment [Math.Max(0, Math.Min(storedXmlComment.Count - 1, line))]; - //// var idx = comment.Content.IndexOfAny(new char[] { '"', '\'' }, x); - //// return idx < 0 ? x : idx + 1; - //// } - //// - //// void CheckXmlDoc(AstNode node) - //// { - //// ResolveResult resolveResult = ctx.Resolve(node); - //// IEntity member = null; - //// if (resolveResult is TypeResolveResult) - //// member = resolveResult.Type.GetDefinition(); - //// if (resolveResult is MemberResolveResult) - //// member = ((MemberResolveResult)resolveResult).Member; - //// var xml = new StringBuilder(); - //// xml.AppendLine(""); - //// foreach (var cmt in storedXmlComment) - //// xml.AppendLine(cmt.Content); - //// xml.AppendLine(""); - //// - //// List> parameters = new List>(); - //// - //// using (var reader = new XmlTextReader(new StringReader(xml.ToString()))) { - //// reader.XmlResolver = null; - //// try { - //// while (reader.Read()) { - //// if (member == null) - //// continue; - //// if (reader.NodeType == XmlNodeType.Element) { - //// switch (reader.Name) { - //// case "param": - //// reader.MoveToFirstAttribute(); - //// var line = reader.LineNumber; - //// var name = reader.GetAttribute("name"); - //// if (name == null) - //// break; - //// parameters.Add(Tuple.Create(name, line)); - //// break; - //// - //// } - //// } - //// } - //// } catch (XmlException) { - //// } - //// - //// if (storedXmlComment.Count > 0 && parameters.Count > 0) { - //// var pm = member as IParameterizedMember; - //// if (pm != null) { - //// for (int i = 0; i < pm.Parameters.Count; i++) { - //// var p = pm.Parameters [i]; - //// if (!parameters.Any(tp => tp.Item1 == p.Name)) { - //// AstNode before = i < parameters.Count ? storedXmlComment [parameters [i].Item2 - 2] : null; - //// AstNode afterNode = before == null ? storedXmlComment [storedXmlComment.Count - 1] : null; - //// AddDiagnosticAnalyzer(new CodeIssue( - //// GetParameterHighlightNode(node, i), - //// string.Format(ctx.TranslateString("Missing xml documentation for Parameter '{0}'"), p.Name), - //// string.Format(ctx.TranslateString("Create xml documentation for Parameter '{0}'"), p.Name), - //// script => { - //// if (before != null) { - //// script.InsertBefore( - //// before, - //// new Comment(string.Format(" ", p.Name), CommentType.Documentation) - //// ); - //// } else { - //// script.InsertAfter( - //// afterNode, - //// new Comment(string.Format(" ", p.Name), CommentType.Documentation) - //// ); - //// } - //// })); - //// } - //// } - //// - //// } - //// } - //// storedXmlComment.Clear(); - //// } - //// } - //// - //// AstNode GetParameterHighlightNode(AstNode node, int i) - //// { - //// if (node is MethodDeclaration) - //// return ((MethodDeclaration)node).Parameters.ElementAt(i).NameToken; - //// if (node is ConstructorDeclaration) - //// return ((ConstructorDeclaration)node).Parameters.ElementAt(i).NameToken; - //// if (node is OperatorDeclaration) - //// return ((OperatorDeclaration)node).Parameters.ElementAt(i).NameToken; - //// if (node is IndexerDeclaration) - //// return ((IndexerDeclaration)node).Parameters.ElementAt(i).NameToken; - //// throw new InvalidOperationException("invalid parameterized node:" + node); - //// } - //// - //// protected virtual void VisitXmlChildren(AstNode node) - //// { - //// AstNode next; - //// var child = node.FirstChild; - //// while (child != null && (child is Comment || child is PreProcessorDirective || child.Role == Roles.NewLine)) { - //// next = child.NextSibling; - //// child.AcceptVisitor(this); - //// child = next; - //// } - //// - //// CheckXmlDoc(node); - //// - //// for (; child != null; child = next) { - //// // Store next to allow the loop to continue - //// // if the visitor removes/replaces child. - //// next = child.NextSibling; - //// child.AcceptVisitor(this); - //// } - //// InvalideXmlComments(); - //// } - //// - //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) - //// { - //// VisitXmlChildren(typeDeclaration); - //// } - //// - //// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) - //// { - //// VisitXmlChildren(methodDeclaration); - //// } - //// - //// public override void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration) - //// { - //// VisitXmlChildren(delegateDeclaration); - //// } - //// - //// public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration) - //// { - //// VisitXmlChildren(constructorDeclaration); - //// } - //// - //// public override void VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration) - //// { - //// VisitXmlChildren(eventDeclaration); - //// } - //// - //// public override void VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration) - //// { - //// VisitXmlChildren(destructorDeclaration); - //// } - //// - //// public override void VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration) - //// { - //// VisitXmlChildren(enumMemberDeclaration); - //// } - //// - //// public override void VisitEventDeclaration(EventDeclaration eventDeclaration) - //// { - //// VisitXmlChildren(eventDeclaration); - //// } - //// - //// public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration) - //// { - //// VisitXmlChildren(fieldDeclaration); - //// } - //// - //// public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration) - //// { - //// VisitXmlChildren(indexerDeclaration); - //// } - //// - //// public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration) - //// { - //// VisitXmlChildren(propertyDeclaration); - //// } - //// - //// public override void VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration) - //// { - //// VisitXmlChildren(operatorDeclaration); - //// } - // } - } +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // } +// //// +// //// void InvalideXmlComments() +// //// { +// //// storedXmlComment.Clear(); +// //// } +// //// +// //// public override void VisitComment(Comment comment) +// //// { +// //// base.VisitComment(comment); +// //// if (comment.CommentType == CommentType.Documentation) +// //// storedXmlComment.Add(comment); +// //// } +// //// +// //// public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration) +// //// { +// //// InvalideXmlComments(); +// //// base.VisitNamespaceDeclaration(namespaceDeclaration); +// //// } +// //// +// //// public override void VisitUsingDeclaration(UsingDeclaration usingDeclaration) +// //// { +// //// InvalideXmlComments(); +// //// base.VisitUsingDeclaration(usingDeclaration); +// //// } +// //// +// //// public override void VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration) +// //// { +// //// InvalideXmlComments(); +// //// base.VisitUsingAliasDeclaration(usingDeclaration); +// //// } +// //// +// //// public override void VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration) +// //// { +// //// InvalideXmlComments(); +// //// base.VisitExternAliasDeclaration(externAliasDeclaration); +// //// } +// //// +// //// void AddXmlIssue(int line, int col, int length, string str) +// //// { +// //// var cmt = storedXmlComment [Math.Max(0, Math.Min(storedXmlComment.Count - 1, line))]; +// //// +// //// AddDiagnosticAnalyzer(new CodeIssue(new TextLocation(cmt.StartLocation.Line, cmt.StartLocation.Column + 3 + col), +// //// new TextLocation(cmt.StartLocation.Line, cmt.StartLocation.Column + 3 + col + length), +// //// str)); +// //// } +// //// +// //// int SearchAttributeColumn(int x, int line) +// //// { +// //// var comment = storedXmlComment [Math.Max(0, Math.Min(storedXmlComment.Count - 1, line))]; +// //// var idx = comment.Content.IndexOfAny(new char[] { '"', '\'' }, x); +// //// return idx < 0 ? x : idx + 1; +// //// } +// //// +// //// void CheckXmlDoc(AstNode node) +// //// { +// //// ResolveResult resolveResult = ctx.Resolve(node); +// //// IEntity member = null; +// //// if (resolveResult is TypeResolveResult) +// //// member = resolveResult.Type.GetDefinition(); +// //// if (resolveResult is MemberResolveResult) +// //// member = ((MemberResolveResult)resolveResult).Member; +// //// var xml = new StringBuilder(); +// //// xml.AppendLine(""); +// //// foreach (var cmt in storedXmlComment) +// //// xml.AppendLine(cmt.Content); +// //// xml.AppendLine(""); +// //// +// //// List> parameters = new List>(); +// //// +// //// using (var reader = new XmlTextReader(new StringReader(xml.ToString()))) { +// //// reader.XmlResolver = null; +// //// try { +// //// while (reader.Read()) { +// //// if (member == null) +// //// continue; +// //// if (reader.NodeType == XmlNodeType.Element) { +// //// switch (reader.Name) { +// //// case "param": +// //// reader.MoveToFirstAttribute(); +// //// var line = reader.LineNumber; +// //// var name = reader.GetAttribute("name"); +// //// if (name == null) +// //// break; +// //// parameters.Add(Tuple.Create(name, line)); +// //// break; +// //// +// //// } +// //// } +// //// } +// //// } catch (XmlException) { +// //// } +// //// +// //// if (storedXmlComment.Count > 0 && parameters.Count > 0) { +// //// var pm = member as IParameterizedMember; +// //// if (pm != null) { +// //// for (int i = 0; i < pm.Parameters.Count; i++) { +// //// var p = pm.Parameters [i]; +// //// if (!parameters.Any(tp => tp.Item1 == p.Name)) { +// //// AstNode before = i < parameters.Count ? storedXmlComment [parameters [i].Item2 - 2] : null; +// //// AstNode afterNode = before == null ? storedXmlComment [storedXmlComment.Count - 1] : null; +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// GetParameterHighlightNode(node, i), +// //// string.Format(ctx.TranslateString("Missing xml documentation for Parameter '{0}'"), p.Name), +// //// string.Format(ctx.TranslateString("Create xml documentation for Parameter '{0}'"), p.Name), +// //// script => { +// //// if (before != null) { +// //// script.InsertBefore( +// //// before, +// //// new Comment(string.Format(" ", p.Name), CommentType.Documentation) +// //// ); +// //// } else { +// //// script.InsertAfter( +// //// afterNode, +// //// new Comment(string.Format(" ", p.Name), CommentType.Documentation) +// //// ); +// //// } +// //// })); +// //// } +// //// } +// //// +// //// } +// //// } +// //// storedXmlComment.Clear(); +// //// } +// //// } +// //// +// //// AstNode GetParameterHighlightNode(AstNode node, int i) +// //// { +// //// if (node is MethodDeclaration) +// //// return ((MethodDeclaration)node).Parameters.ElementAt(i).NameToken; +// //// if (node is ConstructorDeclaration) +// //// return ((ConstructorDeclaration)node).Parameters.ElementAt(i).NameToken; +// //// if (node is OperatorDeclaration) +// //// return ((OperatorDeclaration)node).Parameters.ElementAt(i).NameToken; +// //// if (node is IndexerDeclaration) +// //// return ((IndexerDeclaration)node).Parameters.ElementAt(i).NameToken; +// //// throw new InvalidOperationException("invalid parameterized node:" + node); +// //// } +// //// +// //// protected virtual void VisitXmlChildren(AstNode node) +// //// { +// //// AstNode next; +// //// var child = node.FirstChild; +// //// while (child != null && (child is Comment || child is PreProcessorDirective || child.Role == Roles.NewLine)) { +// //// next = child.NextSibling; +// //// child.AcceptVisitor(this); +// //// child = next; +// //// } +// //// +// //// CheckXmlDoc(node); +// //// +// //// for (; child != null; child = next) { +// //// // Store next to allow the loop to continue +// //// // if the visitor removes/replaces child. +// //// next = child.NextSibling; +// //// child.AcceptVisitor(this); +// //// } +// //// InvalideXmlComments(); +// //// } +// //// +// //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) +// //// { +// //// VisitXmlChildren(typeDeclaration); +// //// } +// //// +// //// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) +// //// { +// //// VisitXmlChildren(methodDeclaration); +// //// } +// //// +// //// public override void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration) +// //// { +// //// VisitXmlChildren(delegateDeclaration); +// //// } +// //// +// //// public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration) +// //// { +// //// VisitXmlChildren(constructorDeclaration); +// //// } +// //// +// //// public override void VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration) +// //// { +// //// VisitXmlChildren(eventDeclaration); +// //// } +// //// +// //// public override void VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration) +// //// { +// //// VisitXmlChildren(destructorDeclaration); +// //// } +// //// +// //// public override void VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration) +// //// { +// //// VisitXmlChildren(enumMemberDeclaration); +// //// } +// //// +// //// public override void VisitEventDeclaration(EventDeclaration eventDeclaration) +// //// { +// //// VisitXmlChildren(eventDeclaration); +// //// } +// //// +// //// public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration) +// //// { +// //// VisitXmlChildren(fieldDeclaration); +// //// } +// //// +// //// public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration) +// //// { +// //// VisitXmlChildren(indexerDeclaration); +// //// } +// //// +// //// public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration) +// //// { +// //// VisitXmlChildren(propertyDeclaration); +// //// } +// //// +// //// public override void VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration) +// //// { +// //// VisitXmlChildren(operatorDeclaration); +// //// } +// // } +// } - [ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared] - public class CS1573ParameterHasNoMatchingParamTagFixProvider : CodeFixProvider - { - public override ImmutableArray FixableDiagnosticIds - { - get - { - return ImmutableArray.Create(CS1573ParameterHasNoMatchingParamTagAnalyzer.DiagnosticId); - } - } +// [ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared] +// public class CS1573ParameterHasNoMatchingParamTagFixProvider : CodeFixProvider +// { +// public override ImmutableArray FixableDiagnosticIds +// { +// get +// { +// return ImmutableArray.Create(CS1573ParameterHasNoMatchingParamTagAnalyzer.DiagnosticId); +// } +// } - public override FixAllProvider GetFixAllProvider() - { - return WellKnownFixAllProviders.BatchFixer; - } +// public override FixAllProvider GetFixAllProvider() +// { +// return WellKnownFixAllProviders.BatchFixer; +// } - public async override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var document = context.Document; - var cancellationToken = context.CancellationToken; - var span = context.Span; - var diagnostics = context.Diagnostics; - var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var diagnostic = diagnostics.First(); - var node = root.FindNode(context.Span); - //if (!node.IsKind(SyntaxKind.BaseList)) - // continue; - var newRoot = root.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia); - context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, diagnostic.GetMessage(), document.WithSyntaxRoot(newRoot)), diagnostic); - } - } -} \ No newline at end of file +// public async override Task RegisterCodeFixesAsync(CodeFixContext context) +// { +// var document = context.Document; +// var cancellationToken = context.CancellationToken; +// var span = context.Span; +// var diagnostics = context.Diagnostics; +// var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); +// var diagnostic = diagnostics.First(); +// var node = root.FindNode(context.Span); +// //if (!node.IsKind(SyntaxKind.BaseList)) +// // continue; +// var newRoot = root.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia); +// context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, diagnostic.GetMessage(), document.WithSyntaxRoot(newRoot)), diagnostic); +// } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/ConstraintViolations/InconsistentNaming/InconsistentNamingAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/ConstraintViolations/InconsistentNaming/InconsistentNamingAnalyzer.cs index d987ae29..0d89cd06 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/ConstraintViolations/InconsistentNaming/InconsistentNamingAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/ConstraintViolations/InconsistentNaming/InconsistentNamingAnalyzer.cs @@ -1,409 +1,409 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis.CodeFixes; -using System.Threading.Tasks; -using System.Linq; +//using Microsoft.CodeAnalysis; +//using Microsoft.CodeAnalysis.Diagnostics; +//using System.Collections.Immutable; +//using Microsoft.CodeAnalysis.CodeFixes; +//using System.Threading.Tasks; +//using System.Linq; -namespace RefactoringEssentials.CSharp.Diagnostics -{ - //[DiagnosticAnalyzer(LanguageNames.CSharp)] - [NotPortedYet] - public class InconsistentNamingAnalyzer : DiagnosticAnalyzer - { - internal const string DiagnosticId = "InconsistentNaming"; - const string Description = "Inconsistent Naming"; - const string MessageFormat = ""; - const string Category = DiagnosticAnalyzerCategories.ConstraintViolations; +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// //[DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class InconsistentNamingAnalyzer : DiagnosticAnalyzer +// { +// internal const string DiagnosticId = "InconsistentNaming"; +// const string Description = "Inconsistent Naming"; +// const string MessageFormat = ""; +// const string Category = DiagnosticAnalyzerCategories.ConstraintViolations; - static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning, true, "Name doesn't match the defined style for this entity."); +// static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning, true, "Name doesn't match the defined style for this entity."); - public override ImmutableArray SupportedDiagnostics - { - get - { - return ImmutableArray.Create(Rule); - } - } +// public override ImmutableArray SupportedDiagnostics +// { +// get +// { +// return ImmutableArray.Create(Rule); +// } +// } - 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 NamingConventionService service; +// // class GatherVisitor : GatherVisitorBase +// // { +// // //readonly NamingConventionService service; - // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) - // : base (semanticModel, addDiagnostic, cancellationToken) - // { - // // service = (NamingConventionService)ctx.GetService (typeof (NamingConventionService)); - // } +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // // service = (NamingConventionService)ctx.GetService (typeof (NamingConventionService)); +// // } - //// void CheckName(TypeDeclaration node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty) - //// { - //// TypeResolveResult resolveResult = ctx.Resolve(node) as TypeResolveResult; - //// if (resolveResult == null) - //// return; - //// var type = resolveResult.Type; - //// if (type.DirectBaseTypes.Any(t => t.FullName == "System.Attribute")) { - //// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomAttributes, identifier, accessibilty)) { - //// return; - //// } - //// } else if (type.DirectBaseTypes.Any(t => t.FullName == "System.EventArgs")) { - //// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomEventArgs, identifier, accessibilty)) { - //// return; - //// } - //// } else if (type.DirectBaseTypes.Any(t => t.FullName == "System.Exception")) { - //// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomExceptions, identifier, accessibilty)) { - //// return; - //// } - //// } - //// - //// var typeDef = type.GetDefinition(); - //// if (typeDef != null && typeDef.Attributes.Any(attr => attr.AttributeType.FullName == "NUnit.Framework.TestFixtureAttribute")) { - //// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.TestType, identifier, accessibilty)) { - //// return; - //// } - //// } - //// - //// CheckNamedResolveResult(resolveResult, node, entity, identifier, accessibilty); - //// } - //// - //// void CheckName(MethodDeclaration node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty) - //// { - //// ResolveResult resolveResult = null; - //// if (node != null && node.Attributes.Any ()) - //// resolveResult = ctx.Resolve(node); - //// - //// if (resolveResult is MemberResolveResult) { - //// var member = ((MemberResolveResult)resolveResult).Member; - //// if (member.SymbolKind == SymbolKind.Method && member.Attributes.Any(attr => attr.AttributeType.FullName == "NUnit.Framework.TestAttribute")) { - //// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.TestMethod, identifier, accessibilty)) { - //// return; - //// } - //// } - //// } - //// - //// CheckNamedResolveResult(resolveResult, node, entity, identifier, accessibilty); - //// } - //// - //// void CheckName(AstNode node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty) - //// { - //// CheckNamedResolveResult(null, node, entity, identifier, accessibilty); - //// } - //// - //// bool CheckNamedResolveResult(ResolveResult resolveResult, AstNode node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty) - //// { - //// bool wasHandled = false; - //// foreach (var rule in service.Rules) { - //// if (!rule.AffectedEntity.HasFlag(entity)) { - //// continue; - //// } - //// if (!rule.VisibilityMask.HasFlag(accessibilty)) { - //// continue; - //// } - //// if (!rule.IncludeInstanceMembers || !rule.IncludeStaticEntities) { - //// EntityDeclaration typeSystemEntity; - //// if (node is VariableInitializer) { - //// typeSystemEntity = node.Parent as EntityDeclaration; - //// } else { - //// typeSystemEntity = node as EntityDeclaration; - //// } - //// if (!rule.IncludeInstanceMembers) { - //// if (typeSystemEntity == null || !typeSystemEntity.HasModifier (Modifiers.Static) || typeSystemEntity.HasModifier (Modifiers.Sealed)) { - //// continue; - //// } - //// } - //// if (!rule.IncludeStaticEntities) { - //// if (typeSystemEntity == null || typeSystemEntity.HasModifier (Modifiers.Static) || typeSystemEntity.HasModifier (Modifiers.Sealed)) { - //// continue; - //// } - //// } - //// } - //// - //// wasHandled = true; - //// if (!rule.IsValid(identifier.Name)) { - //// IList suggestedNames; - //// var msg = rule.GetErrorMessage(ctx, identifier.Name, out suggestedNames); - //// var actions = new List(suggestedNames.Select(n => new CodeAction(string.Format(ctx.TranslateString("Rename to '{0}'"), n), (Script script) => { - //// if (resolveResult == null) - //// resolveResult = ctx.Resolve (node); - //// if (resolveResult is MemberResolveResult) { - //// script.Rename(((MemberResolveResult)resolveResult).Member, n); - //// } else if (resolveResult is TypeResolveResult) { - //// var def = resolveResult.Type.GetDefinition(); - //// if (def != null) { - //// script.Rename(def, n); - //// } else if (resolveResult.Type.Kind == TypeKind.TypeParameter) { - //// script.Rename((ITypeParameter)resolveResult.Type, n); - //// } - //// } else if (resolveResult is LocalResolveResult) { - //// script.Rename(((LocalResolveResult)resolveResult).Variable, n); - //// } else if (resolveResult is NamespaceResolveResult) { - //// script.Rename(((NamespaceResolveResult)resolveResult).Namespace, n); - //// } else { - //// script.Replace(identifier, Identifier.Create(n)); - //// } - //// }, identifier))); - //// - //// if (entity != AffectedEntity.Label) { - //// actions.Add(new CodeAction(string.Format(ctx.TranslateString("Rename '{0}'..."), identifier.Name), (Script script) => { - //// if (resolveResult == null) - //// resolveResult = ctx.Resolve (node); - //// if (resolveResult is MemberResolveResult) { - //// script.Rename(((MemberResolveResult)resolveResult).Member); - //// } else if (resolveResult is TypeResolveResult) { - //// var def = resolveResult.Type.GetDefinition(); - //// if (def != null) { - //// script.Rename(def); - //// } else if (resolveResult.Type.Kind == TypeKind.TypeParameter) { - //// script.Rename((ITypeParameter)resolveResult.Type); - //// } - //// } else if (resolveResult is LocalResolveResult) { - //// script.Rename(((LocalResolveResult)resolveResult).Variable); - //// } else if (resolveResult is NamespaceResolveResult) { - //// script.Rename(((NamespaceResolveResult)resolveResult).Namespace); - //// } - //// }, identifier)); - //// } - //// - //// AddDiagnosticAnalyzer(new CodeIssue(identifier, msg, actions)); - //// } - //// } - //// return wasHandled; - //// } - //// - //// public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration) - //// { - //// base.VisitNamespaceDeclaration(namespaceDeclaration); - //// var type = namespaceDeclaration.NamespaceName; - //// while (type is MemberType) { - //// var mt = (MemberType)type; - //// CheckNamedResolveResult(null, namespaceDeclaration, AffectedEntity.Namespace, mt.MemberNameToken, Modifiers.None); - //// type = mt.Target; - //// } - //// if (type is SimpleType) - //// CheckNamedResolveResult(null, namespaceDeclaration, AffectedEntity.Namespace, ((SimpleType)type).IdentifierToken, Modifiers.None); - //// } - //// - //// Modifiers GetAccessibiltiy(EntityDeclaration decl, Modifiers defaultModifier) - //// { - //// var accessibility = (decl.Modifiers & Modifiers.VisibilityMask); - //// if (accessibility == Modifiers.None) { - //// return defaultModifier; - //// } - //// return accessibility; - //// } - //// - //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) - //// { - //// base.VisitTypeDeclaration(typeDeclaration); - //// AffectedEntity entity; - //// switch (typeDeclaration.ClassType) { - //// case ClassType.Class: - //// entity = AffectedEntity.Class; - //// break; - //// case ClassType.Struct: - //// entity = AffectedEntity.Struct; - //// break; - //// case ClassType.Interface: - //// entity = AffectedEntity.Interface; - //// break; - //// case ClassType.Enum: - //// entity = AffectedEntity.Enum; - //// break; - //// default: - //// throw new System.ArgumentOutOfRangeException(); - //// } - //// CheckName(typeDeclaration, entity, typeDeclaration.NameToken, GetAccessibiltiy(typeDeclaration, typeDeclaration.Parent is TypeDeclaration ? Modifiers.Private : Modifiers.Internal)); - //// } - //// - //// public override void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration) - //// { - //// base.VisitDelegateDeclaration(delegateDeclaration); - //// CheckName(delegateDeclaration, AffectedEntity.Delegate, delegateDeclaration.NameToken, GetAccessibiltiy(delegateDeclaration, delegateDeclaration.Parent is TypeDeclaration ? Modifiers.Private : Modifiers.Internal)); - //// } - //// - //// public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration) - //// { - //// if (propertyDeclaration.Modifiers.HasFlag (Modifiers.Override)) - //// return; - //// base.VisitPropertyDeclaration(propertyDeclaration); - //// CheckName(propertyDeclaration, AffectedEntity.Property, propertyDeclaration.NameToken, GetAccessibiltiy(propertyDeclaration, Modifiers.Private)); - //// } - //// - //// public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration) - //// { - //// if (indexerDeclaration.Modifiers.HasFlag(Modifiers.Override)) { - //// var rr = ctx.Resolve (indexerDeclaration) as MemberResolveResult; - //// if (rr == null) - //// return; - //// var baseType = rr.Member.DeclaringType.DirectBaseTypes.FirstOrDefault (t => t.Kind != TypeKind.Interface); - //// var method = baseType != null ? baseType.GetProperties (m => m.IsIndexer && m.IsOverridable && m.Parameters.Count == indexerDeclaration.Parameters.Count).FirstOrDefault () : null; - //// if (method == null) - //// return; - //// int i = 0; - //// foreach (var par in indexerDeclaration.Parameters) { - //// if (method.Parameters[i++].Name != par.Name) { - //// par.AcceptVisitor (this); - //// } - //// } - //// return; - //// } - //// base.VisitIndexerDeclaration(indexerDeclaration); - //// } - //// - //// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) - //// { - //// if (methodDeclaration.Modifiers.HasFlag(Modifiers.Override)) { - //// var rr = ctx.Resolve (methodDeclaration) as MemberResolveResult; - //// if (rr == null) - //// return; - //// var baseType = rr.Member.DeclaringType.DirectBaseTypes.FirstOrDefault (t => t.Kind != TypeKind.Interface); - //// var method = baseType != null ? baseType.GetMethods (m => m.Name == rr.Member.Name && m.IsOverridable && m.Parameters.Count == methodDeclaration.Parameters.Count).FirstOrDefault () : null; - //// if (method == null) - //// return; - //// int i = 0; - //// foreach (var par in methodDeclaration.Parameters) { - //// if (method.Parameters[i++].Name != par.Name) { - //// par.AcceptVisitor (this); - //// } - //// } - //// - //// return; - //// } - //// base.VisitMethodDeclaration(methodDeclaration); - //// - //// CheckName(methodDeclaration, methodDeclaration.Modifiers.HasFlag(Modifiers.Async) ? AffectedEntity.AsyncMethod : AffectedEntity.Method, methodDeclaration.NameToken, GetAccessibiltiy(methodDeclaration, Modifiers.Private)); - //// } - //// - //// public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration) - //// { - //// base.VisitFieldDeclaration(fieldDeclaration); - //// var entity = AffectedEntity.Field; - //// if (fieldDeclaration.Modifiers.HasFlag(Modifiers.Const)) { - //// entity = AffectedEntity.ConstantField; - //// } else if (fieldDeclaration.Modifiers.HasFlag(Modifiers.Readonly)) { - //// entity = AffectedEntity.ReadonlyField; - //// } - //// foreach (var init in fieldDeclaration.Variables) { - //// CheckName(init, entity, init.NameToken, GetAccessibiltiy(fieldDeclaration, Modifiers.Private)); - //// } - //// } - //// - //// public override void VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration) - //// { - //// base.VisitFixedFieldDeclaration(fixedFieldDeclaration); - //// var entity = AffectedEntity.Field; - //// if (fixedFieldDeclaration.Modifiers.HasFlag(Modifiers.Const)) { - //// entity = AffectedEntity.ConstantField; - //// } else if (fixedFieldDeclaration.Modifiers.HasFlag(Modifiers.Readonly)) { - //// entity = AffectedEntity.ReadonlyField; - //// } - //// CheckName(fixedFieldDeclaration, entity, fixedFieldDeclaration.NameToken, GetAccessibiltiy(fixedFieldDeclaration, Modifiers.Private)); - //// } - //// - //// public override void VisitEventDeclaration(EventDeclaration eventDeclaration) - //// { - //// base.VisitEventDeclaration(eventDeclaration); - //// foreach (var init in eventDeclaration.Variables) { - //// CheckName(init, AffectedEntity.Event, init.NameToken, GetAccessibiltiy(eventDeclaration, Modifiers.Private)); - //// } - //// } - //// - //// public override void VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration) - //// { - //// if (eventDeclaration.Modifiers.HasFlag (Modifiers.Override)) - //// return; - //// base.VisitCustomEventDeclaration(eventDeclaration); - //// CheckName(eventDeclaration, AffectedEntity.Event, eventDeclaration.NameToken, GetAccessibiltiy(eventDeclaration, Modifiers.Private)); - //// } - //// - //// public override void VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration) - //// { - //// base.VisitEnumMemberDeclaration(enumMemberDeclaration); - //// CheckName(enumMemberDeclaration, AffectedEntity.EnumMember, enumMemberDeclaration.NameToken, GetAccessibiltiy(enumMemberDeclaration, Modifiers.Private)); - //// } - //// - //// public override void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration) - //// { - //// base.VisitParameterDeclaration(parameterDeclaration); - //// CheckNamedResolveResult(null, parameterDeclaration, parameterDeclaration.Parent is LambdaExpression ? AffectedEntity.LambdaParameter : AffectedEntity.Parameter, parameterDeclaration.NameToken, Modifiers.None); - //// } - //// - //// public override void VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration) - //// { - //// base.VisitTypeParameterDeclaration(typeParameterDeclaration); - //// CheckNamedResolveResult(null, typeParameterDeclaration, AffectedEntity.TypeParameter, typeParameterDeclaration.NameToken, Modifiers.None); - //// } - //// - //// public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement) - //// { - //// base.VisitVariableDeclarationStatement(variableDeclarationStatement); - //// var entity = variableDeclarationStatement.Modifiers.HasFlag(Modifiers.Const) ? AffectedEntity.LocalConstant : AffectedEntity.LocalVariable; - //// foreach (var init in variableDeclarationStatement.Variables) { - //// CheckNamedResolveResult(null, init, entity, init.NameToken, Modifiers.None); - //// } - //// } - //// - //// public override void VisitLabelStatement(LabelStatement labelStatement) - //// { - //// base.VisitLabelStatement(labelStatement); - //// CheckNamedResolveResult(null, labelStatement, AffectedEntity.Label, labelStatement.LabelToken, Modifiers.None); - //// } - // } - } +// //// void CheckName(TypeDeclaration node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty) +// //// { +// //// TypeResolveResult resolveResult = ctx.Resolve(node) as TypeResolveResult; +// //// if (resolveResult == null) +// //// return; +// //// var type = resolveResult.Type; +// //// if (type.DirectBaseTypes.Any(t => t.FullName == "System.Attribute")) { +// //// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomAttributes, identifier, accessibilty)) { +// //// return; +// //// } +// //// } else if (type.DirectBaseTypes.Any(t => t.FullName == "System.EventArgs")) { +// //// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomEventArgs, identifier, accessibilty)) { +// //// return; +// //// } +// //// } else if (type.DirectBaseTypes.Any(t => t.FullName == "System.Exception")) { +// //// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomExceptions, identifier, accessibilty)) { +// //// return; +// //// } +// //// } +// //// +// //// var typeDef = type.GetDefinition(); +// //// if (typeDef != null && typeDef.Attributes.Any(attr => attr.AttributeType.FullName == "NUnit.Framework.TestFixtureAttribute")) { +// //// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.TestType, identifier, accessibilty)) { +// //// return; +// //// } +// //// } +// //// +// //// CheckNamedResolveResult(resolveResult, node, entity, identifier, accessibilty); +// //// } +// //// +// //// void CheckName(MethodDeclaration node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty) +// //// { +// //// ResolveResult resolveResult = null; +// //// if (node != null && node.Attributes.Any ()) +// //// resolveResult = ctx.Resolve(node); +// //// +// //// if (resolveResult is MemberResolveResult) { +// //// var member = ((MemberResolveResult)resolveResult).Member; +// //// if (member.SymbolKind == SymbolKind.Method && member.Attributes.Any(attr => attr.AttributeType.FullName == "NUnit.Framework.TestAttribute")) { +// //// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.TestMethod, identifier, accessibilty)) { +// //// return; +// //// } +// //// } +// //// } +// //// +// //// CheckNamedResolveResult(resolveResult, node, entity, identifier, accessibilty); +// //// } +// //// +// //// void CheckName(AstNode node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty) +// //// { +// //// CheckNamedResolveResult(null, node, entity, identifier, accessibilty); +// //// } +// //// +// //// bool CheckNamedResolveResult(ResolveResult resolveResult, AstNode node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty) +// //// { +// //// bool wasHandled = false; +// //// foreach (var rule in service.Rules) { +// //// if (!rule.AffectedEntity.HasFlag(entity)) { +// //// continue; +// //// } +// //// if (!rule.VisibilityMask.HasFlag(accessibilty)) { +// //// continue; +// //// } +// //// if (!rule.IncludeInstanceMembers || !rule.IncludeStaticEntities) { +// //// EntityDeclaration typeSystemEntity; +// //// if (node is VariableInitializer) { +// //// typeSystemEntity = node.Parent as EntityDeclaration; +// //// } else { +// //// typeSystemEntity = node as EntityDeclaration; +// //// } +// //// if (!rule.IncludeInstanceMembers) { +// //// if (typeSystemEntity == null || !typeSystemEntity.HasModifier (Modifiers.Static) || typeSystemEntity.HasModifier (Modifiers.Sealed)) { +// //// continue; +// //// } +// //// } +// //// if (!rule.IncludeStaticEntities) { +// //// if (typeSystemEntity == null || typeSystemEntity.HasModifier (Modifiers.Static) || typeSystemEntity.HasModifier (Modifiers.Sealed)) { +// //// continue; +// //// } +// //// } +// //// } +// //// +// //// wasHandled = true; +// //// if (!rule.IsValid(identifier.Name)) { +// //// IList suggestedNames; +// //// var msg = rule.GetErrorMessage(ctx, identifier.Name, out suggestedNames); +// //// var actions = new List(suggestedNames.Select(n => new CodeAction(string.Format(ctx.TranslateString("Rename to '{0}'"), n), (Script script) => { +// //// if (resolveResult == null) +// //// resolveResult = ctx.Resolve (node); +// //// if (resolveResult is MemberResolveResult) { +// //// script.Rename(((MemberResolveResult)resolveResult).Member, n); +// //// } else if (resolveResult is TypeResolveResult) { +// //// var def = resolveResult.Type.GetDefinition(); +// //// if (def != null) { +// //// script.Rename(def, n); +// //// } else if (resolveResult.Type.Kind == TypeKind.TypeParameter) { +// //// script.Rename((ITypeParameter)resolveResult.Type, n); +// //// } +// //// } else if (resolveResult is LocalResolveResult) { +// //// script.Rename(((LocalResolveResult)resolveResult).Variable, n); +// //// } else if (resolveResult is NamespaceResolveResult) { +// //// script.Rename(((NamespaceResolveResult)resolveResult).Namespace, n); +// //// } else { +// //// script.Replace(identifier, Identifier.Create(n)); +// //// } +// //// }, identifier))); +// //// +// //// if (entity != AffectedEntity.Label) { +// //// actions.Add(new CodeAction(string.Format(ctx.TranslateString("Rename '{0}'..."), identifier.Name), (Script script) => { +// //// if (resolveResult == null) +// //// resolveResult = ctx.Resolve (node); +// //// if (resolveResult is MemberResolveResult) { +// //// script.Rename(((MemberResolveResult)resolveResult).Member); +// //// } else if (resolveResult is TypeResolveResult) { +// //// var def = resolveResult.Type.GetDefinition(); +// //// if (def != null) { +// //// script.Rename(def); +// //// } else if (resolveResult.Type.Kind == TypeKind.TypeParameter) { +// //// script.Rename((ITypeParameter)resolveResult.Type); +// //// } +// //// } else if (resolveResult is LocalResolveResult) { +// //// script.Rename(((LocalResolveResult)resolveResult).Variable); +// //// } else if (resolveResult is NamespaceResolveResult) { +// //// script.Rename(((NamespaceResolveResult)resolveResult).Namespace); +// //// } +// //// }, identifier)); +// //// } +// //// +// //// AddDiagnosticAnalyzer(new CodeIssue(identifier, msg, actions)); +// //// } +// //// } +// //// return wasHandled; +// //// } +// //// +// //// public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration) +// //// { +// //// base.VisitNamespaceDeclaration(namespaceDeclaration); +// //// var type = namespaceDeclaration.NamespaceName; +// //// while (type is MemberType) { +// //// var mt = (MemberType)type; +// //// CheckNamedResolveResult(null, namespaceDeclaration, AffectedEntity.Namespace, mt.MemberNameToken, Modifiers.None); +// //// type = mt.Target; +// //// } +// //// if (type is SimpleType) +// //// CheckNamedResolveResult(null, namespaceDeclaration, AffectedEntity.Namespace, ((SimpleType)type).IdentifierToken, Modifiers.None); +// //// } +// //// +// //// Modifiers GetAccessibiltiy(EntityDeclaration decl, Modifiers defaultModifier) +// //// { +// //// var accessibility = (decl.Modifiers & Modifiers.VisibilityMask); +// //// if (accessibility == Modifiers.None) { +// //// return defaultModifier; +// //// } +// //// return accessibility; +// //// } +// //// +// //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) +// //// { +// //// base.VisitTypeDeclaration(typeDeclaration); +// //// AffectedEntity entity; +// //// switch (typeDeclaration.ClassType) { +// //// case ClassType.Class: +// //// entity = AffectedEntity.Class; +// //// break; +// //// case ClassType.Struct: +// //// entity = AffectedEntity.Struct; +// //// break; +// //// case ClassType.Interface: +// //// entity = AffectedEntity.Interface; +// //// break; +// //// case ClassType.Enum: +// //// entity = AffectedEntity.Enum; +// //// break; +// //// default: +// //// throw new System.ArgumentOutOfRangeException(); +// //// } +// //// CheckName(typeDeclaration, entity, typeDeclaration.NameToken, GetAccessibiltiy(typeDeclaration, typeDeclaration.Parent is TypeDeclaration ? Modifiers.Private : Modifiers.Internal)); +// //// } +// //// +// //// public override void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration) +// //// { +// //// base.VisitDelegateDeclaration(delegateDeclaration); +// //// CheckName(delegateDeclaration, AffectedEntity.Delegate, delegateDeclaration.NameToken, GetAccessibiltiy(delegateDeclaration, delegateDeclaration.Parent is TypeDeclaration ? Modifiers.Private : Modifiers.Internal)); +// //// } +// //// +// //// public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration) +// //// { +// //// if (propertyDeclaration.Modifiers.HasFlag (Modifiers.Override)) +// //// return; +// //// base.VisitPropertyDeclaration(propertyDeclaration); +// //// CheckName(propertyDeclaration, AffectedEntity.Property, propertyDeclaration.NameToken, GetAccessibiltiy(propertyDeclaration, Modifiers.Private)); +// //// } +// //// +// //// public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration) +// //// { +// //// if (indexerDeclaration.Modifiers.HasFlag(Modifiers.Override)) { +// //// var rr = ctx.Resolve (indexerDeclaration) as MemberResolveResult; +// //// if (rr == null) +// //// return; +// //// var baseType = rr.Member.DeclaringType.DirectBaseTypes.FirstOrDefault (t => t.Kind != TypeKind.Interface); +// //// var method = baseType != null ? baseType.GetProperties (m => m.IsIndexer && m.IsOverridable && m.Parameters.Count == indexerDeclaration.Parameters.Count).FirstOrDefault () : null; +// //// if (method == null) +// //// return; +// //// int i = 0; +// //// foreach (var par in indexerDeclaration.Parameters) { +// //// if (method.Parameters[i++].Name != par.Name) { +// //// par.AcceptVisitor (this); +// //// } +// //// } +// //// return; +// //// } +// //// base.VisitIndexerDeclaration(indexerDeclaration); +// //// } +// //// +// //// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) +// //// { +// //// if (methodDeclaration.Modifiers.HasFlag(Modifiers.Override)) { +// //// var rr = ctx.Resolve (methodDeclaration) as MemberResolveResult; +// //// if (rr == null) +// //// return; +// //// var baseType = rr.Member.DeclaringType.DirectBaseTypes.FirstOrDefault (t => t.Kind != TypeKind.Interface); +// //// var method = baseType != null ? baseType.GetMethods (m => m.Name == rr.Member.Name && m.IsOverridable && m.Parameters.Count == methodDeclaration.Parameters.Count).FirstOrDefault () : null; +// //// if (method == null) +// //// return; +// //// int i = 0; +// //// foreach (var par in methodDeclaration.Parameters) { +// //// if (method.Parameters[i++].Name != par.Name) { +// //// par.AcceptVisitor (this); +// //// } +// //// } +// //// +// //// return; +// //// } +// //// base.VisitMethodDeclaration(methodDeclaration); +// //// +// //// CheckName(methodDeclaration, methodDeclaration.Modifiers.HasFlag(Modifiers.Async) ? AffectedEntity.AsyncMethod : AffectedEntity.Method, methodDeclaration.NameToken, GetAccessibiltiy(methodDeclaration, Modifiers.Private)); +// //// } +// //// +// //// public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration) +// //// { +// //// base.VisitFieldDeclaration(fieldDeclaration); +// //// var entity = AffectedEntity.Field; +// //// if (fieldDeclaration.Modifiers.HasFlag(Modifiers.Const)) { +// //// entity = AffectedEntity.ConstantField; +// //// } else if (fieldDeclaration.Modifiers.HasFlag(Modifiers.Readonly)) { +// //// entity = AffectedEntity.ReadonlyField; +// //// } +// //// foreach (var init in fieldDeclaration.Variables) { +// //// CheckName(init, entity, init.NameToken, GetAccessibiltiy(fieldDeclaration, Modifiers.Private)); +// //// } +// //// } +// //// +// //// public override void VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration) +// //// { +// //// base.VisitFixedFieldDeclaration(fixedFieldDeclaration); +// //// var entity = AffectedEntity.Field; +// //// if (fixedFieldDeclaration.Modifiers.HasFlag(Modifiers.Const)) { +// //// entity = AffectedEntity.ConstantField; +// //// } else if (fixedFieldDeclaration.Modifiers.HasFlag(Modifiers.Readonly)) { +// //// entity = AffectedEntity.ReadonlyField; +// //// } +// //// CheckName(fixedFieldDeclaration, entity, fixedFieldDeclaration.NameToken, GetAccessibiltiy(fixedFieldDeclaration, Modifiers.Private)); +// //// } +// //// +// //// public override void VisitEventDeclaration(EventDeclaration eventDeclaration) +// //// { +// //// base.VisitEventDeclaration(eventDeclaration); +// //// foreach (var init in eventDeclaration.Variables) { +// //// CheckName(init, AffectedEntity.Event, init.NameToken, GetAccessibiltiy(eventDeclaration, Modifiers.Private)); +// //// } +// //// } +// //// +// //// public override void VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration) +// //// { +// //// if (eventDeclaration.Modifiers.HasFlag (Modifiers.Override)) +// //// return; +// //// base.VisitCustomEventDeclaration(eventDeclaration); +// //// CheckName(eventDeclaration, AffectedEntity.Event, eventDeclaration.NameToken, GetAccessibiltiy(eventDeclaration, Modifiers.Private)); +// //// } +// //// +// //// public override void VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration) +// //// { +// //// base.VisitEnumMemberDeclaration(enumMemberDeclaration); +// //// CheckName(enumMemberDeclaration, AffectedEntity.EnumMember, enumMemberDeclaration.NameToken, GetAccessibiltiy(enumMemberDeclaration, Modifiers.Private)); +// //// } +// //// +// //// public override void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration) +// //// { +// //// base.VisitParameterDeclaration(parameterDeclaration); +// //// CheckNamedResolveResult(null, parameterDeclaration, parameterDeclaration.Parent is LambdaExpression ? AffectedEntity.LambdaParameter : AffectedEntity.Parameter, parameterDeclaration.NameToken, Modifiers.None); +// //// } +// //// +// //// public override void VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration) +// //// { +// //// base.VisitTypeParameterDeclaration(typeParameterDeclaration); +// //// CheckNamedResolveResult(null, typeParameterDeclaration, AffectedEntity.TypeParameter, typeParameterDeclaration.NameToken, Modifiers.None); +// //// } +// //// +// //// public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement) +// //// { +// //// base.VisitVariableDeclarationStatement(variableDeclarationStatement); +// //// var entity = variableDeclarationStatement.Modifiers.HasFlag(Modifiers.Const) ? AffectedEntity.LocalConstant : AffectedEntity.LocalVariable; +// //// foreach (var init in variableDeclarationStatement.Variables) { +// //// CheckNamedResolveResult(null, init, entity, init.NameToken, Modifiers.None); +// //// } +// //// } +// //// +// //// public override void VisitLabelStatement(LabelStatement labelStatement) +// //// { +// //// base.VisitLabelStatement(labelStatement); +// //// CheckNamedResolveResult(null, labelStatement, AffectedEntity.Label, labelStatement.LabelToken, Modifiers.None); +// //// } +// // } +// } - [ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared] - public class InconsistentNamingIssueFixProvider : CodeFixProvider - { - public override ImmutableArray FixableDiagnosticIds - { - get - { - return ImmutableArray.Create(InconsistentNamingAnalyzer.DiagnosticId); - } - } +// [ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared] +// public class InconsistentNamingIssueFixProvider : CodeFixProvider +// { +// public override ImmutableArray FixableDiagnosticIds +// { +// get +// { +// return ImmutableArray.Create(InconsistentNamingAnalyzer.DiagnosticId); +// } +// } - public override FixAllProvider GetFixAllProvider() - { - return WellKnownFixAllProviders.BatchFixer; - } +// public override FixAllProvider GetFixAllProvider() +// { +// return WellKnownFixAllProviders.BatchFixer; +// } - public async override Task RegisterCodeFixesAsync(CodeFixContext context) - { - var document = context.Document; - var cancellationToken = context.CancellationToken; - var span = context.Span; - var diagnostics = context.Diagnostics; - var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var diagnostic = diagnostics.First(); - var node = root.FindNode(context.Span); - //if (!node.IsKind(SyntaxKind.BaseList)) - // continue; - var newRoot = root.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia); - context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, diagnostic.GetMessage(), document.WithSyntaxRoot(newRoot)), diagnostic); - } - } -} \ No newline at end of file +// public async override Task RegisterCodeFixesAsync(CodeFixContext context) +// { +// var document = context.Document; +// var cancellationToken = context.CancellationToken; +// var span = context.Span; +// var diagnostics = context.Diagnostics; +// var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); +// var diagnostic = diagnostics.First(); +// var node = root.FindNode(context.Span); +// //if (!node.IsKind(SyntaxKind.BaseList)) +// // continue; +// var newRoot = root.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia); +// context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, diagnostic.GetMessage(), document.WithSyntaxRoot(newRoot)), diagnostic); +// } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertIfStatementToNullCoalescingExpressionAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertIfStatementToNullCoalescingExpressionAnalyzer.cs index 4a19e084..b50e6de0 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertIfStatementToNullCoalescingExpressionAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertIfStatementToNullCoalescingExpressionAnalyzer.cs @@ -1,77 +1,77 @@ -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 ConvertIfStatementToNullCoalescingExpressionAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.ConvertIfStatementToNullCoalescingExpressionAnalyzerID, - GettextCatalog.GetString("Convert 'if' to '??'"), - GettextCatalog.GetString("Convert to '??' expresssion"), - DiagnosticAnalyzerCategories.Opportunities, - DiagnosticSeverity.Info, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ConvertIfStatementToNullCoalescingExpressionAnalyzerID) - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class ConvertIfStatementToNullCoalescingExpressionAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.ConvertIfStatementToNullCoalescingExpressionAnalyzerID, +// GettextCatalog.GetString("Convert 'if' to '??'"), +// GettextCatalog.GetString("Convert to '??' expresssion"), +// DiagnosticAnalyzerCategories.Opportunities, +// DiagnosticSeverity.Info, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ConvertIfStatementToNullCoalescingExpressionAnalyzerID) +// ); - 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 VisitIfElseStatement(IfElseStatement ifElseStatement) - //// { - //// base.VisitIfElseStatement(ifElseStatement); - //// Expression rightSide; - //// var leftSide = ConvertIfStatementToNullCoalescingExpressionAction.CheckNode(ifElseStatement, out rightSide); - //// if (leftSide == null) - //// return; - //// if (ConvertIfStatementToConditionalTernaryExpressionAnalyzer.IsComplexExpression(leftSide) || - //// ConvertIfStatementToConditionalTernaryExpressionAnalyzer.IsComplexExpression(rightSide)) - //// return; - //// var previousNode = ifElseStatement.GetPrevSibling(sibling => sibling is Statement) as VariableDeclarationStatement; - //// if (previousNode == null || ConvertIfStatementToConditionalTernaryExpressionAnalyzer.IsComplexExpression(previousNode)) - //// return; - //// - //// AddDiagnosticAnalyzer(new CodeIssue( - //// ifElseStatement.IfToken, - //// ctx.TranslateString("") - //// ){ IssueMarker = IssueMarker.DottedLine, ActionProvider = { typeof(ConvertIfStatementToNullCoalescingExpressionAction) } }); - //// } - // } - } +// //// public override void VisitIfElseStatement(IfElseStatement ifElseStatement) +// //// { +// //// base.VisitIfElseStatement(ifElseStatement); +// //// Expression rightSide; +// //// var leftSide = ConvertIfStatementToNullCoalescingExpressionAction.CheckNode(ifElseStatement, out rightSide); +// //// if (leftSide == null) +// //// return; +// //// if (ConvertIfStatementToConditionalTernaryExpressionAnalyzer.IsComplexExpression(leftSide) || +// //// ConvertIfStatementToConditionalTernaryExpressionAnalyzer.IsComplexExpression(rightSide)) +// //// return; +// //// var previousNode = ifElseStatement.GetPrevSibling(sibling => sibling is Statement) as VariableDeclarationStatement; +// //// if (previousNode == null || ConvertIfStatementToConditionalTernaryExpressionAnalyzer.IsComplexExpression(previousNode)) +// //// return; +// //// +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// ifElseStatement.IfToken, +// //// ctx.TranslateString("") +// //// ){ IssueMarker = IssueMarker.DottedLine, ActionProvider = { typeof(ConvertIfStatementToNullCoalescingExpressionAction) } }); +// //// } +// // } +// } -} \ No newline at end of file +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertIfStatementToSwitchStatementAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertIfStatementToSwitchStatementAnalyzer.cs index cd3226d2..80e07cb9 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertIfStatementToSwitchStatementAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertIfStatementToSwitchStatementAnalyzer.cs @@ -103,7 +103,7 @@ internal static ExpressionSyntax GetSwitchExpression(SemanticModel context, Expr ExpressionSyntax switchExpr = null; if (IsConstantExpression(context, binaryOp.Right)) switchExpr = binaryOp.Left; - if (IsConstantExpression(context, binaryOp.Left)) + else if (IsConstantExpression(context, binaryOp.Left)) switchExpr = binaryOp.Right; if (switchExpr != null && IsValidSwitchType(context.GetTypeInfo(switchExpr).Type)) return switchExpr; @@ -119,23 +119,22 @@ internal static bool CollectSwitchSections(List result, Sem var labels = new List(); if (!CollectCaseLabels(labels, context, ifStatement.Condition, switchExpr)) return false; + if (ifStatement.Statement.DescendantNodes().OfType ().Any()) + return false; + var statements = new List(); CollectSwitchSectionStatements(statements, context, ifStatement.Statement); result.Add(SyntaxFactory.SwitchSection(new SyntaxList().AddRange(labels), new SyntaxList().AddRange(statements))); - - if (ifStatement.Statement.DescendantNodes().Any(n => n is BreakStatementSyntax)) - return false; - if (ifStatement.Else == null) return true; + if (ifStatement.Else.Statement.DescendantNodes().OfType().Any()) + return false; + // else if - var falseStatement = ifStatement.Else.Statement as IfStatementSyntax; - if (falseStatement != null) + if (ifStatement.Else.Statement is IfStatementSyntax falseStatement) return CollectSwitchSections(result, context, falseStatement, switchExpr); - if (ifStatement.Else.Statement.DescendantNodes().Any(n => n is BreakStatementSyntax)) - return false; // else (default label) labels = new List(); labels.Add(SyntaxFactory.DefaultSwitchLabel()); diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertToAutoPropertyAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertToAutoPropertyAnalyzer.cs index 2ecf3580..8c4a4384 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertToAutoPropertyAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertToAutoPropertyAnalyzer.cs @@ -1,101 +1,101 @@ -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 ConvertToAutoPropertyAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.ConvertToAutoPropertyAnalyzerID, - GettextCatalog.GetString("Convert property to auto property"), - GettextCatalog.GetString("Convert to auto property"), - DiagnosticAnalyzerCategories.Opportunities, - DiagnosticSeverity.Warning, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ConvertToAutoPropertyAnalyzerID) - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class ConvertToAutoPropertyAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.ConvertToAutoPropertyAnalyzerID, +// GettextCatalog.GetString("Convert property to auto property"), +// GettextCatalog.GetString("Convert to auto property"), +// DiagnosticAnalyzerCategories.Opportunities, +// DiagnosticSeverity.Warning, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ConvertToAutoPropertyAnalyzerID) +// ); - 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 Stack typeStack = new Stack(); +// // class GatherVisitor : GatherVisitorBase +// // { +// // //readonly Stack typeStack = new Stack(); - // 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 VisitBlockStatement(BlockStatement blockStatement) - //// { - //// // SKIP - //// } - //// - //// bool IsValidField(IField field) - //// { - //// if (field == null || field.Attributes.Count > 0 || field.IsVolatile) - //// return false; - //// foreach (var m in typeStack.Peek().Members.OfType()) { - //// foreach (var i in m.Variables) { - //// if (i.StartLocation == field.BodyRegion.Begin) { - //// if (!i.Initializer.IsNull) - //// return false; - //// break; - //// } - //// } - //// } - //// return true; - //// } - //// - //// public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration) - //// { - //// var field = RemoveBackingStoreAction.GetBackingField(ctx, propertyDeclaration); - //// if (!IsValidField(field)) - //// return; - //// AddDiagnosticAnalyzer(new CodeIssue( - //// propertyDeclaration.NameToken, - //// ctx.TranslateString("Convert to auto property") - //// ) { - //// ActionProvider = { typeof (RemoveBackingStoreAction) } - //// } - //// ); - //// } - //// - //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) - //// { - //// typeStack.Push(typeDeclaration); - //// base.VisitTypeDeclaration(typeDeclaration); - //// typeStack.Pop(); - //// } - // } - } +// //// public override void VisitBlockStatement(BlockStatement blockStatement) +// //// { +// //// // SKIP +// //// } +// //// +// //// bool IsValidField(IField field) +// //// { +// //// if (field == null || field.Attributes.Count > 0 || field.IsVolatile) +// //// return false; +// //// foreach (var m in typeStack.Peek().Members.OfType()) { +// //// foreach (var i in m.Variables) { +// //// if (i.StartLocation == field.BodyRegion.Begin) { +// //// if (!i.Initializer.IsNull) +// //// return false; +// //// break; +// //// } +// //// } +// //// } +// //// return true; +// //// } +// //// +// //// public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration) +// //// { +// //// var field = RemoveBackingStoreAction.GetBackingField(ctx, propertyDeclaration); +// //// if (!IsValidField(field)) +// //// return; +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// propertyDeclaration.NameToken, +// //// ctx.TranslateString("Convert to auto property") +// //// ) { +// //// ActionProvider = { typeof (RemoveBackingStoreAction) } +// //// } +// //// ); +// //// } +// //// +// //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) +// //// { +// //// typeStack.Push(typeDeclaration); +// //// base.VisitTypeDeclaration(typeDeclaration); +// //// typeStack.Pop(); +// //// } +// // } +// } -} \ No newline at end of file +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertToLambdaExpressionAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertToLambdaExpressionAnalyzer.cs index 10816fe2..c84b93aa 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertToLambdaExpressionAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ConvertToLambdaExpressionAnalyzer.cs @@ -1,123 +1,123 @@ -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 ConvertToLambdaExpressionAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.ConvertToLambdaExpressionAnalyzerID, - GettextCatalog.GetString("Convert to lambda with expression"), - GettextCatalog.GetString("Can be converted to expression"), - DiagnosticAnalyzerCategories.Opportunities, - DiagnosticSeverity.Info, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ConvertToLambdaExpressionAnalyzerID) - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class ConvertToLambdaExpressionAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.ConvertToLambdaExpressionAnalyzerID, +// GettextCatalog.GetString("Convert to lambda with expression"), +// GettextCatalog.GetString("Can be converted to expression"), +// DiagnosticAnalyzerCategories.Opportunities, +// DiagnosticSeverity.Info, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ConvertToLambdaExpressionAnalyzerID) +// ); - 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 VisitLambdaExpression(LambdaExpression lambdaExpression) - //// { - //// base.VisitLambdaExpression(lambdaExpression); - //// BlockStatement block; - //// Expression expr; - //// if (!ConvertLambdaBodyStatementToExpressionAction.TryGetConvertableExpression(lambdaExpression.Body, out block, out expr)) - //// return; - //// var node = block.Statements.FirstOrDefault() ?? block; - //// var expressionStatement = node as ExpressionStatement; - //// if (expressionStatement != null) { - //// if (expressionStatement.Expression is AssignmentExpression) - //// return; - //// } - //// var returnTypes = new List(); - //// foreach (var type in TypeGuessing.GetValidTypes(ctx.Resolver, lambdaExpression)) { - //// if (type.Kind != TypeKind.Delegate) - //// continue; - //// var invoke = type.GetDelegateInvokeMethod(); - //// if (!returnTypes.Contains(invoke.ReturnType)) - //// returnTypes.Add(invoke.ReturnType); - //// } - //// if (returnTypes.Count > 1) - //// return; - //// - //// AddDiagnosticAnalyzer(new CodeIssue( - //// node, - //// ctx.TranslateString(""), - //// ConvertLambdaBodyStatementToExpressionAction.CreateAction(ctx, node, block, expr) - //// )); - //// } - //// - //// public override void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression) - //// { - //// base.VisitAnonymousMethodExpression(anonymousMethodExpression); - //// if (!anonymousMethodExpression.HasParameterList) - //// return; - //// BlockStatement block; - //// Expression expr; - //// if (!ConvertLambdaBodyStatementToExpressionAction.TryGetConvertableExpression(anonymousMethodExpression.Body, out block, out expr)) - //// return; - //// var node = block.Statements.FirstOrDefault() ?? block; - //// var returnTypes = new List(); - //// foreach (var type in TypeGuessing.GetValidTypes(ctx.Resolver, anonymousMethodExpression)) { - //// if (type.Kind != TypeKind.Delegate) - //// continue; - //// var invoke = type.GetDelegateInvokeMethod(); - //// if (!returnTypes.Contains(invoke.ReturnType)) - //// returnTypes.Add(invoke.ReturnType); - //// } - //// if (returnTypes.Count > 1) - //// return; - //// - //// AddDiagnosticAnalyzer(new CodeIssue( - //// node, - //// ctx.TranslateString(""), - //// ctx.TranslateString("Convert to lambda expression"), - //// script => { - //// var lambdaExpression = new LambdaExpression(); - //// foreach (var parameter in anonymousMethodExpression.Parameters) - //// lambdaExpression.Parameters.Add(parameter.Clone()); - //// lambdaExpression.Body = expr.Clone(); - //// script.Replace(anonymousMethodExpression, lambdaExpression); - //// } - //// )); - //// } - // } - } +// // class GatherVisitor : GatherVisitorBase +// // { +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // } +// //// +// //// public override void VisitLambdaExpression(LambdaExpression lambdaExpression) +// //// { +// //// base.VisitLambdaExpression(lambdaExpression); +// //// BlockStatement block; +// //// Expression expr; +// //// if (!ConvertLambdaBodyStatementToExpressionAction.TryGetConvertableExpression(lambdaExpression.Body, out block, out expr)) +// //// return; +// //// var node = block.Statements.FirstOrDefault() ?? block; +// //// var expressionStatement = node as ExpressionStatement; +// //// if (expressionStatement != null) { +// //// if (expressionStatement.Expression is AssignmentExpression) +// //// return; +// //// } +// //// var returnTypes = new List(); +// //// foreach (var type in TypeGuessing.GetValidTypes(ctx.Resolver, lambdaExpression)) { +// //// if (type.Kind != TypeKind.Delegate) +// //// continue; +// //// var invoke = type.GetDelegateInvokeMethod(); +// //// if (!returnTypes.Contains(invoke.ReturnType)) +// //// returnTypes.Add(invoke.ReturnType); +// //// } +// //// if (returnTypes.Count > 1) +// //// return; +// //// +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// node, +// //// ctx.TranslateString(""), +// //// ConvertLambdaBodyStatementToExpressionAction.CreateAction(ctx, node, block, expr) +// //// )); +// //// } +// //// +// //// public override void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression) +// //// { +// //// base.VisitAnonymousMethodExpression(anonymousMethodExpression); +// //// if (!anonymousMethodExpression.HasParameterList) +// //// return; +// //// BlockStatement block; +// //// Expression expr; +// //// if (!ConvertLambdaBodyStatementToExpressionAction.TryGetConvertableExpression(anonymousMethodExpression.Body, out block, out expr)) +// //// return; +// //// var node = block.Statements.FirstOrDefault() ?? block; +// //// var returnTypes = new List(); +// //// foreach (var type in TypeGuessing.GetValidTypes(ctx.Resolver, anonymousMethodExpression)) { +// //// if (type.Kind != TypeKind.Delegate) +// //// continue; +// //// var invoke = type.GetDelegateInvokeMethod(); +// //// if (!returnTypes.Contains(invoke.ReturnType)) +// //// returnTypes.Add(invoke.ReturnType); +// //// } +// //// if (returnTypes.Count > 1) +// //// return; +// //// +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// node, +// //// ctx.TranslateString(""), +// //// ctx.TranslateString("Convert to lambda expression"), +// //// script => { +// //// var lambdaExpression = new LambdaExpression(); +// //// foreach (var parameter in anonymousMethodExpression.Parameters) +// //// lambdaExpression.Parameters.Add(parameter.Clone()); +// //// lambdaExpression.Body = expr.Clone(); +// //// script.Replace(anonymousMethodExpression, lambdaExpression); +// //// } +// //// )); +// //// } +// // } +// } -} \ No newline at end of file +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ForCanBeConvertedToForeachAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ForCanBeConvertedToForeachAnalyzer.cs index 511dfc31..db71f3ea 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ForCanBeConvertedToForeachAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/Opportunities/ForCanBeConvertedToForeachAnalyzer.cs @@ -1,228 +1,228 @@ -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 ForCanBeConvertedToForeachAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.ForCanBeConvertedToForeachAnalyzerID, - GettextCatalog.GetString("Foreach loops are more efficient"), - GettextCatalog.GetString("'for' loop can be converted to 'foreach'"), - DiagnosticAnalyzerCategories.Opportunities, - DiagnosticSeverity.Warning, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ForCanBeConvertedToForeachAnalyzerID) - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class ForCanBeConvertedToForeachAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.ForCanBeConvertedToForeachAnalyzerID, +// GettextCatalog.GetString("Foreach loops are more efficient"), +// GettextCatalog.GetString("'for' loop can be converted to 'foreach'"), +// DiagnosticAnalyzerCategories.Opportunities, +// DiagnosticSeverity.Warning, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ForCanBeConvertedToForeachAnalyzerID) +// ); - 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) - // { - // } - //// - //// static readonly AstNode forPattern = - //// new Choice { - //// new ForStatement { - //// Initializers = { - //// new VariableDeclarationStatement { - //// Type = new AnyNode("int"), - //// Variables = { - //// new NamedNode("iteratorInitialzer", new VariableInitializer(Pattern.AnyString, new PrimitiveExpression(0))) - //// } - //// } - //// }, - //// Condition = PatternHelper.OptionalParentheses( - //// new BinaryOperatorExpression( - //// PatternHelper.OptionalParentheses(new AnyNode("iterator")), - //// BinaryOperatorType.LessThan, - //// PatternHelper.OptionalParentheses( - //// new NamedNode("upperBound", new MemberReferenceExpression(new AnyNode (), Pattern.AnyString)) - //// ) - //// ) - //// ), - //// Iterators = { - //// new ExpressionStatement( - //// new Choice { - //// new UnaryOperatorExpression(UnaryOperatorType.Increment, new Backreference("iterator")), - //// new UnaryOperatorExpression(UnaryOperatorType.PostIncrement, new Backreference("iterator")) - //// } - //// ) - //// }, - //// EmbeddedStatement = new AnyNode("body") - //// }, - //// new ForStatement { - //// Initializers = { - //// new VariableDeclarationStatement { - //// Type = new AnyNode("int"), - //// Variables = { - //// new NamedNode("iteratorInitialzer", new VariableInitializer(Pattern.AnyString, new PrimitiveExpression(0))), - //// new NamedNode("upperBoundInitializer", new VariableInitializer(Pattern.AnyString, new NamedNode("upperBound", new MemberReferenceExpression(new AnyNode (), Pattern.AnyString)))), - //// } - //// } - //// }, - //// Condition = PatternHelper.OptionalParentheses( - //// new BinaryOperatorExpression( - //// PatternHelper.OptionalParentheses(new AnyNode("iterator")), - //// BinaryOperatorType.LessThan, - //// PatternHelper.OptionalParentheses( - //// new AnyNode("upperBoundInitializerName") - //// ) - //// ) - //// ), - //// Iterators = { - //// new ExpressionStatement( - //// new Choice { - //// new UnaryOperatorExpression(UnaryOperatorType.Increment, new Backreference("iterator")), - //// new UnaryOperatorExpression(UnaryOperatorType.PostIncrement, new Backreference("iterator")) - //// } - //// ) - //// }, - //// EmbeddedStatement = new AnyNode("body") - //// }, - //// }; - //// static readonly AstNode varDeclPattern = - //// new VariableDeclarationStatement { - //// Type = new AnyNode(), - //// Variables = { - //// new VariableInitializer(Pattern.AnyString, new NamedNode("indexer", new IndexerExpression(new AnyNode(), new IdentifierExpression(Pattern.AnyString)))) - //// } - //// }; - //// static readonly AstNode varTypePattern = - //// new SimpleType("var"); - //// - //// static bool IsEnumerable(IType type) - //// { - //// return type.Name == "IEnumerable" && (type.Namespace == "System.Collections.Generic" || type.Namespace == "System.Collections"); - //// } - //// - //// public override void VisitForStatement(ForStatement forStatement) - //// { - //// base.VisitForStatement(forStatement); - //// var forMatch = forPattern.Match(forStatement); - //// if (!forMatch.Success) - //// return; - //// var body = forStatement.EmbeddedStatement as BlockStatement; - //// if (body == null || !body.Statements.Any()) - //// return; - //// var varDeclStmt = body.Statements.First() as VariableDeclarationStatement; - //// if (varDeclStmt == null) - //// return; - //// var varMatch = varDeclPattern.Match(varDeclStmt); - //// if (!varMatch.Success) - //// return; - //// var typeNode = forMatch.Get("int").FirstOrDefault(); - //// var varDecl = forMatch.Get("iteratorInitialzer").FirstOrDefault(); - //// var iterator = forMatch.Get("iterator").FirstOrDefault(); - //// var upperBound = forMatch.Get("upperBound").FirstOrDefault(); - //// if (typeNode == null || varDecl == null || iterator == null || upperBound == null) - //// return; - //// - //// // Check iterator type - //// if (!varTypePattern.IsMatch(typeNode)) { - //// var typeRR = ctx.Resolve(typeNode); - //// if (!typeRR.Type.IsKnownType(KnownTypeCode.Int32)) - //// return; - //// } - //// - //// if (varDecl.Name != iterator.Identifier) - //// return; - //// - //// var upperBoundInitializer = forMatch.Get("upperBoundInitializer").FirstOrDefault(); - //// var upperBoundInitializerName = forMatch.Get("upperBoundInitializerName").FirstOrDefault(); - //// if (upperBoundInitializer != null) { - //// if (upperBoundInitializerName == null || upperBoundInitializer.Name != upperBoundInitializerName.Identifier) - //// return; - //// } - //// - //// var indexer = varMatch.Get("indexer").Single(); - //// if (((IdentifierExpression)indexer.Arguments.First()).Identifier != iterator.Identifier) - //// return; - //// if (!indexer.Target.IsMatch(upperBound.Target)) - //// return; - //// - //// var rr = ctx.Resolve(upperBound) as MemberResolveResult; - //// if (rr == null || rr.IsError) - //// return; - //// - //// if (!(rr.Member.Name == "Length" && rr.Member.DeclaringType.Name == "Array" && rr.Member.DeclaringType.Namespace == "System") && - //// !(rr.Member.Name == "Count" && (IsEnumerable(rr.TargetResult.Type) || rr.TargetResult.Type.GetAllBaseTypes().Any(IsEnumerable)))) - //// return; - //// - //// var variableInitializer = varDeclStmt.Variables.First(); - //// var lr = ctx.Resolve(variableInitializer) as LocalResolveResult; - //// if (lr == null) - //// return; - //// - //// var ir = ctx.Resolve(varDecl) as LocalResolveResult; - //// if (ir == null) - //// return; - //// - //// var analyze = new ConvertToConstantAnalyzer.VariableUsageAnalyzation(ctx); - //// analyze.SetAnalyzedRange( - //// varDeclStmt, - //// forStatement.EmbeddedStatement, - //// false - //// ); - //// forStatement.EmbeddedStatement.AcceptVisitor(analyze); - //// if (analyze.GetStatus(lr.Variable) == RefactoringEssentials.Refactoring.ExtractMethod.VariableState.Changed || - //// analyze.GetStatus(ir.Variable) == RefactoringEssentials.Refactoring.ExtractMethod.VariableState.Changed || - //// analyze.GetStatus(ir.Variable) == RefactoringEssentials.Refactoring.ExtractMethod.VariableState.Used) - //// return; - //// - //// AddDiagnosticAnalyzer(new CodeIssue( - //// forStatement.ForToken, - //// ctx.TranslateString(""), - //// ctx.TranslateString(""), - //// script => { - //// var foreachBody = (BlockStatement)forStatement.EmbeddedStatement.Clone(); - //// foreachBody.Statements.First().Remove(); - //// - //// var fe = new ForeachStatement { - //// VariableType = new PrimitiveType("var"), - //// VariableName = variableInitializer.Name, - //// InExpression = upperBound.Target.Clone(), - //// EmbeddedStatement = foreachBody - //// }; - //// script.Replace(forStatement, fe); - //// } - //// ) { IssueMarker = IssueMarker.DottedLine }); - //// - //// } - // } - } +// // class GatherVisitor : GatherVisitorBase +// // { +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // } +// //// +// //// static readonly AstNode forPattern = +// //// new Choice { +// //// new ForStatement { +// //// Initializers = { +// //// new VariableDeclarationStatement { +// //// Type = new AnyNode("int"), +// //// Variables = { +// //// new NamedNode("iteratorInitialzer", new VariableInitializer(Pattern.AnyString, new PrimitiveExpression(0))) +// //// } +// //// } +// //// }, +// //// Condition = PatternHelper.OptionalParentheses( +// //// new BinaryOperatorExpression( +// //// PatternHelper.OptionalParentheses(new AnyNode("iterator")), +// //// BinaryOperatorType.LessThan, +// //// PatternHelper.OptionalParentheses( +// //// new NamedNode("upperBound", new MemberReferenceExpression(new AnyNode (), Pattern.AnyString)) +// //// ) +// //// ) +// //// ), +// //// Iterators = { +// //// new ExpressionStatement( +// //// new Choice { +// //// new UnaryOperatorExpression(UnaryOperatorType.Increment, new Backreference("iterator")), +// //// new UnaryOperatorExpression(UnaryOperatorType.PostIncrement, new Backreference("iterator")) +// //// } +// //// ) +// //// }, +// //// EmbeddedStatement = new AnyNode("body") +// //// }, +// //// new ForStatement { +// //// Initializers = { +// //// new VariableDeclarationStatement { +// //// Type = new AnyNode("int"), +// //// Variables = { +// //// new NamedNode("iteratorInitialzer", new VariableInitializer(Pattern.AnyString, new PrimitiveExpression(0))), +// //// new NamedNode("upperBoundInitializer", new VariableInitializer(Pattern.AnyString, new NamedNode("upperBound", new MemberReferenceExpression(new AnyNode (), Pattern.AnyString)))), +// //// } +// //// } +// //// }, +// //// Condition = PatternHelper.OptionalParentheses( +// //// new BinaryOperatorExpression( +// //// PatternHelper.OptionalParentheses(new AnyNode("iterator")), +// //// BinaryOperatorType.LessThan, +// //// PatternHelper.OptionalParentheses( +// //// new AnyNode("upperBoundInitializerName") +// //// ) +// //// ) +// //// ), +// //// Iterators = { +// //// new ExpressionStatement( +// //// new Choice { +// //// new UnaryOperatorExpression(UnaryOperatorType.Increment, new Backreference("iterator")), +// //// new UnaryOperatorExpression(UnaryOperatorType.PostIncrement, new Backreference("iterator")) +// //// } +// //// ) +// //// }, +// //// EmbeddedStatement = new AnyNode("body") +// //// }, +// //// }; +// //// static readonly AstNode varDeclPattern = +// //// new VariableDeclarationStatement { +// //// Type = new AnyNode(), +// //// Variables = { +// //// new VariableInitializer(Pattern.AnyString, new NamedNode("indexer", new IndexerExpression(new AnyNode(), new IdentifierExpression(Pattern.AnyString)))) +// //// } +// //// }; +// //// static readonly AstNode varTypePattern = +// //// new SimpleType("var"); +// //// +// //// static bool IsEnumerable(IType type) +// //// { +// //// return type.Name == "IEnumerable" && (type.Namespace == "System.Collections.Generic" || type.Namespace == "System.Collections"); +// //// } +// //// +// //// public override void VisitForStatement(ForStatement forStatement) +// //// { +// //// base.VisitForStatement(forStatement); +// //// var forMatch = forPattern.Match(forStatement); +// //// if (!forMatch.Success) +// //// return; +// //// var body = forStatement.EmbeddedStatement as BlockStatement; +// //// if (body == null || !body.Statements.Any()) +// //// return; +// //// var varDeclStmt = body.Statements.First() as VariableDeclarationStatement; +// //// if (varDeclStmt == null) +// //// return; +// //// var varMatch = varDeclPattern.Match(varDeclStmt); +// //// if (!varMatch.Success) +// //// return; +// //// var typeNode = forMatch.Get("int").FirstOrDefault(); +// //// var varDecl = forMatch.Get("iteratorInitialzer").FirstOrDefault(); +// //// var iterator = forMatch.Get("iterator").FirstOrDefault(); +// //// var upperBound = forMatch.Get("upperBound").FirstOrDefault(); +// //// if (typeNode == null || varDecl == null || iterator == null || upperBound == null) +// //// return; +// //// +// //// // Check iterator type +// //// if (!varTypePattern.IsMatch(typeNode)) { +// //// var typeRR = ctx.Resolve(typeNode); +// //// if (!typeRR.Type.IsKnownType(KnownTypeCode.Int32)) +// //// return; +// //// } +// //// +// //// if (varDecl.Name != iterator.Identifier) +// //// return; +// //// +// //// var upperBoundInitializer = forMatch.Get("upperBoundInitializer").FirstOrDefault(); +// //// var upperBoundInitializerName = forMatch.Get("upperBoundInitializerName").FirstOrDefault(); +// //// if (upperBoundInitializer != null) { +// //// if (upperBoundInitializerName == null || upperBoundInitializer.Name != upperBoundInitializerName.Identifier) +// //// return; +// //// } +// //// +// //// var indexer = varMatch.Get("indexer").Single(); +// //// if (((IdentifierExpression)indexer.Arguments.First()).Identifier != iterator.Identifier) +// //// return; +// //// if (!indexer.Target.IsMatch(upperBound.Target)) +// //// return; +// //// +// //// var rr = ctx.Resolve(upperBound) as MemberResolveResult; +// //// if (rr == null || rr.IsError) +// //// return; +// //// +// //// if (!(rr.Member.Name == "Length" && rr.Member.DeclaringType.Name == "Array" && rr.Member.DeclaringType.Namespace == "System") && +// //// !(rr.Member.Name == "Count" && (IsEnumerable(rr.TargetResult.Type) || rr.TargetResult.Type.GetAllBaseTypes().Any(IsEnumerable)))) +// //// return; +// //// +// //// var variableInitializer = varDeclStmt.Variables.First(); +// //// var lr = ctx.Resolve(variableInitializer) as LocalResolveResult; +// //// if (lr == null) +// //// return; +// //// +// //// var ir = ctx.Resolve(varDecl) as LocalResolveResult; +// //// if (ir == null) +// //// return; +// //// +// //// var analyze = new ConvertToConstantAnalyzer.VariableUsageAnalyzation(ctx); +// //// analyze.SetAnalyzedRange( +// //// varDeclStmt, +// //// forStatement.EmbeddedStatement, +// //// false +// //// ); +// //// forStatement.EmbeddedStatement.AcceptVisitor(analyze); +// //// if (analyze.GetStatus(lr.Variable) == RefactoringEssentials.Refactoring.ExtractMethod.VariableState.Changed || +// //// analyze.GetStatus(ir.Variable) == RefactoringEssentials.Refactoring.ExtractMethod.VariableState.Changed || +// //// analyze.GetStatus(ir.Variable) == RefactoringEssentials.Refactoring.ExtractMethod.VariableState.Used) +// //// return; +// //// +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// forStatement.ForToken, +// //// ctx.TranslateString(""), +// //// ctx.TranslateString(""), +// //// script => { +// //// var foreachBody = (BlockStatement)forStatement.EmbeddedStatement.Clone(); +// //// foreachBody.Statements.First().Remove(); +// //// +// //// var fe = new ForeachStatement { +// //// VariableType = new PrimitiveType("var"), +// //// VariableName = variableInitializer.Name, +// //// InExpression = upperBound.Target.Clone(), +// //// EmbeddedStatement = foreachBody +// //// }; +// //// script.Replace(forStatement, fe); +// //// } +// //// ) { IssueMarker = IssueMarker.DottedLine }); +// //// +// //// } +// // } +// } -} +//} diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ConvertToConstantAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ConvertToConstantAnalyzer.cs index 19217f51..54be1b98 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ConvertToConstantAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ConvertToConstantAnalyzer.cs @@ -1,318 +1,318 @@ -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 ConvertToConstantAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.ConvertToConstantAnalyzerID, - GettextCatalog.GetString("Convert local variable or field to constant"), - GettextCatalog.GetString("Convert to constant"), - DiagnosticAnalyzerCategories.PracticesAndImprovements, - DiagnosticSeverity.Info, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ConvertToConstantAnalyzerID) - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class ConvertToConstantAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.ConvertToConstantAnalyzerID, +// GettextCatalog.GetString("Convert local variable or field to constant"), +// GettextCatalog.GetString("Convert to constant"), +// DiagnosticAnalyzerCategories.PracticesAndImprovements, +// DiagnosticSeverity.Info, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ConvertToConstantAnalyzerID) +// ); - 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; - } - // - // internal static IEnumerable CollectFields(GatherVisitorBase provider, TypeDeclaration typeDeclaration) where T : CodeIssueProvider - // { - // var fieldVisitor = new ConvertToConstantAnalyzer.FieldCollectVisitor(provider.Ctx, typeDeclaration); - // typeDeclaration.AcceptVisitor(fieldVisitor); - // return fieldVisitor.CollectedFields; - // } - // - // class FieldCollectVisitor : GatherVisitorBase where T : CodeIssueProvider - // { - // readonly TypeDeclaration typeDeclaration; - // public readonly List CollectedFields = new List(); - // - // public FieldCollectVisitor(BaseSemanticModel context, TypeDeclaration typeDeclaration) : base (context) - // { - // this.typeDeclaration = typeDeclaration; - // } - // - // public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration) - // { - // if (IsSuppressed(fieldDeclaration.StartLocation)) - // return; - // CollectedFields.Add(fieldDeclaration); - // } - // - // public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) - // { - // if (typeDeclaration != this.typeDeclaration) - // return; - // base.VisitTypeDeclaration(typeDeclaration); - // } - // - // public override void VisitBlockStatement(BlockStatement blockStatement) - // { - // // SKIP - // } - // } - // - // class GatherVisitor : GatherVisitorBase - // { - //// readonly Stack>> fieldStack = new Stack>>(); +// 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; +// } +// // +// // internal static IEnumerable CollectFields(GatherVisitorBase provider, TypeDeclaration typeDeclaration) where T : CodeIssueProvider +// // { +// // var fieldVisitor = new ConvertToConstantAnalyzer.FieldCollectVisitor(provider.Ctx, typeDeclaration); +// // typeDeclaration.AcceptVisitor(fieldVisitor); +// // return fieldVisitor.CollectedFields; +// // } +// // +// // class FieldCollectVisitor : GatherVisitorBase where T : CodeIssueProvider +// // { +// // readonly TypeDeclaration typeDeclaration; +// // public readonly List CollectedFields = new List(); +// // +// // public FieldCollectVisitor(BaseSemanticModel context, TypeDeclaration typeDeclaration) : base (context) +// // { +// // this.typeDeclaration = typeDeclaration; +// // } +// // +// // public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration) +// // { +// // if (IsSuppressed(fieldDeclaration.StartLocation)) +// // return; +// // CollectedFields.Add(fieldDeclaration); +// // } +// // +// // public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) +// // { +// // if (typeDeclaration != this.typeDeclaration) +// // return; +// // base.VisitTypeDeclaration(typeDeclaration); +// // } +// // +// // public override void VisitBlockStatement(BlockStatement blockStatement) +// // { +// // // SKIP +// // } +// // } +// // +// // class GatherVisitor : GatherVisitorBase +// // { +// //// readonly Stack>> fieldStack = new Stack>>(); - // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) - // : base (semanticModel, addDiagnostic, cancellationToken) - // { - // } - //// - //// virtual void Collect() - //// { - //// foreach (var varDecl in fieldStack.Peek()) { - //// AddDiagnosticAnalyzer(new CodeIssue( - //// varDecl.Item1.NameToken, - //// ctx.TranslateString("Convert to constant"), - //// ctx.TranslateString("To const"), - //// script => { - //// var constVarDecl = (FieldDeclaration)varDecl.Item1.Parent; - //// script.ChangeModifier(constVarDecl, (constVarDecl.Modifiers & ~Modifiers.Static) | Modifiers.Const); - //// } - //// )); - //// } - //// } - //// - //// - //// public override void VisitBlockStatement(BlockStatement blockStatement) - //// { - //// base.VisitBlockStatement(blockStatement); - //// if (blockStatement.Parent is EntityDeclaration || blockStatement.Parent is Accessor) { - //// var assignmentAnalysis = new VariableUsageAnalyzation (ctx); - //// var newVars = new List>(); - //// blockStatement.AcceptVisitor(assignmentAnalysis); - //// foreach (var variable in fieldStack.Pop()) { - //// if (assignmentAnalysis.GetStatus(variable.Item2) == VariableState.Changed) - //// continue; - //// newVars.Add(variable); - //// } - //// fieldStack.Push(newVars); - //// } - //// } - //// - //// static bool IsValidConstType(IType type) - //// { - //// var def = type.GetDefinition(); - //// if (def == null) - //// return false; - //// return KnownTypeCode.Boolean <= def.KnownTypeCode && def.KnownTypeCode <= KnownTypeCode.Decimal || - //// def.KnownTypeCode == KnownTypeCode.String; - //// } - //// - //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) - //// { - //// var list = new List>(); - //// fieldStack.Push(list); - //// foreach (var fieldDeclaration in ConvertToConstantAnalyzer.CollectFields(this, typeDeclaration)) { - //// if (IsSuppressed(fieldDeclaration.StartLocation)) - //// continue; - //// if (fieldDeclaration.Modifiers.HasFlag (Modifiers.Const) || fieldDeclaration.Modifiers.HasFlag (Modifiers.Readonly)) - //// continue; - //// if (fieldDeclaration.HasModifier(Modifiers.Public) || fieldDeclaration.HasModifier(Modifiers.Protected) || fieldDeclaration.HasModifier(Modifiers.Internal)) - //// continue; - //// if (fieldDeclaration.Variables.Any (v => !ctx.Resolve (v.Initializer).IsCompileTimeConstant)) - //// continue; - //// var rr = ctx.Resolve(fieldDeclaration.ReturnType); - //// if (!IsValidConstType(rr.Type)) - //// continue; - //// if (fieldDeclaration.Variables.Count() > 1) - //// continue; - //// var variable = fieldDeclaration.Variables.First(); - //// var mr = ctx.Resolve(variable) as MemberResolveResult; - //// if (mr == null || !(mr.Member is IVariable)) - //// continue; - //// list.Add(Tuple.Create(variable, (IVariable)mr.Member)); - //// } - //// base.VisitTypeDeclaration(typeDeclaration); - //// Collect(); - //// fieldStack.Pop(); - //// } - //// - //// public override void VisitVariableDeclarationStatement (VariableDeclarationStatement varDecl) - //// { - //// base.VisitVariableDeclarationStatement(varDecl); - //// if (varDecl.Modifiers.HasFlag (Modifiers.Const) || varDecl.Role == ForStatement.InitializerRole) - //// return; - //// if (varDecl.Variables.Count () > 1) - //// return; - //// if (varDecl.Variables.Any (v => !ctx.Resolve (v.Initializer).IsCompileTimeConstant)) - //// return; - //// var containingBlock = varDecl.GetParent (); - //// if (containingBlock == null) - //// return; - //// - //// var returnTypeRR = ctx.Resolve(varDecl.Type); - //// if (returnTypeRR.Type.IsReferenceType.HasValue && returnTypeRR.Type.IsReferenceType.Value) - //// return; - //// - //// var variable = varDecl.Variables.First(); - //// var vr = ctx.Resolve(variable) as LocalResolveResult; - //// if (vr == null) - //// return; - //// - //// if (ctx.Resolve(variable.Initializer).ConstantValue == null) - //// return; - //// - //// var assignmentAnalysis = new VariableUsageAnalyzation (ctx); - //// - //// containingBlock.AcceptVisitor(assignmentAnalysis); - //// - //// if (assignmentAnalysis.GetStatus(vr.Variable) == VariableState.Changed) - //// return; - //// AddDiagnosticAnalyzer (new CodeIssue( - //// variable.NameToken, - //// ctx.TranslateString ("Convert to constant"), - //// ctx.TranslateString ("To const"), - //// script => { - //// var constVarDecl = (VariableDeclarationStatement)varDecl.Clone (); - //// constVarDecl.Modifiers |= Modifiers.Const; - //// if (varDecl.Type.IsVar()) { - //// var builder = ctx.CreateTypeSystemAstBuilder(varDecl); - //// constVarDecl.Type = builder.ConvertType (ctx.Resolve(varDecl.Type).Type); - //// } - //// script.Replace (varDecl, constVarDecl); - //// } - //// )); - //// } - //// - // } +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // } +// //// +// //// virtual void Collect() +// //// { +// //// foreach (var varDecl in fieldStack.Peek()) { +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// varDecl.Item1.NameToken, +// //// ctx.TranslateString("Convert to constant"), +// //// ctx.TranslateString("To const"), +// //// script => { +// //// var constVarDecl = (FieldDeclaration)varDecl.Item1.Parent; +// //// script.ChangeModifier(constVarDecl, (constVarDecl.Modifiers & ~Modifiers.Static) | Modifiers.Const); +// //// } +// //// )); +// //// } +// //// } +// //// +// //// +// //// public override void VisitBlockStatement(BlockStatement blockStatement) +// //// { +// //// base.VisitBlockStatement(blockStatement); +// //// if (blockStatement.Parent is EntityDeclaration || blockStatement.Parent is Accessor) { +// //// var assignmentAnalysis = new VariableUsageAnalyzation (ctx); +// //// var newVars = new List>(); +// //// blockStatement.AcceptVisitor(assignmentAnalysis); +// //// foreach (var variable in fieldStack.Pop()) { +// //// if (assignmentAnalysis.GetStatus(variable.Item2) == VariableState.Changed) +// //// continue; +// //// newVars.Add(variable); +// //// } +// //// fieldStack.Push(newVars); +// //// } +// //// } +// //// +// //// static bool IsValidConstType(IType type) +// //// { +// //// var def = type.GetDefinition(); +// //// if (def == null) +// //// return false; +// //// return KnownTypeCode.Boolean <= def.KnownTypeCode && def.KnownTypeCode <= KnownTypeCode.Decimal || +// //// def.KnownTypeCode == KnownTypeCode.String; +// //// } +// //// +// //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) +// //// { +// //// var list = new List>(); +// //// fieldStack.Push(list); +// //// foreach (var fieldDeclaration in ConvertToConstantAnalyzer.CollectFields(this, typeDeclaration)) { +// //// if (IsSuppressed(fieldDeclaration.StartLocation)) +// //// continue; +// //// if (fieldDeclaration.Modifiers.HasFlag (Modifiers.Const) || fieldDeclaration.Modifiers.HasFlag (Modifiers.Readonly)) +// //// continue; +// //// if (fieldDeclaration.HasModifier(Modifiers.Public) || fieldDeclaration.HasModifier(Modifiers.Protected) || fieldDeclaration.HasModifier(Modifiers.Internal)) +// //// continue; +// //// if (fieldDeclaration.Variables.Any (v => !ctx.Resolve (v.Initializer).IsCompileTimeConstant)) +// //// continue; +// //// var rr = ctx.Resolve(fieldDeclaration.ReturnType); +// //// if (!IsValidConstType(rr.Type)) +// //// continue; +// //// if (fieldDeclaration.Variables.Count() > 1) +// //// continue; +// //// var variable = fieldDeclaration.Variables.First(); +// //// var mr = ctx.Resolve(variable) as MemberResolveResult; +// //// if (mr == null || !(mr.Member is IVariable)) +// //// continue; +// //// list.Add(Tuple.Create(variable, (IVariable)mr.Member)); +// //// } +// //// base.VisitTypeDeclaration(typeDeclaration); +// //// Collect(); +// //// fieldStack.Pop(); +// //// } +// //// +// //// public override void VisitVariableDeclarationStatement (VariableDeclarationStatement varDecl) +// //// { +// //// base.VisitVariableDeclarationStatement(varDecl); +// //// if (varDecl.Modifiers.HasFlag (Modifiers.Const) || varDecl.Role == ForStatement.InitializerRole) +// //// return; +// //// if (varDecl.Variables.Count () > 1) +// //// return; +// //// if (varDecl.Variables.Any (v => !ctx.Resolve (v.Initializer).IsCompileTimeConstant)) +// //// return; +// //// var containingBlock = varDecl.GetParent (); +// //// if (containingBlock == null) +// //// return; +// //// +// //// var returnTypeRR = ctx.Resolve(varDecl.Type); +// //// if (returnTypeRR.Type.IsReferenceType.HasValue && returnTypeRR.Type.IsReferenceType.Value) +// //// return; +// //// +// //// var variable = varDecl.Variables.First(); +// //// var vr = ctx.Resolve(variable) as LocalResolveResult; +// //// if (vr == null) +// //// return; +// //// +// //// if (ctx.Resolve(variable.Initializer).ConstantValue == null) +// //// return; +// //// +// //// var assignmentAnalysis = new VariableUsageAnalyzation (ctx); +// //// +// //// containingBlock.AcceptVisitor(assignmentAnalysis); +// //// +// //// if (assignmentAnalysis.GetStatus(vr.Variable) == VariableState.Changed) +// //// return; +// //// AddDiagnosticAnalyzer (new CodeIssue( +// //// variable.NameToken, +// //// ctx.TranslateString ("Convert to constant"), +// //// ctx.TranslateString ("To const"), +// //// script => { +// //// var constVarDecl = (VariableDeclarationStatement)varDecl.Clone (); +// //// constVarDecl.Modifiers |= Modifiers.Const; +// //// if (varDecl.Type.IsVar()) { +// //// var builder = ctx.CreateTypeSystemAstBuilder(varDecl); +// //// constVarDecl.Type = builder.ConvertType (ctx.Resolve(varDecl.Type).Type); +// //// } +// //// script.Replace (varDecl, constVarDecl); +// //// } +// //// )); +// //// } +// //// +// // } - // - // public class VariableUsageAnalyzation : DepthFirstAstVisitor - // { - // readonly BaseSemanticModel context; - // - // readonly Dictionary states = new Dictionary (); - // - // TextLocation startLocation = TextLocation.Empty; - // TextLocation endLocation = TextLocation.Empty; - // - // public VariableUsageAnalyzation (BaseSemanticModel context) - // { - // this.context = context; - // } - // - // public bool Has(IVariable variable) - // { - // return states.ContainsKey (variable); - // } - // - // public void SetAnalyzedRange(AstNode start, AstNode end, bool startInclusive = true, bool endInclusive = true) - // { - // if (start == null) - // throw new ArgumentNullException("start"); - // if (end == null) - // throw new ArgumentNullException("end"); - // startLocation = startInclusive ? start.StartLocation : start.EndLocation; - // endLocation = endInclusive ? end.EndLocation : end.StartLocation; - // states.Clear (); - // } - // - // public VariableState GetStatus (IVariable variable) - // { - // VariableState state; - // if (!states.TryGetValue (variable, out state)) - // return VariableState.None; - // return state; - // } - // - // void SetState (ResolveResult rr, VariableState state) - // { - // IVariable variable = null; - // var lr = rr as LocalResolveResult; - // if (lr != null) - // variable = lr.Variable; - // var mr = rr as MemberResolveResult; - // if (mr != null) - // variable = mr.Member as IVariable; - // if (variable == null) - // return; - // var sv = variable as SpecializedField; - // if (sv != null) { - // variable = sv.MemberDefinition as IVariable; - // } - // VariableState oldState; - // if (states.TryGetValue (variable, out oldState)) { - // if (oldState < state) - // states [variable] = state; - // } else { - // states [variable] = state; - // } - // } - // - // public override void VisitIdentifierExpression(IdentifierExpression identifierExpression) - // { - // if (startLocation.IsEmpty || startLocation <= identifierExpression.StartLocation && identifierExpression.EndLocation <= endLocation) { - // SetState (context.Resolve(identifierExpression), VariableState.Used); - // } - // } - // - // public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression) - // { - // if (startLocation.IsEmpty || startLocation <= assignmentExpression.StartLocation && assignmentExpression.EndLocation <= endLocation) { - // SetState(context.Resolve(assignmentExpression.Left), VariableState.Changed); - // } - // base.VisitAssignmentExpression (assignmentExpression); - // } - // - // public override void VisitDirectionExpression(DirectionExpression directionExpression) - // { - // if (startLocation.IsEmpty || startLocation <= directionExpression.StartLocation && directionExpression.EndLocation <= endLocation) { - // SetState(context.Resolve(directionExpression.Expression), VariableState.Changed); - // } - // base.VisitDirectionExpression (directionExpression); - // } - // - // public override void VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression) - // { - // if (startLocation.IsEmpty || startLocation <= unaryOperatorExpression.StartLocation && unaryOperatorExpression.EndLocation <= endLocation) { - // if (unaryOperatorExpression.Operator == UnaryOperatorType.Increment || unaryOperatorExpression.Operator == UnaryOperatorType.Decrement || - // unaryOperatorExpression.Operator == UnaryOperatorType.PostIncrement || unaryOperatorExpression.Operator == UnaryOperatorType.PostDecrement) { - // SetState(context.Resolve(unaryOperatorExpression.Expression), VariableState.Changed); - // } - // } - // base.VisitUnaryOperatorExpression (unaryOperatorExpression); - // } - // - // public override void VisitNamedExpression(NamedExpression namedExpression) - // { - // SetState(context.Resolve(namedExpression), VariableState.Changed); - // base.VisitNamedExpression(namedExpression); - // } - // - // } - // - } -} \ No newline at end of file +// // +// // public class VariableUsageAnalyzation : DepthFirstAstVisitor +// // { +// // readonly BaseSemanticModel context; +// // +// // readonly Dictionary states = new Dictionary (); +// // +// // TextLocation startLocation = TextLocation.Empty; +// // TextLocation endLocation = TextLocation.Empty; +// // +// // public VariableUsageAnalyzation (BaseSemanticModel context) +// // { +// // this.context = context; +// // } +// // +// // public bool Has(IVariable variable) +// // { +// // return states.ContainsKey (variable); +// // } +// // +// // public void SetAnalyzedRange(AstNode start, AstNode end, bool startInclusive = true, bool endInclusive = true) +// // { +// // if (start == null) +// // throw new ArgumentNullException("start"); +// // if (end == null) +// // throw new ArgumentNullException("end"); +// // startLocation = startInclusive ? start.StartLocation : start.EndLocation; +// // endLocation = endInclusive ? end.EndLocation : end.StartLocation; +// // states.Clear (); +// // } +// // +// // public VariableState GetStatus (IVariable variable) +// // { +// // VariableState state; +// // if (!states.TryGetValue (variable, out state)) +// // return VariableState.None; +// // return state; +// // } +// // +// // void SetState (ResolveResult rr, VariableState state) +// // { +// // IVariable variable = null; +// // var lr = rr as LocalResolveResult; +// // if (lr != null) +// // variable = lr.Variable; +// // var mr = rr as MemberResolveResult; +// // if (mr != null) +// // variable = mr.Member as IVariable; +// // if (variable == null) +// // return; +// // var sv = variable as SpecializedField; +// // if (sv != null) { +// // variable = sv.MemberDefinition as IVariable; +// // } +// // VariableState oldState; +// // if (states.TryGetValue (variable, out oldState)) { +// // if (oldState < state) +// // states [variable] = state; +// // } else { +// // states [variable] = state; +// // } +// // } +// // +// // public override void VisitIdentifierExpression(IdentifierExpression identifierExpression) +// // { +// // if (startLocation.IsEmpty || startLocation <= identifierExpression.StartLocation && identifierExpression.EndLocation <= endLocation) { +// // SetState (context.Resolve(identifierExpression), VariableState.Used); +// // } +// // } +// // +// // public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression) +// // { +// // if (startLocation.IsEmpty || startLocation <= assignmentExpression.StartLocation && assignmentExpression.EndLocation <= endLocation) { +// // SetState(context.Resolve(assignmentExpression.Left), VariableState.Changed); +// // } +// // base.VisitAssignmentExpression (assignmentExpression); +// // } +// // +// // public override void VisitDirectionExpression(DirectionExpression directionExpression) +// // { +// // if (startLocation.IsEmpty || startLocation <= directionExpression.StartLocation && directionExpression.EndLocation <= endLocation) { +// // SetState(context.Resolve(directionExpression.Expression), VariableState.Changed); +// // } +// // base.VisitDirectionExpression (directionExpression); +// // } +// // +// // public override void VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression) +// // { +// // if (startLocation.IsEmpty || startLocation <= unaryOperatorExpression.StartLocation && unaryOperatorExpression.EndLocation <= endLocation) { +// // if (unaryOperatorExpression.Operator == UnaryOperatorType.Increment || unaryOperatorExpression.Operator == UnaryOperatorType.Decrement || +// // unaryOperatorExpression.Operator == UnaryOperatorType.PostIncrement || unaryOperatorExpression.Operator == UnaryOperatorType.PostDecrement) { +// // SetState(context.Resolve(unaryOperatorExpression.Expression), VariableState.Changed); +// // } +// // } +// // base.VisitUnaryOperatorExpression (unaryOperatorExpression); +// // } +// // +// // public override void VisitNamedExpression(NamedExpression namedExpression) +// // { +// // SetState(context.Resolve(namedExpression), VariableState.Changed); +// // base.VisitNamedExpression(namedExpression); +// // } +// // +// // } +// // +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ParameterCanBeDeclaredWithBaseTypeAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ParameterCanBeDeclaredWithBaseTypeAnalyzer.cs index b57976e5..40f6b678 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ParameterCanBeDeclaredWithBaseTypeAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ParameterCanBeDeclaredWithBaseTypeAnalyzer.cs @@ -1,557 +1,557 @@ -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 ParameterCanBeDeclaredWithBaseTypeAnalyzer : DiagnosticAnalyzer - { - //bool tryResolve; +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class ParameterCanBeDeclaredWithBaseTypeAnalyzer : DiagnosticAnalyzer +// { +// //bool tryResolve; - public ParameterCanBeDeclaredWithBaseTypeAnalyzer() : this(true) - { - } +// public ParameterCanBeDeclaredWithBaseTypeAnalyzer() : this(true) +// { +// } - public ParameterCanBeDeclaredWithBaseTypeAnalyzer(bool tryResolve) - { - //this.tryResolve = tryResolve; - } +// public ParameterCanBeDeclaredWithBaseTypeAnalyzer(bool tryResolve) +// { +// //this.tryResolve = tryResolve; +// } - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.ParameterCanBeDeclaredWithBaseTypeAnalyzerID, - GettextCatalog.GetString("Finds parameters that can be demoted to a base class"), - GettextCatalog.GetString("Parameter can be declared with base type"), - DiagnosticAnalyzerCategories.RedundanciesInCode, - DiagnosticSeverity.Info, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ParameterCanBeDeclaredWithBaseTypeAnalyzerID) - ); +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.ParameterCanBeDeclaredWithBaseTypeAnalyzerID, +// GettextCatalog.GetString("Finds parameters that can be demoted to a base class"), +// GettextCatalog.GetString("Parameter can be declared with base type"), +// DiagnosticAnalyzerCategories.RedundanciesInCode, +// DiagnosticSeverity.Info, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ParameterCanBeDeclaredWithBaseTypeAnalyzerID) +// ); - 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 tryResolve; +// // class GatherVisitor : GatherVisitorBase +// // { +// // //bool tryResolve; - // 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 VisitMethodDeclaration(MethodDeclaration methodDeclaration) - //// { - //// methodDeclaration.Attributes.AcceptVisitor(this); - //// if (HasEntryPointSignature(methodDeclaration) || methodDeclaration.HasModifier(Modifiers.Public) || methodDeclaration.HasModifier(Modifiers.Protected)) - //// return; - //// var eligibleParameters = methodDeclaration.Parameters - //// .Where(p => p.ParameterModifier != ParameterModifier.Out && p.ParameterModifier != ParameterModifier.Ref) - //// .ToList(); - //// if (eligibleParameters.Count == 0) - //// return; - //// var declarationResolveResult = ctx.Resolve(methodDeclaration) as MemberResolveResult; - //// if (declarationResolveResult == null) - //// return; - //// var member = declarationResolveResult.Member; - //// if (member.IsOverride || member.IsOverridable || member.ImplementedInterfaceMembers.Any()) - //// return; - //// - //// var collector = new TypeCriteriaCollector(ctx); - //// methodDeclaration.AcceptVisitor(collector); - //// - //// foreach (var parameter in eligibleParameters) { - //// ProcessParameter(parameter, methodDeclaration.Body, collector); - //// } - //// } - //// - //// bool HasEntryPointSignature(MethodDeclaration methodDeclaration) - //// { - //// if (!methodDeclaration.Modifiers.HasFlag(Modifiers.Static)) - //// return false; - //// var returnType = ctx.Resolve(methodDeclaration.ReturnType).Type; - //// if (!returnType.IsKnownType(KnownTypeCode.Int32) && !returnType.IsKnownType(KnownTypeCode.Void)) - //// return false; - //// var parameterCount = methodDeclaration.Parameters.Count; - //// if (parameterCount == 0) - //// return true; - //// if (parameterCount != 1) - //// return false; - //// var parameterType = ctx.Resolve(methodDeclaration.Parameters.First()).Type as ArrayType; - //// if (parameterType == null || !parameterType.ElementType.IsKnownType(KnownTypeCode.String)) - //// return false; - //// return true; - //// } - //// - //// bool FilterOut(IType current, IType newType) - //// { - //// // Filter out some strange framework types like _Exception - //// return newType.Namespace.StartsWith("System.", StringComparison.Ordinal) && - //// newType.Name.StartsWith("_", StringComparison.Ordinal) ? true : false; - //// } - //// - //// void ProcessParameter(ParameterDeclaration parameter, AstNode rootResolutionNode, TypeCriteriaCollector collector) - //// { - //// var localResolveResult = ctx.Resolve(parameter) as LocalResolveResult; - //// if (localResolveResult == null) - //// return; - //// var variable = localResolveResult.Variable; - //// var typeKind = variable.Type.Kind; - //// if (!(typeKind == TypeKind.Class || - //// typeKind == TypeKind.Struct || - //// typeKind == TypeKind.Interface || - //// typeKind == TypeKind.Array) || - //// parameter.Type is PrimitiveType || - //// !collector.UsedVariables.Contains(variable)) { - //// return; - //// } - //// - //// var candidateTypes = localResolveResult.Type.GetAllBaseTypes().ToList(); - //// TypesChecked += candidateTypes.Count; - //// var criterion = collector.GetCriterion(variable); - //// - //// var possibleTypes = - //// (from type in candidateTypes - //// where !type.Equals(localResolveResult.Type) && criterion.SatisfiedBy(type) - //// select type).ToList(); - //// - //// TypeResolveCount += possibleTypes.Count; - //// var validTypes = - //// (from type in possibleTypes - //// where (!tryResolve || TypeChangeResolvesCorrectly(ctx, parameter, rootResolutionNode, type)) && !FilterOut (variable.Type, type) - //// select type).ToList(); - //// if (validTypes.Any()) { - // // AddDiagnosticAnalyzer(new CodeIssue(parameter.Type, ctx.TranslateString("Parameter can be declared with base type"), GetActions(parameter, validTypes)) { - //// IssueMarker = IssueMarker.DottedLine - //// }); - //// MembersWithIssues++; - //// } - //// } - //// - //// internal int TypeResolveCount = 0; - //// internal int TypesChecked = 0; - //// internal int MembersWithIssues = 0; - //// internal int MethodResolveCount = 0; - //// - //// IEnumerable GetActions(ParameterDeclaration parameter, IEnumerable possibleTypes) - //// { - //// var csResolver = ctx.Resolver.GetResolverStateBefore(parameter); - //// var astBuilder = new TypeSystemAstBuilder(csResolver); - //// foreach (var type in possibleTypes) { - //// var localType = type; - //// var message = String.Format(ctx.TranslateString("Demote parameter to '{0}'"), type.FullName); - //// yield return new CodeAction(message, script => { - //// script.Replace(parameter.Type, astBuilder.ConvertType(localType)); - //// }, parameter.Type); - //// } - //// } - //// } - //// - //// public static bool TypeChangeResolvesCorrectly(BaseSemanticModel ctx, ParameterDeclaration parameter, AstNode rootNode, IType type) - //// { - //// var resolver = ctx.GetResolverStateBefore(rootNode); - //// resolver = resolver.AddVariable(new DefaultParameter(type, parameter.Name)); - //// var astResolver = new CSharpAstResolver(resolver, rootNode, ctx.UnresolvedFile); - //// var validator = new TypeChangeValidationNavigator(); - //// astResolver.ApplyNavigator(validator, ctx.CancellationToken); - //// return !validator.FoundErrors; - //// } - //// - //// class TypeChangeValidationNavigator : IResolveVisitorNavigator - //// { - //// public bool FoundErrors { get; private set; } - //// - //// #region IResolveVisitorNavigator implementation - //// public ResolveVisitorNavigationMode Scan(AstNode node) - //// { - //// if (FoundErrors) - //// return ResolveVisitorNavigationMode.Skip; - //// return ResolveVisitorNavigationMode.Resolve; - //// } - //// - //// public void Resolved(AstNode node, ResolveResult result) - //// { - ////// bool errors = result.IsError; - //// FoundErrors |= result.IsError; - //// } - //// - //// public void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType) - //// { - //// // no-op - //// } - //// #endregion - //// - //// } - // } - // - // public interface ITypeCriterion - // { - // /// - // /// Checks if the given type satisfies the critrion. - // /// - // /// - // /// true, if the type satisfies the criterion, false otherwise. - // /// - // /// - // /// The type to check. - // /// - // bool SatisfiedBy(IType type); - // } - // - // public class SupportsIndexingCriterion : ITypeCriterion - // { - // IType returnType; - // - // IList argumentTypes; - // - // CSharpConversions conversions; - // - // bool isWriteAccess; - // - // public SupportsIndexingCriterion(IType returnType, IEnumerable argumentTypes, CSharpConversions conversions, bool isWriteAccess = false) - // { - // if (returnType == null) - // throw new ArgumentNullException("returnType"); - // if (argumentTypes == null) - // throw new ArgumentNullException("argumentTypes"); - // if (conversions == null) - // throw new ArgumentNullException("conversions"); - // - // this.returnType = returnType; - // this.argumentTypes = argumentTypes.ToList(); - // this.conversions = conversions; - // this.isWriteAccess = isWriteAccess; - // } - // - // #region ITypeCriterion implementation - // - // public bool SatisfiedBy(IType type) - // { - // var accessors = type.GetAccessors().ToList(); - // return accessors.Any(member => { - // var parameterizedMember = member as IParameterizedMember; - // if (parameterizedMember == null) - // return false; - // - // if (isWriteAccess) { - // var parameterCount = member.Parameters.Count; - // if (member.Name != "set_Item" || parameterCount < 2) - // return false; - // var indexerElementType = parameterizedMember.Parameters.Last().Type; - // var indexerParameterTypes = parameterizedMember.Parameters.Take(parameterCount - 1).Select(p => p.Type).ToList(); - // return IsSignatureMatch(indexerElementType, indexerParameterTypes); - // } else { - // if (member.Name != "get_Item" || member.Parameters.Count < 1) - // return false; - // var indexerElementType = parameterizedMember.ReturnType; - // var indexerParameterTypes = parameterizedMember.Parameters.Select(p => p.Type).ToList(); - // return IsSignatureMatch(indexerElementType, indexerParameterTypes); - // } - // }); - // } - // - // #endregion - // - // bool IsSignatureMatch(IType indexerElementType, IList indexerParameterTypes) - // { - // indexerElementType.GetAllBaseTypes(); - // if (indexerParameterTypes.Count != argumentTypes.Count) - // return false; - // var returnConversion = conversions.ImplicitConversion(indexerElementType, returnType); - // if (!returnConversion.IsValid) - // return false; - // for (int i = 0; i < argumentTypes.Count; i++) { - // var conversion = conversions.ImplicitConversion(indexerParameterTypes[i], argumentTypes[i]); - // if (!conversion.IsValid) - // return false; - // } - // return true; - // } - // } - // - // public class TypeCriteriaCollector : DepthFirstAstVisitor - // { - // BaseSemanticModel context; - // - // public TypeCriteriaCollector(BaseSemanticModel context) - // { - // this.context = context; - // TypeCriteria = new Dictionary>(); - // UsedVariables = new HashSet(); - // } - // - // IDictionary> TypeCriteria { get; set; } - // - // public HashSet UsedVariables { get; private set; } - // - // public ITypeCriterion GetCriterion(IVariable variable) - // { - // if (!TypeCriteria.ContainsKey(variable)) - // return new ConjunctionCriteria(new List()); - // return new ConjunctionCriteria(TypeCriteria[variable]); - // } - // - // void AddCriterion(IVariable variable, ITypeCriterion criterion) - // { - // if (!TypeCriteria.ContainsKey(variable)) - // TypeCriteria[variable] = new List(); - // TypeCriteria[variable].Add(criterion); - // } - // - // public override void VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression) - // { - // base.VisitMemberReferenceExpression(memberReferenceExpression); - // - // var targetResolveResult = context.Resolve(memberReferenceExpression.Target) as LocalResolveResult; - // if (targetResolveResult == null) - // return; - // var variable = targetResolveResult.Variable; - // var conversion = context.GetConversion(memberReferenceExpression); - // if (conversion.IsMethodGroupConversion) { - // AddCriterion(variable, new HasMemberCriterion(conversion.Method)); - // } else { - // var resolveResult = context.Resolve(memberReferenceExpression); - // var memberResolveResult = resolveResult as MemberResolveResult; - // if (memberResolveResult != null) - // AddCriterion(variable, new HasMemberCriterion(memberResolveResult.Member)); - // } - // } - // - // public override void VisitIndexerExpression(IndexerExpression indexerExpression) - // { - // base.VisitIndexerExpression(indexerExpression); - // - // var localResolveResult = context.Resolve(indexerExpression.Target) as LocalResolveResult; - // if (localResolveResult == null) - // return; - // var resolveResult = context.Resolve(indexerExpression); - // if (resolveResult == null) - // return; - // var parent = indexerExpression.Parent; - // while (parent is ParenthesizedExpression) - // parent = parent.Parent; - // if (parent is DirectionExpression) { - // // The only types which are indexable and where the indexing expression - // // results in a variable is an actual array type - // AddCriterion(localResolveResult.Variable, new IsArrayTypeCriterion()); - // } else if (resolveResult is ArrayAccessResolveResult) { - // var arrayResolveResult = (ArrayAccessResolveResult)resolveResult; - // var arrayType = arrayResolveResult.Array.Type as ArrayType; - // if (arrayType != null) { - // var parameterTypes = arrayResolveResult.Indexes.Select(index => index.Type); - // var criterion = new SupportsIndexingCriterion(arrayType.ElementType, parameterTypes, CSharpConversions.Get(context.Compilation)); - // AddCriterion(localResolveResult.Variable, criterion); - // } - // } else if (resolveResult is CSharpInvocationResolveResult) { - // var invocationResolveResult = (CSharpInvocationResolveResult)resolveResult; - // var parameterTypes = invocationResolveResult.Arguments.Select(arg => arg.Type); - // var criterion = new SupportsIndexingCriterion(invocationResolveResult.Member.ReturnType, parameterTypes, CSharpConversions.Get(context.Compilation)); - // AddCriterion(localResolveResult.Variable, criterion); - // } - // } - // - // public override void VisitInvocationExpression(InvocationExpression invocationExpression) - // { - // base.VisitInvocationExpression(invocationExpression); - // - // var resolveResult = context.Resolve(invocationExpression); - // var invocationResolveResult = resolveResult as InvocationResolveResult; - // if (invocationResolveResult == null) - // return; - // - // // invocationExpression.Target resolves to a method group and VisitMemberReferenceExpression - // // only handles members, so handle method groups here - // var targetResolveResult = invocationResolveResult.TargetResult as LocalResolveResult; - // if (targetResolveResult != null) { - // var variable = targetResolveResult.Variable; - // AddCriterion(variable, new HasMemberCriterion(invocationResolveResult.Member)); - // } - // } - // - // public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) - // { - // base.VisitMethodDeclaration(methodDeclaration); - // - // var lastParameter = methodDeclaration.Parameters.LastOrNullObject(); - // if (lastParameter.IsNull || !lastParameter.ParameterModifier.HasFlag(ParameterModifier.Params)) - // return; - // var localResolveResult = context.Resolve(lastParameter) as LocalResolveResult; - // if (localResolveResult == null) - // return; - // AddCriterion(localResolveResult.Variable, new IsArrayTypeCriterion()); - // } - // - // Role[] roles = new [] { - // Roles.Expression, - // Roles.Argument, - // Roles.Condition, - // BinaryOperatorExpression.RightRole, - // BinaryOperatorExpression.LeftRole - // }; - // - // public override void VisitIdentifierExpression(IdentifierExpression identifierExpression) - // { - // var resolveResult = context.Resolve(identifierExpression); - // var localResolveResult = resolveResult as LocalResolveResult; - // if (localResolveResult == null) - // return; - // - // var variable = localResolveResult.Variable; - // if (!UsedVariables.Contains(variable)) - // UsedVariables.Add(variable); - // - // // Assignment expressions are checked separately, see VisitAssignmentExpression - // if (!roles.Contains(identifierExpression.Role) || identifierExpression.Parent is AssignmentExpression) - // return; - // - // CheckForCriterion(identifierExpression, variable); - // } - // - // public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression) - // { - // base.VisitAssignmentExpression(assignmentExpression); - // - // // Only check the right side; The left side always has the type of - // // the variable, which is not what we want to check - // - // var rightResolveResult = context.Resolve(assignmentExpression.Right) as LocalResolveResult; - // if (rightResolveResult != null) { - // CheckForCriterion(assignmentExpression.Right, rightResolveResult.Variable); - // } - // } - // - // void CheckForCriterion(Expression expression, IVariable variable) - // { - // AddCriterion(variable, new IsTypeCriterion(context.GetExpectedType(expression))); - // } - // - // class ConjunctionCriteria : ITypeCriterion - // { - // IList criteria; - // - // public ConjunctionCriteria(IList criteria) - // { - // this.criteria = criteria; - // } - // - // public bool SatisfiedBy(IType type) - // { - // foreach (var criterion in criteria) { - // if (!criterion.SatisfiedBy(type)) { - // return false; - // } - // } - // return true; - // } - // } - } +// //// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) +// //// { +// //// methodDeclaration.Attributes.AcceptVisitor(this); +// //// if (HasEntryPointSignature(methodDeclaration) || methodDeclaration.HasModifier(Modifiers.Public) || methodDeclaration.HasModifier(Modifiers.Protected)) +// //// return; +// //// var eligibleParameters = methodDeclaration.Parameters +// //// .Where(p => p.ParameterModifier != ParameterModifier.Out && p.ParameterModifier != ParameterModifier.Ref) +// //// .ToList(); +// //// if (eligibleParameters.Count == 0) +// //// return; +// //// var declarationResolveResult = ctx.Resolve(methodDeclaration) as MemberResolveResult; +// //// if (declarationResolveResult == null) +// //// return; +// //// var member = declarationResolveResult.Member; +// //// if (member.IsOverride || member.IsOverridable || member.ImplementedInterfaceMembers.Any()) +// //// return; +// //// +// //// var collector = new TypeCriteriaCollector(ctx); +// //// methodDeclaration.AcceptVisitor(collector); +// //// +// //// foreach (var parameter in eligibleParameters) { +// //// ProcessParameter(parameter, methodDeclaration.Body, collector); +// //// } +// //// } +// //// +// //// bool HasEntryPointSignature(MethodDeclaration methodDeclaration) +// //// { +// //// if (!methodDeclaration.Modifiers.HasFlag(Modifiers.Static)) +// //// return false; +// //// var returnType = ctx.Resolve(methodDeclaration.ReturnType).Type; +// //// if (!returnType.IsKnownType(KnownTypeCode.Int32) && !returnType.IsKnownType(KnownTypeCode.Void)) +// //// return false; +// //// var parameterCount = methodDeclaration.Parameters.Count; +// //// if (parameterCount == 0) +// //// return true; +// //// if (parameterCount != 1) +// //// return false; +// //// var parameterType = ctx.Resolve(methodDeclaration.Parameters.First()).Type as ArrayType; +// //// if (parameterType == null || !parameterType.ElementType.IsKnownType(KnownTypeCode.String)) +// //// return false; +// //// return true; +// //// } +// //// +// //// bool FilterOut(IType current, IType newType) +// //// { +// //// // Filter out some strange framework types like _Exception +// //// return newType.Namespace.StartsWith("System.", StringComparison.Ordinal) && +// //// newType.Name.StartsWith("_", StringComparison.Ordinal) ? true : false; +// //// } +// //// +// //// void ProcessParameter(ParameterDeclaration parameter, AstNode rootResolutionNode, TypeCriteriaCollector collector) +// //// { +// //// var localResolveResult = ctx.Resolve(parameter) as LocalResolveResult; +// //// if (localResolveResult == null) +// //// return; +// //// var variable = localResolveResult.Variable; +// //// var typeKind = variable.Type.Kind; +// //// if (!(typeKind == TypeKind.Class || +// //// typeKind == TypeKind.Struct || +// //// typeKind == TypeKind.Interface || +// //// typeKind == TypeKind.Array) || +// //// parameter.Type is PrimitiveType || +// //// !collector.UsedVariables.Contains(variable)) { +// //// return; +// //// } +// //// +// //// var candidateTypes = localResolveResult.Type.GetAllBaseTypes().ToList(); +// //// TypesChecked += candidateTypes.Count; +// //// var criterion = collector.GetCriterion(variable); +// //// +// //// var possibleTypes = +// //// (from type in candidateTypes +// //// where !type.Equals(localResolveResult.Type) && criterion.SatisfiedBy(type) +// //// select type).ToList(); +// //// +// //// TypeResolveCount += possibleTypes.Count; +// //// var validTypes = +// //// (from type in possibleTypes +// //// where (!tryResolve || TypeChangeResolvesCorrectly(ctx, parameter, rootResolutionNode, type)) && !FilterOut (variable.Type, type) +// //// select type).ToList(); +// //// if (validTypes.Any()) { +// // // AddDiagnosticAnalyzer(new CodeIssue(parameter.Type, ctx.TranslateString("Parameter can be declared with base type"), GetActions(parameter, validTypes)) { +// //// IssueMarker = IssueMarker.DottedLine +// //// }); +// //// MembersWithIssues++; +// //// } +// //// } +// //// +// //// internal int TypeResolveCount = 0; +// //// internal int TypesChecked = 0; +// //// internal int MembersWithIssues = 0; +// //// internal int MethodResolveCount = 0; +// //// +// //// IEnumerable GetActions(ParameterDeclaration parameter, IEnumerable possibleTypes) +// //// { +// //// var csResolver = ctx.Resolver.GetResolverStateBefore(parameter); +// //// var astBuilder = new TypeSystemAstBuilder(csResolver); +// //// foreach (var type in possibleTypes) { +// //// var localType = type; +// //// var message = String.Format(ctx.TranslateString("Demote parameter to '{0}'"), type.FullName); +// //// yield return new CodeAction(message, script => { +// //// script.Replace(parameter.Type, astBuilder.ConvertType(localType)); +// //// }, parameter.Type); +// //// } +// //// } +// //// } +// //// +// //// public static bool TypeChangeResolvesCorrectly(BaseSemanticModel ctx, ParameterDeclaration parameter, AstNode rootNode, IType type) +// //// { +// //// var resolver = ctx.GetResolverStateBefore(rootNode); +// //// resolver = resolver.AddVariable(new DefaultParameter(type, parameter.Name)); +// //// var astResolver = new CSharpAstResolver(resolver, rootNode, ctx.UnresolvedFile); +// //// var validator = new TypeChangeValidationNavigator(); +// //// astResolver.ApplyNavigator(validator, ctx.CancellationToken); +// //// return !validator.FoundErrors; +// //// } +// //// +// //// class TypeChangeValidationNavigator : IResolveVisitorNavigator +// //// { +// //// public bool FoundErrors { get; private set; } +// //// +// //// #region IResolveVisitorNavigator implementation +// //// public ResolveVisitorNavigationMode Scan(AstNode node) +// //// { +// //// if (FoundErrors) +// //// return ResolveVisitorNavigationMode.Skip; +// //// return ResolveVisitorNavigationMode.Resolve; +// //// } +// //// +// //// public void Resolved(AstNode node, ResolveResult result) +// //// { +// ////// bool errors = result.IsError; +// //// FoundErrors |= result.IsError; +// //// } +// //// +// //// public void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType) +// //// { +// //// // no-op +// //// } +// //// #endregion +// //// +// //// } +// // } +// // +// // public interface ITypeCriterion +// // { +// // /// +// // /// Checks if the given type satisfies the critrion. +// // /// +// // /// +// // /// true, if the type satisfies the criterion, false otherwise. +// // /// +// // /// +// // /// The type to check. +// // /// +// // bool SatisfiedBy(IType type); +// // } +// // +// // public class SupportsIndexingCriterion : ITypeCriterion +// // { +// // IType returnType; +// // +// // IList argumentTypes; +// // +// // CSharpConversions conversions; +// // +// // bool isWriteAccess; +// // +// // public SupportsIndexingCriterion(IType returnType, IEnumerable argumentTypes, CSharpConversions conversions, bool isWriteAccess = false) +// // { +// // if (returnType == null) +// // throw new ArgumentNullException("returnType"); +// // if (argumentTypes == null) +// // throw new ArgumentNullException("argumentTypes"); +// // if (conversions == null) +// // throw new ArgumentNullException("conversions"); +// // +// // this.returnType = returnType; +// // this.argumentTypes = argumentTypes.ToList(); +// // this.conversions = conversions; +// // this.isWriteAccess = isWriteAccess; +// // } +// // +// // #region ITypeCriterion implementation +// // +// // public bool SatisfiedBy(IType type) +// // { +// // var accessors = type.GetAccessors().ToList(); +// // return accessors.Any(member => { +// // var parameterizedMember = member as IParameterizedMember; +// // if (parameterizedMember == null) +// // return false; +// // +// // if (isWriteAccess) { +// // var parameterCount = member.Parameters.Count; +// // if (member.Name != "set_Item" || parameterCount < 2) +// // return false; +// // var indexerElementType = parameterizedMember.Parameters.Last().Type; +// // var indexerParameterTypes = parameterizedMember.Parameters.Take(parameterCount - 1).Select(p => p.Type).ToList(); +// // return IsSignatureMatch(indexerElementType, indexerParameterTypes); +// // } else { +// // if (member.Name != "get_Item" || member.Parameters.Count < 1) +// // return false; +// // var indexerElementType = parameterizedMember.ReturnType; +// // var indexerParameterTypes = parameterizedMember.Parameters.Select(p => p.Type).ToList(); +// // return IsSignatureMatch(indexerElementType, indexerParameterTypes); +// // } +// // }); +// // } +// // +// // #endregion +// // +// // bool IsSignatureMatch(IType indexerElementType, IList indexerParameterTypes) +// // { +// // indexerElementType.GetAllBaseTypes(); +// // if (indexerParameterTypes.Count != argumentTypes.Count) +// // return false; +// // var returnConversion = conversions.ImplicitConversion(indexerElementType, returnType); +// // if (!returnConversion.IsValid) +// // return false; +// // for (int i = 0; i < argumentTypes.Count; i++) { +// // var conversion = conversions.ImplicitConversion(indexerParameterTypes[i], argumentTypes[i]); +// // if (!conversion.IsValid) +// // return false; +// // } +// // return true; +// // } +// // } +// // +// // public class TypeCriteriaCollector : DepthFirstAstVisitor +// // { +// // BaseSemanticModel context; +// // +// // public TypeCriteriaCollector(BaseSemanticModel context) +// // { +// // this.context = context; +// // TypeCriteria = new Dictionary>(); +// // UsedVariables = new HashSet(); +// // } +// // +// // IDictionary> TypeCriteria { get; set; } +// // +// // public HashSet UsedVariables { get; private set; } +// // +// // public ITypeCriterion GetCriterion(IVariable variable) +// // { +// // if (!TypeCriteria.ContainsKey(variable)) +// // return new ConjunctionCriteria(new List()); +// // return new ConjunctionCriteria(TypeCriteria[variable]); +// // } +// // +// // void AddCriterion(IVariable variable, ITypeCriterion criterion) +// // { +// // if (!TypeCriteria.ContainsKey(variable)) +// // TypeCriteria[variable] = new List(); +// // TypeCriteria[variable].Add(criterion); +// // } +// // +// // public override void VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression) +// // { +// // base.VisitMemberReferenceExpression(memberReferenceExpression); +// // +// // var targetResolveResult = context.Resolve(memberReferenceExpression.Target) as LocalResolveResult; +// // if (targetResolveResult == null) +// // return; +// // var variable = targetResolveResult.Variable; +// // var conversion = context.GetConversion(memberReferenceExpression); +// // if (conversion.IsMethodGroupConversion) { +// // AddCriterion(variable, new HasMemberCriterion(conversion.Method)); +// // } else { +// // var resolveResult = context.Resolve(memberReferenceExpression); +// // var memberResolveResult = resolveResult as MemberResolveResult; +// // if (memberResolveResult != null) +// // AddCriterion(variable, new HasMemberCriterion(memberResolveResult.Member)); +// // } +// // } +// // +// // public override void VisitIndexerExpression(IndexerExpression indexerExpression) +// // { +// // base.VisitIndexerExpression(indexerExpression); +// // +// // var localResolveResult = context.Resolve(indexerExpression.Target) as LocalResolveResult; +// // if (localResolveResult == null) +// // return; +// // var resolveResult = context.Resolve(indexerExpression); +// // if (resolveResult == null) +// // return; +// // var parent = indexerExpression.Parent; +// // while (parent is ParenthesizedExpression) +// // parent = parent.Parent; +// // if (parent is DirectionExpression) { +// // // The only types which are indexable and where the indexing expression +// // // results in a variable is an actual array type +// // AddCriterion(localResolveResult.Variable, new IsArrayTypeCriterion()); +// // } else if (resolveResult is ArrayAccessResolveResult) { +// // var arrayResolveResult = (ArrayAccessResolveResult)resolveResult; +// // var arrayType = arrayResolveResult.Array.Type as ArrayType; +// // if (arrayType != null) { +// // var parameterTypes = arrayResolveResult.Indexes.Select(index => index.Type); +// // var criterion = new SupportsIndexingCriterion(arrayType.ElementType, parameterTypes, CSharpConversions.Get(context.Compilation)); +// // AddCriterion(localResolveResult.Variable, criterion); +// // } +// // } else if (resolveResult is CSharpInvocationResolveResult) { +// // var invocationResolveResult = (CSharpInvocationResolveResult)resolveResult; +// // var parameterTypes = invocationResolveResult.Arguments.Select(arg => arg.Type); +// // var criterion = new SupportsIndexingCriterion(invocationResolveResult.Member.ReturnType, parameterTypes, CSharpConversions.Get(context.Compilation)); +// // AddCriterion(localResolveResult.Variable, criterion); +// // } +// // } +// // +// // public override void VisitInvocationExpression(InvocationExpression invocationExpression) +// // { +// // base.VisitInvocationExpression(invocationExpression); +// // +// // var resolveResult = context.Resolve(invocationExpression); +// // var invocationResolveResult = resolveResult as InvocationResolveResult; +// // if (invocationResolveResult == null) +// // return; +// // +// // // invocationExpression.Target resolves to a method group and VisitMemberReferenceExpression +// // // only handles members, so handle method groups here +// // var targetResolveResult = invocationResolveResult.TargetResult as LocalResolveResult; +// // if (targetResolveResult != null) { +// // var variable = targetResolveResult.Variable; +// // AddCriterion(variable, new HasMemberCriterion(invocationResolveResult.Member)); +// // } +// // } +// // +// // public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration) +// // { +// // base.VisitMethodDeclaration(methodDeclaration); +// // +// // var lastParameter = methodDeclaration.Parameters.LastOrNullObject(); +// // if (lastParameter.IsNull || !lastParameter.ParameterModifier.HasFlag(ParameterModifier.Params)) +// // return; +// // var localResolveResult = context.Resolve(lastParameter) as LocalResolveResult; +// // if (localResolveResult == null) +// // return; +// // AddCriterion(localResolveResult.Variable, new IsArrayTypeCriterion()); +// // } +// // +// // Role[] roles = new [] { +// // Roles.Expression, +// // Roles.Argument, +// // Roles.Condition, +// // BinaryOperatorExpression.RightRole, +// // BinaryOperatorExpression.LeftRole +// // }; +// // +// // public override void VisitIdentifierExpression(IdentifierExpression identifierExpression) +// // { +// // var resolveResult = context.Resolve(identifierExpression); +// // var localResolveResult = resolveResult as LocalResolveResult; +// // if (localResolveResult == null) +// // return; +// // +// // var variable = localResolveResult.Variable; +// // if (!UsedVariables.Contains(variable)) +// // UsedVariables.Add(variable); +// // +// // // Assignment expressions are checked separately, see VisitAssignmentExpression +// // if (!roles.Contains(identifierExpression.Role) || identifierExpression.Parent is AssignmentExpression) +// // return; +// // +// // CheckForCriterion(identifierExpression, variable); +// // } +// // +// // public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression) +// // { +// // base.VisitAssignmentExpression(assignmentExpression); +// // +// // // Only check the right side; The left side always has the type of +// // // the variable, which is not what we want to check +// // +// // var rightResolveResult = context.Resolve(assignmentExpression.Right) as LocalResolveResult; +// // if (rightResolveResult != null) { +// // CheckForCriterion(assignmentExpression.Right, rightResolveResult.Variable); +// // } +// // } +// // +// // void CheckForCriterion(Expression expression, IVariable variable) +// // { +// // AddCriterion(variable, new IsTypeCriterion(context.GetExpectedType(expression))); +// // } +// // +// // class ConjunctionCriteria : ITypeCriterion +// // { +// // IList criteria; +// // +// // public ConjunctionCriteria(IList criteria) +// // { +// // this.criteria = criteria; +// // } +// // +// // public bool SatisfiedBy(IType type) +// // { +// // foreach (var criterion in criteria) { +// // if (!criterion.SatisfiedBy(type)) { +// // return false; +// // } +// // } +// // return true; +// // } +// // } +// } - // public class IsTypeCriterion : ITypeCriterion - // { - // IType isType; - // - // public IsTypeCriterion(IType isType) - // { - // this.isType = isType; - // } - // - // #region ITypeCriterion implementation - // public bool SatisfiedBy (IType type) - // { - // return isType == type || - // type.GetAllBaseTypes().Any(t => t == isType); - // } - // #endregion - // } - // - // public class IsArrayTypeCriterion : ITypeCriterion - // { - // #region ITypeCriterion implementation - // - // public bool SatisfiedBy(IType type) - // { - // return type is ArrayType; - // } - // - // #endregion - // } - // - // public class HasMemberCriterion : ITypeCriterion - // { - //// IMember neededMember; - // IList acceptableMembers; - // - // public HasMemberCriterion(IMember neededMember) - // { - //// this.neededMember = neededMember; - // - // if (neededMember.ImplementedInterfaceMembers.Any()) { - // acceptableMembers = neededMember.ImplementedInterfaceMembers.ToList(); - // } else if (neededMember.IsOverride) { - // acceptableMembers = new List(); - // foreach (var member in InheritanceHelper.GetBaseMembers(neededMember, true)) { - // acceptableMembers.Add(member); - // if (member.IsShadowing) - // break; - // } - // acceptableMembers.Add(neededMember); - // } else { - // acceptableMembers = new List { neededMember }; - // } - // } - // - // #region ITypeCriterion implementation - // public bool SatisfiedBy (IType type) - // { - // if (type == null) - // throw new ArgumentNullException("type"); - // - // var typeMembers = type.GetMembers(); - // return typeMembers.Any(member => HasCommonMemberDeclaration(acceptableMembers, member)); - // } - // #endregion - // - // static bool HasCommonMemberDeclaration(IEnumerable acceptableMembers, IMember member) - // { - // var implementedInterfaceMembers = member.MemberDefinition.ImplementedInterfaceMembers; - // if (implementedInterfaceMembers.Any()) { - // return ContainsAny(acceptableMembers, implementedInterfaceMembers); - // } else { - // return acceptableMembers.Contains(member/* .MemberDefinition*/); - // } - // } - // - // static bool ContainsAny(IEnumerable collection, IEnumerable items) - // { - // foreach (var item in items) { - // if (collection.Contains(item)) - // return true; - // } - // return false; - // } - // } -} \ No newline at end of file +// // public class IsTypeCriterion : ITypeCriterion +// // { +// // IType isType; +// // +// // public IsTypeCriterion(IType isType) +// // { +// // this.isType = isType; +// // } +// // +// // #region ITypeCriterion implementation +// // public bool SatisfiedBy (IType type) +// // { +// // return isType == type || +// // type.GetAllBaseTypes().Any(t => t == isType); +// // } +// // #endregion +// // } +// // +// // public class IsArrayTypeCriterion : ITypeCriterion +// // { +// // #region ITypeCriterion implementation +// // +// // public bool SatisfiedBy(IType type) +// // { +// // return type is ArrayType; +// // } +// // +// // #endregion +// // } +// // +// // public class HasMemberCriterion : ITypeCriterion +// // { +// //// IMember neededMember; +// // IList acceptableMembers; +// // +// // public HasMemberCriterion(IMember neededMember) +// // { +// //// this.neededMember = neededMember; +// // +// // if (neededMember.ImplementedInterfaceMembers.Any()) { +// // acceptableMembers = neededMember.ImplementedInterfaceMembers.ToList(); +// // } else if (neededMember.IsOverride) { +// // acceptableMembers = new List(); +// // foreach (var member in InheritanceHelper.GetBaseMembers(neededMember, true)) { +// // acceptableMembers.Add(member); +// // if (member.IsShadowing) +// // break; +// // } +// // acceptableMembers.Add(neededMember); +// // } else { +// // acceptableMembers = new List { neededMember }; +// // } +// // } +// // +// // #region ITypeCriterion implementation +// // public bool SatisfiedBy (IType type) +// // { +// // if (type == null) +// // throw new ArgumentNullException("type"); +// // +// // var typeMembers = type.GetMembers(); +// // return typeMembers.Any(member => HasCommonMemberDeclaration(acceptableMembers, member)); +// // } +// // #endregion +// // +// // static bool HasCommonMemberDeclaration(IEnumerable acceptableMembers, IMember member) +// // { +// // var implementedInterfaceMembers = member.MemberDefinition.ImplementedInterfaceMembers; +// // if (implementedInterfaceMembers.Any()) { +// // return ContainsAny(acceptableMembers, implementedInterfaceMembers); +// // } else { +// // return acceptableMembers.Contains(member/* .MemberDefinition*/); +// // } +// // } +// // +// // static bool ContainsAny(IEnumerable collection, IEnumerable items) +// // { +// // foreach (var item in items) { +// // if (collection.Contains(item)) +// // return true; +// // } +// // return false; +// // } +// // } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ReferenceEqualsWithValueTypeAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ReferenceEqualsWithValueTypeAnalyzer.cs index 85945cb2..09ee3a0c 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ReferenceEqualsWithValueTypeAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/ReferenceEqualsWithValueTypeAnalyzer.cs @@ -1,84 +1,84 @@ -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 ReferenceEqualsWithValueTypeAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.ReferenceEqualsWithValueTypeAnalyzerID, - GettextCatalog.GetString("Check for reference equality instead"), - GettextCatalog.GetString("'Object.ReferenceEquals' is always false because it is called with value type"), - DiagnosticAnalyzerCategories.PracticesAndImprovements, - DiagnosticSeverity.Info, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ReferenceEqualsWithValueTypeAnalyzerID) - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class ReferenceEqualsWithValueTypeAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.ReferenceEqualsWithValueTypeAnalyzerID, +// GettextCatalog.GetString("Check for reference equality instead"), +// GettextCatalog.GetString("'Object.ReferenceEquals' is always false because it is called with value type"), +// DiagnosticAnalyzerCategories.PracticesAndImprovements, +// DiagnosticSeverity.Info, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ReferenceEqualsWithValueTypeAnalyzerID) +// ); - 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); - //// - //// // Quickly determine if this invocation is eligible to speed up the inspector - //// var nameToken = invocationExpression.Target.GetChildByRole(Roles.Identifier); - //// if (nameToken.Name != "ReferenceEquals") - //// return; - //// - //// var resolveResult = ctx.Resolve(invocationExpression) as InvocationResolveResult; - //// if (resolveResult == null || - //// resolveResult.Member.DeclaringTypeDefinition == null || - //// resolveResult.Member.DeclaringTypeDefinition.KnownTypeCode != KnownTypeCode.Object || - //// resolveResult.Member.Name != "ReferenceEquals" || - //// invocationExpression.Arguments.All(arg => ctx.Resolve(arg).Type.IsReferenceType ?? true)) - //// return; - //// - //// var action1 = new CodeAction(ctx.TranslateString("Replace expression with 'false'"), - //// script => script.Replace(invocationExpression, new PrimitiveExpression(false)), invocationExpression); - //// - //// var action2 = new CodeAction(ctx.TranslateString("Use Equals()"), - //// script => script.Replace(invocationExpression.Target, - //// new PrimitiveType("object").Member("Equals")), invocationExpression); - //// - //// AddDiagnosticAnalyzer(new CodeIssue(invocationExpression, - //// ctx.TranslateString("'Object.ReferenceEquals' is always false because it is called with value type"), - //// new [] { action1, action2 })); - //// } - // } - } -} \ No newline at end of file +// //// public override void VisitInvocationExpression(InvocationExpression invocationExpression) +// //// { +// //// base.VisitInvocationExpression(invocationExpression); +// //// +// //// // Quickly determine if this invocation is eligible to speed up the inspector +// //// var nameToken = invocationExpression.Target.GetChildByRole(Roles.Identifier); +// //// if (nameToken.Name != "ReferenceEquals") +// //// return; +// //// +// //// var resolveResult = ctx.Resolve(invocationExpression) as InvocationResolveResult; +// //// if (resolveResult == null || +// //// resolveResult.Member.DeclaringTypeDefinition == null || +// //// resolveResult.Member.DeclaringTypeDefinition.KnownTypeCode != KnownTypeCode.Object || +// //// resolveResult.Member.Name != "ReferenceEquals" || +// //// invocationExpression.Arguments.All(arg => ctx.Resolve(arg).Type.IsReferenceType ?? true)) +// //// return; +// //// +// //// var action1 = new CodeAction(ctx.TranslateString("Replace expression with 'false'"), +// //// script => script.Replace(invocationExpression, new PrimitiveExpression(false)), invocationExpression); +// //// +// //// var action2 = new CodeAction(ctx.TranslateString("Use Equals()"), +// //// script => script.Replace(invocationExpression.Target, +// //// new PrimitiveType("object").Member("Equals")), invocationExpression); +// //// +// //// AddDiagnosticAnalyzer(new CodeIssue(invocationExpression, +// //// ctx.TranslateString("'Object.ReferenceEquals' is always false because it is called with value type"), +// //// new [] { action1, action2 })); +// //// } +// // } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/SimplifyLinqExpressionAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/SimplifyLinqExpressionAnalyzer.cs index 862b5fc3..232444ed 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/SimplifyLinqExpressionAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/SimplifyLinqExpressionAnalyzer.cs @@ -1,119 +1,119 @@ -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 SimplifyLinqExpressionAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.SimplifyLinqExpressionAnalyzerID, - GettextCatalog.GetString("Simplify LINQ expression"), - GettextCatalog.GetString("Simplify LINQ expression"), - DiagnosticAnalyzerCategories.PracticesAndImprovements, - DiagnosticSeverity.Info, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.SimplifyLinqExpressionAnalyzerID), - customTags: DiagnosticCustomTags.Unnecessary - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class SimplifyLinqExpressionAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.SimplifyLinqExpressionAnalyzerID, +// GettextCatalog.GetString("Simplify LINQ expression"), +// GettextCatalog.GetString("Simplify LINQ expression"), +// DiagnosticAnalyzerCategories.PracticesAndImprovements, +// DiagnosticSeverity.Info, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.SimplifyLinqExpressionAnalyzerID), +// 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) - // { - // } +// // class GatherVisitor : GatherVisitorBase +// // { +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // } - //// static readonly Expression simpleExpression = new Choice { - //// new UnaryOperatorExpression (UnaryOperatorType.Not, new AnyNode()), - //// new BinaryOperatorExpression(new AnyNode(), BinaryOperatorType.Equality, new AnyNode()), - //// new BinaryOperatorExpression(new AnyNode(), BinaryOperatorType.InEquality, new AnyNode()) - //// }; - //// - //// static readonly AstNode argumentPattern = new Choice { - //// new LambdaExpression { - //// Parameters = { new ParameterDeclaration(PatternHelper.AnyType(true), Pattern.AnyString) }, - //// Body = new Choice { - //// new NamedNode ("expr", simpleExpression), - //// new BlockStatement { new ReturnStatement(new NamedNode ("expr", simpleExpression))} - //// } - //// }, - //// new AnonymousMethodExpression { - //// Parameters = { new ParameterDeclaration(PatternHelper.AnyType(true), Pattern.AnyString) }, - //// Body = new BlockStatement { new ReturnStatement(new NamedNode ("expr", simpleExpression))} - //// } - //// }; - //// - //// public override void VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression) - //// { - //// base.VisitUnaryOperatorExpression(unaryOperatorExpression); - //// if (unaryOperatorExpression.Operator != UnaryOperatorType.Not) - //// return; - //// var invocation = CSharpUtil.GetInnerMostExpression(unaryOperatorExpression.Expression) as InvocationExpression; - //// if (invocation == null) - //// return; - //// var rr = ctx.Resolve(invocation) as CSharpInvocationResolveResult; - //// if (rr == null || rr.IsError) - //// return; - //// - //// if (rr.Member.DeclaringType.Name != "Enumerable" || rr.Member.DeclaringType.Namespace != "System.Linq") - //// return; - //// if (!new[] { "All", "Any" }.Contains(rr.Member.Name)) - //// return; - //// if (invocation.Arguments.Count != 1) - //// return; - //// var arg = invocation.Arguments.First(); - //// var match = argumentPattern.Match(arg); - //// if (!match.Success) - //// return; - //// AddDiagnosticAnalyzer(new CodeIssue ( - //// unaryOperatorExpression, - //// ctx.TranslateString(""), - //// ctx.TranslateString("Simplify LINQ expression"), - //// s => { - //// var target = invocation.Target.Clone() as MemberReferenceExpression; - //// target.MemberName = target.MemberName == "All" ? "Any" : "All"; - //// - //// var expr = arg.Clone(); - //// var nmatch = argumentPattern.Match(expr); - //// var cond = nmatch.Get("expr").Single(); - //// cond.ReplaceWith(CSharpUtil.InvertCondition(cond)); - //// var simplifiedInvocation = new InvocationExpression( - //// target, - //// expr - //// ); - //// s.Replace(unaryOperatorExpression, simplifiedInvocation); - //// } - //// )); - //// } - // } - } -} \ No newline at end of file +// //// static readonly Expression simpleExpression = new Choice { +// //// new UnaryOperatorExpression (UnaryOperatorType.Not, new AnyNode()), +// //// new BinaryOperatorExpression(new AnyNode(), BinaryOperatorType.Equality, new AnyNode()), +// //// new BinaryOperatorExpression(new AnyNode(), BinaryOperatorType.InEquality, new AnyNode()) +// //// }; +// //// +// //// static readonly AstNode argumentPattern = new Choice { +// //// new LambdaExpression { +// //// Parameters = { new ParameterDeclaration(PatternHelper.AnyType(true), Pattern.AnyString) }, +// //// Body = new Choice { +// //// new NamedNode ("expr", simpleExpression), +// //// new BlockStatement { new ReturnStatement(new NamedNode ("expr", simpleExpression))} +// //// } +// //// }, +// //// new AnonymousMethodExpression { +// //// Parameters = { new ParameterDeclaration(PatternHelper.AnyType(true), Pattern.AnyString) }, +// //// Body = new BlockStatement { new ReturnStatement(new NamedNode ("expr", simpleExpression))} +// //// } +// //// }; +// //// +// //// public override void VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression) +// //// { +// //// base.VisitUnaryOperatorExpression(unaryOperatorExpression); +// //// if (unaryOperatorExpression.Operator != UnaryOperatorType.Not) +// //// return; +// //// var invocation = CSharpUtil.GetInnerMostExpression(unaryOperatorExpression.Expression) as InvocationExpression; +// //// if (invocation == null) +// //// return; +// //// var rr = ctx.Resolve(invocation) as CSharpInvocationResolveResult; +// //// if (rr == null || rr.IsError) +// //// return; +// //// +// //// if (rr.Member.DeclaringType.Name != "Enumerable" || rr.Member.DeclaringType.Namespace != "System.Linq") +// //// return; +// //// if (!new[] { "All", "Any" }.Contains(rr.Member.Name)) +// //// return; +// //// if (invocation.Arguments.Count != 1) +// //// return; +// //// var arg = invocation.Arguments.First(); +// //// var match = argumentPattern.Match(arg); +// //// if (!match.Success) +// //// return; +// //// AddDiagnosticAnalyzer(new CodeIssue ( +// //// unaryOperatorExpression, +// //// ctx.TranslateString(""), +// //// ctx.TranslateString("Simplify LINQ expression"), +// //// s => { +// //// var target = invocation.Target.Clone() as MemberReferenceExpression; +// //// target.MemberName = target.MemberName == "All" ? "Any" : "All"; +// //// +// //// var expr = arg.Clone(); +// //// var nmatch = argumentPattern.Match(expr); +// //// var cond = nmatch.Get("expr").Single(); +// //// cond.ReplaceWith(CSharpUtil.InvertCondition(cond)); +// //// var simplifiedInvocation = new InvocationExpression( +// //// target, +// //// expr +// //// ); +// //// s.Replace(unaryOperatorExpression, simplifiedInvocation); +// //// } +// //// )); +// //// } +// // } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/StringCompareIsCultureSpecificAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/StringCompareIsCultureSpecificAnalyzer.cs index 937a68da..a60dd89e 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/StringCompareIsCultureSpecificAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/StringCompareIsCultureSpecificAnalyzer.cs @@ -1,86 +1,86 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using System.Linq; +//using Microsoft.CodeAnalysis; +//using Microsoft.CodeAnalysis.CSharp; +//using Microsoft.CodeAnalysis.Diagnostics; +//using System.Collections.Immutable; +//using Microsoft.CodeAnalysis.CSharp.Syntax; +//using System.Linq; -namespace RefactoringEssentials.CSharp.Diagnostics -{ - [DiagnosticAnalyzer(LanguageNames.CSharp)] - [NotPortedYet] - public class StringCompareIsCultureSpecificAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.StringCompareIsCultureSpecificAnalyzerID, - GettextCatalog.GetString("Warns when a culture-aware 'Compare' call is used by default"), - GettextCatalog.GetString("'string.Compare' is culture-aware"), - DiagnosticAnalyzerCategories.PracticesAndImprovements, - DiagnosticSeverity.Warning, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.StringCompareIsCultureSpecificAnalyzerID) - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class StringCompareIsCultureSpecificAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.StringCompareIsCultureSpecificAnalyzerID, +// GettextCatalog.GetString("Warns when a culture-aware 'Compare' call is used by default"), +// GettextCatalog.GetString("'string.Compare' is culture-aware"), +// DiagnosticAnalyzerCategories.PracticesAndImprovements, +// DiagnosticSeverity.Warning, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.StringCompareIsCultureSpecificAnalyzerID) +// ); - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor); +// public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor); - //static readonly DiagnosticDescriptor Rule1 = new DiagnosticDescriptor (DiagnosticId, Description, "Use ordinal comparison", Category, DiagnosticSeverity.Warning, true, "'string.Compare' is culture-aware"); - //static readonly DiagnosticDescriptor Rule2 = new DiagnosticDescriptor (DiagnosticId, Description, "Use culture-aware comparison", Category, DiagnosticSeverity.Warning, true, "'string.Compare' is culture-aware"); +// //static readonly DiagnosticDescriptor Rule1 = new DiagnosticDescriptor (DiagnosticId, Description, "Use ordinal comparison", Category, DiagnosticSeverity.Warning, true, "'string.Compare' is culture-aware"); +// //static readonly DiagnosticDescriptor Rule2 = new DiagnosticDescriptor (DiagnosticId, Description, "Use culture-aware comparison", Category, DiagnosticSeverity.Warning, true, "'string.Compare' is culture-aware"); - 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.InvocationExpression } - ); - } +// 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.InvocationExpression } +// ); +// } - static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic) - { - diagnostic = default(Diagnostic); - var node = nodeContext.Node as InvocationExpressionSyntax; - MemberAccessExpressionSyntax mre = node.Expression as MemberAccessExpressionSyntax; - if (mre == null) - return false; - if (mre.Name.Identifier.ValueText != "Compare") - return false; - if (node.ArgumentList.Arguments.Count != 2 && - node.ArgumentList.Arguments.Count != 3 && - node.ArgumentList.Arguments.Count != 5 && - node.ArgumentList.Arguments.Count != 6) - return false; +// static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic) +// { +// diagnostic = default(Diagnostic); +// var node = nodeContext.Node as InvocationExpressionSyntax; +// MemberAccessExpressionSyntax mre = node.Expression as MemberAccessExpressionSyntax; +// if (mre == null) +// return false; +// if (mre.Name.Identifier.ValueText != "Compare") +// return false; +// if (node.ArgumentList.Arguments.Count != 2 && +// node.ArgumentList.Arguments.Count != 3 && +// node.ArgumentList.Arguments.Count != 5 && +// node.ArgumentList.Arguments.Count != 6) +// return false; - var rr = nodeContext.SemanticModel.GetSymbolInfo(node, nodeContext.CancellationToken); - if (rr.Symbol == null) - return false; - var symbol = rr.Symbol; - if (!(symbol.ContainingType != null && symbol.ContainingType.SpecialType == SpecialType.System_String)) - return false; - if (!symbol.IsStatic) - return false; - var parameters = symbol.GetParameters(); - var firstParameter = parameters.FirstOrDefault(); - if (firstParameter == null || firstParameter.Type.SpecialType != SpecialType.System_String) - return false; // First parameter not a string +// var rr = nodeContext.SemanticModel.GetSymbolInfo(node, nodeContext.CancellationToken); +// if (rr.Symbol == null) +// return false; +// var symbol = rr.Symbol; +// if (!(symbol.ContainingType != null && symbol.ContainingType.SpecialType == SpecialType.System_String)) +// return false; +// if (!symbol.IsStatic) +// return false; +// var parameters = symbol.GetParameters(); +// var firstParameter = parameters.FirstOrDefault(); +// if (firstParameter == null || firstParameter.Type.SpecialType != SpecialType.System_String) +// return false; // First parameter not a string - var lastParameter = parameters.Last(); - if (lastParameter.Type.Name == "StringComparison") - return false; // already specifying a string comparison +// var lastParameter = parameters.Last(); +// if (lastParameter.Type.Name == "StringComparison") +// return false; // already specifying a string comparison - diagnostic = Diagnostic.Create( - descriptor, - node.GetLocation() - ); - return true; - } - } -} \ No newline at end of file +// diagnostic = Diagnostic.Create( +// descriptor, +// node.GetLocation() +// ); +// return true; +// } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/UseArrayCreationExpressionAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/UseArrayCreationExpressionAnalyzer.cs index dbad1a20..824d58b9 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/UseArrayCreationExpressionAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/UseArrayCreationExpressionAnalyzer.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 UseArrayCreationExpressionAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.UseArrayCreationExpressionAnalyzerID, - GettextCatalog.GetString("Use array creation expression"), - GettextCatalog.GetString("Use array create expression"), - DiagnosticAnalyzerCategories.PracticesAndImprovements, - DiagnosticSeverity.Info, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.UseArrayCreationExpressionAnalyzerID) - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class UseArrayCreationExpressionAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.UseArrayCreationExpressionAnalyzerID, +// GettextCatalog.GetString("Use array creation expression"), +// GettextCatalog.GetString("Use array create expression"), +// DiagnosticAnalyzerCategories.PracticesAndImprovements, +// DiagnosticSeverity.Info, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.UseArrayCreationExpressionAnalyzerID) +// ); - 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) as CSharpInvocationResolveResult; - //// if (rr == null || rr.IsError) - //// return; - //// - //// if (rr.Member.Name != "CreateInstance" || - //// !rr.Member.DeclaringType.IsKnownType(KnownTypeCode.Array)) - //// return; - //// var firstArg = invocationExpression.Arguments.FirstOrDefault() as TypeOfExpression; - //// if (firstArg == null) - //// return; - //// var argRR = ctx.Resolve(invocationExpression.Arguments.ElementAt(1)); - //// if (!argRR.Type.IsKnownType(KnownTypeCode.Int32)) - //// return; - //// - //// AddDiagnosticAnalyzer(new CodeIssue( - //// invocationExpression, - //// ctx.TranslateString(""), - //// ctx.TranslateString(""), - //// script => { - //// var ac = new ArrayCreateExpression { - //// Type = firstArg.Type.Clone() - //// }; - //// foreach (var arg in invocationExpression.Arguments.Skip(1)) - //// ac.Arguments.Add(arg.Clone()) ; - //// script.Replace(invocationExpression, ac); - //// } - //// )); - //// } - // } - } -} \ No newline at end of file +// //// public override void VisitInvocationExpression(InvocationExpression invocationExpression) +// //// { +// //// base.VisitInvocationExpression(invocationExpression); +// //// +// //// var rr = ctx.Resolve(invocationExpression) as CSharpInvocationResolveResult; +// //// if (rr == null || rr.IsError) +// //// return; +// //// +// //// if (rr.Member.Name != "CreateInstance" || +// //// !rr.Member.DeclaringType.IsKnownType(KnownTypeCode.Array)) +// //// return; +// //// var firstArg = invocationExpression.Arguments.FirstOrDefault() as TypeOfExpression; +// //// if (firstArg == null) +// //// return; +// //// var argRR = ctx.Resolve(invocationExpression.Arguments.ElementAt(1)); +// //// if (!argRR.Type.IsKnownType(KnownTypeCode.Int32)) +// //// return; +// //// +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// invocationExpression, +// //// ctx.TranslateString(""), +// //// ctx.TranslateString(""), +// //// script => { +// //// var ac = new ArrayCreateExpression { +// //// Type = firstArg.Type.Clone() +// //// }; +// //// foreach (var arg in invocationExpression.Arguments.Skip(1)) +// //// ac.Arguments.Add(arg.Clone()) ; +// //// script.Replace(invocationExpression, ac); +// //// } +// //// )); +// //// } +// // } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/UseIsOperatorAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/UseIsOperatorAnalyzer.cs index 034c09f5..2cff285f 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/UseIsOperatorAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/UseIsOperatorAnalyzer.cs @@ -1,127 +1,127 @@ -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 UseIsOperatorAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.UseIsOperatorAnalyzerID, - GettextCatalog.GetString("'is' operator can be used"), - GettextCatalog.GetString("Use 'is' operator"), - DiagnosticAnalyzerCategories.PracticesAndImprovements, - DiagnosticSeverity.Info, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.UseIsOperatorAnalyzerID) - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class UseIsOperatorAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.UseIsOperatorAnalyzerID, +// GettextCatalog.GetString("'is' operator can be used"), +// GettextCatalog.GetString("Use 'is' operator"), +// DiagnosticAnalyzerCategories.PracticesAndImprovements, +// DiagnosticSeverity.Info, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.UseIsOperatorAnalyzerID) +// ); - 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) +// // { +// // } - //// static readonly Expression pattern1 = new InvocationExpression( - //// new MemberReferenceExpression(new TypeOfExpression(new AnyNode("Type")), "IsAssignableFrom"), - //// new InvocationExpression( - //// new MemberReferenceExpression(new AnyNode("object"), "GetType") - //// ) - //// ); - //// static readonly Expression pattern2 = new InvocationExpression( - //// new MemberReferenceExpression(new TypeOfExpression(new AnyNode("Type")), "IsInstanceOfType"), - //// new AnyNode("object") - //// ); - //// - //// - //// - //// void AddDiagnosticAnalyzer(AstNode invocationExpression, Match match, bool negate = false) - //// { - //// AddDiagnosticAnalyzer(new CodeIssue( - //// invocationExpression, - //// ctx.TranslateString(""), - //// ctx.TranslateString(""), - //// s => { - //// Expression expression = new IsExpression(CSharpUtil.AddParensForUnaryExpressionIfRequired(match.Get("object").Single().Clone()), match.Get("Type").Single().Clone()); - //// if (negate) - //// expression = new UnaryOperatorExpression (UnaryOperatorType.Not, new ParenthesizedExpression(expression)); - //// s.Replace(invocationExpression, expression); - //// } - //// )); - //// } - //// - //// public override void VisitInvocationExpression(InvocationExpression invocationExpression) - //// { - //// base.VisitInvocationExpression(invocationExpression); - //// var match = pattern1.Match(invocationExpression); - //// if (!match.Success) - //// match = pattern2.Match(invocationExpression); - //// if (match.Success) { - //// AddDiagnosticAnalyzer(invocationExpression, match); - //// } - //// } +// //// static readonly Expression pattern1 = new InvocationExpression( +// //// new MemberReferenceExpression(new TypeOfExpression(new AnyNode("Type")), "IsAssignableFrom"), +// //// new InvocationExpression( +// //// new MemberReferenceExpression(new AnyNode("object"), "GetType") +// //// ) +// //// ); +// //// static readonly Expression pattern2 = new InvocationExpression( +// //// new MemberReferenceExpression(new TypeOfExpression(new AnyNode("Type")), "IsInstanceOfType"), +// //// new AnyNode("object") +// //// ); +// //// +// //// +// //// +// //// void AddDiagnosticAnalyzer(AstNode invocationExpression, Match match, bool negate = false) +// //// { +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// invocationExpression, +// //// ctx.TranslateString(""), +// //// ctx.TranslateString(""), +// //// s => { +// //// Expression expression = new IsExpression(CSharpUtil.AddParensForUnaryExpressionIfRequired(match.Get("object").Single().Clone()), match.Get("Type").Single().Clone()); +// //// if (negate) +// //// expression = new UnaryOperatorExpression (UnaryOperatorType.Not, new ParenthesizedExpression(expression)); +// //// s.Replace(invocationExpression, expression); +// //// } +// //// )); +// //// } +// //// +// //// public override void VisitInvocationExpression(InvocationExpression invocationExpression) +// //// { +// //// base.VisitInvocationExpression(invocationExpression); +// //// var match = pattern1.Match(invocationExpression); +// //// if (!match.Success) +// //// match = pattern2.Match(invocationExpression); +// //// if (match.Success) { +// //// AddDiagnosticAnalyzer(invocationExpression, match); +// //// } +// //// } - // /* Unfortunately not quite the same :/ - // static readonly AstNode equalityComparePattern = - // PatternHelper.CommutativeOperator( - // PatternHelper.OptionalParentheses(new TypeOfExpression(new AnyNode("Type"))), - // BinaryOperatorType.Equality, - // PatternHelper.OptionalParentheses(new InvocationExpression( - // new MemberReferenceExpression(new AnyNode("object"), "GetType") - // )) - // ); - // static readonly AstNode inEqualityComparePattern = - // PatternHelper.CommutativeOperator( - // PatternHelper.OptionalParentheses(new TypeOfExpression(new AnyNode("Type"))), - // BinaryOperatorType.InEquality, - // PatternHelper.OptionalParentheses(new InvocationExpression( - // new MemberReferenceExpression(new AnyNode("object"), "GetType") - // )) - // ); - // public override void VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression) - // { - // base.VisitBinaryOperatorExpression(binaryOperatorExpression); - // var match = equalityComparePattern.Match(binaryOperatorExpression); - // if (match.Success) { - // AddDiagnosticAnalyzer(new CodeIssue(binaryOperatorExpression, match); - // return; - // } +// // /* Unfortunately not quite the same :/ +// // static readonly AstNode equalityComparePattern = +// // PatternHelper.CommutativeOperator( +// // PatternHelper.OptionalParentheses(new TypeOfExpression(new AnyNode("Type"))), +// // BinaryOperatorType.Equality, +// // PatternHelper.OptionalParentheses(new InvocationExpression( +// // new MemberReferenceExpression(new AnyNode("object"), "GetType") +// // )) +// // ); +// // static readonly AstNode inEqualityComparePattern = +// // PatternHelper.CommutativeOperator( +// // PatternHelper.OptionalParentheses(new TypeOfExpression(new AnyNode("Type"))), +// // BinaryOperatorType.InEquality, +// // PatternHelper.OptionalParentheses(new InvocationExpression( +// // new MemberReferenceExpression(new AnyNode("object"), "GetType") +// // )) +// // ); +// // public override void VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression) +// // { +// // base.VisitBinaryOperatorExpression(binaryOperatorExpression); +// // var match = equalityComparePattern.Match(binaryOperatorExpression); +// // if (match.Success) { +// // AddDiagnosticAnalyzer(new CodeIssue(binaryOperatorExpression, match); +// // return; +// // } - // match = inEqualityComparePattern.Match(binaryOperatorExpression); - // if (match.Success) { - // AddDiagnosticAnalyzer(new CodeIssue(binaryOperatorExpression, match, true); - // return; - // } - // }*/ - // } - } -} \ No newline at end of file +// // match = inEqualityComparePattern.Match(binaryOperatorExpression); +// // if (match.Success) { +// // AddDiagnosticAnalyzer(new CodeIssue(binaryOperatorExpression, match, true); +// // return; +// // } +// // }*/ +// // } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/UseMethodIsInstanceOfTypeAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/UseMethodIsInstanceOfTypeAnalyzer.cs index 05f47d81..d6546ddc 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/UseMethodIsInstanceOfTypeAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/PracticesAndImprovements/UseMethodIsInstanceOfTypeAnalyzer.cs @@ -1,81 +1,81 @@ -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 UseMethodIsInstanceOfTypeAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.UseMethodIsInstanceOfTypeAnalyzerID, - GettextCatalog.GetString("Use method IsInstanceOfType"), - GettextCatalog.GetString("Use method IsInstanceOfType (...)"), - DiagnosticAnalyzerCategories.PracticesAndImprovements, - DiagnosticSeverity.Info, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.UseMethodIsInstanceOfTypeAnalyzerID) - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class UseMethodIsInstanceOfTypeAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.UseMethodIsInstanceOfTypeAnalyzerID, +// GettextCatalog.GetString("Use method IsInstanceOfType"), +// GettextCatalog.GetString("Use method IsInstanceOfType (...)"), +// DiagnosticAnalyzerCategories.PracticesAndImprovements, +// DiagnosticSeverity.Info, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.UseMethodIsInstanceOfTypeAnalyzerID) +// ); - 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) +// // { +// // } - //// static readonly Expression pattern = new InvocationExpression( - //// new MemberReferenceExpression(new AnyNode("target"), "IsAssignableFrom"), - //// new InvocationExpression( - //// new MemberReferenceExpression(new AnyNode("object"), "GetType") - //// ) - //// ); - //// - //// public override void VisitInvocationExpression(InvocationExpression invocationExpression) - //// { - //// base.VisitInvocationExpression(invocationExpression); - //// var match = pattern.Match(invocationExpression); - //// if (match.Success) { - //// AddDiagnosticAnalyzer(new CodeIssue( - //// invocationExpression, - //// ctx.TranslateString(""), - //// ctx.TranslateString(""), - //// s => { - //// s.Replace(invocationExpression, new InvocationExpression( - //// new MemberReferenceExpression(match.Get("target").Single().Clone(), "IsInstanceOfType"), - //// match.Get("object").Single().Clone() - //// )); - //// } - //// )); - //// } - //// } - // } - } -} \ No newline at end of file +// //// static readonly Expression pattern = new InvocationExpression( +// //// new MemberReferenceExpression(new AnyNode("target"), "IsAssignableFrom"), +// //// new InvocationExpression( +// //// new MemberReferenceExpression(new AnyNode("object"), "GetType") +// //// ) +// //// ); +// //// +// //// public override void VisitInvocationExpression(InvocationExpression invocationExpression) +// //// { +// //// base.VisitInvocationExpression(invocationExpression); +// //// var match = pattern.Match(invocationExpression); +// //// if (match.Success) { +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// invocationExpression, +// //// ctx.TranslateString(""), +// //// ctx.TranslateString(""), +// //// s => { +// //// s.Replace(invocationExpression, new InvocationExpression( +// //// new MemberReferenceExpression(match.Get("target").Single().Clone(), "IsInstanceOfType"), +// //// match.Get("object").Single().Clone() +// //// )); +// //// } +// //// )); +// //// } +// //// } +// // } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantArgumentDefaultValueAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantArgumentDefaultValueAnalyzer.cs index c2ccee58..2d44de92 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantArgumentDefaultValueAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantArgumentDefaultValueAnalyzer.cs @@ -1,271 +1,271 @@ -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 RedundantArgumentDefaultValueAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.RedundantArgumentDefaultValueAnalyzerID, - GettextCatalog.GetString("Default argument value is redundant"), - GettextCatalog.GetString("The parameter is optional with the same default value"), - DiagnosticAnalyzerCategories.RedundanciesInCode, - DiagnosticSeverity.Hidden, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantArgumentDefaultValueAnalyzerID), - customTags: DiagnosticCustomTags.Unnecessary - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class RedundantArgumentDefaultValueAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.RedundantArgumentDefaultValueAnalyzerID, +// GettextCatalog.GetString("Default argument value is redundant"), +// GettextCatalog.GetString("The parameter is optional with the same default value"), +// DiagnosticAnalyzerCategories.RedundanciesInCode, +// DiagnosticSeverity.Hidden, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantArgumentDefaultValueAnalyzerID), +// 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) - // { - // } +// // class GatherVisitor : GatherVisitorBase +// // { +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // } - //// bool IsDefaultValue(Expression arg, RefactoringEssentials.TypeSystem.IParameter par) - //// { - //// var ne = arg as NamedArgumentExpression; - //// if (ne != null) { - //// if (ne.Name != par.Name) - //// return false; - //// arg = ne.Expression; - //// } - //// var cr = ctx.Resolve(arg); - //// if (cr == null || !cr.IsCompileTimeConstant || !par.IsOptional) - //// return false; - //// return - //// cr.ConstantValue == null && par.ConstantValue == null || - //// cr.ConstantValue.Equals(par.ConstantValue); - //// } - //// - //// public override void VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression) - //// { - //// base.VisitObjectCreateExpression(objectCreateExpression); - //// Check(objectCreateExpression, objectCreateExpression.Arguments.ToList()); - //// } - //// - //// public override void VisitInvocationExpression(InvocationExpression invocationExpression) - //// { - //// base.VisitInvocationExpression(invocationExpression); - //// Check(invocationExpression, invocationExpression.Arguments.ToList()); - //// } - //// - //// public override void VisitIndexerExpression(IndexerExpression indexerExpression) - //// { - //// base.VisitIndexerExpression(indexerExpression); - //// Check(indexerExpression, indexerExpression.Arguments.ToList()); - //// } - //// - //// void Check(AstNode invocationExpression, List arguments) - //// { - //// var rr = ctx.Resolve(invocationExpression) as CSharpInvocationResolveResult; - //// if (rr == null || rr.IsError) - //// return; - //// - //// for (int i = 0; i < arguments.Count && i < rr.Member.Parameters.Count; i++) { - //// - //// if (!IsDefaultValue(arguments[i], rr.Member.Parameters[i])) - //// continue; - //// bool nextAreAllDefault = true; - //// for (int j = i + 1; j < arguments.Count && j < rr.Member.Parameters.Count; j++) { - //// if (!IsDefaultValue(arguments[j], rr.Member.Parameters[j])) { - //// nextAreAllDefault = false; - //// break; - //// } - //// } - //// if (!nextAreAllDefault) - //// continue; - //// for (int j = i; j < arguments.Count && j < rr.Member.Parameters.Count; j++) { - //// var _i = j; - //// AddDiagnosticAnalyzer(new CodeIssue( - //// arguments[j], - //// i + 1 < arguments.Count ? ctx.TranslateString("Argument values are redundant") : ctx.TranslateString("Argument value is redundant"), - //// i + 1 < arguments.Count ? ctx.TranslateString("Remove redundant arguments") : ctx.TranslateString("Remove redundant argument"), - //// script => { - //// var invoke = invocationExpression.Clone(); - //// - //// var argCollection = invoke.GetChildrenByRole(Roles.Argument); - //// argCollection.Clear(); - //// for (int k = 0; k < _i; k++) - //// argCollection.Add(arguments[k].Clone()); - //// script.Replace(invocationExpression, invoke); - //// } - //// ) { IssueMarker = IssueMarker.GrayOut }); - //// } - //// break; - //// } - //// } - // } - } +// //// bool IsDefaultValue(Expression arg, RefactoringEssentials.TypeSystem.IParameter par) +// //// { +// //// var ne = arg as NamedArgumentExpression; +// //// if (ne != null) { +// //// if (ne.Name != par.Name) +// //// return false; +// //// arg = ne.Expression; +// //// } +// //// var cr = ctx.Resolve(arg); +// //// if (cr == null || !cr.IsCompileTimeConstant || !par.IsOptional) +// //// return false; +// //// return +// //// cr.ConstantValue == null && par.ConstantValue == null || +// //// cr.ConstantValue.Equals(par.ConstantValue); +// //// } +// //// +// //// public override void VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression) +// //// { +// //// base.VisitObjectCreateExpression(objectCreateExpression); +// //// Check(objectCreateExpression, objectCreateExpression.Arguments.ToList()); +// //// } +// //// +// //// public override void VisitInvocationExpression(InvocationExpression invocationExpression) +// //// { +// //// base.VisitInvocationExpression(invocationExpression); +// //// Check(invocationExpression, invocationExpression.Arguments.ToList()); +// //// } +// //// +// //// public override void VisitIndexerExpression(IndexerExpression indexerExpression) +// //// { +// //// base.VisitIndexerExpression(indexerExpression); +// //// Check(indexerExpression, indexerExpression.Arguments.ToList()); +// //// } +// //// +// //// void Check(AstNode invocationExpression, List arguments) +// //// { +// //// var rr = ctx.Resolve(invocationExpression) as CSharpInvocationResolveResult; +// //// if (rr == null || rr.IsError) +// //// return; +// //// +// //// for (int i = 0; i < arguments.Count && i < rr.Member.Parameters.Count; i++) { +// //// +// //// if (!IsDefaultValue(arguments[i], rr.Member.Parameters[i])) +// //// continue; +// //// bool nextAreAllDefault = true; +// //// for (int j = i + 1; j < arguments.Count && j < rr.Member.Parameters.Count; j++) { +// //// if (!IsDefaultValue(arguments[j], rr.Member.Parameters[j])) { +// //// nextAreAllDefault = false; +// //// break; +// //// } +// //// } +// //// if (!nextAreAllDefault) +// //// continue; +// //// for (int j = i; j < arguments.Count && j < rr.Member.Parameters.Count; j++) { +// //// var _i = j; +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// arguments[j], +// //// i + 1 < arguments.Count ? ctx.TranslateString("Argument values are redundant") : ctx.TranslateString("Argument value is redundant"), +// //// i + 1 < arguments.Count ? ctx.TranslateString("Remove redundant arguments") : ctx.TranslateString("Remove redundant argument"), +// //// script => { +// //// var invoke = invocationExpression.Clone(); +// //// +// //// var argCollection = invoke.GetChildrenByRole(Roles.Argument); +// //// argCollection.Clear(); +// //// for (int k = 0; k < _i; k++) +// //// argCollection.Add(arguments[k].Clone()); +// //// script.Replace(invocationExpression, invoke); +// //// } +// //// ) { IssueMarker = IssueMarker.GrayOut }); +// //// } +// //// break; +// //// } +// //// } +// // } +// } - /* TODO: Merge: -[IssueDescription("Optional argument has default value and can be skipped", - Description = "Finds calls to functions where optional parameters are used and the passed argument is the same as the default.", - Category = IssueCategories.RedundanciesInCode, - Severity = Severity.Hint)] - public class OptionalParameterCouldBeSkippedAnalyzer : GatherVisitorCodeIssueProvider - { - protected override IGatherVisitor CreateVisitor(BaseSemanticModel context) - { - return new GatherVisitor(context); - } +// /* TODO: Merge: +//[IssueDescription("Optional argument has default value and can be skipped", +// Description = "Finds calls to functions where optional parameters are used and the passed argument is the same as the default.", +// Category = IssueCategories.RedundanciesInCode, +// Severity = Severity.Hint)] +// public class OptionalParameterCouldBeSkippedAnalyzer : GatherVisitorCodeIssueProvider +// { +// protected override IGatherVisitor CreateVisitor(BaseSemanticModel context) +// { +// return new GatherVisitor(context); +// } - class GatherVisitor : GatherVisitorBase - { - static readonly object removeAllRedundantArgumentsKey = new object (); +// class GatherVisitor : GatherVisitorBase +// { +// static readonly object removeAllRedundantArgumentsKey = new object (); - public GatherVisitor(BaseSemanticModel context) : base (context) - { - } +// public GatherVisitor(BaseSemanticModel context) : base (context) +// { +// } - public override void VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression) - { - base.VisitObjectCreateExpression(objectCreateExpression); +// public override void VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression) +// { +// base.VisitObjectCreateExpression(objectCreateExpression); - CheckMethodCall(objectCreateExpression, objectCreateExpression.Arguments, - (objectCreation, args) => new ObjectCreateExpression(objectCreation.Type.Clone(), args)); - } +// CheckMethodCall(objectCreateExpression, objectCreateExpression.Arguments, +// (objectCreation, args) => new ObjectCreateExpression(objectCreation.Type.Clone(), args)); +// } - public override void VisitInvocationExpression(InvocationExpression invocationExpression) - { - base.VisitInvocationExpression(invocationExpression); +// public override void VisitInvocationExpression(InvocationExpression invocationExpression) +// { +// base.VisitInvocationExpression(invocationExpression); - CheckMethodCall(invocationExpression, invocationExpression.Arguments, - (invocation, args) => new InvocationExpression(invocation.Target.Clone(), args)); - } +// CheckMethodCall(invocationExpression, invocationExpression.Arguments, +// (invocation, args) => new InvocationExpression(invocation.Target.Clone(), args)); +// } - void CheckMethodCall (T node, IEnumerable args, Func, T> generateReplacement) where T: AstNode - { - // The first two checks are unnecessary, but eliminates the majority of calls early, - // improving performance. - var arguments = args.ToArray(); - if (arguments.Length == 0) - return; - var lastArg = arguments[arguments.Length - 1]; - if (!(lastArg is PrimitiveExpression || lastArg is NamedArgumentExpression)) - return; +// void CheckMethodCall (T node, IEnumerable args, Func, T> generateReplacement) where T: AstNode +// { +// // The first two checks are unnecessary, but eliminates the majority of calls early, +// // improving performance. +// var arguments = args.ToArray(); +// if (arguments.Length == 0) +// return; +// var lastArg = arguments[arguments.Length - 1]; +// if (!(lastArg is PrimitiveExpression || lastArg is NamedArgumentExpression)) +// return; - var invocationResolveResult = ctx.Resolve(node) as CSharpInvocationResolveResult; - if (invocationResolveResult == null) - return; +// var invocationResolveResult = ctx.Resolve(node) as CSharpInvocationResolveResult; +// if (invocationResolveResult == null) +// return; - string actionMessage = ctx.TranslateString("Remove redundant arguments"); +// string actionMessage = ctx.TranslateString("Remove redundant arguments"); - var redundantArguments = GetRedundantArguments(arguments, invocationResolveResult); - var action = new CodeAction(actionMessage, script => { - var newArgumentList = arguments - .Where(arg => !redundantArguments.Contains(arg)) - .Select(arg => arg.Clone()); - var newInvocation = generateReplacement(node, newArgumentList); - script.Replace(node, newInvocation); - }, node, removeAllRedundantArgumentsKey); - var issueMessage = ctx.TranslateString("Argument is identical to the default value"); - var lastPositionalArgument = redundantArguments.FirstOrDefault(expression => !(expression is NamedArgumentExpression)); +// var redundantArguments = GetRedundantArguments(arguments, invocationResolveResult); +// var action = new CodeAction(actionMessage, script => { +// var newArgumentList = arguments +// .Where(arg => !redundantArguments.Contains(arg)) +// .Select(arg => arg.Clone()); +// var newInvocation = generateReplacement(node, newArgumentList); +// script.Replace(node, newInvocation); +// }, node, removeAllRedundantArgumentsKey); +// var issueMessage = ctx.TranslateString("Argument is identical to the default value"); +// var lastPositionalArgument = redundantArguments.FirstOrDefault(expression => !(expression is NamedArgumentExpression)); - foreach (var argument in redundantArguments) { - var localArgument = argument; - var actions = new List(); - actions.Add(action); +// foreach (var argument in redundantArguments) { +// var localArgument = argument; +// var actions = new List(); +// actions.Add(action); - if (localArgument is NamedArgumentExpression || localArgument == lastPositionalArgument) { - var title = ctx.TranslateString("Remove this argument"); - actions.Add(new CodeAction(title, script => { - var newArgumentList = arguments - .Where(arg => arg != localArgument) - .Select(arg => arg.Clone()); - var newInvocation = generateReplacement(node, newArgumentList); - script.Replace(node, newInvocation); - }, node, null)); - } else { - var title = ctx.TranslateString("Remove this and the following positional arguments"); - actions.Add(new CodeAction(title, script => { - var newArgumentList = arguments - .Where(arg => arg.StartLocation < localArgument.StartLocation && !(arg is NamedArgumentExpression)) - .Select(arg => arg.Clone()); - var newInvocation = generateReplacement(node, newArgumentList); - script.Replace(node, newInvocation); - }, node, null)); - } +// if (localArgument is NamedArgumentExpression || localArgument == lastPositionalArgument) { +// var title = ctx.TranslateString("Remove this argument"); +// actions.Add(new CodeAction(title, script => { +// var newArgumentList = arguments +// .Where(arg => arg != localArgument) +// .Select(arg => arg.Clone()); +// var newInvocation = generateReplacement(node, newArgumentList); +// script.Replace(node, newInvocation); +// }, node, null)); +// } else { +// var title = ctx.TranslateString("Remove this and the following positional arguments"); +// actions.Add(new CodeAction(title, script => { +// var newArgumentList = arguments +// .Where(arg => arg.StartLocation < localArgument.StartLocation && !(arg is NamedArgumentExpression)) +// .Select(arg => arg.Clone()); +// var newInvocation = generateReplacement(node, newArgumentList); +// script.Replace(node, newInvocation); +// }, node, null)); +// } - AddDiagnosticAnalyzer(new CodeIssue(localArgument, issueMessage, actions) { IssueMarker = IssueMarker.GrayOut }); - } - } +// AddDiagnosticAnalyzer(new CodeIssue(localArgument, issueMessage, actions) { IssueMarker = IssueMarker.GrayOut }); +// } +// } - IList GetRedundantArguments(Expression[] arguments, CSharpInvocationResolveResult invocationResolveResult) - { - var argumentToParameterMap = invocationResolveResult.GetArgumentToParameterMap(); - var resolvedParameters = invocationResolveResult.Member.Parameters; +// IList GetRedundantArguments(Expression[] arguments, CSharpInvocationResolveResult invocationResolveResult) +// { +// var argumentToParameterMap = invocationResolveResult.GetArgumentToParameterMap(); +// var resolvedParameters = invocationResolveResult.Member.Parameters; - IList redundantArguments = new List(); +// IList redundantArguments = new List(); - for (int i = arguments.Length - 1; i >= 0; i--) { - var parameterIndex = argumentToParameterMap[i]; - if (parameterIndex == -1) - // This particular parameter is an error, but keep trying the other ones - continue; - var parameter = resolvedParameters[parameterIndex]; - var argument = arguments[i]; - if (argument is PrimitiveExpression) { - if (parameter.IsParams) - // before positional params arguments all optional arguments are needed, otherwise some of the - // param arguments will be shifted out of the params into the fixed parameters - break; - if (!parameter.IsOptional) - // There can be no optional parameters preceding a required one - break; - var argumentResolveResult = ctx.Resolve(argument) as ConstantResolveResult; - if (argumentResolveResult == null || parameter.ConstantValue != argumentResolveResult.ConstantValue) - // Stop here since any arguments before this one has to be there - // to enable the passing of this argument - break; - redundantArguments.Add(argument); - } else if (argument is NamedArgumentExpression) { - var expression = ((NamedArgumentExpression)argument).Expression as PrimitiveExpression; - if (expression == null) - continue; - var expressionResolveResult = ctx.Resolve(expression) as ConstantResolveResult; - if (expressionResolveResult == null || parameter.ConstantValue != expressionResolveResult.ConstantValue) - // continue, since there can still be more arguments that are redundant - continue; - redundantArguments.Add(argument); - } else { - // This is a non-constant positional argument => no more redundancies are possible - break; - } - } - return redundantArguments; - } - } - } -*/ -} \ No newline at end of file +// for (int i = arguments.Length - 1; i >= 0; i--) { +// var parameterIndex = argumentToParameterMap[i]; +// if (parameterIndex == -1) +// // This particular parameter is an error, but keep trying the other ones +// continue; +// var parameter = resolvedParameters[parameterIndex]; +// var argument = arguments[i]; +// if (argument is PrimitiveExpression) { +// if (parameter.IsParams) +// // before positional params arguments all optional arguments are needed, otherwise some of the +// // param arguments will be shifted out of the params into the fixed parameters +// break; +// if (!parameter.IsOptional) +// // There can be no optional parameters preceding a required one +// break; +// var argumentResolveResult = ctx.Resolve(argument) as ConstantResolveResult; +// if (argumentResolveResult == null || parameter.ConstantValue != argumentResolveResult.ConstantValue) +// // Stop here since any arguments before this one has to be there +// // to enable the passing of this argument +// break; +// redundantArguments.Add(argument); +// } else if (argument is NamedArgumentExpression) { +// var expression = ((NamedArgumentExpression)argument).Expression as PrimitiveExpression; +// if (expression == null) +// continue; +// var expressionResolveResult = ctx.Resolve(expression) as ConstantResolveResult; +// if (expressionResolveResult == null || parameter.ConstantValue != expressionResolveResult.ConstantValue) +// // continue, since there can still be more arguments that are redundant +// continue; +// redundantArguments.Add(argument); +// } else { +// // This is a non-constant positional argument => no more redundancies are possible +// break; +// } +// } +// return redundantArguments; +// } +// } +// } +//*/ +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantBoolCompareAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantBoolCompareAnalyzer.cs index 83ef092f..ce279a60 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantBoolCompareAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantBoolCompareAnalyzer.cs @@ -1,109 +1,109 @@ -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 RedundantBoolCompareAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.RedundantBoolCompareAnalyzerID, - GettextCatalog.GetString("Comparison of a boolean value with 'true' or 'false' constant"), - GettextCatalog.GetString("Comparison with '{0}' is redundant"), - DiagnosticAnalyzerCategories.RedundanciesInCode, - DiagnosticSeverity.Hidden, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantBoolCompareAnalyzerID), - customTags: DiagnosticCustomTags.Unnecessary - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class RedundantBoolCompareAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.RedundantBoolCompareAnalyzerID, +// GettextCatalog.GetString("Comparison of a boolean value with 'true' or 'false' constant"), +// GettextCatalog.GetString("Comparison with '{0}' is redundant"), +// DiagnosticAnalyzerCategories.RedundanciesInCode, +// DiagnosticSeverity.Hidden, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantBoolCompareAnalyzerID), +// 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 - // { - //// // note:this action should only check == true or != null - it needs excectly - //// // mimic the RedundantBoolCompare behavior otherwise it's no 1:1 mapping - //// static readonly Pattern pattern = new Choice { - //// PatternHelper.CommutativeOperatorWithOptionalParentheses( - //// new NamedNode ("const", new Choice { new PrimitiveExpression(true), new PrimitiveExpression(false) }), - //// BinaryOperatorType.Equality, new AnyNode("expr")), - //// PatternHelper.CommutativeOperatorWithOptionalParentheses( - //// new NamedNode ("const", new Choice { new PrimitiveExpression(true), new PrimitiveExpression(false) }), - //// BinaryOperatorType.InEquality, new AnyNode("expr")), - //// }; - //// - //// static readonly InsertParenthesesVisitor insertParenthesesVisitor = new InsertParenthesesVisitor (); +// // class GatherVisitor : GatherVisitorBase +// // { +// //// // note:this action should only check == true or != null - it needs excectly +// //// // mimic the RedundantBoolCompare behavior otherwise it's no 1:1 mapping +// //// static readonly Pattern pattern = new Choice { +// //// PatternHelper.CommutativeOperatorWithOptionalParentheses( +// //// new NamedNode ("const", new Choice { new PrimitiveExpression(true), new PrimitiveExpression(false) }), +// //// BinaryOperatorType.Equality, new AnyNode("expr")), +// //// PatternHelper.CommutativeOperatorWithOptionalParentheses( +// //// new NamedNode ("const", new Choice { new PrimitiveExpression(true), new PrimitiveExpression(false) }), +// //// BinaryOperatorType.InEquality, new AnyNode("expr")), +// //// }; +// //// +// //// static readonly InsertParenthesesVisitor insertParenthesesVisitor = new InsertParenthesesVisitor (); - // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) - // : base (semanticModel, addDiagnostic, cancellationToken) - // { - // } - //// - //// public override void VisitBinaryOperatorExpression (BinaryOperatorExpression binaryOperatorExpression) - //// { - //// base.VisitBinaryOperatorExpression (binaryOperatorExpression); - //// - //// var match = pattern.Match (binaryOperatorExpression); - //// if (!match.Success) - //// return; - //// var expr = match.Get ("expr").First (); - //// // check if expr is of boolean type - //// var exprType = ctx.Resolve (expr).Type.GetDefinition (); - //// if (exprType == null || exprType.KnownTypeCode != KnownTypeCode.Boolean) - //// return; - //// - //// var boolExpr = match.Get("const").First(); - //// var boolConstant = (bool)boolExpr.Value; - //// - //// TextLocation start, end; - //// if (boolExpr == binaryOperatorExpression.Left) { - //// start = binaryOperatorExpression.StartLocation; - //// end = binaryOperatorExpression.OperatorToken.EndLocation; - //// } else { - //// start = binaryOperatorExpression.OperatorToken.StartLocation; - //// end = binaryOperatorExpression.EndLocation; - //// } - //// - //// AddDiagnosticAnalyzer (new CodeIssue( - //// start, end, - // // boolConstant ? ctx.TranslateString ("Comparison with 'true' is redundant") : ctx.TranslateString ("Comparison with 'false' is redundant"), - // // ctx.TranslateString ("Remove redundant comparison"), - //// script => { - //// if ((binaryOperatorExpression.Operator == BinaryOperatorType.InEquality && boolConstant) || - //// (binaryOperatorExpression.Operator == BinaryOperatorType.Equality && !boolConstant)) { - //// expr = new UnaryOperatorExpression (UnaryOperatorType.Not, expr.Clone()); - //// expr.AcceptVisitor (insertParenthesesVisitor); - //// } - //// script.Replace (binaryOperatorExpression, expr); - //// } - //// ) { IssueMarker = IssueMarker.GrayOut }); - //// } - // } - } -} +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // } +// //// +// //// public override void VisitBinaryOperatorExpression (BinaryOperatorExpression binaryOperatorExpression) +// //// { +// //// base.VisitBinaryOperatorExpression (binaryOperatorExpression); +// //// +// //// var match = pattern.Match (binaryOperatorExpression); +// //// if (!match.Success) +// //// return; +// //// var expr = match.Get ("expr").First (); +// //// // check if expr is of boolean type +// //// var exprType = ctx.Resolve (expr).Type.GetDefinition (); +// //// if (exprType == null || exprType.KnownTypeCode != KnownTypeCode.Boolean) +// //// return; +// //// +// //// var boolExpr = match.Get("const").First(); +// //// var boolConstant = (bool)boolExpr.Value; +// //// +// //// TextLocation start, end; +// //// if (boolExpr == binaryOperatorExpression.Left) { +// //// start = binaryOperatorExpression.StartLocation; +// //// end = binaryOperatorExpression.OperatorToken.EndLocation; +// //// } else { +// //// start = binaryOperatorExpression.OperatorToken.StartLocation; +// //// end = binaryOperatorExpression.EndLocation; +// //// } +// //// +// //// AddDiagnosticAnalyzer (new CodeIssue( +// //// start, end, +// // // boolConstant ? ctx.TranslateString ("Comparison with 'true' is redundant") : ctx.TranslateString ("Comparison with 'false' is redundant"), +// // // ctx.TranslateString ("Remove redundant comparison"), +// //// script => { +// //// if ((binaryOperatorExpression.Operator == BinaryOperatorType.InEquality && boolConstant) || +// //// (binaryOperatorExpression.Operator == BinaryOperatorType.Equality && !boolConstant)) { +// //// expr = new UnaryOperatorExpression (UnaryOperatorType.Not, expr.Clone()); +// //// expr.AcceptVisitor (insertParenthesesVisitor); +// //// } +// //// script.Replace (binaryOperatorExpression, expr); +// //// } +// //// ) { IssueMarker = IssueMarker.GrayOut }); +// //// } +// // } +// } +//} diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCatchClauseAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCatchClauseAnalyzer.cs index ba2ccc60..637ee4fa 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCatchClauseAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCatchClauseAnalyzer.cs @@ -1,164 +1,164 @@ -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 RedundantCatchClauseAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.RedundantCatchClauseAnalyzerID, - GettextCatalog.GetString("Catch clause with a single 'throw' statement is redundant"), - "{0}", - DiagnosticAnalyzerCategories.RedundanciesInCode, - DiagnosticSeverity.Hidden, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantCatchClauseAnalyzerID), - customTags: DiagnosticCustomTags.Unnecessary - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class RedundantCatchClauseAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.RedundantCatchClauseAnalyzerID, +// GettextCatalog.GetString("Catch clause with a single 'throw' statement is redundant"), +// "{0}", +// DiagnosticAnalyzerCategories.RedundanciesInCode, +// DiagnosticSeverity.Hidden, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantCatchClauseAnalyzerID), +// customTags: DiagnosticCustomTags.Unnecessary +// ); - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor); +// public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(descriptor); - // "Remove redundant catch clauses" / "Remove 'catch'" / "'try' statement is redundant" / "Remove all '{0}' redundant 'catch' clauses" / "Remove 'try' statement" - 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 } - //); - } +// // "Remove redundant catch clauses" / "Remove 'catch'" / "'try' statement is redundant" / "Remove all '{0}' redundant 'catch' clauses" / "Remove 'try' statement" +// 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 VisitTryCatchStatement(TryCatchStatement tryCatchStatement) - //// { - //// var redundantCatchClauses = new List(); - //// bool hasNonRedundantCatch = false; - //// foreach (var catchClause in tryCatchStatement.CatchClauses) { - //// if (IsRedundant(catchClause)) { - //// redundantCatchClauses.Add(catchClause); - //// } else { - //// hasNonRedundantCatch = true; - //// } - //// } - //// - //// if (hasNonRedundantCatch || !tryCatchStatement.FinallyBlock.IsNull) { - //// AddDiagnosticAnalyzersForClauses(tryCatchStatement, redundantCatchClauses); - //// } else { - //// AddDiagnosticAnalyzerForTryCatchStatement(tryCatchStatement); - //// } - //// } - //// - //// void AddDiagnosticAnalyzersForClauses(AstNode node, List redundantCatchClauses) - //// { - // // var allCatchClausesMessage = ctx.TranslateString(""); - //// var removeAllRedundantClausesAction = new CodeAction(allCatchClausesMessage, script => { - //// foreach (var redundantCatchClause in redundantCatchClauses) { - //// script.Remove(redundantCatchClause); - //// } - //// }, node); - //// var singleCatchClauseMessage = ctx.TranslateString(""); - //// var redundantCatchClauseMessage = ctx.TranslateString(""); - //// foreach (var redundantCatchClause in redundantCatchClauses) { - //// var closureLocalCatchClause = redundantCatchClause; - //// var removeRedundantClauseAction = new CodeAction(singleCatchClauseMessage, script => { - //// script.Remove(closureLocalCatchClause); - //// }, node); - //// var actions = new List(); - //// actions.Add(removeRedundantClauseAction); - //// if (redundantCatchClauses.Count > 1) { - //// actions.Add(removeAllRedundantClausesAction); - //// } - //// AddDiagnosticAnalyzer(new CodeIssue(closureLocalCatchClause, redundantCatchClauseMessage, actions) { IssueMarker = IssueMarker.GrayOut }); - //// } - //// } - //// - //// void AddDiagnosticAnalyzerForTryCatchStatement(TryCatchStatement tryCatchStatement) - //// { - //// var lastCatch = tryCatchStatement.CatchClauses.LastOrNullObject(); - //// if (lastCatch.IsNull) - //// return; - //// - //// var removeTryCatchMessage = ctx.TranslateString(""); - //// - //// var removeTryStatementAction = new CodeAction(removeTryCatchMessage, script => { - //// var statements = tryCatchStatement.TryBlock.Statements; - //// if (statements.Count == 1 || tryCatchStatement.Parent is BlockStatement) { - //// foreach (var statement in statements) { - //// script.InsertAfter(tryCatchStatement.GetPrevSibling (s => !(s is NewLineNode)), statement.Clone()); - //// } - //// script.Remove(tryCatchStatement); - //// } else { - //// var blockStatement = new BlockStatement(); - //// foreach (var statement in statements) { - //// blockStatement.Statements.Add(statement.Clone()); - //// } - //// script.Replace(tryCatchStatement, blockStatement); - //// } - //// // The replace and insert script functions does not format these things well on their own - //// script.FormatText(tryCatchStatement.Parent); - //// }, tryCatchStatement); - //// - //// var fixes = new [] { - //// removeTryStatementAction - //// }; - //// AddDiagnosticAnalyzer(new CodeIssue(tryCatchStatement.TryBlock.EndLocation, lastCatch.EndLocation, removeTryCatchMessage, fixes) { IssueMarker = IssueMarker.GrayOut }); - //// } - //// - //// static bool IsThrowsClause (CatchClause catchClause) - //// { - //// var firstStatement = catchClause.Body.Statements.FirstOrNullObject(); - //// if (firstStatement.IsNull) - //// return false; - //// var throwStatement = firstStatement as ThrowStatement; - //// if (throwStatement == null || !throwStatement.Expression.IsNull) - //// return false; - //// return true; - //// } - //// - //// bool IsRedundant(CatchClause catchClause) - //// { - //// if (!IsThrowsClause (catchClause)) - //// return false; - //// - //// var type = ctx.Resolve (catchClause.Type).Type; - //// var n = catchClause.NextSibling; - //// while (n != null) { - //// var nextClause = n as CatchClause; - //// if (nextClause != null) { - //// if (nextClause.Type.IsNull && !IsThrowsClause(nextClause)) - //// return false; - //// if (!IsThrowsClause(nextClause) && type.GetDefinition ().IsDerivedFrom (ctx.Resolve (nextClause.Type).Type.GetDefinition ())) - //// return false; - //// } - //// n = n.NextSibling; - //// } - //// return true; - //// } - // } - } -} +// //// public override void VisitTryCatchStatement(TryCatchStatement tryCatchStatement) +// //// { +// //// var redundantCatchClauses = new List(); +// //// bool hasNonRedundantCatch = false; +// //// foreach (var catchClause in tryCatchStatement.CatchClauses) { +// //// if (IsRedundant(catchClause)) { +// //// redundantCatchClauses.Add(catchClause); +// //// } else { +// //// hasNonRedundantCatch = true; +// //// } +// //// } +// //// +// //// if (hasNonRedundantCatch || !tryCatchStatement.FinallyBlock.IsNull) { +// //// AddDiagnosticAnalyzersForClauses(tryCatchStatement, redundantCatchClauses); +// //// } else { +// //// AddDiagnosticAnalyzerForTryCatchStatement(tryCatchStatement); +// //// } +// //// } +// //// +// //// void AddDiagnosticAnalyzersForClauses(AstNode node, List redundantCatchClauses) +// //// { +// // // var allCatchClausesMessage = ctx.TranslateString(""); +// //// var removeAllRedundantClausesAction = new CodeAction(allCatchClausesMessage, script => { +// //// foreach (var redundantCatchClause in redundantCatchClauses) { +// //// script.Remove(redundantCatchClause); +// //// } +// //// }, node); +// //// var singleCatchClauseMessage = ctx.TranslateString(""); +// //// var redundantCatchClauseMessage = ctx.TranslateString(""); +// //// foreach (var redundantCatchClause in redundantCatchClauses) { +// //// var closureLocalCatchClause = redundantCatchClause; +// //// var removeRedundantClauseAction = new CodeAction(singleCatchClauseMessage, script => { +// //// script.Remove(closureLocalCatchClause); +// //// }, node); +// //// var actions = new List(); +// //// actions.Add(removeRedundantClauseAction); +// //// if (redundantCatchClauses.Count > 1) { +// //// actions.Add(removeAllRedundantClausesAction); +// //// } +// //// AddDiagnosticAnalyzer(new CodeIssue(closureLocalCatchClause, redundantCatchClauseMessage, actions) { IssueMarker = IssueMarker.GrayOut }); +// //// } +// //// } +// //// +// //// void AddDiagnosticAnalyzerForTryCatchStatement(TryCatchStatement tryCatchStatement) +// //// { +// //// var lastCatch = tryCatchStatement.CatchClauses.LastOrNullObject(); +// //// if (lastCatch.IsNull) +// //// return; +// //// +// //// var removeTryCatchMessage = ctx.TranslateString(""); +// //// +// //// var removeTryStatementAction = new CodeAction(removeTryCatchMessage, script => { +// //// var statements = tryCatchStatement.TryBlock.Statements; +// //// if (statements.Count == 1 || tryCatchStatement.Parent is BlockStatement) { +// //// foreach (var statement in statements) { +// //// script.InsertAfter(tryCatchStatement.GetPrevSibling (s => !(s is NewLineNode)), statement.Clone()); +// //// } +// //// script.Remove(tryCatchStatement); +// //// } else { +// //// var blockStatement = new BlockStatement(); +// //// foreach (var statement in statements) { +// //// blockStatement.Statements.Add(statement.Clone()); +// //// } +// //// script.Replace(tryCatchStatement, blockStatement); +// //// } +// //// // The replace and insert script functions does not format these things well on their own +// //// script.FormatText(tryCatchStatement.Parent); +// //// }, tryCatchStatement); +// //// +// //// var fixes = new [] { +// //// removeTryStatementAction +// //// }; +// //// AddDiagnosticAnalyzer(new CodeIssue(tryCatchStatement.TryBlock.EndLocation, lastCatch.EndLocation, removeTryCatchMessage, fixes) { IssueMarker = IssueMarker.GrayOut }); +// //// } +// //// +// //// static bool IsThrowsClause (CatchClause catchClause) +// //// { +// //// var firstStatement = catchClause.Body.Statements.FirstOrNullObject(); +// //// if (firstStatement.IsNull) +// //// return false; +// //// var throwStatement = firstStatement as ThrowStatement; +// //// if (throwStatement == null || !throwStatement.Expression.IsNull) +// //// return false; +// //// return true; +// //// } +// //// +// //// bool IsRedundant(CatchClause catchClause) +// //// { +// //// if (!IsThrowsClause (catchClause)) +// //// return false; +// //// +// //// var type = ctx.Resolve (catchClause.Type).Type; +// //// var n = catchClause.NextSibling; +// //// while (n != null) { +// //// var nextClause = n as CatchClause; +// //// if (nextClause != null) { +// //// if (nextClause.Type.IsNull && !IsThrowsClause(nextClause)) +// //// return false; +// //// if (!IsThrowsClause(nextClause) && type.GetDefinition ().IsDerivedFrom (ctx.Resolve (nextClause.Type).Type.GetDefinition ())) +// //// return false; +// //// } +// //// n = n.NextSibling; +// //// } +// //// return true; +// //// } +// // } +// } +//} diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCommaInArrayInitializerAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCommaInArrayInitializerAnalyzer.cs index 9b4f05c8..7224729c 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCommaInArrayInitializerAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantCommaInArrayInitializerAnalyzer.cs @@ -53,13 +53,11 @@ static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnost return false; var elementCount = node.Expressions.Count; - if (elementCount > node.Expressions.GetSeparators().Count()) + var separatorCount = node.Expressions.SeparatorCount; + if (elementCount > separatorCount || separatorCount <= 0) return false; - var tokens = node.ChildTokens().ToArray(); - if (tokens.Length < 2) - return false; - var commaToken = tokens[tokens.Length - 2]; + var commaToken = node.Expressions.GetSeparator(separatorCount - 1); if (!commaToken.IsKind(SyntaxKind.CommaToken)) return false; @@ -67,4 +65,4 @@ static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnost return true; } } -} \ No newline at end of file +} diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantComparisonWithNullAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantComparisonWithNullAnalyzer.cs index fc946ca1..e10a9c82 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantComparisonWithNullAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantComparisonWithNullAnalyzer.cs @@ -1,102 +1,102 @@ -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 RedundantComparisonWithNullAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.RedundantComparisonWithNullAnalyzerID, - GettextCatalog.GetString("When 'is' keyword is used, which implicitly check null"), - GettextCatalog.GetString("Redundant comparison with 'null'"), - DiagnosticAnalyzerCategories.RedundanciesInCode, - DiagnosticSeverity.Hidden, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantComparisonWithNullAnalyzerID), - customTags: DiagnosticCustomTags.Unnecessary - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class RedundantComparisonWithNullAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.RedundantComparisonWithNullAnalyzerID, +// GettextCatalog.GetString("When 'is' keyword is used, which implicitly check null"), +// GettextCatalog.GetString("Redundant comparison with 'null'"), +// DiagnosticAnalyzerCategories.RedundanciesInCode, +// DiagnosticSeverity.Hidden, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantComparisonWithNullAnalyzerID), +// 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) - // { - // } +// // class GatherVisitor : GatherVisitorBase +// // { +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // } - //// public override void VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression) - //// { - //// base.VisitBinaryOperatorExpression(binaryOperatorExpression); - //// Match m1 = pattern1.Match(binaryOperatorExpression); - //// if (m1.Success) { - //// AddDiagnosticAnalyzer(new CodeIssue(binaryOperatorExpression, - //// ctx.TranslateString(""), - //// ctx.TranslateString(""), - //// script => { - //// var isExpr = m1.Get("t").Single().Parent; - //// script.Replace(binaryOperatorExpression, isExpr); - //// } - //// ) { IssueMarker = IssueMarker.GrayOut }); - //// return; - //// } - //// } - // } +// //// public override void VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression) +// //// { +// //// base.VisitBinaryOperatorExpression(binaryOperatorExpression); +// //// Match m1 = pattern1.Match(binaryOperatorExpression); +// //// if (m1.Success) { +// //// AddDiagnosticAnalyzer(new CodeIssue(binaryOperatorExpression, +// //// ctx.TranslateString(""), +// //// ctx.TranslateString(""), +// //// script => { +// //// var isExpr = m1.Get("t").Single().Parent; +// //// script.Replace(binaryOperatorExpression, isExpr); +// //// } +// //// ) { IssueMarker = IssueMarker.GrayOut }); +// //// return; +// //// } +// //// } +// // } - // private static readonly Pattern pattern1 - // = new Choice { - // // a is Record && a != null - // new BinaryOperatorExpression( - // PatternHelper.OptionalParentheses( - // new IsExpression { - // Expression = new AnyNode("a"), - // Type = new AnyNode("t") - // }), - // BinaryOperatorType.ConditionalAnd, - // PatternHelper.CommutativeOperatorWithOptionalParentheses(new Backreference("a"), - // BinaryOperatorType.InEquality, - // new NullReferenceExpression()) - // ), - // // a != null && a is Record - // new BinaryOperatorExpression ( - // PatternHelper.CommutativeOperatorWithOptionalParentheses(new AnyNode("a"), - // BinaryOperatorType.InEquality, - // new NullReferenceExpression()), - // BinaryOperatorType.ConditionalAnd, - // PatternHelper.OptionalParentheses( - // new IsExpression { - // Expression = new Backreference("a"), - // Type = new AnyNode("t") - // }) - // ) - // }; +// // private static readonly Pattern pattern1 +// // = new Choice { +// // // a is Record && a != null +// // new BinaryOperatorExpression( +// // PatternHelper.OptionalParentheses( +// // new IsExpression { +// // Expression = new AnyNode("a"), +// // Type = new AnyNode("t") +// // }), +// // BinaryOperatorType.ConditionalAnd, +// // PatternHelper.CommutativeOperatorWithOptionalParentheses(new Backreference("a"), +// // BinaryOperatorType.InEquality, +// // new NullReferenceExpression()) +// // ), +// // // a != null && a is Record +// // new BinaryOperatorExpression ( +// // PatternHelper.CommutativeOperatorWithOptionalParentheses(new AnyNode("a"), +// // BinaryOperatorType.InEquality, +// // new NullReferenceExpression()), +// // BinaryOperatorType.ConditionalAnd, +// // PatternHelper.OptionalParentheses( +// // new IsExpression { +// // Expression = new Backreference("a"), +// // Type = new AnyNode("t") +// // }) +// // ) +// // }; - } -} \ No newline at end of file +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantEnumerableCastCallAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantEnumerableCastCallAnalyzer.cs index 5c7ef58d..45ebd05a 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantEnumerableCastCallAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantEnumerableCastCallAnalyzer.cs @@ -1,114 +1,114 @@ -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 -{ - // OfType -> Underline (+suggest to compare to null) - [DiagnosticAnalyzer(LanguageNames.CSharp)] - [NotPortedYet] - public class RedundantEnumerableCastCallAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.RedundantEnumerableCastCallAnalyzerID, - GettextCatalog.GetString("Redundant 'IEnumerable.Cast' or 'IEnumerable.OfType' call"), - GettextCatalog.GetString("Redundant '{0}' call"), - DiagnosticAnalyzerCategories.RedundanciesInCode, - DiagnosticSeverity.Hidden, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantEnumerableCastCallAnalyzerID), - customTags: DiagnosticCustomTags.Unnecessary - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// // OfType -> Underline (+suggest to compare to null) +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class RedundantEnumerableCastCallAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.RedundantEnumerableCastCallAnalyzerID, +// GettextCatalog.GetString("Redundant 'IEnumerable.Cast' or 'IEnumerable.OfType' call"), +// GettextCatalog.GetString("Redundant '{0}' call"), +// DiagnosticAnalyzerCategories.RedundanciesInCode, +// DiagnosticSeverity.Hidden, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantEnumerableCastCallAnalyzerID), +// 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) - // { - // } +// // 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 mt = invocationExpression.Target as MemberReferenceExpression; - //// if (mt == null) - //// return; - //// var rr = ctx.Resolve(invocationExpression) as CSharpInvocationResolveResult; - //// if (rr == null || rr.IsError) - //// return; - //// if (rr.Member.DeclaringType.Name != "Enumerable" || rr.Member.DeclaringType.Namespace != "System.Linq") - //// return; - //// bool isCast = rr.Member.Name == "Cast"; - //// if (!isCast && rr.Member.Name != "OfType") - //// return; - //// var tr = ctx.Resolve(mt.Target); - //// if (tr.Type.Equals(rr.Type) || tr.Type.GetAllBaseTypes().Any (bt=> bt.Equals(rr.Type))) { - //// if (isCast) { - //// AddDiagnosticAnalyzer(new CodeIssue( - //// mt.DotToken.StartLocation, - //// mt.EndLocation, - //// ctx.TranslateString(""), - //// ctx.TranslateString(""), - //// s => s.Replace(invocationExpression, mt.Target.Clone()) - //// ) { IssueMarker = IssueMarker.GrayOut }); - //// } else { - //// AddDiagnosticAnalyzer(new CodeIssue( - //// mt.DotToken.StartLocation, - //// mt.EndLocation, - //// ctx.TranslateString(""), - //// new [] { - //// new CodeAction( - //// ctx.TranslateString("Compare items with null"), - //// s => { - //// var name = ctx.GetNameProposal("i", mt.StartLocation); - //// s.Replace(invocationExpression, - //// new InvocationExpression( - //// new MemberReferenceExpression(mt.Target.Clone(), "Where"), - //// new LambdaExpression { - //// Parameters = { new ParameterDeclaration(name) }, - //// Body = new BinaryOperatorExpression(new IdentifierExpression(name), BinaryOperatorType.InEquality, new NullReferenceExpression()) - //// } - //// ) - //// ); - //// }, - //// mt - //// ), - //// new CodeAction( - //// ctx.TranslateString("Remove 'OfType' call"), - //// s => s.Replace(invocationExpression, mt.Target.Clone()), - //// mt - //// ), - //// } - //// )); - //// } - //// } - //// } - // } - } -} \ No newline at end of file +// //// public override void VisitInvocationExpression(InvocationExpression invocationExpression) +// //// { +// //// base.VisitInvocationExpression(invocationExpression); +// //// var mt = invocationExpression.Target as MemberReferenceExpression; +// //// if (mt == null) +// //// return; +// //// var rr = ctx.Resolve(invocationExpression) as CSharpInvocationResolveResult; +// //// if (rr == null || rr.IsError) +// //// return; +// //// if (rr.Member.DeclaringType.Name != "Enumerable" || rr.Member.DeclaringType.Namespace != "System.Linq") +// //// return; +// //// bool isCast = rr.Member.Name == "Cast"; +// //// if (!isCast && rr.Member.Name != "OfType") +// //// return; +// //// var tr = ctx.Resolve(mt.Target); +// //// if (tr.Type.Equals(rr.Type) || tr.Type.GetAllBaseTypes().Any (bt=> bt.Equals(rr.Type))) { +// //// if (isCast) { +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// mt.DotToken.StartLocation, +// //// mt.EndLocation, +// //// ctx.TranslateString(""), +// //// ctx.TranslateString(""), +// //// s => s.Replace(invocationExpression, mt.Target.Clone()) +// //// ) { IssueMarker = IssueMarker.GrayOut }); +// //// } else { +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// mt.DotToken.StartLocation, +// //// mt.EndLocation, +// //// ctx.TranslateString(""), +// //// new [] { +// //// new CodeAction( +// //// ctx.TranslateString("Compare items with null"), +// //// s => { +// //// var name = ctx.GetNameProposal("i", mt.StartLocation); +// //// s.Replace(invocationExpression, +// //// new InvocationExpression( +// //// new MemberReferenceExpression(mt.Target.Clone(), "Where"), +// //// new LambdaExpression { +// //// Parameters = { new ParameterDeclaration(name) }, +// //// Body = new BinaryOperatorExpression(new IdentifierExpression(name), BinaryOperatorType.InEquality, new NullReferenceExpression()) +// //// } +// //// ) +// //// ); +// //// }, +// //// mt +// //// ), +// //// new CodeAction( +// //// ctx.TranslateString("Remove 'OfType' call"), +// //// s => s.Replace(invocationExpression, mt.Target.Clone()), +// //// mt +// //// ), +// //// } +// //// )); +// //// } +// //// } +// //// } +// // } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantExplicitArrayCreationAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantExplicitArrayCreationAnalyzer.cs index 36f33559..73310e36 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantExplicitArrayCreationAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantExplicitArrayCreationAnalyzer.cs @@ -1,98 +1,98 @@ -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 RedundantExplicitArrayCreationAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.RedundantExplicitArrayCreationAnalyzerID, - GettextCatalog.GetString("Redundant explicit type in array creation"), - GettextCatalog.GetString("Redundant explicit array type specification"), - DiagnosticAnalyzerCategories.RedundanciesInCode, - DiagnosticSeverity.Hidden, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantExplicitArrayCreationAnalyzerID), - customTags: DiagnosticCustomTags.Unnecessary - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class RedundantExplicitArrayCreationAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.RedundantExplicitArrayCreationAnalyzerID, +// GettextCatalog.GetString("Redundant explicit type in array creation"), +// GettextCatalog.GetString("Redundant explicit array type specification"), +// DiagnosticAnalyzerCategories.RedundanciesInCode, +// DiagnosticSeverity.Hidden, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantExplicitArrayCreationAnalyzerID), +// 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) - // { - // } +// // class GatherVisitor : GatherVisitorBase +// // { +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // } - //// public override void VisitSyntaxTree(SyntaxTree syntaxTree) - //// { - //// if (!ctx.Supports(new Version(3, 0))) - //// return; - //// base.VisitSyntaxTree(syntaxTree); - //// } - //// - //// public override void VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression) - //// { - //// base.VisitArrayCreateExpression(arrayCreateExpression); - //// if (arrayCreateExpression.Arguments.Count != 0) - //// return; - //// var arrayType = arrayCreateExpression.Type; - //// if (arrayType.IsNull) - //// return; - //// var arrayTypeRR = ctx.Resolve(arrayType); - //// if (arrayTypeRR.IsError) - //// return; - //// - //// IType elementType = null; - //// foreach (var element in arrayCreateExpression.Initializer.Elements) { - //// var elementTypeRR = ctx.Resolve(element); - //// if (elementTypeRR.IsError) - //// return; - //// if (elementType == null) { - //// elementType = elementTypeRR.Type; - //// continue; - //// } - //// if (elementType != elementTypeRR.Type) - //// return; - //// } - //// if (elementType != arrayTypeRR.Type) - //// return; - //// - //// AddDiagnosticAnalyzer( - //// new CodeIssue ( - //// arrayType, - //// s => s.Remove(arrayType) - //// ) { IssueMarker = IssueMarker.GrayOut } - //// ); - //// } - // } - } -} \ No newline at end of file +// //// public override void VisitSyntaxTree(SyntaxTree syntaxTree) +// //// { +// //// if (!ctx.Supports(new Version(3, 0))) +// //// return; +// //// base.VisitSyntaxTree(syntaxTree); +// //// } +// //// +// //// public override void VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression) +// //// { +// //// base.VisitArrayCreateExpression(arrayCreateExpression); +// //// if (arrayCreateExpression.Arguments.Count != 0) +// //// return; +// //// var arrayType = arrayCreateExpression.Type; +// //// if (arrayType.IsNull) +// //// return; +// //// var arrayTypeRR = ctx.Resolve(arrayType); +// //// if (arrayTypeRR.IsError) +// //// return; +// //// +// //// IType elementType = null; +// //// foreach (var element in arrayCreateExpression.Initializer.Elements) { +// //// var elementTypeRR = ctx.Resolve(element); +// //// if (elementTypeRR.IsError) +// //// return; +// //// if (elementType == null) { +// //// elementType = elementTypeRR.Type; +// //// continue; +// //// } +// //// if (elementType != elementTypeRR.Type) +// //// return; +// //// } +// //// if (elementType != arrayTypeRR.Type) +// //// return; +// //// +// //// AddDiagnosticAnalyzer( +// //// new CodeIssue ( +// //// arrayType, +// //// s => s.Remove(arrayType) +// //// ) { IssueMarker = IssueMarker.GrayOut } +// //// ); +// //// } +// // } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantExtendsListEntryAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantExtendsListEntryAnalyzer.cs index fcbf48fe..4fe8c4e1 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantExtendsListEntryAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantExtendsListEntryAnalyzer.cs @@ -1,150 +1,150 @@ -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 -{ - /// - /// Type is either mentioned in the base type list of other part, or it is interface and appears as other's type base and contains no explicit implementation. - /// - [DiagnosticAnalyzer(LanguageNames.CSharp)] - [NotPortedYet] - public class RedundantExtendsListEntryAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.RedundantExtendsListEntryAnalyzerID, - GettextCatalog.GetString("Type is either mentioned in the base type list of another part or in another base type"), - "{0}", - DiagnosticAnalyzerCategories.RedundanciesInCode, - DiagnosticSeverity.Hidden, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantExtendsListEntryAnalyzerID), - customTags: DiagnosticCustomTags.Unnecessary - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// /// +// /// Type is either mentioned in the base type list of other part, or it is interface and appears as other's type base and contains no explicit implementation. +// /// +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class RedundantExtendsListEntryAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.RedundantExtendsListEntryAnalyzerID, +// GettextCatalog.GetString("Type is either mentioned in the base type list of another part or in another base type"), +// "{0}", +// DiagnosticAnalyzerCategories.RedundanciesInCode, +// DiagnosticSeverity.Hidden, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantExtendsListEntryAnalyzerID), +// 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) - // { - // } +// // class GatherVisitor : GatherVisitorBase +// // { +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // } - //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) - //// { - //// if (typeDeclaration == null) - //// return; - //// - //// base.VisitTypeDeclaration(typeDeclaration); - //// - //// if (typeDeclaration.BaseTypes.Count == 0) - //// return; - //// - //// List redundantBase = new List(); - //// var type = ctx.Resolve(typeDeclaration).Type; - //// - //// if (typeDeclaration.HasModifier(Modifiers.Partial) && type.GetDefinition() != null) { - //// var parts = type.GetDefinition().Parts; - //// foreach (var node in typeDeclaration.BaseTypes) { - //// int count = 0; - //// foreach (var unresolvedTypeDefinition in parts) { - //// var baseTypes = unresolvedTypeDefinition.BaseTypes; - //// - //// if (baseTypes.Any(f => f.ToString().Equals(node.ToString()))) { - //// count++; - //// if (count > 1) { - //// if (!redundantBase.Contains(node)) - //// redundantBase.Add(node); - //// break; - //// } - //// } - //// } - //// } - //// } - //// - //// var directBaseType = type.DirectBaseTypes.Where(f => f.Kind == TypeKind.Class); - //// if (directBaseType.Count() != 1) - //// return; - //// var members = type.GetMembers(); - //// var memberDeclaration = typeDeclaration.Members; - //// var interfaceBase = typeDeclaration.BaseTypes.Where(delegate(AstType f) { - //// var resolveResult = ctx.Resolve(f); - //// if (resolveResult.IsError || resolveResult.Type.GetDefinition() == null) - //// return false; - //// return resolveResult.Type.GetDefinition().Kind == TypeKind.Interface; - //// }); - //// foreach (var node in interfaceBase) { - //// if (directBaseType.Single().GetDefinition().GetAllBaseTypeDefinitions().Any(f => f.Name.Equals(node.ToString()))) { - //// bool flag = false; - //// foreach (var member in members) { - //// if (!memberDeclaration.Any(f => f.Name.Equals(member.Name))) { - //// continue; - //// } - //// if ( - //// member.ImplementedInterfaceMembers.Any( - //// g => g.DeclaringType.Name.Equals(node.ToString()))) { - //// flag = true; - //// break; - //// } - //// } - //// if (!flag) { - //// if (!redundantBase.Contains(node)) - //// redundantBase.Add(node); - //// } - //// } - //// } - //// foreach (var node in redundantBase) { - //// var nodeType = ctx.Resolve(node).Type; - //// var issueText = nodeType.Kind == TypeKind.Interface ? - // // ctx.TranslateString("") : - //// ctx.TranslateString(""); - //// - //// AddDiagnosticAnalyzer(new CodeIssue( - //// node, - //// string.Format(issueText, nodeType.Name), - //// new CodeAction ( - //// ctx.TranslateString(""), - //// script => { - //// if (typeDeclaration.GetCSharpNodeBefore(node).ToString().Equals(":")) { - //// if (node.GetNextNode().Role != Roles.BaseType) { - //// script.Remove(typeDeclaration.GetCSharpNodeBefore(node)); - //// } - //// } - //// if (typeDeclaration.GetCSharpNodeBefore(node).ToString().Equals(",")) { - //// script.Remove(typeDeclaration.GetCSharpNodeBefore(node)); - //// } - //// script.Remove(node); - //// }, - //// node) - //// ) { IssueMarker = IssueMarker.GrayOut }); - //// } - //// } +// //// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration) +// //// { +// //// if (typeDeclaration == null) +// //// return; +// //// +// //// base.VisitTypeDeclaration(typeDeclaration); +// //// +// //// if (typeDeclaration.BaseTypes.Count == 0) +// //// return; +// //// +// //// List redundantBase = new List(); +// //// var type = ctx.Resolve(typeDeclaration).Type; +// //// +// //// if (typeDeclaration.HasModifier(Modifiers.Partial) && type.GetDefinition() != null) { +// //// var parts = type.GetDefinition().Parts; +// //// foreach (var node in typeDeclaration.BaseTypes) { +// //// int count = 0; +// //// foreach (var unresolvedTypeDefinition in parts) { +// //// var baseTypes = unresolvedTypeDefinition.BaseTypes; +// //// +// //// if (baseTypes.Any(f => f.ToString().Equals(node.ToString()))) { +// //// count++; +// //// if (count > 1) { +// //// if (!redundantBase.Contains(node)) +// //// redundantBase.Add(node); +// //// break; +// //// } +// //// } +// //// } +// //// } +// //// } +// //// +// //// var directBaseType = type.DirectBaseTypes.Where(f => f.Kind == TypeKind.Class); +// //// if (directBaseType.Count() != 1) +// //// return; +// //// var members = type.GetMembers(); +// //// var memberDeclaration = typeDeclaration.Members; +// //// var interfaceBase = typeDeclaration.BaseTypes.Where(delegate(AstType f) { +// //// var resolveResult = ctx.Resolve(f); +// //// if (resolveResult.IsError || resolveResult.Type.GetDefinition() == null) +// //// return false; +// //// return resolveResult.Type.GetDefinition().Kind == TypeKind.Interface; +// //// }); +// //// foreach (var node in interfaceBase) { +// //// if (directBaseType.Single().GetDefinition().GetAllBaseTypeDefinitions().Any(f => f.Name.Equals(node.ToString()))) { +// //// bool flag = false; +// //// foreach (var member in members) { +// //// if (!memberDeclaration.Any(f => f.Name.Equals(member.Name))) { +// //// continue; +// //// } +// //// if ( +// //// member.ImplementedInterfaceMembers.Any( +// //// g => g.DeclaringType.Name.Equals(node.ToString()))) { +// //// flag = true; +// //// break; +// //// } +// //// } +// //// if (!flag) { +// //// if (!redundantBase.Contains(node)) +// //// redundantBase.Add(node); +// //// } +// //// } +// //// } +// //// foreach (var node in redundantBase) { +// //// var nodeType = ctx.Resolve(node).Type; +// //// var issueText = nodeType.Kind == TypeKind.Interface ? +// // // ctx.TranslateString("") : +// //// ctx.TranslateString(""); +// //// +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// node, +// //// string.Format(issueText, nodeType.Name), +// //// new CodeAction ( +// //// ctx.TranslateString(""), +// //// script => { +// //// if (typeDeclaration.GetCSharpNodeBefore(node).ToString().Equals(":")) { +// //// if (node.GetNextNode().Role != Roles.BaseType) { +// //// script.Remove(typeDeclaration.GetCSharpNodeBefore(node)); +// //// } +// //// } +// //// if (typeDeclaration.GetCSharpNodeBefore(node).ToString().Equals(",")) { +// //// script.Remove(typeDeclaration.GetCSharpNodeBefore(node)); +// //// } +// //// script.Remove(node); +// //// }, +// //// node) +// //// ) { IssueMarker = IssueMarker.GrayOut }); +// //// } +// //// } - // } - } -} \ No newline at end of file +// // } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantIfElseBlockAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantIfElseBlockAnalyzer.cs index 086968ef..bb0a4458 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantIfElseBlockAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantIfElseBlockAnalyzer.cs @@ -48,7 +48,7 @@ static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnost if (ifElseStatement == null) return false; - if (!ElseIsRedundantControlFlow(ifElseStatement, nodeContext) || HasConflictingNames(nodeContext, ifElseStatement)) + if (HasConflictingNames(nodeContext, ifElseStatement) || !ElseIsRedundantControlFlow(ifElseStatement, nodeContext)) return false; diagnostic = Diagnostic.Create(descriptor, ifElseStatement.Else.ElseKeyword.GetLocation()); @@ -70,13 +70,13 @@ static bool ElseIsRedundantControlFlow(IfStatementSyntax ifElseStatement, Syntax static bool HasConflictingNames(SyntaxNodeAnalysisContext nodeContext, IfStatementSyntax ifElseStatement) { - var block = ifElseStatement.Else.Statement as BlockSyntax; + var block = ifElseStatement.Else?.Statement as BlockSyntax; if (block == null || block.Statements.Count == 0) return false; var member = ifElseStatement.Ancestors().FirstOrDefault(a => a is MemberDeclarationSyntax); - var priorLocalDeclarations = new List(); + var priorLocalDeclarations = new HashSet(); foreach (var localDecl in member.DescendantNodes().Where(n => n.SpanStart < ifElseStatement.Else.SpanStart).OfType()) { foreach (var v in localDecl.Declaration.Variables) priorLocalDeclarations.Add(v.Identifier.ValueText); @@ -87,11 +87,12 @@ static bool HasConflictingNames(SyntaxNodeAnalysisContext nodeContext, IfStateme var decl = sym as LocalDeclarationStatementSyntax; if (decl == null) continue; - - if (priorLocalDeclarations.Contains(s => decl.Declaration.Variables.Any(v => v.Identifier.ValueText == s))) - return true; + + foreach (var variable in decl.Declaration.Variables) + if (priorLocalDeclarations.Contains(variable.Identifier.ValueText)) + return true; } return false; } } -} \ No newline at end of file +} diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantLambdaParameterTypeAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantLambdaParameterTypeAnalyzer.cs index c418e300..7e5b08de 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantLambdaParameterTypeAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantLambdaParameterTypeAnalyzer.cs @@ -1,102 +1,102 @@ -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 RedundantLambdaParameterTypeAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.RedundantLambdaParameterTypeAnalyzerID, - GettextCatalog.GetString("Explicit type specification can be removed as it can be implicitly inferred"), - GettextCatalog.GetString("Redundant lambda explicit type specification"), - DiagnosticAnalyzerCategories.RedundanciesInCode, - DiagnosticSeverity.Hidden, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantLambdaParameterTypeAnalyzerID), - customTags: DiagnosticCustomTags.Unnecessary - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class RedundantLambdaParameterTypeAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.RedundantLambdaParameterTypeAnalyzerID, +// GettextCatalog.GetString("Explicit type specification can be removed as it can be implicitly inferred"), +// GettextCatalog.GetString("Redundant lambda explicit type specification"), +// DiagnosticAnalyzerCategories.RedundanciesInCode, +// DiagnosticSeverity.Hidden, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantLambdaParameterTypeAnalyzerID), +// 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) - // { - // } +// // class GatherVisitor : GatherVisitorBase +// // { +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // } - //// public override void VisitLambdaExpression(LambdaExpression lambdaExpression) - //// { - //// base.VisitLambdaExpression(lambdaExpression); - //// - //// var arguments = lambdaExpression.Parameters.ToList(); - //// if (arguments.Any(f => f.Type.IsNull)) - //// return; - //// if (!LambdaTypeCanBeInferred(ctx, lambdaExpression, arguments)) - //// return; - //// - //// foreach (var argument in arguments) { - //// AddDiagnosticAnalyzer(new CodeIssue( - //// argument.Type, - //// ctx.TranslateString(""), - //// ctx.TranslateString(""), - //// script => { - //// if (arguments.Count == 1) { - //// if (argument.NextSibling.ToString().Equals(")") && argument.PrevSibling.ToString().Equals("(")) { - //// script.Remove(argument.NextSibling); - //// script.Remove(argument.PrevSibling); - //// } - //// } - //// foreach (var arg in arguments) - //// script.Replace(arg, new ParameterDeclaration(arg.Name)); - //// }) { IssueMarker = IssueMarker.GrayOut }); - //// } - //// } - // } +// //// public override void VisitLambdaExpression(LambdaExpression lambdaExpression) +// //// { +// //// base.VisitLambdaExpression(lambdaExpression); +// //// +// //// var arguments = lambdaExpression.Parameters.ToList(); +// //// if (arguments.Any(f => f.Type.IsNull)) +// //// return; +// //// if (!LambdaTypeCanBeInferred(ctx, lambdaExpression, arguments)) +// //// return; +// //// +// //// foreach (var argument in arguments) { +// //// AddDiagnosticAnalyzer(new CodeIssue( +// //// argument.Type, +// //// ctx.TranslateString(""), +// //// ctx.TranslateString(""), +// //// script => { +// //// if (arguments.Count == 1) { +// //// if (argument.NextSibling.ToString().Equals(")") && argument.PrevSibling.ToString().Equals("(")) { +// //// script.Remove(argument.NextSibling); +// //// script.Remove(argument.PrevSibling); +// //// } +// //// } +// //// foreach (var arg in arguments) +// //// script.Replace(arg, new ParameterDeclaration(arg.Name)); +// //// }) { IssueMarker = IssueMarker.GrayOut }); +// //// } +// //// } +// // } - // public static bool LambdaTypeCanBeInferred(BaseSemanticModel ctx, Expression expression, List parameters) - // { - // var validTypes = TypeGuessing.GetValidTypes(ctx.Resolver, expression).ToList(); - // foreach (var type in validTypes) { - // if (type.Kind != TypeKind.Delegate) - // continue; - // var invokeMethod = type.GetDelegateInvokeMethod(); - // if (invokeMethod == null || invokeMethod.Parameters.Count != parameters.Count) - // continue; - // for (int p = 0; p < invokeMethod.Parameters.Count; p++) { - // var resolvedArgument = ctx.Resolve(parameters[p].Type); - // if (!invokeMethod.Parameters [p].Type.Equals(resolvedArgument.Type)) - // return false; - // } - // } - // return true; - // } - } -} \ No newline at end of file +// // public static bool LambdaTypeCanBeInferred(BaseSemanticModel ctx, Expression expression, List parameters) +// // { +// // var validTypes = TypeGuessing.GetValidTypes(ctx.Resolver, expression).ToList(); +// // foreach (var type in validTypes) { +// // if (type.Kind != TypeKind.Delegate) +// // continue; +// // var invokeMethod = type.GetDelegateInvokeMethod(); +// // if (invokeMethod == null || invokeMethod.Parameters.Count != parameters.Count) +// // continue; +// // for (int p = 0; p < invokeMethod.Parameters.Count; p++) { +// // var resolvedArgument = ctx.Resolve(parameters[p].Type); +// // if (!invokeMethod.Parameters [p].Type.Equals(resolvedArgument.Type)) +// // return false; +// // } +// // } +// // return true; +// // } +// } +//} \ No newline at end of file diff --git a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantLambdaSignatureParenthesesAnalyzer.cs b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantLambdaSignatureParenthesesAnalyzer.cs index 70fb3010..14b12a30 100644 --- a/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantLambdaSignatureParenthesesAnalyzer.cs +++ b/RefactoringEssentials/CSharp/Diagnostics/Synced/RedundanciesInCode/RedundantLambdaSignatureParenthesesAnalyzer.cs @@ -1,79 +1,79 @@ -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 RedundantLambdaSignatureParenthesesAnalyzer : DiagnosticAnalyzer - { - static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( - CSharpDiagnosticIDs.RedundantLambdaSignatureParenthesesAnalyzerID, - GettextCatalog.GetString("Redundant lambda signature parentheses"), - GettextCatalog.GetString("Redundant lambda signature parentheses"), - DiagnosticAnalyzerCategories.RedundanciesInCode, - DiagnosticSeverity.Hidden, - isEnabledByDefault: true, - helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantLambdaSignatureParenthesesAnalyzerID), - customTags: DiagnosticCustomTags.Unnecessary - ); +//namespace RefactoringEssentials.CSharp.Diagnostics +//{ +// [DiagnosticAnalyzer(LanguageNames.CSharp)] +// [NotPortedYet] +// public class RedundantLambdaSignatureParenthesesAnalyzer : DiagnosticAnalyzer +// { +// static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( +// CSharpDiagnosticIDs.RedundantLambdaSignatureParenthesesAnalyzerID, +// GettextCatalog.GetString("Redundant lambda signature parentheses"), +// GettextCatalog.GetString("Redundant lambda signature parentheses"), +// DiagnosticAnalyzerCategories.RedundanciesInCode, +// DiagnosticSeverity.Hidden, +// isEnabledByDefault: true, +// helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.RedundantLambdaSignatureParenthesesAnalyzerID), +// 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) - // { - // } +// // class GatherVisitor : GatherVisitorBase +// // { +// // public GatherVisitor(SemanticModel semanticModel, Action addDiagnostic, CancellationToken cancellationToken) +// // : base (semanticModel, addDiagnostic, cancellationToken) +// // { +// // } - //// public override void VisitLambdaExpression(LambdaExpression lambdaExpression) - //// { - //// base.VisitLambdaExpression(lambdaExpression); - //// var p = lambdaExpression.Parameters.FirstOrDefault(); - //// if (p == null || !p.Type.IsNull) - //// return; - //// var lParToken = lambdaExpression.LParToken; - //// if (lParToken.IsNull) - //// return; - //// if (p.GetNextSibling(n => n.Role == Roles.Parameter) != null) - //// return; - //// Action