runWithReporter method
Override this method to implement your lint rule.
Use context to register callbacks for AST node types:
context.addMethodInvocation((node) {
if (condition) {
reporter.atNode(node);
}
});
Implementation
@override
void runWithReporter(
SaropaDiagnosticReporter reporter,
SaropaContext context,
) {
context.addSwitchPatternCase((SwitchPatternCase node) {
// Check if the case body is just an if statement (possibly in a block)
final List<Statement> statements = node.statements;
if (statements.isEmpty) return;
Statement? firstStatement;
if (statements.length == 1) {
firstStatement = statements.first;
} else if (statements.length == 2 && statements[1] is BreakStatement) {
// Allow if + break pattern
firstStatement = statements.first;
}
if (firstStatement == null) return;
// Check if it's an if statement or a block with just an if
IfStatement? ifStmt;
if (firstStatement is IfStatement) {
ifStmt = firstStatement;
} else if (firstStatement is Block &&
firstStatement.statements.length == 1) {
final Statement inner = firstStatement.statements.first;
if (inner is IfStatement) {
ifStmt = inner;
}
}
if (ifStmt == null) return;
// Check that the if statement doesn't already have a when guard on the case
if (node.guardedPattern.whenClause != null) return;
// Check that the if has no else branch (simpler to convert)
if (ifStmt.elseStatement != null) return;
// The if condition could be moved to a when guard
reporter.atNode(ifStmt);
});
// Note: Traditional SwitchCase (`case 1:`) does NOT support when guards.
// Only SwitchPatternCase (`case int n:`, `case Circle():`) supports when.
// We intentionally do not flag traditional SwitchCase.
}