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
4 changes: 3 additions & 1 deletion Docs/pages/10-analyzers.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ or later and C# 13 or later. Upgrade the target framework or `<LangVersion>` to

`Span<T>` and `ReadOnlySpan<T>` 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<T>()` adds to the mock at the type argument `T`.

<details>
<summary>Virtual members of class mocks are not reported</summary>

Expand All @@ -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<T>()` that the mocked class implements with a non-virtual member or leaves to its default implementation, because the mock implements the interface again.

</details>

Expand Down
102 changes: 86 additions & 16 deletions Source/Mockolate.Analyzers/MockabilityAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,12 @@ private static void AnalyzeSealedCreateMock(SyntaxNodeAnalysisContext context,

/// <summary>
/// Emits <see cref="s_refStructRule" /> for each method/indexer on
/// <paramref name="type" /> (and its base/interface hierarchy) that the ref-struct generator
/// <paramref name="type" /> (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
/// <c>CreateMock</c> site; users get a complete picture of what to fix.
/// <c>CreateMock</c> or <c>Implementing&lt;T&gt;()</c> site; users get a complete picture of what to fix.
/// </summary>
private static void ReportRefStructIssuesForType(SyntaxNodeAnalysisContext context, ITypeSymbol type,
Location location)
Location location, Func<ISymbol, bool>? isEmittedElsewhere = null)
{
string? pipelineUnsupportedReason = GetRefStructPipelineUnsupportedReason(context.Compilation);

Expand All @@ -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)
{
Expand Down Expand Up @@ -273,14 +273,17 @@ when NeedsRefStructPipeline(p.Type) && !ForwardsToBaseImplementation(p):
/// <see langword="virtual" />/<see langword="abstract" /> 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 <paramref name="isEmittedElsewhere" /> returns <see langword="true" /> are dropped
/// before that, so they do not hide another member with the same signature.
/// </summary>
private static IEnumerable<ISymbol> EnumerateAllMembers(ITypeSymbol type)
private static IEnumerable<ISymbol> EnumerateAllMembers(ITypeSymbol type, Func<ISymbol, bool>? isEmittedElsewhere)
{
bool isInterface = type.TypeKind == TypeKind.Interface;
HashSet<string> 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;
Expand All @@ -295,16 +298,17 @@ private static IEnumerable<ISymbol> 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;
}

Expand Down Expand Up @@ -607,8 +611,77 @@ private static void AnalyzeImplementing(SyntaxNodeAnalysisContext context,
}

spellings.Add(new MockedSpelling(typeArgument, typeArgumentLocation));

if (GetImplementingChain(context, memberAccess) is { } chain)
{
HashSet<string> 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));
}
}

/// <summary>
/// The mocked type at the root of the <c>Implementing&lt;T&gt;()</c> chain and the interfaces that the
/// calls before this one add. Mirrors <c>MockGeneratorHelpers.ExtractMockedTypes</c>.
/// </summary>
private static (ITypeSymbol MockedType, List<ITypeSymbol> EarlierInterfaces)? GetImplementingChain(
SyntaxNodeAnalysisContext context, MemberAccessExpressionSyntax memberAccess)
{
List<ITypeSymbol> 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);
}

/// <summary>
/// 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 (<c>AppendMockSubject_ImplementClass</c>).
/// </summary>
private static string GetMemberKey(ISymbol member)
=> member.ContainingType.ToDisplayString() + "." + GetSignatureKey(member);

/// <summary>
/// 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 (<c>Class.RebaseOnto</c>). A default interface
/// implementation is no class member, so the combination implements the interface member again.
/// </summary>
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);

/// <summary>
/// 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).
Expand Down Expand Up @@ -1118,11 +1191,8 @@ bool IsDeclarationAccessible(INamedTypeSymbol candidate)
/// chain (for a class).
/// </summary>
/// <remarks>
/// Deliberately narrower than <see cref="GetCandidateMembers" />, which also walks
/// <see cref="ITypeSymbol.AllInterfaces" /> 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.
/// </remarks>
private static IEnumerable<ITypeSymbol> EnumerateImplementedTypes(ITypeSymbol type)
{
Expand Down
Loading
Loading