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