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