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