11using System ;
22using System . Collections . Immutable ;
3- using System . Linq ;
4- using CSharpGuidelinesAnalyzer . Extensions ;
53using JetBrains . Annotations ;
64using Microsoft . CodeAnalysis ;
5+ using Microsoft . CodeAnalysis . CSharp ;
6+ using Microsoft . CodeAnalysis . CSharp . Syntax ;
77using Microsoft . CodeAnalysis . Diagnostics ;
8- using Microsoft . CodeAnalysis . Operations ;
98
109namespace CSharpGuidelinesAnalyzer . Rules . Maintainability
1110{
@@ -29,39 +28,35 @@ public sealed class ClauseInSwitchStatementShouldHaveBlockAnalyzer : DiagnosticA
2928 public override ImmutableArray < DiagnosticDescriptor > SupportedDiagnostics => ImmutableArray . Create ( Rule ) ;
3029
3130 [ NotNull ]
32- private static readonly Action < OperationAnalysisContext > AnalyzeSwitchCaseAction =
33- context => context . SkipInvalid ( AnalyzeSwitchCase ) ;
31+ private static readonly Action < SyntaxNodeAnalysisContext > AnalyzeSwitchSectionAction = AnalyzeSwitchSection ;
3432
3533 public override void Initialize ( [ NotNull ] AnalysisContext context )
3634 {
3735 context . EnableConcurrentExecution ( ) ;
3836 context . ConfigureGeneratedCodeAnalysis ( GeneratedCodeAnalysisFlags . None ) ;
3937
40- context . RegisterOperationAction ( AnalyzeSwitchCaseAction , OperationKind . SwitchCase ) ;
38+ context . RegisterSyntaxNodeAction ( AnalyzeSwitchSectionAction , SyntaxKind . SwitchSection ) ;
4139 }
4240
43- private static void AnalyzeSwitchCase ( OperationAnalysisContext context )
41+ private static void AnalyzeSwitchSection ( SyntaxNodeAnalysisContext context )
4442 {
45- var switchCase = ( ISwitchCaseOperation ) context . Operation ;
43+ var switchSection = ( SwitchSectionSyntax ) context . Node ;
4644
47- if ( switchCase . Body . Length > 0 )
45+ if ( switchSection . Statements . Count > 0 && ! SectionHasBlock ( switchSection ) )
4846 {
49- if ( ! ( switchCase . Body [ 0 ] is IBlockOperation ) )
50- {
51- ReportAtLastClause ( switchCase , context ) ;
52- }
47+ ReportAtLastLabel ( switchSection , context ) ;
5348 }
5449 }
5550
56- private static void ReportAtLastClause ( [ NotNull ] ISwitchCaseOperation switchCase , OperationAnalysisContext context )
51+ private static bool SectionHasBlock ( [ NotNull ] SwitchSectionSyntax switchSection )
5752 {
58- ICaseClauseOperation lastClause = switchCase . Clauses . Last ( ) ;
53+ return switchSection . Statements [ 0 ] is BlockSyntax ;
54+ }
5955
60- Location location = lastClause . TryGetLocationForKeyword ( ) ;
61- if ( location != null )
62- {
63- context . ReportDiagnostic ( Diagnostic . Create ( Rule , location ) ) ;
64- }
56+ private static void ReportAtLastLabel ( [ NotNull ] SwitchSectionSyntax switchSection , SyntaxNodeAnalysisContext context )
57+ {
58+ SwitchLabelSyntax lastLabel = switchSection . Labels . Last ( ) ;
59+ context . ReportDiagnostic ( Diagnostic . Create ( Rule , lastLabel . Keyword . GetLocation ( ) ) ) ;
6560 }
6661 }
6762}
0 commit comments