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 sync over async blocking in Extract Method/Interface options code #76510

Merged
merged 1 commit into from
Dec 19, 2024
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 @@ -8,63 +8,56 @@
using System.Collections.Generic;
Copy link
Member Author

Choose a reason for hiding this comment

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

view with whitespace off.

using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.ExtractInterface;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.Notification;

namespace Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface
namespace Microsoft.CodeAnalysis.Editor.UnitTests.ExtractInterface;

[ExportWorkspaceService(typeof(IExtractInterfaceOptionsService), ServiceLayer.Test), Shared, PartNotDiscoverable]
[method: ImportingConstructor]
[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
internal sealed class TestExtractInterfaceOptionsService() : IExtractInterfaceOptionsService
{
[ExportWorkspaceService(typeof(IExtractInterfaceOptionsService), ServiceLayer.Test), Shared, PartNotDiscoverable]
internal class TestExtractInterfaceOptionsService : IExtractInterfaceOptionsService
public IEnumerable<ISymbol> AllExtractableMembers { get; private set; }
public string DefaultInterfaceName { get; private set; }
public List<string> ConflictingTypeNames { get; private set; }
public string DefaultNamespace { get; private set; }
public string GeneratedNameTypeParameterSuffix { get; set; }

public bool IsCancelled { get; set; }
public string ChosenInterfaceName { get; set; }
public string ChosenFileName { get; set; }
public IEnumerable<ISymbol> ChosenMembers { get; set; }
public bool SameFile { get; set; }

public ExtractInterfaceOptionsResult GetExtractInterfaceOptions(
ISyntaxFactsService syntaxFactsService,
INotificationService notificationService,
List<ISymbol> extractableMembers,
string defaultInterfaceName,
List<string> conflictingTypeNames,
string defaultNamespace,
string generatedNameTypeParameterSuffix,
string languageName,
CancellationToken cancellationToken)
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestExtractInterfaceOptionsService()
{
}

public IEnumerable<ISymbol> AllExtractableMembers { get; private set; }
public string DefaultInterfaceName { get; private set; }
public List<string> ConflictingTypeNames { get; private set; }
public string DefaultNamespace { get; private set; }
public string GeneratedNameTypeParameterSuffix { get; set; }

public bool IsCancelled { get; set; }
public string ChosenInterfaceName { get; set; }
public string ChosenFileName { get; set; }
public IEnumerable<ISymbol> ChosenMembers { get; set; }
public bool SameFile { get; set; }

public Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync(
ISyntaxFactsService syntaxFactsService,
INotificationService notificationService,
List<ISymbol> extractableMembers,
string defaultInterfaceName,
List<string> conflictingTypeNames,
string defaultNamespace,
string generatedNameTypeParameterSuffix,
string languageName,
CancellationToken cancellationToken)
{
this.AllExtractableMembers = extractableMembers;
this.DefaultInterfaceName = defaultInterfaceName;
this.ConflictingTypeNames = conflictingTypeNames;
this.DefaultNamespace = defaultNamespace;
this.GeneratedNameTypeParameterSuffix = generatedNameTypeParameterSuffix;

var result = IsCancelled
? ExtractInterfaceOptionsResult.Cancelled
: new ExtractInterfaceOptionsResult(
isCancelled: false,
includedMembers: (ChosenMembers ?? AllExtractableMembers).AsImmutable(),
interfaceName: ChosenInterfaceName ?? defaultInterfaceName,
fileName: ChosenFileName ?? defaultInterfaceName,
location: SameFile ? ExtractInterfaceOptionsResult.ExtractLocation.SameFile : ExtractInterfaceOptionsResult.ExtractLocation.NewFile);

return Task.FromResult(result);
}
this.AllExtractableMembers = extractableMembers;
this.DefaultInterfaceName = defaultInterfaceName;
this.ConflictingTypeNames = conflictingTypeNames;
this.DefaultNamespace = defaultNamespace;
this.GeneratedNameTypeParameterSuffix = generatedNameTypeParameterSuffix;

var result = IsCancelled
? ExtractInterfaceOptionsResult.Cancelled
: new ExtractInterfaceOptionsResult(
isCancelled: false,
includedMembers: (ChosenMembers ?? AllExtractableMembers).AsImmutable(),
interfaceName: ChosenInterfaceName ?? defaultInterfaceName,
fileName: ChosenFileName ?? defaultInterfaceName,
location: SameFile ? ExtractInterfaceOptionsResult.ExtractLocation.SameFile : ExtractInterfaceOptionsResult.ExtractLocation.NewFile);

return result;
}
}
17 changes: 11 additions & 6 deletions src/Features/CSharpTest/ExtractClass/ExtractClassTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.ExtractClass;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.PullMemberUp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
Expand Down Expand Up @@ -3086,7 +3087,7 @@ public void M() { }
private static IEnumerable<(string name, bool makeAbstract)> MakeSelection(params string[] memberNames)
=> memberNames.Select(m => (m, false));

