|
| 1 | +//----------------------------------------------------------------------- |
| 2 | +// <copyright file="AsMustBeUsedWithInterfaceAnalyzer.cs" company="P.O.S Informatique"> |
| 3 | +// Copyright (c) P.O.S Informatique. All rights reserved. |
| 4 | +// </copyright> |
| 5 | +//----------------------------------------------------------------------- |
| 6 | + |
| 7 | +namespace PosInformatique.Moq.Analyzers |
| 8 | +{ |
| 9 | + using System.Collections.Immutable; |
| 10 | + using Microsoft.CodeAnalysis; |
| 11 | + using Microsoft.CodeAnalysis.CSharp; |
| 12 | + using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 13 | + using Microsoft.CodeAnalysis.Diagnostics; |
| 14 | + |
| 15 | + [DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 16 | + public class AsMustBeUsedWithInterfaceAnalyzer : DiagnosticAnalyzer |
| 17 | + { |
| 18 | + internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( |
| 19 | + "PosInfoMoq2007", |
| 20 | + "The As<T>() method can be used only with interfaces", |
| 21 | + "The As<T>() method can be used only with interfaces", |
| 22 | + "Compilation", |
| 23 | + DiagnosticSeverity.Error, |
| 24 | + isEnabledByDefault: true, |
| 25 | + description: "The As<T>() method can be used only with interfaces.", |
| 26 | + helpLinkUri: "https://posinformatique.github.io/PosInformatique.Moq.Analyzers/docs/Compilation/PosInfoMoq2007.html"); |
| 27 | + |
| 28 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); |
| 29 | + |
| 30 | + public override void Initialize(AnalysisContext context) |
| 31 | + { |
| 32 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 33 | + context.EnableConcurrentExecution(); |
| 34 | + |
| 35 | + context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); |
| 36 | + } |
| 37 | + |
| 38 | + private static void Analyze(SyntaxNodeAnalysisContext context) |
| 39 | + { |
| 40 | + var invocationExpression = (InvocationExpressionSyntax)context.Node; |
| 41 | + |
| 42 | + var moqSymbols = MoqSymbols.FromCompilation(context.Compilation); |
| 43 | + |
| 44 | + if (moqSymbols is null) |
| 45 | + { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + var moqExpressionAnalyzer = new MoqExpressionAnalyzer(moqSymbols, context.SemanticModel); |
| 50 | + |
| 51 | + var asMethodType = moqExpressionAnalyzer.ExtractAsMethodType(invocationExpression, out var typeSyntax, context.CancellationToken); |
| 52 | + |
| 53 | + if (asMethodType is null) |
| 54 | + { |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + if (asMethodType.TypeKind == TypeKind.Interface) |
| 59 | + { |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + var diagnostic = Diagnostic.Create(Rule, typeSyntax!.GetLocation()); |
| 64 | + context.ReportDiagnostic(diagnostic); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments