]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/qualify_min_const_fn.rs
Merge remote-tracking branch 'upstream/master' into rustup
[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, .. } | StatementKind::Deinit(place) => {
215             check_place(tcx, **place, span, body)
216         },
217
218         StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping { dst, src, count }) => {
219             check_operand(tcx, dst, span, body)?;
220             check_operand(tcx, src, span, body)?;
221             check_operand(tcx, count, span, body)
222         },
223         // These are all NOPs
224         StatementKind::StorageLive(_)
225         | StatementKind::StorageDead(_)
226         | StatementKind::Retag { .. }
227         | StatementKind::AscribeUserType(..)
228         | StatementKind::Coverage(..)
229         | StatementKind::Nop => Ok(()),
230     }
231 }
232
233 fn check_operand<'tcx>(tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult {
234     match operand {
235         Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, body),
236         Operand::Constant(c) => match c.check_static_ptr(tcx) {
237             Some(_) => Err((span, "cannot access `static` items in const fn".into())),
238             None => Ok(()),
239         },
240     }
241 }
242
243 fn check_place<'tcx>(tcx: TyCtxt<'tcx>, place: Place<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult {
244     let mut cursor = place.projection.as_ref();
245     while let [ref proj_base @ .., elem] = *cursor {
246         cursor = proj_base;
247         match elem {
248             ProjectionElem::Field(..) => {
249                 let base_ty = Place::ty_from(place.local, proj_base, body, tcx).ty;
250                 if let Some(def) = base_ty.ty_adt_def() {
251                     // No union field accesses in `const fn`
252                     if def.is_union() {
253                         return Err((span, "accessing union fields is unstable".into()));
254                     }
255                 }
256             },
257             ProjectionElem::ConstantIndex { .. }
258             | ProjectionElem::Downcast(..)
259             | ProjectionElem::Subslice { .. }
260             | ProjectionElem::Deref
261             | ProjectionElem::Index(_) => {},
262         }
263     }
264
265     Ok(())
266 }
267
268 fn check_terminator<'a, 'tcx>(
269     tcx: TyCtxt<'tcx>,
270     body: &'a Body<'tcx>,
271     terminator: &Terminator<'tcx>,
272     msrv: Option<&RustcVersion>,
273 ) -> 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 !is_const_fn(tcx, fn_def_id, msrv) {
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 }
355
356 fn is_const_fn(tcx: TyCtxt<'_>, def_id: DefId, msrv: Option<&RustcVersion>) -> bool {
357     tcx.is_const_fn(def_id)
358         && tcx.lookup_const_stability(def_id).map_or(true, |const_stab| {
359             if let rustc_attr::StabilityLevel::Stable { since } = const_stab.level {
360                 // Checking MSRV is manually necessary because `rustc` has no such concept. This entire
361                 // function could be removed if `rustc` provided a MSRV-aware version of `is_const_fn`.
362                 // as a part of an unimplemented MSRV check https://github.com/rust-lang/rust/issues/65262.
363                 crate::meets_msrv(
364                     msrv,
365                     &RustcVersion::parse(since.as_str())
366                         .expect("`rustc_attr::StabilityLevel::Stable::since` is ill-formatted"),
367                 )
368             } else {
369                 // Unstable const fn with the feature enabled.
370                 msrv.is_none()
371             }
372         })
373 }