-
Notifications
You must be signed in to change notification settings - Fork 89
Add DiagnosticSuppressor (VSMEF013) for IDE0044 on MEF [Import]/[ImportMany] fields #706
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
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
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
13 changes: 0 additions & 13 deletions
13
src/Microsoft.VisualStudio.Composition.Analyzers/AnalyzerReleases.Shipped.md
This file was deleted.
Oops, something went wrong.
17 changes: 0 additions & 17 deletions
17
src/Microsoft.VisualStudio.Composition.Analyzers/AnalyzerReleases.Unshipped.md
This file was deleted.
Oops, something went wrong.
81 changes: 81 additions & 0 deletions
81
src/Microsoft.VisualStudio.Composition.Analyzers/IDE0044ImportFieldSuppressor.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,81 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
|
||
| namespace Microsoft.VisualStudio.Composition.Analyzers; | ||
|
|
||
| /// <summary> | ||
| /// Suppresses IDE0044 ("Make field readonly") for fields decorated with MEF | ||
| /// <c>[Import]</c> or <c>[ImportMany]</c> attributes, | ||
| /// since such fields are assigned at runtime via reflection and cannot be made readonly. | ||
| /// </summary> | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] | ||
| public class IDE0044ImportFieldSuppressor : DiagnosticSuppressor | ||
| { | ||
| /// <summary> | ||
| /// The suppressor ID. | ||
| /// </summary> | ||
| public const string Id = "VSMEF013"; | ||
|
|
||
| private const string SuppressedDiagnosticId = "IDE0044"; | ||
|
|
||
| /// <summary> | ||
| /// The descriptor for this suppressor. | ||
| /// </summary> | ||
| internal static readonly SuppressionDescriptor Descriptor = new( | ||
| id: Id, | ||
| suppressedDiagnosticId: SuppressedDiagnosticId, | ||
| justification: Strings.VSMEF013_Justification); | ||
|
AArnott marked this conversation as resolved.
|
||
|
|
||
| /// <inheritdoc/> | ||
| public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => | ||
| ImmutableArray.Create(Descriptor); | ||
|
|
||
| /// <inheritdoc/> | ||
| public override void ReportSuppressions(SuppressionAnalysisContext context) | ||
| { | ||
| foreach (Diagnostic diagnostic in context.ReportedDiagnostics) | ||
| { | ||
| if (diagnostic.Id != SuppressedDiagnosticId) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| SyntaxTree? syntaxTree = diagnostic.Location.SourceTree; | ||
| if (syntaxTree is null) | ||
| { | ||
| continue; | ||
| } | ||
|
AArnott marked this conversation as resolved.
|
||
|
|
||
| SemanticModel semanticModel = context.GetSemanticModel(syntaxTree); | ||
| SyntaxNode root = syntaxTree.GetRoot(context.CancellationToken); | ||
| SyntaxNode? node = root.FindNode(diagnostic.Location.SourceSpan); | ||
|
|
||
| IFieldSymbol? field = null; | ||
| while (node is not null) | ||
| { | ||
| ISymbol? symbol = semanticModel.GetDeclaredSymbol(node, context.CancellationToken); | ||
| if (symbol is IFieldSymbol f) | ||
| { | ||
| field = f; | ||
| break; | ||
| } | ||
|
|
||
| node = node.Parent; | ||
| } | ||
|
|
||
| if (field is null) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| foreach (AttributeData attribute in field.GetAttributes()) | ||
| { | ||
| if (Utils.IsFieldImportAttribute(attribute.AttributeClass)) | ||
| { | ||
| context.ReportSuppression(Suppression.Create(Descriptor, diagnostic)); | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
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
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
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
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
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
162 changes: 162 additions & 0 deletions
162
test/Microsoft.VisualStudio.Composition.Analyzers.Tests/IDE0044ImportFieldSuppressorTests.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,162 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
|
||
| using Microsoft.CodeAnalysis.CSharp.Testing; | ||
| using Microsoft.CodeAnalysis.Testing; | ||
| using Microsoft.VisualStudio.Composition.Analyzers; | ||
|
|
||
| public class IDE0044ImportFieldSuppressorTests | ||
| { | ||
| [Fact] | ||
| public async Task FieldWithMefV1ImportAttribute_SuppressesIDE0044() | ||
| { | ||
| string test = """ | ||
| using System.ComponentModel.Composition; | ||
|
|
||
| class Foo | ||
| { | ||
| [Import] | ||
| private object someField; | ||
| } | ||
| """; | ||
|
|
||
| await new Test | ||
| { | ||
| TestCode = test, | ||
| ExpectedDiagnostics = { Ide0044Diagnostic(6, 20, 6, 29, isSuppressed: true) }, | ||
| }.RunAsync(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task FieldWithMefV1ImportManyAttribute_SuppressesIDE0044() | ||
| { | ||
| string test = """ | ||
| using System.Collections.Generic; | ||
| using System.ComponentModel.Composition; | ||
|
|
||
| class Foo | ||
| { | ||
| [ImportMany] | ||
| private IEnumerable<object> someField; | ||
| } | ||
| """; | ||
|
|
||
| await new Test | ||
| { | ||
| TestCode = test, | ||
| ExpectedDiagnostics = { Ide0044Diagnostic(7, 33, 7, 42, isSuppressed: true) }, | ||
| }.RunAsync(); | ||
| } | ||
|
|
||
| [Fact] | ||
|
AArnott marked this conversation as resolved.
|
||
| public async Task FieldWithoutMefAttribute_DoesNotSuppressIDE0044() | ||
| { | ||
| string test = """ | ||
| class Foo | ||
| { | ||
| private object {|IDE0044:someField|}; | ||
| } | ||
| """; | ||
|
|
||
| await new Test { TestCode = test }.RunAsync(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ReadonlyField_NoDiagnostic() | ||
| { | ||
| string test = """ | ||
| using System.ComponentModel.Composition; | ||
|
|
||
| class Foo | ||
| { | ||
| private readonly object someField = null; | ||
| } | ||
| """; | ||
|
|
||
| await new Test { TestCode = test }.RunAsync(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ClassWithMixedFields_OnlyNonMefFieldsGetDiagnostic() | ||
| { | ||
| string test = """ | ||
| using System.ComponentModel.Composition; | ||
|
|
||
| class Foo | ||
| { | ||
| [Import] | ||
| private object mefField; | ||
|
|
||
| private object {|IDE0044:regularField|}; | ||
| } | ||
| """; | ||
|
|
||
| await new Test | ||
| { | ||
| TestCode = test, | ||
| ExpectedDiagnostics = { Ide0044Diagnostic(6, 20, 6, 28, isSuppressed: true) }, | ||
| }.RunAsync(); | ||
| } | ||
|
|
||
| private static DiagnosticResult Ide0044Diagnostic(int startLine, int startColumn, int endLine, int endColumn, bool isSuppressed = false) | ||
| { | ||
| DiagnosticResult result = new DiagnosticResult(FakeIDE0044Analyzer.Descriptor).WithSpan(startLine, startColumn, endLine, endColumn); | ||
| return isSuppressed ? result.WithIsSuppressed(true) : result; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// A fake analyzer that produces IDE0044 for non-readonly, non-const fields, | ||
| /// simulating IDE behavior for suppressor testing. | ||
| /// </summary> | ||
| #pragma warning disable RS1001 // Missing DiagnosticAnalyzerAttribute - intentionally omitted for test-only class | ||
| private sealed class FakeIDE0044Analyzer : DiagnosticAnalyzer | ||
| #pragma warning restore RS1001 | ||
| { | ||
| #pragma warning disable RS2008 // Enable analyzer release tracking - this is a test-only fake analyzer | ||
| internal static readonly DiagnosticDescriptor Descriptor = new( | ||
| id: "IDE0044", | ||
| title: "Make field readonly", | ||
| messageFormat: "Make field readonly", | ||
| category: "Style", | ||
| defaultSeverity: DiagnosticSeverity.Warning, | ||
| isEnabledByDefault: true); | ||
| #pragma warning restore RS2008 | ||
|
|
||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => | ||
| ImmutableArray.Create(Descriptor); | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.EnableConcurrentExecution(); | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.RegisterSymbolAction(AnalyzeField, SymbolKind.Field); | ||
| } | ||
|
|
||
| private static void AnalyzeField(SymbolAnalysisContext context) | ||
| { | ||
| var field = (IFieldSymbol)context.Symbol; | ||
| if (!field.IsReadOnly && !field.IsConst) | ||
| { | ||
| Location? location = field.Locations.FirstOrDefault(); | ||
| if (location is not null) | ||
| { | ||
| context.ReportDiagnostic(Diagnostic.Create(Descriptor, location)); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private sealed class Test : CSharpCodeFixTest<FakeIDE0044Analyzer, EmptyCodeFixProvider, DefaultVerifier> | ||
| { | ||
| public Test() | ||
| { | ||
| this.ReferenceAssemblies = ReferencesHelper.DefaultReferences; | ||
| } | ||
|
|
||
| protected override IEnumerable<DiagnosticAnalyzer> GetDiagnosticAnalyzers() | ||
| { | ||
| yield return new FakeIDE0044Analyzer(); | ||
| yield return new IDE0044ImportFieldSuppressor(); | ||
| } | ||
| } | ||
| } | ||
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
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.