Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove imports should only format the section of the document that was touched #76038

Merged
merged 5 commits into from
Nov 23, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessaryImport
CSharpRemoveUnnecessaryImportsCodeFixProvider>;

[Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public class RemoveUnnecessaryImportsTests
public sealed class RemoveUnnecessaryImportsTests
{
private static readonly string s_tab = "\t";

[Fact]
public async Task TestNoReferences()
{
Expand Down Expand Up @@ -2246,4 +2248,36 @@ static void Main(string[] args)
"""
}.RunAsync();
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/65114")]
public async Task DoNotTouchInnerNamespaceWithoutUsings()
{
await VerifyCS.VerifyCodeFixAsync(
$$"""
[|{|IDE0005:using System;
using System.Collections.Generic;
using System.Linq;|}|]

namespace N
{
{{s_tab}}class Program
{
static void Main(string[] args)
{
}
}
}
""",
$$"""
namespace N
{
{{s_tab}}class Program
{
static void Main(string[] args)
{
}
}
}
""");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;

Expand All @@ -30,19 +28,19 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
context.RegisterCodeFix(
CodeAction.Create(
title,
c => RemoveUnnecessaryImportsAsync(context.Document, c),
cancellationToken => RemoveUnnecessaryImportsAsync(context.Document, cancellationToken),
title),
context.Diagnostics);
return Task.CompletedTask;
}

protected abstract string GetTitle();

private static async Task<Document> RemoveUnnecessaryImportsAsync(
private static Task<Document> RemoveUnnecessaryImportsAsync(
Document document,
CancellationToken cancellationToken)
{
var service = document.GetRequiredLanguageService<IRemoveUnnecessaryImportsService>();
return await service.RemoveUnnecessaryImportsAsync(document, cancellationToken).ConfigureAwait(false);
return service.RemoveUnnecessaryImportsAsync(document, cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
resultCompilationUnit = resultCompilationUnit.ReplaceToken(firstToken, newFirstToken);
}

return resultCompilationUnit;
return resultCompilationUnit.WithAdditionalAnnotations(s_annotation);
}

public override SyntaxNode VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node)
Expand Down Expand Up @@ -241,7 +241,7 @@ private SyntaxNode VisitBaseNamespaceDeclaration(
resultNamespace = resultNamespace.ReplaceToken(firstToken, newFirstToken);
}

return resultNamespace;
return resultNamespace.WithAdditionalAnnotations(s_annotation);
}

public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.RemoveUnnecessaryImports;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
Expand All @@ -22,14 +21,12 @@
namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryImports;

[ExportLanguageService(typeof(IRemoveUnnecessaryImportsService), LanguageNames.CSharp), Shared]
internal partial class CSharpRemoveUnnecessaryImportsService :
[method: ImportingConstructor]
[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
internal partial class CSharpRemoveUnnecessaryImportsService() :
AbstractRemoveUnnecessaryImportsService<UsingDirectiveSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpRemoveUnnecessaryImportsService()
{
}
private static readonly SyntaxAnnotation s_annotation = new();

private static ISyntaxFormatting SyntaxFormatting
=> CSharpSyntaxFormatting.Instance;
Expand All @@ -54,45 +51,27 @@ public override async Task<Document> RemoveUnnecessaryImportsAsync(

var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

var oldRoot = (CompilationUnitSyntax)root;
var newRoot = (CompilationUnitSyntax)new Rewriter(unnecessaryImports, cancellationToken).Visit(oldRoot);
var newRoot = new Rewriter(unnecessaryImports, cancellationToken).Visit(root);

cancellationToken.ThrowIfCancellationRequested();

var spansToFormat = new List<TextSpan>();
AddFormattingSpans(newRoot, spansToFormat, cancellationToken);
using var _ = ArrayBuilder<TextSpan>.GetInstance(out var spansToFormat);
foreach (var node in newRoot.GetAnnotatedNodes(s_annotation))
{
if (node is CompilationUnitSyntax { Members: [var firstMemberA, ..] })
{
spansToFormat.Add(TextSpan.FromBounds(0, firstMemberA.SpanStart));
}
else if (node is BaseNamespaceDeclarationSyntax { Members: [var firstMemberB, ..] } baseNamespace)
{
spansToFormat.Add(TextSpan.FromBounds(baseNamespace.Name.Span.End, firstMemberB.SpanStart));
}
}

var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(SyntaxFormatting, cancellationToken).ConfigureAwait(false);
var formattedRoot = SyntaxFormatting.GetFormattingResult(newRoot, spansToFormat, formattingOptions, rules: default, cancellationToken).GetFormattedRoot(cancellationToken);

return document.WithSyntaxRoot(formattedRoot);
}
}

private static void AddFormattingSpans(
CompilationUnitSyntax compilationUnit,
List<TextSpan> spans,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
spans.Add(TextSpan.FromBounds(0, GetEndPosition(compilationUnit, compilationUnit.Members)));

foreach (var @namespace in compilationUnit.Members.OfType<BaseNamespaceDeclarationSyntax>())
AddFormattingSpans(@namespace, spans, cancellationToken);
}

private static void AddFormattingSpans(
BaseNamespaceDeclarationSyntax namespaceMember,
List<TextSpan> spans,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
spans.Add(TextSpan.FromBounds(namespaceMember.SpanStart, GetEndPosition(namespaceMember, namespaceMember.Members)));

foreach (var @namespace in namespaceMember.Members.OfType<BaseNamespaceDeclarationSyntax>())
AddFormattingSpans(@namespace, spans, cancellationToken);
}

private static int GetEndPosition(SyntaxNode container, SyntaxList<MemberDeclarationSyntax> list)
=> list.Count > 0 ? list[0].SpanStart : container.Span.End;
}
Loading