|
| 1 | +using System.Collections.Immutable; |
| 2 | +using Microsoft.CodeAnalysis; |
| 3 | +using Microsoft.CodeAnalysis.CSharp; |
| 4 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 5 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 6 | + |
| 7 | +namespace Zapto.Mediator.Generator; |
| 8 | + |
| 9 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 10 | +public class UseTypedSenderExtensionAnalyzer : DiagnosticAnalyzer |
| 11 | +{ |
| 12 | + public const string DiagnosticId = "ZM0001"; |
| 13 | + public const string ExtensionMethodNameProperty = "ExtensionMethodName"; |
| 14 | + public const string HasNamespaceArgProperty = "HasNamespaceArg"; |
| 15 | + public const string IsObjectCreationProperty = "IsObjectCreation"; |
| 16 | + |
| 17 | + internal static readonly DiagnosticDescriptor Rule = new( |
| 18 | + DiagnosticId, |
| 19 | + title: "Use typed sender extension method", |
| 20 | + messageFormat: "Use '{0}' instead", |
| 21 | + category: "Usage", |
| 22 | + defaultSeverity: DiagnosticSeverity.Info, |
| 23 | + isEnabledByDefault: true, |
| 24 | + description: "Use the typed extension method generated for this request type instead of the generic Send/Publish/CreateStream overload."); |
| 25 | + |
| 26 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => |
| 27 | + ImmutableArray.Create(Rule); |
| 28 | + |
| 29 | + public override void Initialize(AnalysisContext context) |
| 30 | + { |
| 31 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 32 | + context.EnableConcurrentExecution(); |
| 33 | + context.RegisterSyntaxNodeAction(AnalyzeInvocation, SyntaxKind.InvocationExpression); |
| 34 | + } |
| 35 | + |
| 36 | + private static void AnalyzeInvocation(SyntaxNodeAnalysisContext context) |
| 37 | + { |
| 38 | + var invocation = (InvocationExpressionSyntax)context.Node; |
| 39 | + |
| 40 | + if (invocation.Expression is not MemberAccessExpressionSyntax memberAccess) |
| 41 | + return; |
| 42 | + |
| 43 | + var methodIdentifier = memberAccess.Name.Identifier.ValueText; |
| 44 | + if (methodIdentifier is not ("Send" or "Publish" or "CreateStream")) |
| 45 | + return; |
| 46 | + |
| 47 | + if (context.SemanticModel.GetSymbolInfo(invocation).Symbol is not IMethodSymbol methodSymbol) |
| 48 | + return; |
| 49 | + |
| 50 | + var containingType = methodSymbol.ContainingType; |
| 51 | + if (!IsMediatorInterface(containingType)) |
| 52 | + return; |
| 53 | + |
| 54 | + var args = invocation.ArgumentList.Arguments; |
| 55 | + if (args.Count == 0) return; |
| 56 | + |
| 57 | + // Named outer arguments can cause incorrect argument reordering in the code fix |
| 58 | + foreach (var arg in args) |
| 59 | + { |
| 60 | + if (arg.NameColon != null) return; |
| 61 | + } |
| 62 | + |
| 63 | + // The first argument might be a MediatorNamespace for namespaced calls |
| 64 | + var requestArgIndex = 0; |
| 65 | + var firstArgType = context.SemanticModel.GetTypeInfo(args[0].Expression).Type; |
| 66 | + if (firstArgType?.Name == "MediatorNamespace" && |
| 67 | + firstArgType.ContainingNamespace?.ToDisplayString() == "Zapto.Mediator") |
| 68 | + { |
| 69 | + requestArgIndex = 1; |
| 70 | + } |
| 71 | + |
| 72 | + if (args.Count <= requestArgIndex) return; |
| 73 | + |
| 74 | + var requestArg = args[requestArgIndex]; |
| 75 | + if (context.SemanticModel.GetTypeInfo(requestArg.Expression).Type is not INamedTypeSymbol requestType) |
| 76 | + return; |
| 77 | + |
| 78 | + var interfaceName = FindRequestInterface(requestType); |
| 79 | + if (interfaceName is null) return; |
| 80 | + |
| 81 | + var extensionMethodName = ComputeExtensionMethodName(interfaceName, requestType.Name, methodSymbol); |
| 82 | + |
| 83 | + if (!ExtensionMethodExists(context.Compilation, requestType, extensionMethodName)) |
| 84 | + return; |
| 85 | + |
| 86 | + // Don't unwrap generic types (type arguments may not be inferable from ctor args alone) |
| 87 | + // Don't unwrap when an object initializer is also present (it would be silently dropped) |
| 88 | + var isObjectCreation = !requestType.IsGenericType && |
| 89 | + requestArg.Expression is ObjectCreationExpressionSyntax oc && |
| 90 | + oc.ArgumentList?.Arguments.Count > 0 && |
| 91 | + oc.Initializer == null; |
| 92 | + var hasNamespaceArg = requestArgIndex > 0; |
| 93 | + |
| 94 | + var properties = ImmutableDictionary.CreateBuilder<string, string?>(); |
| 95 | + properties[ExtensionMethodNameProperty] = extensionMethodName; |
| 96 | + properties[HasNamespaceArgProperty] = hasNamespaceArg ? "true" : "false"; |
| 97 | + properties[IsObjectCreationProperty] = isObjectCreation ? "true" : "false"; |
| 98 | + |
| 99 | + var diagnostic = Diagnostic.Create( |
| 100 | + Rule, |
| 101 | + memberAccess.Name.GetLocation(), |
| 102 | + properties.ToImmutable(), |
| 103 | + extensionMethodName); |
| 104 | + |
| 105 | + context.ReportDiagnostic(diagnostic); |
| 106 | + } |
| 107 | + |
| 108 | + private static bool IsMediatorInterface(INamedTypeSymbol type) |
| 109 | + { |
| 110 | + return type.ContainingNamespace?.ToDisplayString() == "Zapto.Mediator" && |
| 111 | + type.Name is "ISender" or "IPublisher" or "IBackgroundPublisher"; |
| 112 | + } |
| 113 | + |
| 114 | + internal static string? FindRequestInterface(INamedTypeSymbol requestType) |
| 115 | + { |
| 116 | + foreach (var iface in requestType.AllInterfaces) |
| 117 | + { |
| 118 | + var ns = iface.ContainingNamespace?.ToDisplayString(); |
| 119 | + if ((ns == "Zapto.Mediator" || ns == "MediatR") && |
| 120 | + iface.Name is "IRequest" or "INotification" or "IStreamRequest") |
| 121 | + { |
| 122 | + return iface.Name; |
| 123 | + } |
| 124 | + } |
| 125 | + return null; |
| 126 | + } |
| 127 | + |
| 128 | + internal static string ComputeExtensionMethodName(string interfaceName, string typeName, IMethodSymbol? methodSymbol = null) |
| 129 | + { |
| 130 | + // Remove the "I" prefix to get suffix: IRequest -> Request, INotification -> Notification |
| 131 | + var suffix = interfaceName.Substring(1); |
| 132 | + var baseName = typeName.EndsWith(suffix) && typeName.Length != suffix.Length |
| 133 | + ? typeName.Substring(0, typeName.Length - suffix.Length) |
| 134 | + : typeName; |
| 135 | + |
| 136 | + // IBackgroundPublisher methods are void, so no "Async" suffix |
| 137 | + var isVoidReturn = methodSymbol?.ReturnType.SpecialType == SpecialType.System_Void; |
| 138 | + return isVoidReturn ? baseName : baseName + "Async"; |
| 139 | + } |
| 140 | + |
| 141 | + internal static bool ExtensionMethodExists(Compilation compilation, INamedTypeSymbol requestType, string methodName) |
| 142 | + { |
| 143 | + var isGlobalNs = requestType.ContainingNamespace?.IsGlobalNamespace ?? true; |
| 144 | + var ns = isGlobalNs ? null : requestType.ContainingNamespace?.ToDisplayString(); |
| 145 | + var fullTypeName = ns is null ? "SenderExtensions" : $"{ns}.SenderExtensions"; |
| 146 | + |
| 147 | + var extensionsType = compilation.GetTypeByMetadataName(fullTypeName); |
| 148 | + if (extensionsType is null) return false; |
| 149 | + |
| 150 | + foreach (var member in extensionsType.GetMembers(methodName)) |
| 151 | + { |
| 152 | + if (member is IMethodSymbol) return true; |
| 153 | + } |
| 154 | + |
| 155 | + return false; |
| 156 | + } |
| 157 | +} |
0 commit comments