Skip to content

Commit

Permalink
Simplify AvoidUsingRedundantElseAnalyzer
Browse files Browse the repository at this point in the history
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 committed Oct 23, 2024
1 parent 3b050d1 commit 23d7cee
Showing 1 changed file with 2 additions and 26 deletions.
28 changes: 2 additions & 26 deletions src/Meziantou.Analyzer/Rules/AvoidUsingRedundantElseAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [Rule];

public override void Initialize(AnalysisContext context)
{
Expand Down 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 23d7cee

Please sign in to comment.