private class TestExtractClassOptionsService : IExtractClassOptionsService
private sealed class TestExtractClassOptionsService : IExtractClassOptionsService
{
private readonly IEnumerable<(string name, bool makeAbstract)>? _dialogSelection;
private readonly bool _sameFile;
Expand All @@ -3102,7 +3103,12 @@ public TestExtractClassOptionsService(IEnumerable<(string name, bool makeAbstrac
public string FileName { get; set; } = "MyBase.cs";
public string BaseName { get; set; } = "MyBase";

public Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalSymbol, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken)
public ExtractClassOptions? GetExtractClassOptions(
Document document,
INamedTypeSymbol originalSymbol,
ImmutableArray<ISymbol> selectedMembers,
SyntaxFormattingOptions formattingOptions,
CancellationToken cancellationToken)
{
var availableMembers = originalSymbol.GetMembers().Where(member => MemberAndDestinationValidator.IsMemberValid(member));

Expand All @@ -3126,13 +3132,12 @@ public TestExtractClassOptionsService(IEnumerable<(string name, bool makeAbstrac
selections = _dialogSelection.Select(selection => (member: availableMembers.Single(symbol => symbol.Name == selection.name), selection.makeAbstract));
}

var memberAnalysis = selections.Select(s =>
var memberAnalysis = selections.SelectAsArray(s =>
new ExtractClassMemberAnalysisResult(
s.member,
s.makeAbstract))
.ToImmutableArray();
s.makeAbstract));

return Task.FromResult<ExtractClassOptions?>(new ExtractClassOptions(FileName, BaseName, _sameFile, memberAnalysis));
return new ExtractClassOptions(FileName, BaseName, _sameFile, memberAnalysis);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.PullMemberUp;
using Microsoft.CodeAnalysis.Shared.Extensions;
Expand Down Expand Up @@ -106,8 +107,9 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte
return (null, false);
}

var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(cancellationToken).ConfigureAwait(false);
var action = new ExtractClassWithDialogCodeAction(
document, memberSpan, optionsService, containingType, containingTypeDeclarationNode, selectedMembers);
document, memberSpan, optionsService, containingType, containingTypeDeclarationNode, selectedMembers, formattingOptions);

return (action, false);
}
Expand All @@ -133,8 +135,9 @@ public override async Task ComputeRefactoringsAsync(CodeRefactoringContext conte
return null;
}

var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(cancellationToken).ConfigureAwait(false);
return new ExtractClassWithDialogCodeAction(
document, span, optionsService, selectedType, selectedClassNode, selectedMembers: []);
document, span, optionsService, selectedType, selectedClassNode, selectedMembers: [], formattingOptions);
}

