-
Notifications
You must be signed in to change notification settings - Fork 158
Add Roslyn analyzer for event sink helper consistency (NOE001-NOE003) #473
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 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
47a859f
Create a analyzer for issues with event sink helpers
jozefizso 20a01ac
Fix code issues flagged in the analyzer project
jozefizso 8e7e4cb
Rebuild `packages.lock.json`
jozefizso 55b26b3
Enable warnings reporting in event handlers implementations
jozefizso 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
252 changes: 252 additions & 0 deletions
252
Source/Analyzers/NetOffice.Analyzers/EventValidateRaiseConsistencyAnalyzer.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,252 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Collections.Immutable; | ||
| using System.Linq; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
| using Microsoft.CodeAnalysis.Operations; | ||
|
|
||
| namespace NetOffice.Analyzers; | ||
|
|
||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class EventValidateRaiseConsistencyAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| public const string ValidateVsRaiseId = "NOE001"; | ||
| public const string RaiseVsMethodId = "NOE002"; | ||
| public const string CannotVerifyId = "NOE003"; | ||
|
|
||
| private static readonly DiagnosticDescriptor ValidateVsRaiseRule = new( | ||
| id: ValidateVsRaiseId, | ||
| title: "Validate event name must match RaiseCustomEvent event name", | ||
| messageFormat: "Validate event name '{0}' does not match RaiseCustomEvent event name '{1}'.", | ||
| category: "NetOffice.Events", | ||
| defaultSeverity: DiagnosticSeverity.Warning, | ||
| isEnabledByDefault: true); | ||
|
|
||
| private static readonly DiagnosticDescriptor RaiseVsMethodRule = new( | ||
| id: RaiseVsMethodId, | ||
| title: "RaiseCustomEvent event name should match method name", | ||
| messageFormat: "RaiseCustomEvent event name '{0}' does not match containing method name '{1}'.", | ||
| category: "NetOffice.Events", | ||
| defaultSeverity: DiagnosticSeverity.Info, | ||
| isEnabledByDefault: true); | ||
|
|
||
| private static readonly DiagnosticDescriptor CannotVerifyRule = new( | ||
| id: CannotVerifyId, | ||
| title: "Unable to verify event name consistency", | ||
| messageFormat: "Unable to verify event name consistency in '{0}': use string literals for Validate/RaiseCustomEvent and avoid multiple distinct event names per method.", | ||
| category: "NetOffice.Events", | ||
| defaultSeverity: DiagnosticSeverity.Info, | ||
| isEnabledByDefault: true); | ||
|
|
||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => | ||
| ImmutableArray.Create(ValidateVsRaiseRule, RaiseVsMethodRule, CannotVerifyRule); | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.EnableConcurrentExecution(); | ||
|
|
||
| context.RegisterOperationBlockStartAction(startContext => | ||
| { | ||
| if (startContext.OwningSymbol is not IMethodSymbol methodSymbol) | ||
| return; | ||
|
|
||
| // This analyzer is meant for NetOffice sink helpers (derived from NetOffice.SinkHelper). | ||
| // Scoping it keeps the signal high and avoids flagging unrelated "Validate"/"RaiseCustomEvent" methods. | ||
| if (!InheritsFrom(methodSymbol.ContainingType, "NetOffice.SinkHelper")) | ||
| return; | ||
|
|
||
| var validateInvocations = new List<IInvocationOperation>(); | ||
| var raiseInvocations = new List<IInvocationOperation>(); | ||
|
|
||
| var validateConstNames = new HashSet<string>(StringComparer.Ordinal); | ||
| var raiseConstNames = new HashSet<string>(StringComparer.Ordinal); | ||
|
|
||
| bool validateHasNonConst = false; | ||
| bool raiseHasNonConst = false; | ||
|
|
||
| startContext.RegisterOperationAction(invocationContext => | ||
| { | ||
| var invocation = (IInvocationOperation)invocationContext.Operation; | ||
| var target = invocation.TargetMethod; | ||
|
|
||
| if (IsValidateCall(target, invocation)) | ||
| { | ||
| validateInvocations.Add(invocation); | ||
|
|
||
| if (TryGetFirstStringConstant(invocation, out var validateName)) | ||
| validateConstNames.Add(validateName); | ||
| else | ||
| validateHasNonConst = true; | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| if (IsRaiseCustomEventCall(target, invocation)) | ||
| { | ||
| raiseInvocations.Add(invocation); | ||
|
|
||
| if (TryGetFirstStringConstant(invocation, out var raiseName)) | ||
| raiseConstNames.Add(raiseName); | ||
| else | ||
| raiseHasNonConst = true; | ||
| } | ||
| }, OperationKind.Invocation); | ||
|
|
||
| startContext.RegisterOperationBlockEndAction(endContext => | ||
| { | ||
| if (validateInvocations.Count == 0 && raiseInvocations.Count == 0) | ||
| return; | ||
|
|
||
| bool raisedAnyDiagnostic = false; | ||
|
|
||
| // NOE001: Validate("...") must match RaiseCustomEvent("...") if both are verifiable. | ||
| if (!validateHasNonConst && | ||
| !raiseHasNonConst && | ||
| validateConstNames.Count == 1 && | ||
| raiseConstNames.Count == 1) | ||
| { | ||
| string validateName = validateConstNames.Single(); | ||
| string raiseName = raiseConstNames.Single(); | ||
|
|
||
| if (!string.Equals(validateName, raiseName, StringComparison.Ordinal)) | ||
| { | ||
| // Report on the Validate call so the fix is obvious (the bug class seen in DocumentEvents2.cs). | ||
| var location = validateInvocations[0].Syntax.GetLocation(); | ||
| endContext.ReportDiagnostic(Diagnostic.Create( | ||
| ValidateVsRaiseRule, | ||
| location, | ||
| validateName, | ||
| raiseName)); | ||
| raisedAnyDiagnostic = true; | ||
| } | ||
| } | ||
|
|
||
| // NOE002: Raised event name should match method name (convention in this codebase). | ||
| if (!raiseHasNonConst && raiseConstNames.Count == 1) | ||
| { | ||
| string raiseName = raiseConstNames.Single(); | ||
| string methodName = methodSymbol.Name; | ||
|
|
||
| if (!string.Equals(raiseName, methodName, StringComparison.Ordinal)) | ||
| { | ||
| var location = raiseInvocations[0].Syntax.GetLocation(); | ||
| endContext.ReportDiagnostic(Diagnostic.Create( | ||
| RaiseVsMethodRule, | ||
| location, | ||
| raiseName, | ||
| methodName)); | ||
| raisedAnyDiagnostic = true; | ||
| } | ||
| } | ||
|
|
||
| // NOE003: Analyzer cannot reliably check the method due to ambiguity / non-literal strings / missing pair. | ||
| if (!raisedAnyDiagnostic && NeedsCannotVerify(validateInvocations, raiseInvocations, validateConstNames, raiseConstNames, validateHasNonConst, raiseHasNonConst)) | ||
| { | ||
| var location = GetMethodNameLocation(methodSymbol) ?? raiseInvocations.FirstOrDefault()?.Syntax.GetLocation() ?? validateInvocations.First().Syntax.GetLocation(); | ||
| endContext.ReportDiagnostic(Diagnostic.Create(CannotVerifyRule, location, methodSymbol.Name)); | ||
| } | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| private static bool IsValidateCall(IMethodSymbol target, IInvocationOperation invocation) | ||
| { | ||
| if (!string.Equals(target.Name, "Validate", StringComparison.Ordinal)) | ||
| return false; | ||
|
|
||
| if (invocation.Arguments.Length < 1) | ||
| return false; | ||
|
|
||
| var firstParam = invocation.Arguments[0].Parameter; | ||
| if (firstParam == null || firstParam.Type.SpecialType != SpecialType.System_String) | ||
| return false; | ||
|
|
||
| // NetOffice uses SinkHelper.Validate(string) -> bool; this guards against unrelated Validate overloads. | ||
| return target.ReturnType.SpecialType == SpecialType.System_Boolean; | ||
| } | ||
|
|
||
| private static bool IsRaiseCustomEventCall(IMethodSymbol target, IInvocationOperation invocation) | ||
| { | ||
| if (!string.Equals(target.Name, "RaiseCustomEvent", StringComparison.Ordinal)) | ||
| return false; | ||
|
|
||
| if (invocation.Arguments.Length < 1) | ||
| return false; | ||
|
|
||
| var firstParam = invocation.Arguments[0].Parameter; | ||
| if (firstParam == null || firstParam.Type.SpecialType != SpecialType.System_String) | ||
| return false; | ||
|
|
||
| // In NetOffice, EventBinding is an IEventBinding and RaiseCustomEvent returns int. | ||
| return target.ReturnType.SpecialType == SpecialType.System_Int32; | ||
| } | ||
|
|
||
| private static bool TryGetFirstStringConstant(IInvocationOperation invocation, out string value) | ||
| { | ||
| value = ""; | ||
| if (invocation.Arguments.Length < 1) | ||
| return false; | ||
|
|
||
| var constant = invocation.Arguments[0].Value.ConstantValue; | ||
| if (!constant.HasValue || constant.Value is not string s) | ||
| return false; | ||
|
|
||
| value = s; | ||
| return true; | ||
| } | ||
|
|
||
| private static bool NeedsCannotVerify( | ||
| List<IInvocationOperation> validateInvocations, | ||
| List<IInvocationOperation> raiseInvocations, | ||
| HashSet<string> validateConstNames, | ||
| HashSet<string> raiseConstNames, | ||
| bool validateHasNonConst, | ||
| bool raiseHasNonConst) | ||
| { | ||
| // If the method is supposed to follow the NetOffice sink-helper pattern, | ||
| // we need exactly one verifiable Validate name and one verifiable RaiseCustomEvent name. | ||
| if (validateInvocations.Count == 0 || raiseInvocations.Count == 0) | ||
| return true; | ||
|
|
||
| if (validateHasNonConst || raiseHasNonConst) | ||
| return true; | ||
|
|
||
| if (validateConstNames.Count != 1 || raiseConstNames.Count != 1) | ||
| return true; | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| private static Location? GetMethodNameLocation(IMethodSymbol methodSymbol) | ||
| { | ||
| var syntaxRef = methodSymbol.DeclaringSyntaxReferences.FirstOrDefault(); | ||
| if (syntaxRef == null) | ||
| return null; | ||
|
|
||
| var node = syntaxRef.GetSyntax(); | ||
| if (node is MethodDeclarationSyntax methodDecl) | ||
| return methodDecl.Identifier.GetLocation(); | ||
|
|
||
| // Best-effort: report on the declaration node. | ||
| return node.GetLocation(); | ||
| } | ||
|
|
||
| private static bool InheritsFrom(INamedTypeSymbol? type, string fullyQualifiedMetadataName) | ||
| { | ||
| for (var current = type; current != null; current = current.BaseType) | ||
| { | ||
| // e.g. "NetOffice.SinkHelper" | ||
| var name = current.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); | ||
| if (name.StartsWith("global::", StringComparison.Ordinal)) | ||
| name = name.Substring("global::".Length); | ||
|
|
||
| if (string.Equals(name, fullyQualifiedMetadataName, StringComparison.Ordinal)) | ||
| return true; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
| } |
15 changes: 15 additions & 0 deletions
15
Source/Analyzers/NetOffice.Analyzers/NetOffice.Analyzers.csproj
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,15 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
| <PropertyGroup> | ||
| <TargetFramework>netstandard2.0</TargetFramework> | ||
| <LangVersion>latest</LangVersion> | ||
| <Nullable>enable</Nullable> | ||
| <IsPackable>false</IsPackable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <!-- VS loads analyzers into its own Roslyn instance; we only need these packages for compilation. --> | ||
| <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.8.0" PrivateAssets="all" /> | ||
| <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" /> | ||
| </ItemGroup> | ||
| </Project> | ||
|
|
||
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,12 @@ | ||
| <Project> | ||
| <!-- | ||
| Pull the custom Roslyn analyzers into every project under Source/ so they run in Visual Studio. | ||
| Projects can opt-out by setting NetOfficeDisableAnalyzers=true. | ||
| --> | ||
| <ItemGroup Condition=" '$(NetOfficeDisableAnalyzers)' != 'true' and '$(MSBuildProjectName)' != 'NetOffice.Analyzers' "> | ||
| <ProjectReference Include="$(MSBuildThisFileDirectory)Analyzers/NetOffice.Analyzers/NetOffice.Analyzers.csproj" | ||
| OutputItemType="Analyzer" | ||
| ReferenceOutputAssembly="false" /> | ||
| </ItemGroup> | ||
| </Project> | ||
|
|
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.