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