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