private static bool HasBaseType(INamedTypeSymbol containingType) => containingType.BaseType?.SpecialType != SpecialType.System_Object;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.ExtractInterface;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
Expand All @@ -28,13 +29,15 @@ internal sealed class ExtractClassWithDialogCodeAction(
IExtractClassOptionsService service,
INamedTypeSymbol selectedType,
SyntaxNode selectedTypeDeclarationNode,
ImmutableArray<ISymbol> selectedMembers) : CodeActionWithOptions
ImmutableArray<ISymbol> selectedMembers,
SyntaxFormattingOptions formattingOptions) : CodeActionWithOptions
{
private readonly Document _document = document;
private readonly ImmutableArray<ISymbol> _selectedMembers = selectedMembers;
private readonly INamedTypeSymbol _selectedType = selectedType;
private readonly SyntaxNode _selectedTypeDeclarationNode = selectedTypeDeclarationNode;
private readonly IExtractClassOptionsService _service = service;
private readonly SyntaxFormattingOptions _formattingOptions = formattingOptions;

// If the user brought up the lightbulb on a class itself, it's more likely that they want to extract a base
// class. on a member however, we deprioritize this as there are likely more member-specific operations
Expand All @@ -52,8 +55,8 @@ protected sealed override CodeActionPriority ComputePriority()
public override object? GetOptions(CancellationToken cancellationToken)
{
var extractClassService = _service ?? _document.Project.Solution.Services.GetRequiredService<IExtractClassOptionsService>();
return extractClassService.GetExtractClassOptionsAsync(_document, _selectedType, _selectedMembers, cancellationToken)
.WaitAndGetResult_CanCallOnBackground(cancellationToken);
return extractClassService.GetExtractClassOptions(
_document, _selectedType, _selectedMembers, _formattingOptions, cancellationToken);
}

protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@

using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host;

namespace Microsoft.CodeAnalysis.ExtractClass;

internal interface IExtractClassOptionsService : IWorkspaceService
{
Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken);
ExtractClassOptions? GetExtractClassOptions(
Document document,
INamedTypeSymbol originalType,
ImmutableArray<ISymbol> selectedMembers,
SyntaxFormattingOptions formattingOptions,
CancellationToken cancellationToken);
}
Original file line number Diff line number Diff line change
Expand Up @@ -104,21 +104,25 @@ public async Task<ExtractInterfaceTypeAnalysisResult> AnalyzeTypeAtPositionAsync
return new ExtractInterfaceTypeAnalysisResult(errorMessage);
}

return new ExtractInterfaceTypeAnalysisResult(document, typeNode, typeToExtractFrom, extractableMembers);
var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(cancellationToken).ConfigureAwait(false);
return new ExtractInterfaceTypeAnalysisResult(document, typeNode, typeToExtractFrom, extractableMembers, formattingOptions);
}

public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync(ExtractInterfaceTypeAnalysisResult refactoringResult, CancellationToken cancellationToken)
public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync(
ExtractInterfaceTypeAnalysisResult refactoringResult,
CancellationToken cancellationToken)
{
var containingNamespaceDisplay = refactoringResult.TypeToExtractFrom.ContainingNamespace.IsGlobalNamespace
? string.Empty
: refactoringResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString();

var extractInterfaceOptions = await GetExtractInterfaceOptionsAsync(
var extractInterfaceOptions = GetExtractInterfaceOptions(
refactoringResult.DocumentToExtractFrom,
refactoringResult.TypeToExtractFrom,
refactoringResult.ExtractableMembers,
containingNamespaceDisplay,
cancellationToken).ConfigureAwait(false);
refactoringResult.FormattingOptions,
cancellationToken);

if (extractInterfaceOptions.IsCancelled)
{
Expand Down Expand Up @@ -249,23 +253,23 @@ private async Task<ExtractInterfaceResult> ExtractInterfaceToSameFileAsync(
navigationDocumentId: refactoringResult.DocumentToExtractFrom.Id);
}

internal static async Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync(
internal static ExtractInterfaceOptionsResult GetExtractInterfaceOptions(
Document document,
INamedTypeSymbol type,
IEnumerable<ISymbol> extractableMembers,
string containingNamespace,
SyntaxFormattingOptions formattingOptions,
CancellationToken cancellationToken)
{
var conflictingTypeNames = type.ContainingNamespace.GetAllTypes(cancellationToken).Select(t => t.Name);
var candidateInterfaceName = type.TypeKind == TypeKind.Interface ? type.Name : "I" + type.Name;
var defaultInterfaceName = NameGenerator.GenerateUniqueName(candidateInterfaceName, name => !conflictingTypeNames.Contains(name));
var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();
var notificationService = document.Project.Solution.Services.GetService<INotificationService>();
var formattingOptions = await document.GetSyntaxFormattingOptionsAsync(cancellationToken).ConfigureAwait(false);
var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>();
var notificationService = document.Project.Solution.Services.GetRequiredService<INotificationService>();
var generatedNameTypeParameterSuffix = ExtractTypeHelpers.GetTypeParameterSuffix(document, formattingOptions, type, extractableMembers, cancellationToken);

var service = document.Project.Solution.Services.GetRequiredService<IExtractInterfaceOptionsService>();
return await service.GetExtractInterfaceOptionsAsync(
return service.GetExtractInterfaceOptions(
syntaxFactsService,
notificationService,
extractableMembers.ToList(),
Expand All @@ -274,7 +278,7 @@ internal static async Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOpt
containingNamespace,
generatedNameTypeParameterSuffix,
document.Project.Language,
cancellationToken).ConfigureAwait(false);
cancellationToken);
}

private static async Task<Solution> GetFormattedSolutionAsync(Solution unformattedSolution, IEnumerable<DocumentId> documentIds, CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ public override object GetOptions(CancellationToken cancellationToken)
? string.Empty
: _typeAnalysisResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString();

return AbstractExtractInterfaceService.GetExtractInterfaceOptionsAsync(
return AbstractExtractInterfaceService.GetExtractInterfaceOptions(
_typeAnalysisResult.DocumentToExtractFrom,
_typeAnalysisResult.TypeToExtractFrom,
_typeAnalysisResult.ExtractableMembers,
containingNamespaceDisplay,
cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
Copy link
Member Author

Choose a reason for hiding this comment

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

removing this was the goal. Note: This was terrifying as the impl was doing a JTF switch to teh ui thread. this was only ok as we're guaranteed to always be on the UI thread to begin with when calling GetOptions (guaranteed as a publicly documented contract of CodeActionWithOptions:

    /// <summary>
    /// Gets the options to use with this code action.
    /// This method is guaranteed to be called on the UI thread.
    /// </summary>

_typeAnalysisResult.FormattingOptions,
cancellationToken);
}

protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#nullable disable

using System.Collections.Generic;
using Microsoft.CodeAnalysis.Formatting;

namespace Microsoft.CodeAnalysis.ExtractInterface;

Expand All @@ -15,19 +16,22 @@ internal sealed class ExtractInterfaceTypeAnalysisResult
public readonly SyntaxNode TypeNode;
public readonly INamedTypeSymbol TypeToExtractFrom;
public readonly IEnumerable<ISymbol> ExtractableMembers;
public readonly SyntaxFormattingOptions FormattingOptions;
public readonly string ErrorMessage;

public ExtractInterfaceTypeAnalysisResult(
Document documentToExtractFrom,
SyntaxNode typeNode,
INamedTypeSymbol typeToExtractFrom,
IEnumerable<ISymbol> extractableMembers)
IEnumerable<ISymbol> extractableMembers,
SyntaxFormattingOptions formattingOptions)
{
CanExtractInterface = true;
DocumentToExtractFrom = documentToExtractFrom;
TypeNode = typeNode;
TypeToExtractFrom = typeToExtractFrom;
ExtractableMembers = extractableMembers;
FormattingOptions = formattingOptions;
}

public ExtractInterfaceTypeAnalysisResult(string errorMessage)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.Notification;
Expand All @@ -16,7 +12,7 @@ namespace Microsoft.CodeAnalysis.ExtractInterface;

internal interface IExtractInterfaceOptionsService : IWorkspaceService
{
Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync(
ExtractInterfaceOptionsResult GetExtractInterfaceOptions(
ISyntaxFactsService syntaxFactsService,
INotificationService notificationService,
List<ISymbol> extractableMembers,
Expand Down
Loading
Loading