-
Notifications
You must be signed in to change notification settings - Fork 649
Analyzer: Error when Feature Defaults are used to enable other features #7468
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 all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d8d8289
Error on Feature Defaults enabling a feature
danielmarbach 9888fb2
CSharp14
danielmarbach 2d14825
Modernize
danielmarbach c30667b
Optimize analyzer performance with syntax-based filtering (#7470)
Copilot c4e0ce9
Simplify
danielmarbach 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
158 changes: 158 additions & 0 deletions
158
src/NServiceBus.Core.Analyzer.Fixes/FeatureDefaultsEnableFeatureFixer.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,158 @@ | ||
| namespace NServiceBus.Core.Analyzer.Fixes | ||
| { | ||
| using System.Collections.Immutable; | ||
| using System.Composition; | ||
| using System.Linq; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Editing; | ||
| using Microsoft.CodeAnalysis.Formatting; | ||
|
|
||
| [Shared] | ||
| [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(FeatureDefaultsEnableFeatureFixer))] | ||
| public class FeatureDefaultsEnableFeatureFixer : CodeFixProvider | ||
| { | ||
| public override ImmutableArray<string> FixableDiagnosticIds => | ||
| [DiagnosticIds.DoNotEnableFeaturesInDefaults]; | ||
|
|
||
| public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| var diagnostic = context.Diagnostics.First(); | ||
| var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
|
|
||
| if (root?.FindNode(context.Span) is not InvocationExpressionSyntax enableInvocation) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var featureType = GetFeatureTypeArgument(enableInvocation)?.ToString(); | ||
| var title = featureType == null | ||
| ? "Call Enable<TFeature>() from the constructor" | ||
| : $"Call Enable<{featureType}>() from the constructor"; | ||
|
|
||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title, | ||
| cancellationToken => MoveEnableCallToConstructor(context.Document, enableInvocation, cancellationToken), | ||
| EquivalenceKey), | ||
| diagnostic); | ||
| } | ||
|
|
||
| static async Task<Document> MoveEnableCallToConstructor( | ||
| Document document, | ||
| InvocationExpressionSyntax enableInvocation, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); | ||
| var semanticModel = editor.SemanticModel; | ||
|
|
||
| var lambda = enableInvocation.FirstAncestorOrSelf<AnonymousFunctionExpressionSyntax>(); | ||
| if (lambda is not | ||
| { | ||
| Parent: ArgumentSyntax | ||
| { | ||
| Parent: ArgumentListSyntax { Parent: InvocationExpressionSyntax defaultsInvocation } | ||
| } | ||
| } || | ||
| semanticModel.GetSymbolInfo(defaultsInvocation, cancellationToken).Symbol is not IMethodSymbol defaultsSymbol) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| var defaultsStatement = defaultsInvocation.FirstAncestorOrSelf<StatementSyntax>(); | ||
| if (defaultsStatement == null) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| var typeArgument = GetFeatureTypeArgument(enableInvocation)?.WithoutTrivia(); | ||
| if (typeArgument == null) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| var compilation = semanticModel.Compilation; | ||
| var featureType = compilation.GetTypeByMetadataName("NServiceBus.Features.Feature"); | ||
| var defaultsDefinition = featureType? | ||
| .GetMembers("Defaults") | ||
| .OfType<IMethodSymbol>() | ||
| .FirstOrDefault()?.OriginalDefinition; | ||
|
|
||
| if (defaultsDefinition == null || | ||
| !SymbolEqualityComparer.IncludeNullability.Equals(defaultsSymbol.OriginalDefinition, defaultsDefinition)) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| bool removeDefaultsInvocation; | ||
| var lambdaBodyBlock = GetLambdaBodyBlock(lambda); | ||
| var invocationStatement = enableInvocation.FirstAncestorOrSelf<StatementSyntax>(); | ||
|
|
||
| if (lambdaBodyBlock == null || invocationStatement == null) | ||
| { | ||
| removeDefaultsInvocation = true; | ||
| } | ||
| else if (invocationStatement.Parent is BlockSyntax) | ||
| { | ||
| var topLevelStatements = lambdaBodyBlock.Statements; | ||
| removeDefaultsInvocation = topLevelStatements.Count == 1 && topLevelStatements[0] == invocationStatement; | ||
| } | ||
| else | ||
| { | ||
| // Unable to safely remove the invocation (e.g. part of an if statement without braces). | ||
| return document; | ||
| } | ||
|
|
||
| if (!removeDefaultsInvocation) | ||
| { | ||
| editor.RemoveNode(invocationStatement, SyntaxRemoveOptions.KeepNoTrivia); | ||
| } | ||
|
|
||
| var enableStatement = SyntaxFactory.ExpressionStatement( | ||
| SyntaxFactory.InvocationExpression( | ||
| SyntaxFactory.GenericName( | ||
| SyntaxFactory.Identifier("Enable"), | ||
| SyntaxFactory.TypeArgumentList(SyntaxFactory.SingletonSeparatedList(typeArgument))), | ||
| SyntaxFactory.ArgumentList())) | ||
| .WithAdditionalAnnotations(Formatter.Annotation); | ||
|
|
||
| editor.InsertBefore(defaultsStatement, enableStatement); | ||
|
|
||
| if (removeDefaultsInvocation) | ||
| { | ||
| editor.RemoveNode(defaultsStatement, SyntaxRemoveOptions.KeepExteriorTrivia); | ||
| } | ||
|
|
||
| var changed = editor.GetChangedDocument(); | ||
| var root = await changed.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||
| var formattedRoot = Formatter.Format(root, Formatter.Annotation, changed.Project.Solution.Workspace, cancellationToken: cancellationToken); | ||
| return changed.WithSyntaxRoot(formattedRoot); | ||
| } | ||
|
|
||
| static TypeSyntax GetFeatureTypeArgument(InvocationExpressionSyntax invocation) => | ||
| invocation.Expression switch | ||
| { | ||
| MemberAccessExpressionSyntax { Name: GenericNameSyntax genericName } => genericName.TypeArgumentList.Arguments.FirstOrDefault(), | ||
| GenericNameSyntax genericName => genericName.TypeArgumentList.Arguments.FirstOrDefault(), | ||
| _ => null, | ||
| }; | ||
|
|
||
| static BlockSyntax GetLambdaBodyBlock(AnonymousFunctionExpressionSyntax lambda) => | ||
| lambda switch | ||
| { | ||
| SimpleLambdaExpressionSyntax { Body: BlockSyntax block } => block, | ||
| ParenthesizedLambdaExpressionSyntax { Body: BlockSyntax block } => block, | ||
| AnonymousMethodExpressionSyntax anonymous => anonymous.Block, | ||
| _ => null, | ||
| }; | ||
|
|
||
| static readonly string EquivalenceKey = typeof(FeatureDefaultsEnableFeatureFixer).FullName; | ||
| } | ||
| } |
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
167 changes: 167 additions & 0 deletions
167
src/NServiceBus.Core.Analyzer.Tests.Common/FeatureDefaultsEnableFeatureAnalyzerTests.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,167 @@ | ||
| #pragma warning disable NUnit1034 // Base TestFixtures should be abstract | ||
|
|
||
| namespace NServiceBus.Core.Analyzer.Tests; | ||
|
|
||
| using System.Threading.Tasks; | ||
| using Helpers; | ||
| using NUnit.Framework; | ||
|
|
||
| [TestFixture] | ||
| public class FeatureDefaultsEnableFeatureAnalyzerTests : AnalyzerTestFixture<FeatureDefaultsEnableFeatureAnalyzer> | ||
| { | ||
| [Test] | ||
| public Task DiagnosticIsReportedForExpressionLambda() | ||
| { | ||
| var source = | ||
| """ | ||
| using NServiceBus.Features; | ||
|
|
||
| class SampleFeature : Feature | ||
| { | ||
| public SampleFeature() | ||
| { | ||
| Defaults(settings => [|settings.EnableFeature<AnotherFeature>()|]); | ||
| } | ||
|
|
||
| protected override void Setup(FeatureConfigurationContext context) { } | ||
| } | ||
|
|
||
| class AnotherFeature : Feature | ||
| { | ||
| protected override void Setup(FeatureConfigurationContext context) { } | ||
| } | ||
| """; | ||
|
|
||
| return Assert(DiagnosticIds.DoNotEnableFeaturesInDefaults, source); | ||
| } | ||
|
|
||
| [Test] | ||
| public Task DiagnosticIsReportedForMultiple() | ||
| { | ||
| var source = | ||
| """ | ||
| using NServiceBus.Features; | ||
|
|
||
| class SampleFeature : Feature | ||
| { | ||
| public SampleFeature() | ||
| { | ||
| Defaults(settings => | ||
| { | ||
| [|settings.EnableFeature<AnotherFeature>()|]; | ||
| [|settings.EnableFeature<YetAnotherFeature>()|]; | ||
| }); | ||
| } | ||
|
|
||
| protected override void Setup(FeatureConfigurationContext context) { } | ||
| } | ||
|
|
||
| class AnotherFeature : Feature | ||
| { | ||
| protected override void Setup(FeatureConfigurationContext context) { } | ||
| } | ||
|
|
||
| class YetAnotherFeature : Feature | ||
| { | ||
| protected override void Setup(FeatureConfigurationContext context) { } | ||
| } | ||
| """; | ||
|
|
||
| return Assert(DiagnosticIds.DoNotEnableFeaturesInDefaults, source); | ||
| } | ||
|
|
||
| [Test] | ||
| public Task DiagnosticIsReportedForBlockLambda() | ||
| { | ||
| var source = | ||
| """ | ||
| using NServiceBus.Features; | ||
|
|
||
| class SampleFeature : Feature | ||
| { | ||
| public SampleFeature() | ||
| { | ||
| Defaults(settings => | ||
| { | ||
| settings.Set("Key1", 7); | ||
| [|settings.EnableFeature<AnotherFeature>()|]; | ||
| settings.Set("Key2", 5); | ||
| }); | ||
| } | ||
|
|
||
| protected override void Setup(FeatureConfigurationContext context) { } | ||
| } | ||
|
|
||
| class AnotherFeature : Feature | ||
| { | ||
| protected override void Setup(FeatureConfigurationContext context) { } | ||
| } | ||
| """; | ||
|
|
||
| return Assert(DiagnosticIds.DoNotEnableFeaturesInDefaults, source); | ||
| } | ||
|
|
||
| [Test] | ||
| public Task DiagnosticIsReportedForMixedMode() | ||
| { | ||
| var source = | ||
| """ | ||
| using NServiceBus.Features; | ||
|
|
||
| class SampleFeature : Feature | ||
| { | ||
| public SampleFeature() | ||
| { | ||
| Enable<AnotherFeature>(); | ||
| Defaults(settings => | ||
| { | ||
| settings.Set("Key1", 7); | ||
| [|settings.EnableFeature<YetAnotherFeature>()|]; | ||
| settings.Set("Key2", 5); | ||
| }); | ||
| } | ||
|
|
||
| protected override void Setup(FeatureConfigurationContext context) { } | ||
| } | ||
|
|
||
| class AnotherFeature : Feature | ||
| { | ||
| protected override void Setup(FeatureConfigurationContext context) { } | ||
| } | ||
|
|
||
| class YetAnotherFeature : Feature | ||
| { | ||
| protected override void Setup(FeatureConfigurationContext context) { } | ||
| } | ||
| """; | ||
|
|
||
| return Assert(DiagnosticIds.DoNotEnableFeaturesInDefaults, source); | ||
| } | ||
|
|
||
| [Test] | ||
| public Task DiagnosticIsNotReportedWhenCallingEnable() | ||
| { | ||
| var source = | ||
| """ | ||
| using NServiceBus.Features; | ||
|
|
||
| class SampleFeature : Feature | ||
| { | ||
| public SampleFeature() | ||
| { | ||
| Enable<AnotherFeature>(); | ||
| Defaults(settings => settings.Set("Key", 5)); | ||
| } | ||
|
|
||
| protected override void Setup(FeatureConfigurationContext context) { } | ||
| } | ||
|
|
||
| class AnotherFeature : Feature | ||
| { | ||
| protected override void Setup(FeatureConfigurationContext context) { } | ||
| } | ||
| """; | ||
|
|
||
| return Assert(source); | ||
| } | ||
| } | ||
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.