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

Enable extract refactorings in LSP #76718

Merged
merged 8 commits into from
Jan 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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 @@ -25,6 +25,8 @@ namespace Microsoft.CodeAnalysis.CodeRefactorings.ExtractMethod;
[method: SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
internal sealed class ExtractMethodCodeRefactoringProvider() : CodeRefactoringProvider
{
internal override CodeRefactoringKind Kind => CodeRefactoringKind.Extract;

public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
// Don't bother if there isn't a selection
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ internal abstract class AbstractExtractClassRefactoringProvider(IExtractClassOpt
protected abstract Task<ImmutableArray<SyntaxNode>> GetSelectedNodesAsync(CodeRefactoringContext context);
protected abstract Task<SyntaxNode?> GetSelectedClassDeclarationAsync(CodeRefactoringContext context);

internal override CodeRefactoringKind Kind => CodeRefactoringKind.Extract;

public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var solution = context.Document.Project.Solution;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ public ExtractInterfaceCodeRefactoringProvider()
{
}

internal override CodeRefactoringKind Kind => CodeRefactoringKind.Extract;

public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ protected AbstractInlineMethodRefactoringProvider(
_semanticFactsService = semanticFactsService;
}

internal override CodeRefactoringKind Kind => CodeRefactoringKind.Inline;

public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, _, cancellationToken) = context;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ internal abstract class AbstractInlineTemporaryCodeRefactoringProvider<
where TIdentifierNameSyntax : SyntaxNode
where TVariableDeclaratorSyntax : SyntaxNode
{
internal override CodeRefactoringKind Kind => CodeRefactoringKind.Inline;

protected static async Task<ImmutableArray<TIdentifierNameSyntax>> GetReferenceLocationsAsync(
Document document,
TVariableDeclaratorSyntax variableDeclarator,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,41 @@

<ItemGroup>
<ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\Microsoft.CodeAnalysis.LanguageServer\Microsoft.CodeAnalysis.LanguageServer.csproj"/>
<ProjectReference Include="..\Microsoft.CodeAnalysis.LanguageServer\Microsoft.CodeAnalysis.LanguageServer.csproj" />
<ProjectReference Include="..\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" />

<ProjectReference Include="..\..\VisualStudio\DevKit\Impl\Microsoft.VisualStudio.LanguageServices.DevKit.csproj"
ReferenceOutputAssembly="false"
Private="false" />
<ProjectReference Include="..\..\VisualStudio\DevKit\Impl\Microsoft.VisualStudio.LanguageServices.DevKit.csproj" ReferenceOutputAssembly="false" Private="false" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing.XUnit" />
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is added to parse test code markup.

</ItemGroup>

<!--
Copy files contained in the project to a RoslynLSP subdirectory to emulate deployment of the language server.
-->
<Target Name="_CopyLanguageServerFiles" AfterTargets="ResolveProjectReferences">
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need the LanguageServer isolated into its own folder. This target works similarly to the already preset _CopyDevKitExtensionFiles.

<MSBuild Projects="..\Microsoft.CodeAnalysis.LanguageServer\Microsoft.CodeAnalysis.LanguageServer.csproj" Targets="GetTargetPath">
<Output TaskParameter="TargetOutputs" ItemName="_LanguageServerFilePath" />
</MSBuild>

<PropertyGroup>
<_LanguageServerOutputPath>$([System.IO.Path]::GetDirectoryName(%(_LanguageServerFilePath.Identity)))</_LanguageServerOutputPath>
</PropertyGroup>

<ItemGroup Condition="'$(_LanguageServerOutputPath)' != ''">
<_LanguageServerFile Include="$(_LanguageServerOutputPath)\**\*.*" />
<_LanguageServerFile Remove="$(_LanguageServerOutputPath)\**\*.mef-composition" />
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this deletes the mef cache right? wonder if we should delete this every time the test runs (instead of in msbuild)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is mostly for local dev scenarios where many compositions may exist in your local build of Microsoft.CodeAnalysis.LangaugeServer and there is no need to move them to the test folder. Lets save deleting compositions on each test run for when we move the ExportProviderBuilder tests to use the LSP.

<Content Include="@(_LanguageServerFile)" Link="RoslynLSP\%(RecursiveDir)\%(_LanguageServerFile.Filename)%(_LanguageServerFile.Extension)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Target>

<!--
Copy files contained in the NPM package to a DevKit subdirectory to emulate deployment of the DevKit extension in VS Code.
-->
<Target Name="_CopyDevKitExtensionFiles" AfterTargets="ResolveProjectReferences">
<MSBuild Projects="..\..\VisualStudio\DevKit\Impl\Microsoft.VisualStudio.LanguageServices.DevKit.csproj"
Targets="GetPackInputs">
<Output TaskParameter="TargetOutputs" ItemName="_DevKitExtensionFile"/>
<MSBuild Projects="..\..\VisualStudio\DevKit\Impl\Microsoft.VisualStudio.LanguageServices.DevKit.csproj" Targets="GetPackInputs">
<Output TaskParameter="TargetOutputs" ItemName="_DevKitExtensionFile" />
</MSBuild>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Licensed to the .NET Foundation under one or more agreements.
// 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.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Roslyn.Test.Utilities;
using Xunit.Abstractions;
using LSP = Roslyn.LanguageServer.Protocol;

namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Services;

public class ExtractRefactoringTests(ITestOutputHelper testOutputHelper) : AbstractLanguageServerClientTests(testOutputHelper)
{
[Theory]
[CombinatorialData]
public async Task TestExtractBaseClass(bool includeDevKitComponents)
{
var markup =
"""
class {|caret:A|}
{
public void M()
{
}
}
""";
var expected =
"""
internal class NewBaseType
{
public void M()
{
}
}

class A : NewBaseType
{
}
""";

await using var testLspServer = await CreateCSharpLanguageServerAsync(markup, includeDevKitComponents);
var caretLocation = testLspServer.GetLocations("caret").Single();

await TestCodeActionAsync(testLspServer, caretLocation, "Extract base class...", expected);
}

[Theory]
[CombinatorialData]
public async Task TestExtractInterface(bool includeDevKitComponents)
{
var markup =
"""
class {|caret:A|}
{
public void M()
{
}
}
""";
var expected =
"""
interface IA
{
void M();
}

class A : IA
{
public void M()
{
}
}
""";

await using var testLspServer = await CreateCSharpLanguageServerAsync(markup, includeDevKitComponents);
var caretLocation = testLspServer.GetLocations("caret").Single();

await TestCodeActionAsync(testLspServer, caretLocation, "Extract interface...", expected);
}

private static async Task TestCodeActionAsync(
TestLspClient testLspClient,
LSP.Location caretLocation,
string codeActionTitle,
[StringSyntax(PredefinedEmbeddedLanguageNames.CSharpTest)] string expected)
{
var codeActionResults = await testLspClient.RunGetCodeActionsAsync(CreateCodeActionParams(caretLocation));

var unresolvedCodeAction = Assert.Single(codeActionResults, codeAction => codeAction.Title == codeActionTitle);

var resolvedCodeAction = await testLspClient.RunGetCodeActionResolveAsync(unresolvedCodeAction);

testLspClient.ApplyWorkspaceEdit(resolvedCodeAction.Edit);

var updatedCode = testLspClient.GetDocumentText(caretLocation.Uri);

AssertEx.Equal(expected, updatedCode);
}
}
Loading
Loading