From 23d7cee3332aeae4f81efece31548f5e7bedd932 Mon Sep 17 00:00:00 2001 From: Louis Zanella Date: Wed, 23 Oct 2024 18:14:09 -0400 Subject: [PATCH] Simplify AvoidUsingRedundantElseAnalyzer Several years ago, an issue was reported (https://github.com/dotnet/roslyn/issues/42447) and bypassed in the AvoidUsingRedundantElseAnalyzer code. It appears that issue has been resolved (https://github.com/dotnet/roslyn/issues/42447#issuecomment-2431773920), which now allows us to simplify the code a bit. --- .../Rules/AvoidUsingRedundantElseAnalyzer.cs | 28 ++----------------- 1 file changed, 2 insertions(+), 26 deletions(-) diff --git a/src/Meziantou.Analyzer/Rules/AvoidUsingRedundantElseAnalyzer.cs b/src/Meziantou.Analyzer/Rules/AvoidUsingRedundantElseAnalyzer.cs index 09339d6f8..f7f22dab6 100644 --- a/src/Meziantou.Analyzer/Rules/AvoidUsingRedundantElseAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/AvoidUsingRedundantElseAnalyzer.cs @@ -21,7 +21,7 @@ public sealed partial class AvoidUsingRedundantElseAnalyzer : DiagnosticAnalyzer description: "The 'if' block contains a jump statement (break, continue, goto, return, throw, yield break). Using 'else' is redundant and needlessly maintains a higher nesting level.", helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.AvoidUsingRedundantElse)); - public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); + public override ImmutableArray SupportedDiagnostics => [Rule]; public override void Initialize(AnalysisContext context) { @@ -65,7 +65,7 @@ private static void AnalyzeElseClause(SyntaxNodeAnalysisContext context) if (controlFlowAnalysis is null || !controlFlowAnalysis.Succeeded) return; - if (!controlFlowAnalysis.EndPointIsReachable || controlFlowAnalysis.ExitPoints.Any(ep => IsDirectAccess(ifStatement, ep))) + if (!controlFlowAnalysis.EndPointIsReachable) { context.ReportDiagnostic(Rule, elseClause.ElseKeyword); } @@ -91,28 +91,4 @@ private static IEnumerable FindLocalIdentifiersIn(SyntaxNode node) } } } - - /// - /// Determines if a given 'if' statement's access to an exit point is straightforward. - /// For instance, access to an exit point in a nested 'if' would not be considered straightforward. - /// - /// The 'if' statement whose 'else' is currently under scrutiny - /// A reachable exit point detected by the semantic model - /// true if the exit point is directly accessible, false otherwise - private static bool IsDirectAccess(IfStatementSyntax ifStatementSyntax, SyntaxNode exitPoint) - { - var node = exitPoint.Parent; - while (node is not null) - { - if (node == ifStatementSyntax) - return true; - - if (!node.IsKind(SyntaxKind.Block)) - break; - - node = node.Parent; - } - - return false; - } }