-
Notifications
You must be signed in to change notification settings - Fork 480
Seal internal private types analyzer #5594
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
stephentoub
merged 4 commits into
dotnet:main
from
NewellClark:seal-internal-private-types-analyzer
Apr 17, 2022
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
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
60 changes: 60 additions & 0 deletions
60
src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/SealInternalTypes.Fixer.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,60 @@ | ||
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. | ||
|
|
||
| using System.Collections.Immutable; | ||
| using System.Composition; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.Editing; | ||
|
|
||
| namespace Microsoft.NetCore.Analyzers.Runtime | ||
| { | ||
| [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic), Shared] | ||
| public sealed class SealInternalTypesFixer : CodeFixProvider | ||
| { | ||
| public override Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| var codeAction = CodeAction.Create( | ||
| MicrosoftNetCoreAnalyzersResources.SealInternalTypesCodeFixTitle, | ||
| SealClassDeclarationsAsync, | ||
| nameof(MicrosoftNetCoreAnalyzersResources.SealInternalTypesCodeFixTitle)); | ||
| context.RegisterCodeFix(codeAction, context.Diagnostics); | ||
| return Task.CompletedTask; | ||
|
|
||
| // Local functions | ||
|
|
||
| async Task<Solution> SealClassDeclarationsAsync(CancellationToken token) | ||
| { | ||
| var solutionEditor = new SolutionEditor(context.Document.Project.Solution); | ||
| await SealDeclarationAt(solutionEditor, context.Diagnostics[0].Location, token).ConfigureAwait(false); | ||
|
|
||
| foreach (var location in context.Diagnostics[0].AdditionalLocations) | ||
| await SealDeclarationAt(solutionEditor, location, token).ConfigureAwait(false); | ||
|
|
||
| return solutionEditor.GetChangedSolution(); | ||
| } | ||
|
|
||
| static async Task SealDeclarationAt(SolutionEditor solutionEditor, Location location, CancellationToken token) | ||
| { | ||
| var solution = solutionEditor.OriginalSolution; | ||
| var document = solution.GetDocument(location.SourceTree); | ||
|
|
||
| if (document is null) | ||
| return; | ||
|
|
||
| var documentEditor = await solutionEditor.GetDocumentEditorAsync(document.Id, token).ConfigureAwait(false); | ||
| var root = await document.GetSyntaxRootAsync(token).ConfigureAwait(false); | ||
| var declaration = root.FindNode(location.SourceSpan); | ||
| var newModifiers = documentEditor.Generator.GetModifiers(declaration).WithIsSealed(true); | ||
| var newDeclaration = documentEditor.Generator.WithModifiers(declaration, newModifiers); | ||
| documentEditor.ReplaceNode(declaration, newDeclaration); | ||
| } | ||
| } | ||
|
|
||
| public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(SealInternalTypes.RuleId); | ||
|
|
||
| public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
| } | ||
| } | ||
80 changes: 80 additions & 0 deletions
80
src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/SealInternalTypes.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,80 @@ | ||
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. | ||
|
|
||
| using System.Collections.Immutable; | ||
| using Analyzer.Utilities; | ||
| using Analyzer.Utilities.Extensions; | ||
| using Analyzer.Utilities.PooledObjects; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
| using Resx = Microsoft.NetCore.Analyzers.MicrosoftNetCoreAnalyzersResources; | ||
|
|
||
| namespace Microsoft.NetCore.Analyzers.Runtime | ||
| { | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] | ||
| public sealed class SealInternalTypes : DiagnosticAnalyzer | ||
stephentoub marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| internal const string RuleId = "CA1852"; | ||
| internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( | ||
| RuleId, | ||
| Resx.CreateLocalizableResourceString(nameof(Resx.SealInternalTypesTitle)), | ||
| Resx.CreateLocalizableResourceString(nameof(Resx.SealInternalTypesMessage)), | ||
| DiagnosticCategory.Performance, | ||
| RuleLevel.IdeHidden_BulkConfigurable, | ||
stephentoub marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| Resx.CreateLocalizableResourceString(nameof(Resx.SealInternalTypesDescription)), | ||
| isPortedFxCopRule: false, | ||
| isDataflowRule: false, | ||
| isReportedAtCompilationEnd: true); | ||
|
|
||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.EnableConcurrentExecution(); | ||
| context.RegisterCompilationStartAction(OnCompilationStart); | ||
| } | ||
|
|
||
| private static void OnCompilationStart(CompilationStartAnalysisContext context) | ||
| { | ||
| INamedTypeSymbol? comImportAttributeType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesComImportAttribute); | ||
|
|
||
| var candidateTypes = PooledConcurrentSet<INamedTypeSymbol>.GetInstance(SymbolEqualityComparer.Default); | ||
| var baseTypes = PooledConcurrentSet<INamedTypeSymbol>.GetInstance(SymbolEqualityComparer.Default); | ||
|
|
||
| context.RegisterSymbolAction(context => | ||
| { | ||
| var type = (INamedTypeSymbol)context.Symbol; | ||
|
|
||
| if (type.TypeKind is TypeKind.Class && | ||
| !type.IsAbstract && | ||
| !type.IsStatic && | ||
| !type.IsSealed && | ||
| !type.IsExternallyVisible() && | ||
| !type.HasAttribute(comImportAttributeType)) | ||
| { | ||
| candidateTypes.Add(type); | ||
| } | ||
|
|
||
| for (INamedTypeSymbol? baseType = type.BaseType; baseType is not null; baseType = baseType.BaseType) | ||
| { | ||
| baseTypes.Add(baseType.OriginalDefinition); | ||
| } | ||
|
|
||
| }, SymbolKind.NamedType); | ||
|
|
||
| context.RegisterCompilationEndAction(context => | ||
| { | ||
| foreach (INamedTypeSymbol type in candidateTypes) | ||
| { | ||
| if (!baseTypes.Contains(type.OriginalDefinition)) | ||
| { | ||
| context.ReportDiagnostic(type.CreateDiagnostic(Rule, type.Name)); | ||
| } | ||
| } | ||
|
|
||
| candidateTypes.Dispose(); | ||
| baseTypes.Dispose(); | ||
| }); | ||
| } | ||
| } | ||
| } | ||
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
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
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.