-
-
Notifications
You must be signed in to change notification settings - Fork 128
fix(mocks): report TM006 instead of CS1729 for unsubclassable classes #6501
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b193e57
fix(mocks): report TM006 instead of CS1729 for unsubclassable classes
thomhurst 38c7f40
fix(mocks): align TM006 chainability with the generator's constructor…
thomhurst 97ee902
fix(mocks): only claim the generated Mock() entry point for TM006
thomhurst 9c17356
fix(mocks): report TM006 for the multi-type Mock.Of overloads
thomhurst File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
211 changes: 211 additions & 0 deletions
211
src/TUnit.Mocks.Analyzers/InaccessibleConstructorMockAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,211 @@ | ||
| using System.Collections.Immutable; | ||
| using System.Linq; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
|
|
||
| namespace TUnit.Mocks.Analyzers; | ||
|
|
||
| /// <summary> | ||
| /// Reports TM006 when a class is mocked but declares no constructor a generated subclass could | ||
| /// chain to. The generator skips code generation for such types, so without this diagnostic the | ||
| /// only feedback would be a missing member at the call site. See issue #6493. | ||
| /// </summary> | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public class InaccessibleConstructorMockAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = | ||
| ImmutableArray.Create(Rules.TM006_CannotMockTypeWithoutAccessibleConstructor); | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.EnableConcurrentExecution(); | ||
|
|
||
| context.RegisterSyntaxNodeAction(AnalyzeInvocation, SyntaxKind.InvocationExpression); | ||
| } | ||
|
|
||
| private static void AnalyzeInvocation(SyntaxNodeAnalysisContext context) | ||
| { | ||
| if (context.Node is not InvocationExpressionSyntax invocation) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var target = ResolveMockTarget(context, invocation); | ||
|
|
||
| if (target is not { TypeKind: TypeKind.Class } namedType) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| // Sealed types and value types are already covered by TM001/TM002 — don't double-report. | ||
| if (namedType.IsSealed || namedType.IsValueType) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (HasAccessibleConstructor(namedType, context.Compilation.Assembly)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| context.ReportDiagnostic( | ||
| Diagnostic.Create( | ||
| Rules.TM006_CannotMockTypeWithoutAccessibleConstructor, | ||
| invocation.GetLocation(), | ||
| namedType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Resolves the mocked type from either entry point: the generic <c>Mock.Of<T>()</c> / | ||
| /// <c>Mock.Wrap<T>()</c> form, or the generated <c>T.Mock()</c> static extension. | ||
| /// </summary> | ||
| private static INamedTypeSymbol? ResolveMockTarget(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocation) | ||
| { | ||
| var symbolInfo = context.SemanticModel.GetSymbolInfo(invocation, context.CancellationToken); | ||
|
|
||
| if (symbolInfo.Symbol is not IMethodSymbol methodSymbol) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| if (IsMockEntryPointMethod(methodSymbol)) | ||
| { | ||
| // The multi-type overloads — Of<T1, T2>() through Of<T1, T2, T3, T4>() — return | ||
| // Mock<T1>: T1 is the type the impl subclasses, T2..T4 are interfaces layered on it, | ||
| // and MockTypeDiscovery reuses T1's constructors for the multi-type model. So the | ||
| // first type argument is the constructor-bearing target for every overload. | ||
| return methodSymbol.TypeArguments.Length >= 1 | ||
| ? methodSymbol.TypeArguments[0] as INamedTypeSymbol | ||
| : null; | ||
| } | ||
|
|
||
| // Generated per-type entry point: `T.Mock()`. | ||
| if (!IsGeneratedStaticEntryPoint(methodSymbol) | ||
| || invocation.Expression is not MemberAccessExpressionSyntax memberAccess) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| return context.SemanticModel.GetSymbolInfo(memberAccess.Expression, context.CancellationToken).Symbol | ||
| as INamedTypeSymbol; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Matches the <c>Mock()</c> the generator emits: a static member of a C# 14 | ||
| /// <c>extension(T)</c> block inside a <c>*_MockStaticExtension</c> class in namespace | ||
| /// <c>TUnit.Mocks</c>. Roslyn reports the member's immediate containing type as the | ||
| /// synthesised, unnamed extension type, so the check walks out to the declaring class — | ||
| /// matching on the namespace alone would claim any static <c>Mock()</c> a consumer happens to | ||
| /// declare there. | ||
| /// </summary> | ||
| private static bool IsGeneratedStaticEntryPoint(IMethodSymbol method) | ||
| { | ||
| if (method is not { Name: "Mock", IsStatic: true } || !IsTUnitMocksNamespace(method.ContainingNamespace)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| for (var containing = method.ContainingType; containing is not null; containing = containing.ContainingType) | ||
| { | ||
| if (containing.Name.EndsWith("_MockStaticExtension", System.StringComparison.Ordinal)) | ||
| { | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| private static bool IsTUnitMocksNamespace(INamespaceSymbol? ns) | ||
| => ns is { Name: "Mocks", ContainingNamespace: { Name: "TUnit", ContainingNamespace.IsGlobalNamespace: true } }; | ||
|
|
||
| private static bool IsMockEntryPointMethod(IMethodSymbol method) | ||
| { | ||
| return method.Name is "Of" or "Wrap" | ||
| && method.ContainingType is { Name: "Mock" or "MockRepository", ContainingNamespace: { Name: "Mocks", ContainingNamespace: { Name: "TUnit", ContainingNamespace.IsGlobalNamespace: true } } } | ||
| && method.IsGenericMethod; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Mirrors the generator's constructor discovery — <c>MemberDiscovery.DiscoverConstructors</c> | ||
| /// → <c>IsMemberAccessible</c> → <c>AreMemberSignatureTypesAccessible</c>. A generated subclass | ||
| /// can chain to a constructor only when the constructor itself is reachable AND every one of | ||
| /// its parameter types is: the generator drops a constructor whose signature mentions an | ||
| /// inaccessible type, and a target left with none is exactly the case this rule reports. | ||
| /// Keep the two in step; they live in separate assemblies with no shared project. | ||
| /// Protected (and protected internal) constructors are reachable precisely because the | ||
| /// generated impl derives from the target. | ||
| /// </summary> | ||
| private static bool HasAccessibleConstructor(INamedTypeSymbol type, IAssemblySymbol compilationAssembly) | ||
| { | ||
| return type.InstanceConstructors.Any(ctor => IsChainable(ctor, compilationAssembly)); | ||
| } | ||
|
|
||
| private static bool IsChainable(IMethodSymbol ctor, IAssemblySymbol compilationAssembly) | ||
| { | ||
| // DiscoverConstructors rejects private constructors outright, same-assembly or not — | ||
| // a subclass can never chain to one. | ||
| if (ctor.DeclaredAccessibility == Accessibility.Private) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| return IsAssemblyReachable(ctor.DeclaredAccessibility, ctor.ContainingAssembly, compilationAssembly) | ||
| && ctor.Parameters.All(p => IsTypeAccessible(p.Type, compilationAssembly)); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Whether a symbol with this accessibility, declared in <paramref name="declaringAssembly"/>, | ||
| /// is reachable from <paramref name="compilationAssembly"/>. Anything in the same assembly is; | ||
| /// across assemblies only <c>internal</c> and <c>private protected</c> are gated (and then only | ||
| /// without InternalsVisibleTo). | ||
| /// </summary> | ||
| private static bool IsAssemblyReachable(Accessibility accessibility, IAssemblySymbol? declaringAssembly, IAssemblySymbol compilationAssembly) | ||
| { | ||
| if (declaringAssembly is null || SymbolEqualityComparer.Default.Equals(declaringAssembly, compilationAssembly)) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| if (accessibility == Accessibility.Private) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| return accessibility is not (Accessibility.Internal or Accessibility.ProtectedAndInternal) | ||
| || declaringAssembly.GivesAccessTo(compilationAssembly); | ||
| } | ||
|
|
||
| private static bool IsTypeAccessible(ITypeSymbol type, IAssemblySymbol compilationAssembly) | ||
| { | ||
| // Type parameters are always accessible. | ||
| if (type is ITypeParameterSymbol) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| // Pointer types can't appear in a generated override signature, even same-assembly. | ||
| if (type is IPointerTypeSymbol or IFunctionPointerTypeSymbol) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| if (type is IArrayTypeSymbol arrayType) | ||
| { | ||
| return IsTypeAccessible(arrayType.ElementType, compilationAssembly); | ||
| } | ||
|
|
||
| if (!IsAssemblyReachable(type.DeclaredAccessibility, type.ContainingAssembly, compilationAssembly)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| return type is not INamedTypeSymbol namedType | ||
| || namedType.TypeArguments.All(arg => IsTypeAccessible(arg, compilationAssembly)); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.