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