Skip to content

Commit

Permalink
Simplify AvoidUsingRedundantElseAnalyzer (#763)
Browse files Browse the repository at this point in the history
* Simplify AvoidUsingRedundantElseAnalyzer

Several years ago, an issue was reported (dotnet/roslyn#42447) and bypassed in the AvoidUsingRedundantElseAnalyzer code. It appears that issue has been resolved (dotnet/roslyn#42447 (comment)), which now allows us to simplify the code a bit.
  • Loading branch information
louis-z authored Oct 24, 2024
1 parent 4812886 commit 7854071
Showing 1 changed file with 1 addition and 25 deletions.
26 changes: 1 addition & 25 deletions src/Meziantou.Analyzer/Rules/AvoidUsingRedundantElseAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -91,28 +91,4 @@ private static IEnumerable<string> FindLocalIdentifiersIn(SyntaxNode node)
}
}
}

/// <summary>
/// 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.
/// </summary>
/// <param name="ifStatementSyntax">The 'if' statement whose 'else' is currently under scrutiny</param>
/// <param name="exitPoint">A reachable exit point detected by the semantic model</param>
/// <returns>true if the exit point is directly accessible, false otherwise</returns>
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;
}
}

0 comments on commit 7854071

Please sign in to comment.