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