]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/qualify_min_const_fn.rs
Rollup merge of #75377 - canova:map_debug_impl, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / utils / qualify_min_const_fn.rs
1 use rustc_hir as hir;
2 use rustc_hir::def_id::DefId;
3 use rustc_middle::mir::*;
4 use rustc_middle::ty::subst::GenericArgKind;
5 use rustc_middle::ty::{self, adjustment::PointerCast, Ty, TyCtxt};
6 use rustc_span::symbol::{sym};
7 use rustc_span::Span;
8 use rustc_target::spec::abi::Abi::RustIntrinsic;
9 use std::borrow::Cow;
10
11 type McfResult = Result<(), (Span, Cow<'static, str>)>;
12
13 pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>) -> McfResult {
14     let mut current = def_id;
15     loop {
16         let predicates = tcx.predicates_of(current);
17         for (predicate, _) in predicates.predicates {
18             match predicate.skip_binders() {
19                 ty::PredicateAtom::RegionOutlives(_)
20                 | ty::PredicateAtom::TypeOutlives(_)
21                 | ty::PredicateAtom::WellFormed(_)
22                 | ty::PredicateAtom::Projection(_)
23                 | ty::PredicateAtom::ConstEvaluatable(..)
24                 | ty::PredicateAtom::ConstEquate(..)
25                 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => continue,
26                 ty::PredicateAtom::ObjectSafe(_) => {
27                     panic!("object safe predicate on function: {:#?}", predicate)
28                 }
29                 ty::PredicateAtom::ClosureKind(..) => {
30                     panic!("closure kind predicate on function: {:#?}", predicate)
31                 }
32                 ty::PredicateAtom::Subtype(_) => {
33                     panic!("subtype predicate on function: {:#?}", predicate)
34                 }
35                 ty::PredicateAtom::Trait(pred, _) => {
36                     if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
37                         continue;
38                     }
39                     match pred.self_ty().kind() {
40                         ty::Param(ref p) => {
41                             let generics = tcx.generics_of(current);
42                             let def = generics.type_param(p, tcx);
43                             let span = tcx.def_span(def.def_id);
44                             return Err((
45                                 span,
46                                 "trait bounds other than `Sized` \
47                                  on const fn parameters are unstable"
48                                     .into(),
49                             ));
50                         }
51                         // other kinds of bounds are either tautologies
52                         // or cause errors in other passes
53                         _ => continue,
54                     }
55                 }
56             }
57         }
58         match predicates.parent {
59             Some(parent) => current = parent,
60             None => break,
61         }
62     }
63
64     for local in &body.local_decls {
65         check_ty(tcx, local.ty, local.source_info.span)?;
66     }
67     // impl trait is gone in MIR, so check the return type manually
68     check_ty(
69         tcx,
70         tcx.fn_sig(def_id).output().skip_binder(),
71         body.local_decls.iter().next().unwrap().source_info.span,
72     )?;
73
74     for bb in body.basic_blocks() {
75         check_terminator(tcx, body, bb.terminator())?;
76         for stmt in &bb.statements {
77             check_statement(tcx, body, def_id, stmt)?;
78         }
79     }
80     Ok(())
81 }
82
83 fn check_ty(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) -> McfResult {
84     for arg in ty.walk() {
85         let ty = match arg.unpack() {
86             GenericArgKind::Type(ty) => ty,
87
88             // No constraints on lifetimes or constants, except potentially
89             // constants' types, but `walk` will get to them as well.
90             GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
91         };
92
93         match ty.kind() {
94             ty::Ref(_, _, hir::Mutability::Mut) => {
95                     return Err((span, "mutable references in const fn are unstable".into()));
96             }
97             ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
98             ty::FnPtr(..) => {
99                     return Err((span, "function pointers in const fn are unstable".into()));
100             }
101             ty::Dynamic(preds, _) => {
102                 for pred in preds.iter() {
103                     match pred.skip_binder() {
104                         ty::ExistentialPredicate::AutoTrait(_)
105                         | ty::ExistentialPredicate::Projection(_) => {
106                             return Err((
107                                 span,
108                                 "trait bounds other than `Sized` \
109                                  on const fn parameters are unstable"
110                                     .into(),
111                             ));
112                         }
113                         ty::ExistentialPredicate::Trait(trait_ref) => {
114                             if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
115                                 return Err((
116                                     span,
117                                     "trait bounds other than `Sized` \
118                                      on const fn parameters are unstable"
119                                         .into(),
120                                 ));
121                             }
122                         }
123                     }
124                 }
125             }
126             _ => {}
127         }
128     }
129     Ok(())
130 }
131
132 fn check_rvalue(
133     tcx: TyCtxt<'tcx>,
134     body: &Body<'tcx>,
135     def_id: DefId,
136     rvalue: &Rvalue<'tcx>,
137     span: Span,
138 ) -> McfResult {
139     match rvalue {
140         Rvalue::ThreadLocalRef(_) => {
141             Err((span, "cannot access thread local storage in const fn".into()))
142         }
143         Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
144             check_operand(tcx, operand, span, body)
145         }
146         Rvalue::Len(place)
147         | Rvalue::Discriminant(place)
148         | Rvalue::Ref(_, _, place)
149         | Rvalue::AddressOf(_, place) => check_place(tcx, *place, span,  body),
150         Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
151             use rustc_middle::ty::cast::CastTy;
152             let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
153             let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
154             match (cast_in, cast_out) {
155                 (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
156                     Err((span, "casting pointers to ints is unstable in const fn".into()))
157                 }
158                 _ => check_operand(tcx, operand, span, body),
159             }
160         }
161         Rvalue::Cast(
162             CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer),
163             operand,
164             _,
165         ) => check_operand(tcx, operand, span, body),
166         Rvalue::Cast(
167             CastKind::Pointer(
168                 PointerCast::UnsafeFnPointer
169                 | PointerCast::ClosureFnPointer(_)
170                 | PointerCast::ReifyFnPointer,
171             ),
172             _,
173             _,
174         ) => Err((span, "function pointer casts are not allowed in const fn".into())),
175         Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), op, cast_ty) => {
176             let pointee_ty = if let Some(deref_ty) = cast_ty.builtin_deref(true) {
177                 deref_ty.ty
178             } else {
179                 // We cannot allow this for now.
180                 return Err((
181                     span,
182                     "unsizing casts are only allowed for references right now".into(),
183                 ));
184             };
185             let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id));
186             if let ty::Slice(_) | ty::Str = unsized_ty.kind() {
187                 check_operand(tcx, op, span, body)?;
188                 // Casting/coercing things to slices is fine.
189                 Ok(())
190             } else {
191                 // We just can't allow trait objects until we have figured out trait method calls.
192                 Err((span, "unsizing casts are not allowed in const fn".into()))
193             }
194         }
195         // binops are fine on integers
196         Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
197             check_operand(tcx, lhs, span, body)?;
198             check_operand(tcx, rhs, span, body)?;
199             let ty = lhs.ty(body, tcx);
200             if ty.is_integral() || ty.is_bool() || ty.is_char() {
201                 Ok(())
202             } else {
203                 Err((span, "only int, `bool` and `char` operations are stable in const fn".into()))
204             }
205         }
206         Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
207         Rvalue::NullaryOp(NullOp::Box, _) => {
208             Err((span, "heap allocations are not allowed in const fn".into()))
209         }
210         Rvalue::UnaryOp(_, operand) => {
211             let ty = operand.ty(body, tcx);
212             if ty.is_integral() || ty.is_bool() {
213                 check_operand(tcx, operand, span, body)
214             } else {
215                 Err((span, "only int and `bool` operations are stable in const fn".into()))
216             }
217         }
218         Rvalue::Aggregate(_, operands) => {
219             for operand in operands {
220                 check_operand(tcx, operand, span, body)?;
221             }
222             Ok(())
223         }
224     }
225 }
226
227 fn check_statement(
228     tcx: TyCtxt<'tcx>,
229     body: &Body<'tcx>,
230     def_id: DefId,
231     statement: &Statement<'tcx>,
232 ) -> McfResult {
233     let span = statement.source_info.span;
234     match &statement.kind {
235         StatementKind::Assign(box (place, rval)) => {
236             check_place(tcx, *place, span,  body)?;
237             check_rvalue(tcx, body, def_id, rval, span)
238         }
239
240         StatementKind::FakeRead(_, place) => check_place(tcx, **place, span, body),
241
242         // just an assignment
243         StatementKind::SetDiscriminant { place, .. } => {
244             check_place(tcx, **place, span,  body)
245         }
246
247         StatementKind::LlvmInlineAsm { .. } => {
248             Err((span, "cannot use inline assembly in const fn".into()))
249         }
250
251         // These are all NOPs
252         StatementKind::StorageLive(_)
253         | StatementKind::StorageDead(_)
254         | StatementKind::Retag { .. }
255         | StatementKind::AscribeUserType(..)
256         | StatementKind::Coverage(..)
257         | StatementKind::Nop => Ok(()),
258     }
259 }
260
261 fn check_operand(
262     tcx: TyCtxt<'tcx>,
263     operand: &Operand<'tcx>,
264     span: Span,
265     body: &Body<'tcx>,
266 ) -> McfResult {
267     match operand {
268         Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, body),
269         Operand::Constant(c) => match c.check_static_ptr(tcx) {
270             Some(_) => Err((span, "cannot access `static` items in const fn".into())),
271             None => Ok(()),
272         },
273     }
274 }
275
276 fn check_place(
277     tcx: TyCtxt<'tcx>,
278     place: Place<'tcx>,
279     span: Span,
280     body: &Body<'tcx>,
281 ) -> McfResult {
282     let mut cursor = place.projection.as_ref();
283     while let &[ref proj_base @ .., elem] = cursor {
284         cursor = proj_base;
285         match elem {
286             ProjectionElem::Field(..) => {
287                 let base_ty = Place::ty_from(place.local, &proj_base, body, tcx).ty;
288                 if let Some(def) = base_ty.ty_adt_def() {
289                     // No union field accesses in `const fn`
290                     if def.is_union() {
291                             return Err((span, "accessing union fields is unstable".into()));
292                     }
293                 }
294             }
295             ProjectionElem::ConstantIndex { .. }
296             | ProjectionElem::Downcast(..)
297             | ProjectionElem::Subslice { .. }
298             | ProjectionElem::Deref
299             | ProjectionElem::Index(_) => {}
300         }
301     }
302
303     Ok(())
304 }
305
306 fn check_terminator(
307     tcx: TyCtxt<'tcx>,
308     body: &'a Body<'tcx>,
309     terminator: &Terminator<'tcx>,
310 ) -> McfResult {
311     let span = terminator.source_info.span;
312     match &terminator.kind {
313         TerminatorKind::FalseEdge { .. }
314         | TerminatorKind::FalseUnwind { .. }
315         | TerminatorKind::Goto { .. }
316         | TerminatorKind::Return
317         | TerminatorKind::Resume
318         | TerminatorKind::Unreachable => Ok(()),
319
320         TerminatorKind::Drop { place, .. } => check_place(tcx, *place, span,  body),
321         TerminatorKind::DropAndReplace { place, value, .. } => {
322             check_place(tcx, *place, span,  body)?;
323             check_operand(tcx, value, span, body)
324         }
325
326         TerminatorKind::SwitchInt { discr, switch_ty: _, values: _, targets: _ } => {
327             check_operand(tcx, discr, span, body)
328         }
329
330         TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())),
331         TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
332             Err((span, "const fn generators are unstable".into()))
333         }
334
335         TerminatorKind::Call {
336             func,
337             args,
338             from_hir_call: _,
339             destination: _,
340             cleanup: _,
341             fn_span: _,
342         } => {
343             let fn_ty = func.ty(body, tcx);
344             if let ty::FnDef(fn_def_id, _) = *fn_ty.kind() {
345                 if !rustc_mir::const_eval::is_min_const_fn(tcx, fn_def_id)
346                 {
347                     return Err((
348                         span,
349                         format!(
350                             "can only call other `const fn` within a `const fn`, \
351                              but `{:?}` is not stable as `const fn`",
352                             func,
353                         )
354                         .into(),
355                     ));
356                 }
357
358                 // HACK: This is to "unstabilize" the `transmute` intrinsic
359                 // within const fns. `transmute` is allowed in all other const contexts.
360                 // This won't really scale to more intrinsics or functions. Let's allow const
361                 // transmutes in const fn before we add more hacks to this.
362                 if tcx.fn_sig(fn_def_id).abi() == RustIntrinsic
363                     && tcx.item_name(fn_def_id) == sym::transmute
364                 {
365                     return Err((
366                         span,
367                         "can only call `transmute` from const items, not `const fn`".into(),
368                     ));
369                 }
370
371                 check_operand(tcx, func, span, body)?;
372
373                 for arg in args {
374                     check_operand(tcx, arg, span, body)?;
375                 }
376                 Ok(())
377             } else {
378                 Err((span, "can only call other const fns within const fn".into()))
379             }
380         }
381
382         TerminatorKind::Assert { cond, expected: _, msg: _, target: _, cleanup: _ } => {
383             check_operand(tcx, cond, span, body)
384         }
385
386         TerminatorKind::InlineAsm { .. } => {
387             Err((span, "cannot use inline assembly in const fn".into()))
388         }
389     }
390 }