|
| 1 | +namespace OpenStackNetAnalyzers |
| 2 | +{ |
| 3 | + using System.Collections.Immutable; |
| 4 | + using System.Linq; |
| 5 | + using Microsoft.CodeAnalysis; |
| 6 | + using Microsoft.CodeAnalysis.Diagnostics; |
| 7 | + |
| 8 | + [DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 9 | + public class ServiceMethodReturnValueAnalyzer : DiagnosticAnalyzer |
| 10 | + { |
| 11 | + public const string DiagnosticId = "ServiceMethodReturnValue"; |
| 12 | + internal const string Title = "Service interface methods should return a Task<T> with a result that implements IHttpApiCall<T>"; |
| 13 | + internal const string MessageFormat = "Service interface methods should return a Task<T> with a result that implements IHttpApiCall<T>"; |
| 14 | + internal const string Category = "OpenStack.Maintainability"; |
| 15 | + internal const string Description = "Service interface methods should return a Task<T> with a result that implements IHttpApiCall<T>"; |
| 16 | + |
| 17 | + private static DiagnosticDescriptor Descriptor = |
| 18 | + new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); |
| 19 | + |
| 20 | + private static readonly ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics = |
| 21 | + ImmutableArray.Create(Descriptor); |
| 22 | + |
| 23 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics |
| 24 | + { |
| 25 | + get |
| 26 | + { |
| 27 | + return _supportedDiagnostics; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + public override void Initialize(AnalysisContext context) |
| 32 | + { |
| 33 | + context.RegisterSymbolAction(HandleNamedType, SymbolKind.NamedType); |
| 34 | + } |
| 35 | + |
| 36 | + private void HandleNamedType(SymbolAnalysisContext context) |
| 37 | + { |
| 38 | + INamedTypeSymbol symbol = (INamedTypeSymbol)context.Symbol; |
| 39 | + if (!symbol.IsHttpServiceInterface()) |
| 40 | + return; |
| 41 | + |
| 42 | + foreach (IMethodSymbol method in symbol.GetMembers().OfType<IMethodSymbol>()) |
| 43 | + { |
| 44 | + INamedTypeSymbol returnType = method.ReturnType as INamedTypeSymbol; |
| 45 | + if (returnType.IsTask() && returnType.IsGenericType && returnType.TypeArguments.Length == 1) |
| 46 | + { |
| 47 | + INamedTypeSymbol genericArgument = returnType.TypeArguments[0] as INamedTypeSymbol; |
| 48 | + if (genericArgument.IsDelegatingHttpApiCall()) |
| 49 | + { |
| 50 | + // the method returns the expected type |
| 51 | + continue; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + ImmutableArray<Location> locations = method.Locations; |
| 56 | + context.ReportDiagnostic(Diagnostic.Create(Descriptor, locations.FirstOrDefault(), locations.Skip(1))); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments