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