|
| 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 Devlooped.WhatsApp; |
| 8 | + |
| 9 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 10 | +public class SendStringAnalyzer : DiagnosticAnalyzer |
| 11 | +{ |
| 12 | + public static DiagnosticDescriptor Rule { get; } = new( |
| 13 | + id: "WA001", |
| 14 | + title: "Invalid Payload Type", |
| 15 | + messageFormat: $"The second parameter of '{nameof(IWhatsAppClient)}.{nameof(IWhatsAppClient.SendAsync)}' should not be a string.", |
| 16 | + category: "Usage", |
| 17 | + defaultSeverity: DiagnosticSeverity.Error, |
| 18 | + description: "The payload parameter is serialized and sent as JSON over HTTP. Use an object instead.", |
| 19 | + isEnabledByDefault: true); |
| 20 | + |
| 21 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); |
| 22 | + |
| 23 | + public override void Initialize(AnalysisContext context) |
| 24 | + { |
| 25 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 26 | + context.EnableConcurrentExecution(); |
| 27 | + context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); |
| 28 | + } |
| 29 | + |
| 30 | + static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) |
| 31 | + { |
| 32 | + var invocation = (InvocationExpressionSyntax)context.Node; |
| 33 | + if (invocation.Expression is MemberAccessExpressionSyntax memberAccess && |
| 34 | + memberAccess.Name.Identifier.Text == nameof(IWhatsAppClient.SendAsync)) |
| 35 | + { |
| 36 | + var methodSymbol = context.SemanticModel.GetSymbolInfo(memberAccess).Symbol as IMethodSymbol; |
| 37 | + if (methodSymbol?.ContainingSymbol.Name == nameof(IWhatsAppClient) && invocation.ArgumentList.Arguments.Count == 2) |
| 38 | + { |
| 39 | + var secondArgument = invocation.ArgumentList.Arguments[1]; |
| 40 | + var argumentType = context.SemanticModel.GetTypeInfo(secondArgument.Expression).Type; |
| 41 | + if (argumentType?.SpecialType == SpecialType.System_String) |
| 42 | + { |
| 43 | + var diagnostic = Diagnostic.Create(Rule, secondArgument.GetLocation()); |
| 44 | + context.ReportDiagnostic(diagnostic); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments