Skip to content
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 @@ -24,7 +24,4 @@ internal sealed class CSharpImplementInterfaceCodeFixProvider()

public sealed override ImmutableArray<string> FixableDiagnosticIds { get; }
= [CS0535, CS0737, CS0738];

protected override bool IsTypeInInterfaceBaseList(TypeSyntax type)
=> type.Parent is BaseTypeSyntax { Parent: BaseListSyntax } baseTypeParent && baseTypeParent.Type == type;
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 was moved from the codefixprovider to the service. so it can be used by teh refactoring as well.

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.ImplementInterface;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.CSharp.ImplementInterface;

[ExportLanguageService(typeof(IImplementInterfaceService), LanguageNames.CSharp), Shared]
[method: ImportingConstructor]
[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
internal sealed class CSharpImplementInterfaceService() : AbstractImplementInterfaceService
internal sealed class CSharpImplementInterfaceService() : AbstractImplementInterfaceService<TypeDeclarationSyntax>
{
protected override ISyntaxFormatting SyntaxFormatting
=> CSharpSyntaxFormatting.Instance;
Expand All @@ -37,6 +38,18 @@ protected override string ToDisplayString(IMethodSymbol disposeImplMethod, Symbo
protected override bool AllowDelegateAndEnumConstraints(ParseOptions options)
=> options.LanguageVersion() >= LanguageVersion.CSharp7_3;

protected override bool IsTypeInInterfaceBaseList(SyntaxNode? type)
=> type?.Parent is BaseTypeSyntax { Parent: BaseListSyntax } baseTypeParent && baseTypeParent.Type == type;

protected override void AddInterfaceTypes(TypeDeclarationSyntax typeDeclaration, ArrayBuilder<SyntaxNode> result)
{
if (typeDeclaration.BaseList != null)
{
foreach (var baseType in typeDeclaration.BaseList.Types)
result.Add(baseType.Type);
}
}

protected override bool TryInitializeState(
Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken,
[NotNullWhen(true)] out SyntaxNode? classOrStructDecl,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@
<Compile Include="$(MSBuildThisFileDirectory)ImplementAbstractClass\ImplementAbstractClassTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ImplementAbstractClass\ImplementAbstractClassTests_FixAllTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ImplementAbstractClass\ImplementAbstractClassTests_ThroughMember.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ImplementInterface\ImplementInterfaceTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ImplementInterface\ImplementInterfaceTests_FixAllTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ImplementInterface\ImplementInterfaceCodeFixTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ImplementInterface\ImplementInterfaceCodeFixTests_FixAllTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Iterator\AddYieldTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Iterator\ChangeToIEnumerableTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)MakeAnonymousFunctionStatic\MakeAnonymousFunctionStaticTests.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementInterface;
CSharpImplementInterfaceCodeFixProvider>;

[Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public sealed class ImplementInterfaceTests
public sealed class ImplementInterfaceCodeFixTests
{
private readonly NamingStylesTestOptionSets _options = new(LanguageNames.CSharp);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementInterface;
EmptyDiagnosticAnalyzer,
CSharpImplementInterfaceCodeFixProvider>;

public sealed class ImplementInterfaceTests_FixAllTests
public sealed class ImplementInterfaceCodeFixTests_FixAllTests
{
#region "Fix all occurrences tests"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,16 @@
// 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.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.ImplementType;
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.ImplementInterface;

using static ImplementHelpers;

internal abstract class AbstractImplementInterfaceCodeFixProvider<TTypeSyntax> : CodeFixProvider
where TTypeSyntax : SyntaxNode
{
protected abstract bool IsTypeInInterfaceBaseList(TTypeSyntax type);
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 was moved from the codefixprovider to the service. so it can be used by teh refactoring as well.


public sealed override FixAllProvider GetFixAllProvider()
=> WellKnownFixAllProviders.BatchFixer;

Expand All @@ -39,173 +27,11 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
if (!token.Span.IntersectsWith(span))
return;

var options = await document.GetImplementTypeOptionsAsync(cancellationToken).ConfigureAwait(false);

foreach (var type in token.Parent.GetAncestorsOrThis<TTypeSyntax>())
{
if (this.IsTypeInInterfaceBaseList(type))
{
var service = document.GetRequiredLanguageService<IImplementInterfaceService>();

var info = await service.AnalyzeAsync(
document, type, cancellationToken).ConfigureAwait(false);
if (info is not null)
{
using var _ = ArrayBuilder<CodeAction>.GetInstance(out var codeActions);
await foreach (var implementOptions in GetImplementOptionsAsync(document, info, cancellationToken))
{
var title = GetTitle(implementOptions);
var equivalenceKey = GetEquivalenceKey(info, implementOptions);
codeActions.Add(CodeAction.Create(
title,
cancellationToken => service.ImplementInterfaceAsync(
document, info, options, implementOptions, cancellationToken),
equivalenceKey));
}

context.RegisterFixes(codeActions, context.Diagnostics);
}

break;
}
}
}

private static string GetTitle(ImplementInterfaceConfiguration options)
Copy link
Member Author

Choose a reason for hiding this comment

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

all teh below was moved from the codefixprovider to the service. so it can be used by teh refactoring as well.

{
if (options.ImplementDisposePattern)
{
return options.Explicitly
? CodeFixesResources.Implement_interface_explicitly_with_Dispose_pattern
: CodeFixesResources.Implement_interface_with_Dispose_pattern;
}
else if (options.Explicitly)
{
return options.OnlyRemaining
? CodeFixesResources.Implement_remaining_members_explicitly
: CodeFixesResources.Implement_all_members_explicitly;
}
else if (options.Abstractly)
{
return CodeFixesResources.Implement_interface_abstractly;
}
else if (options.ThroughMember != null)
{
return string.Format(CodeFixesResources.Implement_interface_through_0, options.ThroughMember.Name);
}
else
{
return CodeFixesResources.Implement_interface;
}
}

private static string GetEquivalenceKey(
ImplementInterfaceInfo state,
ImplementInterfaceConfiguration options)
{
var interfaceType = state.InterfaceTypes.First();
var typeName = interfaceType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);

// Legacy part of the equivalence key. Kept the same to avoid test churn.
var codeActionTypeName = options.ImplementDisposePattern
? "Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction"
: "Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction";

// Consider code actions equivalent if they correspond to the same interface being implemented elsewhere
// in the same manner. Note: 'implement through member' means implementing the same interface through
// an applicable member with the same name in the destination.
return options.Explicitly.ToString() + ";" +
options.Abstractly.ToString() + ";" +
options.OnlyRemaining.ToString() + ":" +
typeName + ";" +
codeActionTypeName + ";" +
options.ThroughMember?.Name;
}

private static async IAsyncEnumerable<ImplementInterfaceConfiguration> GetImplementOptionsAsync(
Document document, ImplementInterfaceInfo state, [EnumeratorCancellation] CancellationToken cancellationToken)
{
var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var supportsImplicitImplementationOfNonPublicInterfaceMembers = syntaxFacts.SupportsImplicitImplementationOfNonPublicInterfaceMembers(document.Project.ParseOptions!);
if (state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length > 0)
{
var totalMemberCount = 0;
var inaccessibleMemberCount = 0;

foreach (var (_, members) in state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented)
{
foreach (var member in members)
{
totalMemberCount++;

if (ContainsTypeLessAccessibleThan(member, state.ClassOrStructType, supportsImplicitImplementationOfNonPublicInterfaceMembers))
inaccessibleMemberCount++;
}
}

// If all members to implement are inaccessible, then "Implement interface" codeaction
// will be the same as "Implement interface explicitly", so there is no point in having both of them
if (totalMemberCount != inaccessibleMemberCount)
yield return new() { OnlyRemaining = true };

if (ShouldImplementDisposePattern(compilation, state, explicitly: false))
yield return new() { OnlyRemaining = true, ImplementDisposePattern = true, };

var delegatableMembers = GetDelegatableMembers(document, state, cancellationToken);
foreach (var member in delegatableMembers)
yield return new() { ThroughMember = member };
var type = token.Parent.GetAncestorsOrThis<TTypeSyntax>().LastOrDefault();

if (state.ClassOrStructType.IsAbstract)
yield return new() { OnlyRemaining = true, Abstractly = true };
}

if (state.MembersWithoutExplicitImplementation.Length > 0)
{
yield return new() { Explicitly = true };

if (ShouldImplementDisposePattern(compilation, state, explicitly: true))
yield return new() { ImplementDisposePattern = true, Explicitly = true };
}

if (AnyImplementedImplicitly(state))
yield return new() { OnlyRemaining = true, Explicitly = true };
}

private static bool AnyImplementedImplicitly(ImplementInterfaceInfo state)
{
if (state.MembersWithoutExplicitOrImplicitImplementation.Length != state.MembersWithoutExplicitImplementation.Length)
{
return true;
}

for (var i = 0; i < state.MembersWithoutExplicitOrImplicitImplementation.Length; i++)
{
var (typeA, membersA) = state.MembersWithoutExplicitOrImplicitImplementation[i];
var (typeB, membersB) = state.MembersWithoutExplicitImplementation[i];
if (!typeA.Equals(typeB))
{
return true;
}

if (!membersA.SequenceEqual(membersB))
{
return true;
}
}

return false;
}

private static ImmutableArray<ISymbol> GetDelegatableMembers(
Document document, ImplementInterfaceInfo state, CancellationToken cancellationToken)
{
var firstInterfaceType = state.InterfaceTypes.First();
var service = document.GetRequiredLanguageService<IImplementInterfaceService>();
var codeActions = await service.GetCodeActionsAsync(document, type, cancellationToken).ConfigureAwait(false);

return ImplementHelpers.GetDelegatableMembers(
document,
state.ClassOrStructType,
t => t.GetAllInterfacesIncludingThis().Contains(firstInterfaceType),
cancellationToken);
context.RegisterFixes(codeActions, context.Diagnostics);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

namespace Microsoft.CodeAnalysis.ImplementInterface;

internal abstract partial class AbstractImplementInterfaceService
internal abstract partial class AbstractImplementInterfaceService<TTypeDeclarationSyntax>
{
internal sealed class State(
Document document,
Expand Down Expand Up @@ -40,7 +40,7 @@ internal sealed class State(
public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitImplementation => Info.MembersWithoutExplicitImplementation;

public static State? Generate(
AbstractImplementInterfaceService service,
AbstractImplementInterfaceService<TTypeDeclarationSyntax> service,
Document document,
SemanticModel model,
SyntaxNode interfaceNode,
Expand Down
Loading
Loading