Use structured suggestions for for_loop_over_fallibles
lint
This commit is contained in:
parent
fa380a82a5
commit
d030ba52e2
1 changed files with 14 additions and 8 deletions
|
@ -1,6 +1,7 @@
|
||||||
use crate::{LateContext, LateLintPass, LintContext};
|
use crate::{LateContext, LateLintPass, LintContext};
|
||||||
|
|
||||||
use hir::{Expr, Pat};
|
use hir::{Expr, Pat};
|
||||||
|
use rustc_errors::Applicability;
|
||||||
use rustc_hir as hir;
|
use rustc_hir as hir;
|
||||||
use rustc_middle::ty;
|
use rustc_middle::ty;
|
||||||
use rustc_span::sym;
|
use rustc_span::sym;
|
||||||
|
@ -65,18 +66,24 @@ impl<'tcx> LateLintPass<'tcx> for ForLoopOverFallibles {
|
||||||
_ => return,
|
_ => return,
|
||||||
};
|
};
|
||||||
|
|
||||||
let Ok(pat_snip) = cx.sess().source_map().span_to_snippet(pat.span) else { return };
|
|
||||||
let Ok(arg_snip) = cx.sess().source_map().span_to_snippet(arg.span) else { return };
|
let Ok(arg_snip) = cx.sess().source_map().span_to_snippet(arg.span) else { return };
|
||||||
|
|
||||||
let help_string = format!(
|
|
||||||
"consider replacing `for {pat_snip} in {arg_snip}` with `if let {var}({pat_snip}) = {arg_snip}`"
|
|
||||||
);
|
|
||||||
let msg = format!(
|
let msg = format!(
|
||||||
"for loop over `{arg_snip}`, which is {article} `{ty}`. This is more readably written as an `if let` statement",
|
"for loop over `{arg_snip}`, which is {article} `{ty}`. This is more readably written as an `if let` statement",
|
||||||
);
|
);
|
||||||
|
|
||||||
cx.struct_span_lint(FOR_LOOP_OVER_FALLIBLES, arg.span, |diag| {
|
cx.struct_span_lint(FOR_LOOP_OVER_FALLIBLES, arg.span, |diag| {
|
||||||
diag.build(msg).help(help_string).emit()
|
diag.build(msg)
|
||||||
|
.multipart_suggestion_verbose(
|
||||||
|
"consider using `if let` to clear intent",
|
||||||
|
vec![
|
||||||
|
// NB can't use `until` here because `expr.span` and `pat.span` have different syntax contexts
|
||||||
|
(expr.span.with_hi(pat.span.lo()), format!("if let {var}(")),
|
||||||
|
(pat.span.between(arg.span), format!(") = ")),
|
||||||
|
],
|
||||||
|
Applicability::MachineApplicable,
|
||||||
|
)
|
||||||
|
.emit()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -95,5 +102,4 @@ fn extract_for_loop<'tcx>(expr: &Expr<'tcx>) -> Option<(&'tcx Pat<'tcx>, &'tcx E
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
Loading…
Add table
Add a link
Reference in a new issue