]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/lints.rs
b21ca6028a221510c20d5a2be8f4bb4507996ef7
[rust.git] / compiler / rustc_mir_build / src / lints.rs
1 use rustc_data_structures::graph::iterate::{
2     NodeStatus, TriColorDepthFirstSearch, TriColorVisitor,
3 };
4 use rustc_hir::intravisit::FnKind;
5 use rustc_middle::mir::{BasicBlock, Body, Operand, TerminatorKind};
6 use rustc_middle::ty::subst::{GenericArg, InternalSubsts};
7 use rustc_middle::ty::{self, AssocItem, AssocItemContainer, Instance, TyCtxt};
8 use rustc_session::lint::builtin::UNCONDITIONAL_RECURSION;
9 use rustc_span::Span;
10 use std::ops::ControlFlow;
11
12 crate fn check<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
13     let def_id = body.source.def_id().expect_local();
14
15     if let Some(fn_kind) = tcx.hir().get_by_def_id(def_id).fn_kind() {
16         if let FnKind::Closure = fn_kind {
17             // closures can't recur, so they don't matter.
18             return;
19         }
20
21         // If this is trait/impl method, extract the trait's substs.
22         let trait_substs = match tcx.opt_associated_item(def_id.to_def_id()) {
23             Some(AssocItem {
24                 container: AssocItemContainer::TraitContainer(trait_def_id), ..
25             }) => {
26                 let trait_substs_count = tcx.generics_of(*trait_def_id).count();
27                 &InternalSubsts::identity_for_item(tcx, def_id.to_def_id())[..trait_substs_count]
28             }
29             _ => &[],
30         };
31
32         let mut vis = Search { tcx, body, reachable_recursive_calls: vec![], trait_substs };
33         if let Some(NonRecursive) = TriColorDepthFirstSearch::new(&body).run_from_start(&mut vis) {
34             return;
35         }
36         if vis.reachable_recursive_calls.is_empty() {
37             return;
38         }
39
40         vis.reachable_recursive_calls.sort();
41
42         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
43         let sp = tcx.sess.source_map().guess_head_span(tcx.hir().span_with_body(hir_id));
44         tcx.struct_span_lint_hir(UNCONDITIONAL_RECURSION, hir_id, sp, |lint| {
45             let mut db = lint.build("function cannot return without recursing");
46             db.span_label(sp, "cannot return without recursing");
47             // offer some help to the programmer.
48             for call_span in vis.reachable_recursive_calls {
49                 db.span_label(call_span, "recursive call site");
50             }
51             db.help("a `loop` may express intention better if this is on purpose");
52             db.emit();
53         });
54     }
55 }
56
57 struct NonRecursive;
58
59 struct Search<'mir, 'tcx> {
60     tcx: TyCtxt<'tcx>,
61     body: &'mir Body<'tcx>,
62     trait_substs: &'tcx [GenericArg<'tcx>],
63
64     reachable_recursive_calls: Vec<Span>,
65 }
66
67 impl<'mir, 'tcx> Search<'mir, 'tcx> {
68     /// Returns `true` if `func` refers to the function we are searching in.
69     fn is_recursive_call(&self, func: &Operand<'tcx>) -> bool {
70         let Search { tcx, body, trait_substs, .. } = *self;
71         let caller = body.source.def_id();
72         let param_env = tcx.param_env(caller);
73
74         let func_ty = func.ty(body, tcx);
75         if let ty::FnDef(callee, substs) = *func_ty.kind() {
76             let normalized_substs = tcx.normalize_erasing_regions(param_env, substs);
77             let (callee, call_substs) = if let Ok(Some(instance)) =
78                 Instance::resolve(tcx, param_env, callee, normalized_substs)
79             {
80                 (instance.def_id(), instance.substs)
81             } else {
82                 (callee, normalized_substs)
83             };
84
85             // FIXME(#57965): Make this work across function boundaries
86
87             // If this is a trait fn, the substs on the trait have to match, or we might be
88             // calling into an entirely different method (for example, a call from the default
89             // method in the trait to `<A as Trait<B>>::method`, where `A` and/or `B` are
90             // specific types).
91             return callee == caller && &call_substs[..trait_substs.len()] == trait_substs;
92         }
93
94         false
95     }
96 }
97
98 impl<'mir, 'tcx> TriColorVisitor<&'mir Body<'tcx>> for Search<'mir, 'tcx> {
99     type BreakVal = NonRecursive;
100
101     fn node_examined(
102         &mut self,
103         bb: BasicBlock,
104         prior_status: Option<NodeStatus>,
105     ) -> ControlFlow<Self::BreakVal> {
106         // Back-edge in the CFG (loop).
107         if let Some(NodeStatus::Visited) = prior_status {
108             return ControlFlow::Break(NonRecursive);
109         }
110
111         match self.body[bb].terminator().kind {
112             // These terminators return control flow to the caller.
113             TerminatorKind::Abort
114             | TerminatorKind::GeneratorDrop
115             | TerminatorKind::Resume
116             | TerminatorKind::Return
117             | TerminatorKind::Unreachable
118             | TerminatorKind::Yield { .. } => ControlFlow::Break(NonRecursive),
119
120             // A diverging InlineAsm is treated as non-recursing
121             TerminatorKind::InlineAsm { destination, .. } => {
122                 if destination.is_some() {
123                     ControlFlow::CONTINUE
124                 } else {
125                     ControlFlow::Break(NonRecursive)
126                 }
127             }
128
129             // These do not.
130             TerminatorKind::Assert { .. }
131             | TerminatorKind::Call { .. }
132             | TerminatorKind::Drop { .. }
133             | TerminatorKind::DropAndReplace { .. }
134             | TerminatorKind::FalseEdge { .. }
135             | TerminatorKind::FalseUnwind { .. }
136             | TerminatorKind::Goto { .. }
137             | TerminatorKind::SwitchInt { .. } => ControlFlow::CONTINUE,
138         }
139     }
140
141     fn node_settled(&mut self, bb: BasicBlock) -> ControlFlow<Self::BreakVal> {
142         // When we examine a node for the last time, remember it if it is a recursive call.
143         let terminator = self.body[bb].terminator();
144         if let TerminatorKind::Call { func, .. } = &terminator.kind {
145             if self.is_recursive_call(func) {
146                 self.reachable_recursive_calls.push(terminator.source_info.span);
147             }
148         }
149
150         ControlFlow::CONTINUE
151     }
152
153     fn ignore_edge(&mut self, bb: BasicBlock, target: BasicBlock) -> bool {
154         let terminator = self.body[bb].terminator();
155         if terminator.unwind() == Some(&Some(target)) && terminator.successors().count() > 1 {
156             return true;
157         }
158         // Don't traverse successors of recursive calls or false CFG edges.
159         match self.body[bb].terminator().kind {
160             TerminatorKind::Call { ref func, .. } => self.is_recursive_call(func),
161             TerminatorKind::FalseEdge { imaginary_target, .. } => imaginary_target == target,
162             _ => false,
163         }
164     }
165 }