refactor(linter): Let fixer functions decide whether to apply a fix or not #4187
Closed
Description
Rules that have fixers for some cases, but not others, all have some logic that looks like this:
fn run<'a>(&self, ctx: &LintContext<'a>) {
// Check for a violation
let diagnostic = create_diagnostic_for_rule();
let can_fix = check_if_fixable(); // <-- this is problematic
if can_fix {
ctx.diagnostic_with_fix(diagnostic, |fixer| do_fix(ctx, fixer, node));
} else {
ctx.diagnostic(diagnostic);
}
}
This pushes a lot of fixing logic outside of the fixer. In cases where --fix
is not used, these are all wasted cycles. If we move fixability checks to inside the fixer's closure, we can prevent rules from doing work that just gets thrown away.
fn run<'a>(&self, ctx: &LintContext<'a>) {
// Check for a violation
let diagnostic = create_diagnostic_for_rule();
ctx.diagnostic_with_fix(diagnostic, |fixer| {
if !check_if_fixable(ctx, fixer, node) {
return None;
}
return do_fix(ctx, fixer, node);
});
}