diff --git a/src/StyleCop.Analyzers.CodeFixes/MaintainabilityRules/SA1402CodeFixProvider.cs b/src/StyleCop.Analyzers.CodeFixes/MaintainabilityRules/SA1402CodeFixProvider.cs index 3dc0f9353..37f31d8b0 100644 --- a/src/StyleCop.Analyzers.CodeFixes/MaintainabilityRules/SA1402CodeFixProvider.cs +++ b/src/StyleCop.Analyzers.CodeFixes/MaintainabilityRules/SA1402CodeFixProvider.cs @@ -164,12 +164,178 @@ private static async Task GetTransformedSolutionAsync(Document documen extractedDocumentNode = RemoveBlankLinesLeftByRemovedSiblings(extractedDocumentNode); Solution updatedSolution = document.Project.Solution.AddDocument(extractedDocumentId, extractedDocumentName, extractedDocumentNode, document.Folders); + List extractedDocumentIds = new List { extractedDocumentId }; // Make sure to also add the file to linked projects foreach (var linkedDocumentId in document.GetLinkedDocumentIds()) { DocumentId linkedExtractedDocumentId = DocumentId.CreateNewId(linkedDocumentId.ProjectId); updatedSolution = updatedSolution.AddDocument(linkedExtractedDocumentId, extractedDocumentName, extractedDocumentNode, document.Folders); + extractedDocumentIds.Add(linkedExtractedDocumentId); + } + + foreach (var linkedExtractedDocumentId in extractedDocumentIds) + { + Document extractedDocument = updatedSolution.GetDocument(linkedExtractedDocumentId); + SemanticModel semanticModel = await extractedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + SyntaxNode linkedExtractedRoot = await extractedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + List unnecessaryUsings = new List(); + foreach (var diagnosticInTree in semanticModel.GetDiagnostics(cancellationToken: cancellationToken)) + { + if (!string.Equals(diagnosticInTree.Id, "CS8019", StringComparison.Ordinal)) + { + continue; + } + + SyntaxNode unnecessaryUsing = linkedExtractedRoot.FindNode(diagnosticInTree.Location.SourceSpan, getInnermostNodeForTie: true); + while (unnecessaryUsing != null && !(unnecessaryUsing is UsingDirectiveSyntax)) + { + unnecessaryUsing = unnecessaryUsing.Parent; + } + + if (unnecessaryUsing != null && !unnecessaryUsing.ContainsDirectives) + { + unnecessaryUsings.Add(unnecessaryUsing); + } + } + + if (unnecessaryUsings.Count > 0) + { + List namespacesToNormalize = new List(); + foreach (var unnecessaryUsing in unnecessaryUsings) + { + if (!(unnecessaryUsing.Parent is NamespaceDeclarationSyntax namespaceDeclaration)) + { + continue; + } + + bool allUsingsRemoved = true; + foreach (var usingDirective in namespaceDeclaration.Usings) + { + if (!ContainsNode(unnecessaryUsings, usingDirective)) + { + allUsingsRemoved = false; + break; + } + } + + if (allUsingsRemoved && !ContainsNode(namespacesToNormalize, namespaceDeclaration)) + { + namespacesToNormalize.Add(namespaceDeclaration); + } + } + + List usingNodesToTrim = new List(); + List usingBlankLinesToKeep = new List(); + foreach (var unnecessaryUsing in unnecessaryUsings) + { + var siblings = new List(); + foreach (var sibling in unnecessaryUsing.Parent.ChildNodes()) + { + siblings.Add(sibling); + } + + int index = IndexOfNode(siblings, unnecessaryUsing); + if (index < 0 || index + 1 >= siblings.Count || ContainsNode(unnecessaryUsings, siblings[index + 1])) + { + continue; + } + + SyntaxNode nextSibling = siblings[index + 1]; + if (!ContainsNode(usingNodesToTrim, nextSibling)) + { + usingNodesToTrim.Add(nextSibling); + int blankLines = CountLeadingBlankLines(nextSibling.GetLeadingTrivia()); + bool hasRemainingSiblingBeforeTarget = false; + for (int i = 0; i < index; i++) + { + if (!ContainsNode(unnecessaryUsings, siblings[i])) + { + hasRemainingSiblingBeforeTarget = true; + break; + } + } + + if (!hasRemainingSiblingBeforeTarget && !(unnecessaryUsing.Parent is CompilationUnitSyntax)) + { + blankLines = CountLeadingBlankLines(unnecessaryUsing.GetLeadingTrivia()); + } + else if (!hasRemainingSiblingBeforeTarget) + { + blankLines = 0; + } + + usingBlankLinesToKeep.Add(blankLines); + } + } + + List nodesToAnnotate = new List(unnecessaryUsings.Count + usingNodesToTrim.Count + namespacesToNormalize.Count); + nodesToAnnotate.AddRange(unnecessaryUsings); + nodesToAnnotate.AddRange(namespacesToNormalize); + foreach (var nodeToTrim in usingNodesToTrim) + { + if (!ContainsNode(nodesToAnnotate, nodeToTrim)) + { + nodesToAnnotate.Add(nodeToTrim); + } + } + + var removeAnnotation = new SyntaxAnnotation("SA1402RemoveUsing"); + linkedExtractedRoot = linkedExtractedRoot.ReplaceNodes( + nodesToAnnotate, + (original, rewritten) => + { + if (ContainsNode(unnecessaryUsings, original)) + { + rewritten = rewritten.WithAdditionalAnnotations(removeAnnotation); + } + + if (ContainsNode(namespacesToNormalize, original)) + { + rewritten = rewritten.WithAdditionalAnnotations(new SyntaxAnnotation("SA1402NormalizeNamespace")); + } + + int trimIndex = IndexOfNode(usingNodesToTrim, original); + if (trimIndex >= 0) + { + var trimAnnotation = new SyntaxAnnotation(TrimAnnotationKind, usingBlankLinesToKeep[trimIndex].ToString()); + rewritten = rewritten.WithAdditionalAnnotations(trimAnnotation); + } + + return rewritten; + }); + + List nodesToRemove = new List(); + foreach (var annotated in linkedExtractedRoot.GetAnnotatedNodes(removeAnnotation)) + { + nodesToRemove.Add(annotated); + } + + linkedExtractedRoot = linkedExtractedRoot.RemoveNodes(nodesToRemove, SyntaxRemoveOptions.KeepExteriorTrivia); + linkedExtractedRoot = RemoveBlankLinesLeftByRemovedSiblings(linkedExtractedRoot); + List annotatedNamespaces = new List(); + foreach (var annotatedNamespace in linkedExtractedRoot.GetAnnotatedNodes("SA1402NormalizeNamespace")) + { + annotatedNamespaces.Add(annotatedNamespace); + } + + foreach (var annotatedNamespace in annotatedNamespaces) + { + if (annotatedNamespace is NamespaceDeclarationSyntax namespaceDeclaration && namespaceDeclaration.Members.Count > 0) + { + SyntaxNode firstMember = namespaceDeclaration.Members[0]; + linkedExtractedRoot = linkedExtractedRoot.ReplaceNode(firstMember, TrimLeadingBlankLines(firstMember, 0)); + } + } + + int leadingHeaderCommentCount = GetLeadingHeaderCommentCount(root); + if (leadingHeaderCommentCount > 0) + { + linkedExtractedRoot = NormalizeLeadingCommentSeparator(linkedExtractedRoot, leadingHeaderCommentCount); + } + + updatedSolution = updatedSolution.WithDocumentSyntaxRoot(linkedExtractedDocumentId, linkedExtractedRoot); + } } // Remove the type from its original location @@ -232,6 +398,129 @@ private static SyntaxNode RemoveBlankLinesLeftByRemovedSiblings(SyntaxNode root) } } + private static SyntaxNode NormalizeLeadingCommentSeparator(SyntaxNode root, int headerCommentCount) + { + SyntaxNode? firstChild = null; + foreach (var child in root.ChildNodes()) + { + firstChild = child; + break; + } + + if (firstChild == null) + { + return root; + } + + var leading = firstChild.GetLeadingTrivia(); + List commentIndices = new List(); + for (int i = 0; i < leading.Count; i++) + { + if (leading[i].IsKind(SyntaxKind.SingleLineCommentTrivia) + || leading[i].IsKind(SyntaxKind.MultiLineCommentTrivia) + || leading[i].IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia) + || leading[i].IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia)) + { + commentIndices.Add(i); + } + } + + if (commentIndices.Count < headerCommentCount) + { + return root; + } + + string? lineEnding = null; + int lastHeaderCommentIndex = commentIndices[headerCommentCount - 1]; + for (int i = 0; i < leading.Count; i++) + { + if (leading[i].IsKind(SyntaxKind.EndOfLineTrivia)) + { + lineEnding ??= leading[i].ToString(); + } + } + + if (lineEnding == null) + { + return root; + } + + int remainderStart = lastHeaderCommentIndex + 1; + while (remainderStart < leading.Count) + { + if (leading[remainderStart].IsKind(SyntaxKind.EndOfLineTrivia)) + { + remainderStart++; + } + else if (leading[remainderStart].IsKind(SyntaxKind.WhitespaceTrivia) + && remainderStart + 1 < leading.Count + && leading[remainderStart + 1].IsKind(SyntaxKind.EndOfLineTrivia)) + { + remainderStart += 2; + } + else + { + break; + } + } + + List normalizedLeading = new List(leading.Count + 1); + for (int i = 0; i <= lastHeaderCommentIndex; i++) + { + normalizedLeading.Add(leading[i]); + } + + normalizedLeading.Add(SyntaxFactory.EndOfLine(lineEnding)); + normalizedLeading.Add(SyntaxFactory.EndOfLine(lineEnding)); + for (int i = remainderStart; i < leading.Count; i++) + { + normalizedLeading.Add(leading[i]); + } + + return root.ReplaceNode(firstChild, firstChild.WithLeadingTrivia(SyntaxFactory.TriviaList(normalizedLeading))); + } + + private static int GetLeadingHeaderCommentCount(SyntaxNode sourceRoot) + { + SyntaxNode? firstChild = null; + foreach (var child in sourceRoot.ChildNodes()) + { + firstChild = child; + break; + } + + if (!(firstChild is UsingDirectiveSyntax usingDirective)) + { + return 0; + } + + int count = 0; + int endOfLineCount = 0; + foreach (var trivia in usingDirective.GetLeadingTrivia()) + { + if (trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) + || trivia.IsKind(SyntaxKind.MultiLineCommentTrivia)) + { + count++; + endOfLineCount = 0; + } + else if (trivia.IsKind(SyntaxKind.EndOfLineTrivia)) + { + endOfLineCount++; + if (endOfLineCount > 1) + { + break; + } + } + else if (!trivia.IsKind(SyntaxKind.WhitespaceTrivia) && trivia.IsDirective) + { + break; + } + } + + return count; + } + /// /// Drops leading blank lines down to . /// A missing previous token means the node now starts the file, so a leading end-of-line is a blank line. diff --git a/test/StyleCop.Analyzers.Test/MaintainabilityRules/SA1402ForClassUnitTests.cs b/test/StyleCop.Analyzers.Test/MaintainabilityRules/SA1402ForClassUnitTests.cs index 0bb329a72..03a6db123 100644 --- a/test/StyleCop.Analyzers.Test/MaintainabilityRules/SA1402ForClassUnitTests.cs +++ b/test/StyleCop.Analyzers.Test/MaintainabilityRules/SA1402ForClassUnitTests.cs @@ -13,6 +13,464 @@ public class SA1402ForClassUnitTests : SA1402ForBlockDeclarationUnitTestsBase protected override bool IsConfiguredAsTopLevelTypeByDefault => true; + [Fact] + [WorkItem(3109, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3109")] + public async Task TestExtractedTypeIncludesOnlyRelevantUsingDirectivesAsync() + { + var testCode = @"using System; +using System.Collections.Generic; + +public class Foo +{ + public List Values { get; } = new List(); +} + +public class {|#0:Bar|} +{ + public DateTime Value { get; set; } +} +"; + + var fixedCode = new[] + { + ("/0/Test0.cs", @"using System; +using System.Collections.Generic; + +public class Foo +{ + public List Values { get; } = new List(); +} +"), + ("Bar.cs", @"using System; + +public class Bar +{ + public DateTime Value { get; set; } +} +"), + }; + + var expected = this.Diagnostic().WithLocation(0); + await this.VerifyCSharpFixAsync(testCode, this.GetSettings(), expected, fixedCode, CancellationToken.None).ConfigureAwait(false); + } + + [Fact] + public async Task TestExtractedTypeRemovesUnnecessaryNamespaceUsingAsync() + { + var testCode = @"namespace TestNamespace +{ + using System; + + public class Foo + { + public DateTime Value { get; set; } + } + + public class {|#0:TestClass|} + { + } +} +"; + + var fixedCode = new[] + { + ("/0/Test0.cs", @"namespace TestNamespace +{ + using System; + + public class Foo + { + public DateTime Value { get; set; } + } +} +"), + ("TestClass.cs", @"namespace TestNamespace +{ + public class TestClass + { + } +} +"), + }; + + var expected = this.Diagnostic().WithLocation(0); + await this.VerifyCSharpFixAsync(testCode, this.GetSettings(), expected, fixedCode, CancellationToken.None).ConfigureAwait(false); + } + + [Fact] + public async Task TestExtractedTypePreservesHeaderWhenRemovingAllUsingsAsync() + { + var testCode = @"// File header +using System.Collections.Generic; +using System.Linq; + +public class Foo +{ +} + +// Type comment +public class {|#0:TestClass|} +{ +} +"; + + var fixedCode = new[] + { + ("/0/Test0.cs", @"// File header +using System.Collections.Generic; +using System.Linq; + +public class Foo +{ +} +"), + ("TestClass.cs", @"// File header + +// Type comment +public class TestClass +{ +} +"), + }; + + var expected = this.Diagnostic().WithLocation(0); + await this.VerifyCSharpFixAsync(testCode, this.GetSettings(), expected, fixedCode, CancellationToken.None).ConfigureAwait(false); + } + + [Fact] + public async Task TestExtractedTypePreservesDirectivesBetweenHeaderAndTypeCommentAsync() + { + var testCode = @"// File header +using System.Collections.Generic; +using System.Linq; + +public class Foo +{ +} + +#pragma warning disable CS0169 +// Type comment +public class {|#0:TestClass|} +{ +} +#pragma warning restore CS0169 +"; + + var fixedCode = new[] + { + ("/0/Test0.cs", @"// File header +using System.Collections.Generic; +using System.Linq; + +public class Foo +{ +} +#pragma warning restore CS0169 +"), + ("TestClass.cs", @"// File header + +#pragma warning disable CS0169 +// Type comment +public class TestClass +{ +} +#pragma warning restore CS0169 +"), + }; + + var expected = this.Diagnostic().WithLocation(0); + await this.VerifyCSharpFixAsync(testCode, this.GetSettings(), expected, fixedCode, CancellationToken.None).ConfigureAwait(false); + } + + [Fact] + public async Task TestExtractedTypePreservesConsecutiveFileHeaderCommentsWhenRemovingUsingAsync() + { + var testCode = @"// File header +// Additional header line +using System.Collections.Generic; +using System.Linq; + +public class Foo +{ + public List Values { get; } = Enumerable.Empty().ToList(); +} + +public class {|#0:TestClass|} +{ + public List Values { get; } = new List(); +} +"; + + var fixedCode = new[] + { + ("/0/Test0.cs", @"// File header +// Additional header line +using System.Collections.Generic; +using System.Linq; + +public class Foo +{ + public List Values { get; } = Enumerable.Empty().ToList(); +} +"), + ("TestClass.cs", @"// File header +// Additional header line + +using System.Collections.Generic; + +public class TestClass +{ + public List Values { get; } = new List(); +} +"), + }; + + var expected = this.Diagnostic().WithLocation(0); + await this.VerifyCSharpFixAsync(testCode, this.GetSettings(), expected, fixedCode, CancellationToken.None).ConfigureAwait(false); + } + + [Fact] + public async Task TestExtractedTypePreservesDirectivesInsideUsingAsync() + { + var testCode = @"using +#if true +System.Collections.Generic; +#endif + +public class Foo +{ +} + +public class {|#0:TestClass|} +{ +} +"; + + var fixedCode = new[] + { + ("/0/Test0.cs", @"using +#if true +System.Collections.Generic; +#endif + +public class Foo +{ +} +"), + ("TestClass.cs", @"using +#if true +System.Collections.Generic; +#endif + +public class TestClass +{ +} +"), + }; + + var expected = this.Diagnostic().WithLocation(0); + await this.VerifyCSharpFixAsync(testCode, this.GetSettings(), expected, fixedCode, CancellationToken.None).ConfigureAwait(false); + } + + [Fact] + public async Task TestExtractedTypePreservesCommentBeforeRetainedUsingAsync() + { + var testCode = @"// File header + +// Import comment +using System; +using System.Collections.Generic; + +public class Foo +{ + public List Values { get; } = new List(); +} + +public class {|#0:TestClass|} +{ + public DateTime Value { get; set; } +} +"; + + var fixedCode = new[] + { + ("/0/Test0.cs", @"// File header + +// Import comment +using System; +using System.Collections.Generic; + +public class Foo +{ + public List Values { get; } = new List(); +} +"), + ("TestClass.cs", @"// File header + +// Import comment +using System; + +public class TestClass +{ + public DateTime Value { get; set; } +} +"), + }; + + var expected = this.Diagnostic().WithLocation(0); + await this.VerifyCSharpFixAsync(testCode, this.GetSettings(), expected, fixedCode, CancellationToken.None).ConfigureAwait(false); + } + + [Fact] + public async Task TestExtractedTypePreservesDocumentationCommentAfterRemovingNamespaceUsingAsync() + { + var testCode = @"namespace TestNamespace +{ + using System; + + public class Foo + { + public DateTime Value { get; set; } + } + + /// + /// The extracted type. + /// + public class {|#0:TestClass|} + { + } +} +"; + + var fixedCode = new[] + { + ("/0/Test0.cs", @"namespace TestNamespace +{ + using System; + + public class Foo + { + public DateTime Value { get; set; } + } +} +"), + ("TestClass.cs", @"namespace TestNamespace +{ + /// + /// The extracted type. + /// + public class TestClass + { + } +} +"), + }; + + var expected = this.Diagnostic().WithLocation(0); + await this.VerifyCSharpFixAsync(testCode, this.GetSettings(), expected, fixedCode, CancellationToken.None).ConfigureAwait(false); + } + + [Fact] + public async Task TestExtractedTypePreservesConditionalUsingDirectivesAsync() + { + var testCode = @"namespace TestNamespace +{ +#if true + using System; +#endif + + public class Foo + { + } + + public class {|#0:TestClass|} + { + } +} +"; + + var fixedCode = new[] + { + ("/0/Test0.cs", @"namespace TestNamespace +{ +#if true + using System; +#endif + + public class Foo + { + } +} +"), + ("TestClass.cs", @"namespace TestNamespace +{ +#if true + using System; +#endif + + public class TestClass + { + } +} +"), + }; + + var expected = this.Diagnostic().WithLocation(0); + await this.VerifyCSharpFixAsync(testCode, this.GetSettings(), expected, fixedCode, CancellationToken.None).ConfigureAwait(false); + } + + [Fact] + public async Task TestExtractedTypePreservesNestedNamespaceFormattingWhenNamesMatchAsync() + { + var testCode = @"namespace TestNamespace +{ + namespace TestNamespace + { + using System; + + public class Foo + { + public DateTime Value { get; set; } + } + + public class {|#0:TestClass|} + { + } + } +} +"; + + var fixedCode = new[] + { + ("/0/Test0.cs", @"namespace TestNamespace +{ + namespace TestNamespace + { + using System; + + public class Foo + { + public DateTime Value { get; set; } + } + } +} +"), + ("TestClass.cs", @"namespace TestNamespace +{ + namespace TestNamespace + { + public class TestClass + { + } + } +} +"), + }; + + var expected = this.Diagnostic().WithLocation(0); + await this.VerifyCSharpFixAsync(testCode, this.GetSettings(), expected, fixedCode, CancellationToken.None).ConfigureAwait(false); + } + [Fact] [WorkItem(3876, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3876")] public async Task TestExtractedTypeDoesNotGainBlankLineAfterNamespaceAsync() @@ -204,7 +662,7 @@ public class TestClass2 [Fact] [WorkItem(3876, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3876")] - public async Task TestExtractedTypeInSecondNamespaceKeepsBlankLineAfterUsingAsync() + public async Task TestExtractedTypeInSecondNamespaceKeepsBlankLineAfterOpeningBraceAsync() { var testCode = @"using System; @@ -239,9 +697,7 @@ namespace TestNamespace { } "), - ("TestClass2.cs", @"using System; - -namespace TestNamespace + ("TestClass2.cs", @"namespace TestNamespace { public class TestClass2