From 3c97be3546a22657e0d1c6f6a35881bcebcc4ab5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Breu=C3=9F=20Valentin?= Date: Fri, 4 Dec 2026 16:40:12 +0100 Subject: [PATCH] fix: report unsupported ref struct members of interfaces added with `Implementing()` Mockolate0003 only looked at the type of `CreateMock()`, so a member of an interface added with `Implementing()` that the combination mock can only stub with a throwing body went unreported, and the user only found out through a NotSupportedException at run time. The analyzer now reports these members at the type argument, like Mockolate0002, and skips the members that the combination does not implement itself: those the mocked type or an earlier `Implementing()` already declares, and those the mocked class implements with a member the mock overrides. A class mock never implements the members of the interfaces the class implements, so the analyzer no longer reports them on `CreateMock()` of such a class, which was a false positive for a class that implements such a member non-virtually. The other ways to get a mock need no change: mock data sources, constructor dependencies and auto-mocking refuse types with such members, and `Wrapping` adds no types. --- Docs/pages/10-analyzers.md | 4 +- .../MockabilityAnalyzer.cs | 102 +++++- ...nalyzerRefStructTests.ImplementingTests.cs | 309 ++++++++++++++++++ .../MockabilityAnalyzerRefStructTests.cs | 6 +- 4 files changed, 403 insertions(+), 18 deletions(-) create mode 100644 Tests/Mockolate.Analyzers.Tests/MockabilityAnalyzerRefStructTests.ImplementingTests.cs diff --git a/Docs/pages/10-analyzers.md b/Docs/pages/10-analyzers.md index 9b91b2304..c5765da84 100644 --- a/Docs/pages/10-analyzers.md +++ b/Docs/pages/10-analyzers.md @@ -127,6 +127,8 @@ or later and C# 13 or later. Upgrade the target framework or `` to `Span` and `ReadOnlySpan` are supported everywhere else, both as parameters and as values returned by value. +The rule reports the members of the mocked type at `CreateMock()`, and the members that `Implementing()` adds to the mock at the type argument `T`. +
Virtual members of class mocks are not reported @@ -136,7 +138,7 @@ class implementation, so there is nothing to fix. The forwarded call ignores the it is not recorded. Interface members, `abstract` members, `init` accessors and members that return by reference have nothing to forward to. These -are the ones the warning reports. +are the ones the warning reports. So is a member of an interface added with `Implementing()` that the mocked class implements with a non-virtual member or leaves to its default implementation, because the mock implements the interface again.
diff --git a/Source/Mockolate.Analyzers/MockabilityAnalyzer.cs b/Source/Mockolate.Analyzers/MockabilityAnalyzer.cs index 2e5ef32c2..a2a03abf4 100644 --- a/Source/Mockolate.Analyzers/MockabilityAnalyzer.cs +++ b/Source/Mockolate.Analyzers/MockabilityAnalyzer.cs @@ -196,12 +196,12 @@ private static void AnalyzeSealedCreateMock(SyntaxNodeAnalysisContext context, /// /// Emits for each method/indexer on - /// (and its base/interface hierarchy) that the ref-struct generator + /// (and its base interfaces or base classes) that the ref-struct generator /// pipeline cannot safely emit on the current compilation. Multiple issues are reported per - /// CreateMock site; users get a complete picture of what to fix. + /// CreateMock or Implementing<T>() site; users get a complete picture of what to fix. /// private static void ReportRefStructIssuesForType(SyntaxNodeAnalysisContext context, ITypeSymbol type, - Location location) + Location location, Func? isEmittedElsewhere = null) { string? pipelineUnsupportedReason = GetRefStructPipelineUnsupportedReason(context.Compilation); @@ -223,7 +223,7 @@ private static void ReportRefStructIssuesForType(SyntaxNodeAnalysisContext conte return; } - foreach (ISymbol member in EnumerateAllMembers(type)) + foreach (ISymbol member in EnumerateAllMembers(type, isEmittedElsewhere)) { switch (member) { @@ -273,14 +273,17 @@ when NeedsRefStructPipeline(p.Type) && !ForwardsToBaseImplementation(p): /// / member on a class (including its base hierarchy). /// Members are de-duplicated by signature so an /// override and its virtual base don't produce two diagnostics for the same logical method. + /// Members for which returns are dropped + /// before that, so they do not hide another member with the same signature. /// - private static IEnumerable EnumerateAllMembers(ITypeSymbol type) + private static IEnumerable EnumerateAllMembers(ITypeSymbol type, Func? isEmittedElsewhere) { bool isInterface = type.TypeKind == TypeKind.Interface; HashSet seen = new(StringComparer.Ordinal); foreach ((ISymbol member, _) in GetCandidateMembers(type, isInterface) .Where(c => IsOverriddenByGenerator(c.member, c.isInterface) && + isEmittedElsewhere?.Invoke(c.member) != true && seen.Add(GetSignatureKey(c.member)))) { yield return member; @@ -295,16 +298,17 @@ private static IEnumerable EnumerateAllMembers(ITypeSymbol type) yield return (m, isInterface); } - foreach (INamedTypeSymbol iface in type.AllInterfaces) + // A class mock only overrides class members: the class itself implements its interfaces. + if (isInterface) { - foreach (ISymbol m in iface.GetMembers()) + foreach (INamedTypeSymbol iface in type.AllInterfaces) { - yield return (m, true); + foreach (ISymbol m in iface.GetMembers()) + { + yield return (m, true); + } } - } - if (isInterface) - { yield break; } @@ -607,8 +611,77 @@ private static void AnalyzeImplementing(SyntaxNodeAnalysisContext context, } spellings.Add(new MockedSpelling(typeArgument, typeArgumentLocation)); + + if (GetImplementingChain(context, memberAccess) is { } chain) + { + HashSet servedMembers = new(chain.EarlierInterfaces.Prepend(chain.MockedType) + .SelectMany(type => GetCandidateMembers(type, type.TypeKind == TypeKind.Interface)) + .Where(candidate => IsOverriddenByGenerator(candidate.member, candidate.isInterface)) + .Select(candidate => GetMemberKey(candidate.member)), StringComparer.Ordinal); + ReportRefStructIssuesForType(context, typeArgument, typeArgumentLocation, + member => servedMembers.Contains(GetMemberKey(member)) || + IsImplementedByClassOverride(chain.MockedType, member)); + } } + /// + /// The mocked type at the root of the Implementing<T>() chain and the interfaces that the + /// calls before this one add. Mirrors MockGeneratorHelpers.ExtractMockedTypes. + /// + private static (ITypeSymbol MockedType, List EarlierInterfaces)? GetImplementingChain( + SyntaxNodeAnalysisContext context, MemberAccessExpressionSyntax memberAccess) + { + List earlierInterfaces = []; + ExpressionSyntax expression = memberAccess.Expression; + while (expression is InvocationExpressionSyntax { Expression: MemberAccessExpressionSyntax innerAccess, } inner) + { + if (innerAccess.Name is GenericNameSyntax { Identifier.ValueText: "Implementing", }) + { + // As for the analyzed call, the host Roslyn version may leave the extension member unresolved. + SymbolInfo innerInfo = context.SemanticModel.GetSymbolInfo(inner, context.CancellationToken); + ITypeSymbol? earlierInterface = null; + if ((innerInfo.Symbol ?? innerInfo.CandidateSymbols.FirstOrDefault()) is not IMethodSymbol innerMethod) + { + earlierInterface = GetTypeArgumentFromSyntax(context, innerAccess); + } + else if (AnalyzerHelpers.IsMockolateNamespace(innerMethod.ContainingNamespace)) + { + earlierInterface = AnalyzerHelpers.GetSingleInvocationTypeArgumentOrNull(innerMethod); + } + + if (earlierInterface is not null) + { + earlierInterfaces.Add(earlierInterface); + } + } + + expression = innerAccess.Expression; + } + + ITypeSymbol? mockedType = context.SemanticModel.GetTypeInfo(expression, context.CancellationToken).Type ?? + context.SemanticModel.GetSymbolInfo(expression, context.CancellationToken).Symbol as + ITypeSymbol; + return mockedType is null or ITypeParameterSymbol ? null : (mockedType, earlierInterfaces); + } + + /// + /// A member of a combination mock is emitted once: an additional interface skips the members that the mocked + /// type or an earlier additional interface already declares (AppendMockSubject_ImplementClass). + /// + private static string GetMemberKey(ISymbol member) + => member.ContainingType.ToDisplayString() + "." + GetSignatureKey(member); + + /// + /// Whether a member of an additional interface is implemented by a member of the mocked class that the mock + /// overrides, in which case the combination keeps that override (Class.RebaseOnto). A default interface + /// implementation is no class member, so the combination implements the interface member again. + /// + private static bool IsImplementedByClassOverride(ITypeSymbol mockedType, ISymbol interfaceMember) + => mockedType.TypeKind == TypeKind.Class && + mockedType.FindImplementationForInterfaceMember(interfaceMember) is + { ContainingType.TypeKind: not TypeKind.Interface, } implementation && + IsOverriddenByGenerator(implementation, isInterface: false); + /// /// Reports every mocked spelling of a type that is also mocked in another spelling, because the generator /// emits a mock per spelling and their extensions make each other ambiguous (CS0121). @@ -1118,11 +1191,8 @@ bool IsDeclarationAccessible(INamedTypeSymbol candidate) /// chain (for a class). /// /// - /// Deliberately narrower than , which also walks - /// for classes. A class must already implement every - /// interface member it inherits (CS0535), so those members are not the mock's obligation and - /// folding them in here would reject types that mock perfectly well. The two walkers are not - /// interchangeable; keep them separate. + /// A class must already implement every interface member it inherits (CS0535), so those members + /// are not the mock's obligation and folding them in here would reject types that mock perfectly well. /// private static IEnumerable EnumerateImplementedTypes(ITypeSymbol type) { diff --git a/Tests/Mockolate.Analyzers.Tests/MockabilityAnalyzerRefStructTests.ImplementingTests.cs b/Tests/Mockolate.Analyzers.Tests/MockabilityAnalyzerRefStructTests.ImplementingTests.cs new file mode 100644 index 000000000..1c8b5da7b --- /dev/null +++ b/Tests/Mockolate.Analyzers.Tests/MockabilityAnalyzerRefStructTests.ImplementingTests.cs @@ -0,0 +1,309 @@ +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; +using Verifier = Mockolate.Analyzers.Tests.Verifiers.CSharpAnalyzerVerifier; + +namespace Mockolate.Analyzers.Tests; + +public sealed partial class MockabilityAnalyzerRefStructTests +{ + public sealed class ImplementingTests + { + [Test] + [Arguments("Packet Produce();", "Produce", "methods returning a non-span ref struct are not supported")] + [Arguments("Packet Current { get; }", "Current", "properties of a non-span ref struct type are not supported")] + [Arguments("ref System.Span GetBuffer();", "GetBuffer", + "methods returning a ref struct by reference are not supported")] + public async Task WhenInterfaceHasUnsupportedRefStructMember_ShouldBeFlaggedAtTypeArgument(string member, + string memberName, string issue) => await Verifier + .VerifyAnalyzerAsync( + $$""" + {{GeneratedPrefix("MyNamespace.IMyService", true)}} + + namespace MyNamespace + { + public readonly ref struct Packet(int id) { public int Id { get; } = id; } + + public interface IMyService + { + void Run(); + } + + public interface IPacketSource + { + {{member}} + } + + public class MyClass + { + public void MyTest() + { + IMyService.CreateMock().Implementing<{|#0:IPacketSource|}>(); + } + } + } + """, + new DiagnosticResult("Mockolate0003", DiagnosticSeverity.Warning) + .WithLocation(0) + .WithArguments("MyNamespace.IPacketSource", memberName, issue) + ); + + [Test] + public async Task WhenInterfaceHasNoUnsupportedRefStructMember_ShouldNotBeFlagged() => await Verifier + .VerifyAnalyzerAsync( + $$""" + {{GeneratedPrefix("MyNamespace.IMyService", true)}} + + namespace MyNamespace + { + public readonly ref struct Packet(int id) { public int Id { get; } = id; } + + public interface IMyService + { + void Run(); + } + + public interface IPacketSink + { + void Consume(Packet packet); + System.Span GetBuffer(); + } + + public class MyClass + { + public void MyTest() + { + IMyService.CreateMock().Implementing(); + } + } + } + """ + ); + + [Test] + public async Task WhenMockedClassImplementsMemberNonVirtually_ShouldOnlyBeFlaggedAtTypeArgument() => await Verifier + .VerifyAnalyzerAsync( + $$""" + {{GeneratedPrefix("MyNamespace.PacketFactory", true)}} + + namespace MyNamespace + { + public readonly ref struct Packet(int id) { public int Id { get; } = id; } + + public interface IPacketFactory + { + Packet Produce(); + } + + public class PacketFactory : IPacketFactory + { + // The class mock cannot override it, but the combination re-implements the interface. + public Packet Produce() => default; + } + + public class MyClass + { + public void MyTest() + { + PacketFactory.CreateMock().Implementing<{|#0:IPacketFactory|}>(); + } + } + } + """, + new DiagnosticResult("Mockolate0003", DiagnosticSeverity.Warning) + .WithLocation(0) + .WithArguments("MyNamespace.IPacketFactory", "Produce", + "methods returning a non-span ref struct are not supported") + ); + + [Test] + public async Task WhenMockedClassImplementsMemberVirtually_ShouldNotBeFlagged() => await Verifier + .VerifyAnalyzerAsync( + $$""" + {{GeneratedPrefix("MyNamespace.PacketFactory", true)}} + + namespace MyNamespace + { + public readonly ref struct Packet(int id) { public int Id { get; } = id; } + + public interface IPacketFactory + { + Packet Produce(); + } + + public class PacketFactory : IPacketFactory + { + // The class mock forwards it to the base implementation, and the combination keeps that override. + public virtual Packet Produce() => default; + } + + public class MyClass + { + public void MyTest() + { + PacketFactory.CreateMock().Implementing(); + } + } + } + """ + ); + + [Test] + public async Task WhenMockedInterfaceAlreadyHasMember_ShouldOnlyBeFlaggedAtMockedType() => await Verifier + .VerifyAnalyzerAsync( + $$""" + {{GeneratedPrefix("MyNamespace.IDerivedFactory", true)}} + + namespace MyNamespace + { + public readonly ref struct Packet(int id) { public int Id { get; } = id; } + + public interface IPacketFactory + { + Packet Produce(); + } + + public interface IDerivedFactory : IPacketFactory + { + void Run(); + } + + public class MyClass + { + public void MyTest() + { + {|#0:IDerivedFactory|}.CreateMock().Implementing(); + } + } + } + """, + new DiagnosticResult("Mockolate0003", DiagnosticSeverity.Warning) + .WithLocation(0) + .WithArguments("MyNamespace.IDerivedFactory", "Produce", + "methods returning a non-span ref struct are not supported") + ); + + [Test] + public async Task WhenEarlierInterfaceInChainAlreadyHasMember_ShouldOnlyBeFlaggedAtEarlierTypeArgument() => + await Verifier + .VerifyAnalyzerAsync( + $$""" + {{GeneratedPrefix("MyNamespace.IMyService", true)}} + + namespace MyNamespace + { + public readonly ref struct Packet(int id) { public int Id { get; } = id; } + + public interface IMyService + { + void Run(); + } + + public interface IPacketFactory + { + Packet Produce(); + } + + public interface IDerivedFactory : IPacketFactory + { + void Reset(); + } + + public class MyClass + { + public void MyTest() + { + IMyService.CreateMock().Implementing<{|#0:IPacketFactory|}>().Implementing(); + } + } + } + """, + new DiagnosticResult("Mockolate0003", DiagnosticSeverity.Warning) + .WithLocation(0) + .WithArguments("MyNamespace.IPacketFactory", "Produce", + "methods returning a non-span ref struct are not supported") + ); + + [Test] + public async Task WhenEarlierInterfaceHasMemberWithSameSignature_ShouldFlagTheOtherMember() => await Verifier + .VerifyAnalyzerAsync( + $$""" + {{GeneratedPrefix("MyNamespace.IMyService", true)}} + + namespace MyNamespace + { + public readonly ref struct Packet(int id) { public int Id { get; } = id; } + + public interface IMyService + { + void Run(); + } + + public interface IPacketFactory + { + Packet Produce(); + } + + public interface IOtherPacketFactory + { + Packet Produce(); + } + + public interface ICombinedFactory : IPacketFactory, IOtherPacketFactory + { + } + + public class MyClass + { + public void MyTest() + { + IMyService.CreateMock().Implementing<{|#0:IPacketFactory|}>().Implementing<{|#1:ICombinedFactory|}>(); + } + } + } + """, + new DiagnosticResult("Mockolate0003", DiagnosticSeverity.Warning) + .WithLocation(0) + .WithArguments("MyNamespace.IPacketFactory", "Produce", + "methods returning a non-span ref struct are not supported"), + new DiagnosticResult("Mockolate0003", DiagnosticSeverity.Warning) + .WithLocation(1) + .WithArguments("MyNamespace.ICombinedFactory", "Produce", + "methods returning a non-span ref struct are not supported") + ); + + [Test] + public async Task WhenMockedClassUsesDefaultImplementation_ShouldBeFlaggedAtTypeArgument() => await Verifier + .VerifyAnalyzerAsync( + $$""" + {{GeneratedPrefix("MyNamespace.PacketFactory", true)}} + + namespace MyNamespace + { + public readonly ref struct Packet(int id) { public int Id { get; } = id; } + + public interface IPacketFactory + { + Packet Produce() => default; + } + + public class PacketFactory : IPacketFactory + { + } + + public class MyClass + { + public void MyTest() + { + PacketFactory.CreateMock().Implementing<{|#0:IPacketFactory|}>(); + } + } + } + """, + new DiagnosticResult("Mockolate0003", DiagnosticSeverity.Warning) + .WithLocation(0) + .WithArguments("MyNamespace.IPacketFactory", "Produce", + "methods returning a non-span ref struct are not supported") + ); + } +} diff --git a/Tests/Mockolate.Analyzers.Tests/MockabilityAnalyzerRefStructTests.cs b/Tests/Mockolate.Analyzers.Tests/MockabilityAnalyzerRefStructTests.cs index 2988e88f6..d33f65898 100644 --- a/Tests/Mockolate.Analyzers.Tests/MockabilityAnalyzerRefStructTests.cs +++ b/Tests/Mockolate.Analyzers.Tests/MockabilityAnalyzerRefStructTests.cs @@ -1327,9 +1327,12 @@ public void MyTest() """ ); - private static string GeneratedPrefix(string fullyQualifiedTypeName) + private static string GeneratedPrefix(string fullyQualifiedTypeName, bool includeImplementing = false) { string simpleName = fullyQualifiedTypeName.Split('.')[^1]; + string implementing = includeImplementing + ? $"public {fullyQualifiedTypeName} Implementing() => default!;" + : ""; return $$""" namespace Mockolate { @@ -1338,6 +1341,7 @@ internal static partial class MockExtensionsFor{{simpleName}} extension({{fullyQualifiedTypeName}} mock) { public static {{fullyQualifiedTypeName}} CreateMock() => default!; + {{implementing}} } } }