-
Notifications
You must be signed in to change notification settings - Fork 22
D2LXXXX: ban default constructor of certain structs #510
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
Open
omsmith
wants to merge
1
commit into
Brightspace:main
Choose a base branch
from
omsmith:omsmith/dont-call-default-struct-constructor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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
70 changes: 0 additions & 70 deletions
70
...CodeStyle.Analyzers/ApiUsage/System.Collections.Immutable/ImmutableCollectionsAnalyzer.cs
This file was deleted.
Oops, something went wrong.
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
59 changes: 59 additions & 0 deletions
59
...deStyle.Analyzers/Language/DefaultStructCreation/DefaultStructCreationAnalyzer.Codefix.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,59 @@ | ||
| using System.Collections.Immutable; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
|
|
||
| namespace D2L.CodeStyle.Analyzers.Language.DefaultStructCreation { | ||
| partial class DefaultStructCreationAnalyzer { | ||
|
|
||
| [ExportCodeFixProvider( | ||
| LanguageNames.CSharp, | ||
| Name = nameof( UseSuggestedInitializerCodefix ) | ||
| )] | ||
| public sealed class UseSuggestedInitializerCodefix : CodeFixProvider { | ||
|
|
||
| public override ImmutableArray<string> FixableDiagnosticIds | ||
| => ImmutableArray.Create( Diagnostics.DontCallDefaultStructConstructor.Id ); | ||
|
|
||
| public override FixAllProvider GetFixAllProvider() | ||
| => WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| public override async Task RegisterCodeFixesAsync( | ||
| CodeFixContext ctx | ||
| ) { | ||
| var root = await ctx.Document | ||
| .GetSyntaxRootAsync( ctx.CancellationToken ) | ||
| .ConfigureAwait( false ); | ||
|
|
||
| foreach( var diagnostic in ctx.Diagnostics ) { | ||
| var span = diagnostic.Location.SourceSpan; | ||
|
|
||
| SyntaxNode syntax = root.FindNode( span, getInnermostNodeForTie: true ); | ||
| if( !( syntax is ObjectCreationExpressionSyntax creationExpression ) ) { | ||
| continue; | ||
| } | ||
|
|
||
| ctx.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title: diagnostic.Properties[ACTION_TITLE_KEY], | ||
| createChangedDocument: ct => { | ||
| SyntaxNode replacement = SyntaxFactory.ParseExpression( | ||
| diagnostic.Properties[REPLACEMENT_KEY] | ||
| ); | ||
|
|
||
| SyntaxNode newRoot = root.ReplaceNode( creationExpression, replacement ); | ||
| Document newDoc = ctx.Document.WithSyntaxRoot( newRoot ); | ||
|
|
||
| return Task.FromResult( newDoc ); | ||
| } | ||
| ), | ||
| diagnostic | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } |
89 changes: 89 additions & 0 deletions
89
src/D2L.CodeStyle.Analyzers/Language/DefaultStructCreation/DefaultStructCreationAnalyzer.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,89 @@ | ||
| using System.Collections.Immutable; | ||
| using D2L.CodeStyle.Analyzers.Language.DefaultStructCreation.Replacements; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
| using Microsoft.CodeAnalysis.Operations; | ||
|
|
||
| namespace D2L.CodeStyle.Analyzers.Language.DefaultStructCreation { | ||
|
|
||
| [DiagnosticAnalyzer( LanguageNames.CSharp )] | ||
| internal sealed partial class DefaultStructCreationAnalyzer : DiagnosticAnalyzer { | ||
|
|
||
| internal const string ACTION_TITLE_KEY = nameof( DefaultStructCreationAnalyzer ) + ".ActionTitle"; | ||
| internal const string REPLACEMENT_KEY = nameof( DefaultStructCreationAnalyzer ) + ".Replacement"; | ||
|
|
||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics | ||
| => ImmutableArray.Create( Diagnostics.DontCallDefaultStructConstructor ); | ||
|
|
||
| public override void Initialize( AnalysisContext context ) { | ||
| context.EnableConcurrentExecution(); | ||
|
|
||
| context.ConfigureGeneratedCodeAnalysis( | ||
| GeneratedCodeAnalysisFlags.None | ||
| ); | ||
|
|
||
| context.RegisterCompilationStartAction( RegisterAnalyzer ); | ||
| } | ||
|
|
||
| private static void RegisterAnalyzer( | ||
| CompilationStartAnalysisContext context | ||
| ) { | ||
| var replacers = ImmutableArray.Create( | ||
| NewGuidBackedIdTypeReplacer.Instance, | ||
| new NewGuidReplacer( context.Compilation ), | ||
| new NewImmutableArrayReplacer( context.Compilation ) | ||
| ); | ||
|
|
||
| context.RegisterOperationAction( | ||
| ctx => AnalyzeObjectCreation( | ||
| context: ctx, | ||
| operation: ctx.Operation as IObjectCreationOperation, | ||
| replacers: replacers | ||
| ), | ||
| OperationKind.ObjectCreation | ||
| ); | ||
| } | ||
|
|
||
| private static void AnalyzeObjectCreation( | ||
omsmith marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| OperationAnalysisContext context, | ||
| IObjectCreationOperation operation, | ||
| ImmutableArray<IDefaultStructCreationReplacer> replacers | ||
| ) { | ||
| if( operation.Type.TypeKind != TypeKind.Struct ) { | ||
| return; | ||
| } | ||
|
|
||
| IMethodSymbol constructor = operation.Constructor; | ||
| if( constructor.Parameters.Length > 0 ) { | ||
| return; | ||
| } | ||
|
|
||
| INamedTypeSymbol structType = operation.Type as INamedTypeSymbol; | ||
|
|
||
| foreach( var replacer in replacers ) { | ||
|
|
||
| if( !replacer.CanReplace( structType ) ) { | ||
| continue; | ||
| } | ||
|
|
||
| var syntax = operation.Syntax as ObjectCreationExpressionSyntax; | ||
| SyntaxNode replacement = replacer | ||
| .GetReplacement( structType, syntax.Type ) | ||
| .WithTriviaFrom( syntax ); | ||
|
|
||
| context.ReportDiagnostic( Diagnostic.Create( | ||
| descriptor: Diagnostics.DontCallDefaultStructConstructor, | ||
| location: operation.Syntax.GetLocation(), | ||
| properties: ImmutableDictionary<string, string> | ||
| .Empty | ||
| .Add( ACTION_TITLE_KEY, replacer.Title ) | ||
| .Add( REPLACEMENT_KEY, replacement.ToFullString() ), | ||
| structType.ToDisplayString( SymbolDisplayFormat.MinimallyQualifiedFormat ) | ||
| ) ); | ||
omsmith marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| break; | ||
| } | ||
| } | ||
| } | ||
| } | ||
20 changes: 20 additions & 0 deletions
20
...e.Analyzers/Language/DefaultStructCreation/Replacements/IDefaultStructCreationReplacer.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,20 @@ | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
|
|
||
| namespace D2L.CodeStyle.Analyzers.Language.DefaultStructCreation.Replacements { | ||
|
|
||
| internal interface IDefaultStructCreationReplacer { | ||
|
|
||
| string Title { get; } | ||
|
|
||
| bool CanReplace( | ||
| INamedTypeSymbol structType | ||
| ); | ||
|
|
||
| SyntaxNode GetReplacement( | ||
| INamedTypeSymbol structType, | ||
| TypeSyntax structName | ||
| ); | ||
|
|
||
| } | ||
| } |
51 changes: 51 additions & 0 deletions
51
...tyle.Analyzers/Language/DefaultStructCreation/Replacements/NewGuidBackedIdTypeReplacer.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,51 @@ | ||
| using System.Collections.Immutable; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
|
|
||
| namespace D2L.CodeStyle.Analyzers.Language.DefaultStructCreation.Replacements { | ||
|
|
||
| internal sealed class NewGuidBackedIdTypeReplacer : IDefaultStructCreationReplacer { | ||
|
|
||
| public static readonly IDefaultStructCreationReplacer Instance = new NewGuidBackedIdTypeReplacer(); | ||
|
|
||
| private NewGuidBackedIdTypeReplacer() { } | ||
|
|
||
| string IDefaultStructCreationReplacer.Title { get; } = "Use GenerateNew()"; | ||
|
|
||
| bool IDefaultStructCreationReplacer.CanReplace( | ||
| INamedTypeSymbol structType | ||
| ) { | ||
| ImmutableArray<ISymbol> maybeGenerateNew = structType.GetMembers( "GenerateNew" ); | ||
| if( maybeGenerateNew.Length != 1 ) { | ||
| return false; | ||
| } | ||
|
|
||
| if( !( maybeGenerateNew[0] is IMethodSymbol generateNew ) ) { | ||
| return false; | ||
| } | ||
|
|
||
| if( generateNew.Parameters.Length != 0 ) { | ||
| return false; | ||
| } | ||
|
|
||
| // Sure seems like one of our Guid-backed IdTypes | ||
| return true; | ||
| } | ||
|
|
||
| SyntaxNode IDefaultStructCreationReplacer.GetReplacement( | ||
| INamedTypeSymbol structType, | ||
| TypeSyntax structName | ||
| ) { | ||
| return SyntaxFactory | ||
| .InvocationExpression( | ||
| SyntaxFactory.MemberAccessExpression( | ||
| SyntaxKind.SimpleMemberAccessExpression, | ||
| structName, | ||
| SyntaxFactory.IdentifierName( "GenerateNew" ) | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| } | ||
| } |
51 changes: 51 additions & 0 deletions
51
src/D2L.CodeStyle.Analyzers/Language/DefaultStructCreation/Replacements/NewGuidReplacer.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,51 @@ | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
|
|
||
| namespace D2L.CodeStyle.Analyzers.Language.DefaultStructCreation.Replacements { | ||
|
|
||
| internal sealed class NewGuidReplacer : IDefaultStructCreationReplacer { | ||
| string IDefaultStructCreationReplacer.Title { get; } = "Use Guid.NewGuid()"; | ||
|
|
||
| private readonly INamedTypeSymbol m_guidType; | ||
|
|
||
| public NewGuidReplacer( | ||
| Compilation compilation | ||
| ) { | ||
| m_guidType = compilation.GetTypeByMetadataName( "System.Guid" ); | ||
| } | ||
|
|
||
| bool IDefaultStructCreationReplacer.CanReplace( | ||
| INamedTypeSymbol structType | ||
| ) { | ||
| if( m_guidType == null ) { | ||
| return false; | ||
| } | ||
|
|
||
| if( m_guidType.TypeKind == TypeKind.Error ) { | ||
| return false; | ||
| } | ||
|
|
||
| if( m_guidType != structType ) { | ||
| return false; | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| SyntaxNode IDefaultStructCreationReplacer.GetReplacement( | ||
| INamedTypeSymbol structType, | ||
| TypeSyntax structName | ||
| ) { | ||
| return SyntaxFactory | ||
| .InvocationExpression( | ||
| SyntaxFactory.MemberAccessExpression( | ||
| SyntaxKind.SimpleMemberAccessExpression, | ||
| structName, | ||
| SyntaxFactory.IdentifierName( "NewGuid" ) | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| } | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Might want to handle
= default( T )at some pointThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
From IRL:
= default( T )is pretty explicit so maybe don't ban it.