]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_lint/src/for_loops_over_fallibles.rs
New upstream version 1.69.0+dfsg1
[rustc.git] / compiler / rustc_lint / src / for_loops_over_fallibles.rs
CommitLineData
9c376795
FG
1use crate::{
2 lints::{
3 ForLoopsOverFalliblesDiag, ForLoopsOverFalliblesLoopSub, ForLoopsOverFalliblesQuestionMark,
4 ForLoopsOverFalliblesSuggestion,
5 },
6 LateContext, LateLintPass, LintContext,
7};
2b03887a
FG
8
9use hir::{Expr, Pat};
2b03887a 10use rustc_hir as hir;
2b03887a
FG
11use rustc_infer::{infer::TyCtxtInferExt, traits::ObligationCause};
12use rustc_middle::ty::{self, List};
13use rustc_span::{sym, Span};
2b03887a
FG
14
15declare_lint! {
16 /// The `for_loops_over_fallibles` lint checks for `for` loops over `Option` or `Result` values.
17 ///
18 /// ### Example
19 ///
20 /// ```rust
21 /// let opt = Some(1);
22 /// for x in opt { /* ... */}
23 /// ```
24 ///
25 /// {{produces}}
26 ///
27 /// ### Explanation
28 ///
29 /// Both `Option` and `Result` implement `IntoIterator` trait, which allows using them in a `for` loop.
30 /// `for` loop over `Option` or `Result` will iterate either 0 (if the value is `None`/`Err(_)`)
31 /// or 1 time (if the value is `Some(_)`/`Ok(_)`). This is not very useful and is more clearly expressed
32 /// via `if let`.
33 ///
34 /// `for` loop can also be accidentally written with the intention to call a function multiple times,
35 /// while the function returns `Some(_)`, in these cases `while let` loop should be used instead.
36 ///
37 /// The "intended" use of `IntoIterator` implementations for `Option` and `Result` is passing them to
38 /// generic code that expects something implementing `IntoIterator`. For example using `.chain(option)`
39 /// to optionally add a value to an iterator.
40 pub FOR_LOOPS_OVER_FALLIBLES,
41 Warn,
42 "for-looping over an `Option` or a `Result`, which is more clearly expressed as an `if let`"
43}
44
45declare_lint_pass!(ForLoopsOverFallibles => [FOR_LOOPS_OVER_FALLIBLES]);
46
47impl<'tcx> LateLintPass<'tcx> for ForLoopsOverFallibles {
48 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
49 let Some((pat, arg)) = extract_for_loop(expr) else { return };
50
51 let ty = cx.typeck_results().expr_ty(arg);
52
53 let &ty::Adt(adt, substs) = ty.kind() else { return };
54
55 let (article, ty, var) = match adt.did() {
56 did if cx.tcx.is_diagnostic_item(sym::Option, did) => ("an", "Option", "Some"),
57 did if cx.tcx.is_diagnostic_item(sym::Result, did) => ("a", "Result", "Ok"),
58 _ => return,
59 };
60
9c376795 61 let sub = if let Some(recv) = extract_iterator_next_call(cx, arg)
2b03887a
FG
62 && let Ok(recv_snip) = cx.sess().source_map().span_to_snippet(recv.span)
63 {
9c376795 64 ForLoopsOverFalliblesLoopSub::RemoveNext { suggestion: recv.span.between(arg.span.shrink_to_hi()), recv_snip }
2b03887a 65 } else {
9c376795
FG
66 ForLoopsOverFalliblesLoopSub::UseWhileLet { start_span: expr.span.with_hi(pat.span.lo()), end_span: pat.span.between(arg.span), var }
67 } ;
9ffffee4
FG
68 let question_mark = suggest_question_mark(cx, adt, substs, expr.span)
69 .then(|| ForLoopsOverFalliblesQuestionMark { suggestion: arg.span.shrink_to_hi() });
9c376795
FG
70 let suggestion = ForLoopsOverFalliblesSuggestion {
71 var,
72 start_span: expr.span.with_hi(pat.span.lo()),
73 end_span: pat.span.between(arg.span),
74 };
2b03887a 75
9c376795
FG
76 cx.emit_spanned_lint(
77 FOR_LOOPS_OVER_FALLIBLES,
78 arg.span,
79 ForLoopsOverFalliblesDiag { article, ty, sub, question_mark, suggestion },
80 );
2b03887a
FG
81 }
82}
83
84fn extract_for_loop<'tcx>(expr: &Expr<'tcx>) -> Option<(&'tcx Pat<'tcx>, &'tcx Expr<'tcx>)> {
85 if let hir::ExprKind::DropTemps(e) = expr.kind
86 && let hir::ExprKind::Match(iterexpr, [arm], hir::MatchSource::ForLoopDesugar) = e.kind
87 && let hir::ExprKind::Call(_, [arg]) = iterexpr.kind
88 && let hir::ExprKind::Loop(block, ..) = arm.body.kind
89 && let [stmt] = block.stmts
90 && let hir::StmtKind::Expr(e) = stmt.kind
91 && let hir::ExprKind::Match(_, [_, some_arm], _) = e.kind
92 && let hir::PatKind::Struct(_, [field], _) = some_arm.pat.kind
93 {
94 Some((field.pat, arg))
95 } else {
96 None
97 }
98}
99
100fn extract_iterator_next_call<'tcx>(
101 cx: &LateContext<'_>,
102 expr: &Expr<'tcx>,
103) -> Option<&'tcx Expr<'tcx>> {
104 // This won't work for `Iterator::next(iter)`, is this an issue?
105 if let hir::ExprKind::MethodCall(_, recv, _, _) = expr.kind
106 && cx.typeck_results().type_dependent_def_id(expr.hir_id) == cx.tcx.lang_items().next_fn()
107 {
108 Some(recv)
109 } else {
110 return None
111 }
112}
113
114fn suggest_question_mark<'tcx>(
115 cx: &LateContext<'tcx>,
116 adt: ty::AdtDef<'tcx>,
117 substs: &List<ty::GenericArg<'tcx>>,
118 span: Span,
119) -> bool {
120 let Some(body_id) = cx.enclosing_body else { return false };
121 let Some(into_iterator_did) = cx.tcx.get_diagnostic_item(sym::IntoIterator) else { return false };
122
123 if !cx.tcx.is_diagnostic_item(sym::Result, adt.did()) {
124 return false;
125 }
126
127 // Check that the function/closure/constant we are in has a `Result` type.
128 // Otherwise suggesting using `?` may not be a good idea.
129 {
130 let ty = cx.typeck_results().expr_ty(&cx.tcx.hir().body(body_id).value);
131 let ty::Adt(ret_adt, ..) = ty.kind() else { return false };
132 if !cx.tcx.is_diagnostic_item(sym::Result, ret_adt.did()) {
133 return false;
134 }
135 }
136
137 let ty = substs.type_at(0);
138 let infcx = cx.tcx.infer_ctxt().build();
9ffffee4 139 let body_def_id = cx.tcx.hir().body_owner_def_id(body_id);
2b03887a
FG
140 let cause = ObligationCause::new(
141 span,
9ffffee4 142 body_def_id,
2b03887a
FG
143 rustc_infer::traits::ObligationCauseCode::MiscObligation,
144 );
487cf647 145 let errors = rustc_trait_selection::traits::fully_solve_bound(
2b03887a 146 &infcx,
487cf647 147 cause,
2b03887a
FG
148 ty::ParamEnv::empty(),
149 // Erase any region vids from the type, which may not be resolved
150 infcx.tcx.erase_regions(ty),
151 into_iterator_did,
2b03887a
FG
152 );
153
2b03887a
FG
154 errors.is_empty()
155}