]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs
Auto merge of #102755 - pcc:data-local-tmp, r=Mark-Simulacrum
[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 rustc_hir as hir;
7 use rustc_hir::def_id::DefId;
8 use rustc_middle::mir::{
9     Body, CastKind, NonDivergingIntrinsic, NullOp, Operand, Place, ProjectionElem, Rvalue, Statement, StatementKind,
10     Terminator, 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 std::borrow::Cow;
18
19 type McfResult = Result<(), (Span, Cow<'static, str>)>;
20
21 pub fn is_min_const_fn<'a, 'tcx>(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, msrv: Option<RustcVersion>) -> McfResult {
22     let def_id = body.source.def_id();
23     let mut current = def_id;
24     loop {
25         let predicates = tcx.predicates_of(current);
26         for (predicate, _) in predicates.predicates {
27             match predicate.kind().skip_binder() {
28                 ty::PredicateKind::RegionOutlives(_)
29                 | ty::PredicateKind::TypeOutlives(_)
30                 | ty::PredicateKind::WellFormed(_)
31                 | ty::PredicateKind::Projection(_)
32                 | ty::PredicateKind::ConstEvaluatable(..)
33                 | ty::PredicateKind::ConstEquate(..)
34                 | ty::PredicateKind::Trait(..)
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             }
41         }
42         match predicates.parent {
43             Some(parent) => current = parent,
44             None => break,
45         }
46     }
47
48     for local in &body.local_decls {
49         check_ty(tcx, local.ty, local.source_info.span)?;
50     }
51     // impl trait is gone in MIR, so check the return type manually
52     check_ty(
53         tcx,
54         tcx.fn_sig(def_id).output().skip_binder(),
55         body.local_decls.iter().next().unwrap().source_info.span,
56     )?;
57
58     for bb in body.basic_blocks.iter() {
59         check_terminator(tcx, body, bb.terminator(), msrv)?;
60         for stmt in &bb.statements {
61             check_statement(tcx, body, def_id, stmt)?;
62         }
63     }
64     Ok(())
65 }
66
67 fn check_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) -> McfResult {
68     for arg in ty.walk() {
69         let ty = match arg.unpack() {
70             GenericArgKind::Type(ty) => ty,
71
72             // No constraints on lifetimes or constants, except potentially
73             // constants' types, but `walk` will get to them as well.
74             GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
75         };
76
77         match ty.kind() {
78             ty::Ref(_, _, hir::Mutability::Mut) => {
79                 return Err((span, "mutable references in const fn are unstable".into()));
80             },
81             ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
82             ty::FnPtr(..) => {
83                 return Err((span, "function pointers in const fn are unstable".into()));
84             },
85             ty::Dynamic(preds, _, _) => {
86                 for pred in preds.iter() {
87                     match pred.skip_binder() {
88                         ty::ExistentialPredicate::AutoTrait(_) | ty::ExistentialPredicate::Projection(_) => {
89                             return Err((
90                                 span,
91                                 "trait bounds other than `Sized` \
92                                  on const fn parameters are unstable"
93                                     .into(),
94                             ));
95                         },
96                         ty::ExistentialPredicate::Trait(trait_ref) => {
97                             if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
98                                 return Err((
99                                     span,
100                                     "trait bounds other than `Sized` \
101                                      on const fn parameters are unstable"
102                                         .into(),
103                                 ));
104                             }
105                         },
106                     }
107                 }
108             },
109             _ => {},
110         }
111     }
112     Ok(())
113 }
114
115 fn check_rvalue<'tcx>(
116     tcx: TyCtxt<'tcx>,
117     body: &Body<'tcx>,
118     def_id: DefId,
119     rvalue: &Rvalue<'tcx>,
120     span: Span,
121 ) -> McfResult {
122     match rvalue {
123         Rvalue::ThreadLocalRef(_) => Err((span, "cannot access thread local storage in const fn".into())),
124         Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
125             check_place(tcx, *place, span, body)
126         },
127         Rvalue::CopyForDeref(place) => check_place(tcx, *place, span, body),
128         Rvalue::Repeat(operand, _)
129         | Rvalue::Use(operand)
130         | Rvalue::Cast(
131             CastKind::PointerFromExposedAddress
132             | CastKind::IntToInt
133             | CastKind::FloatToInt
134             | CastKind::IntToFloat
135             | CastKind::FloatToFloat
136             | CastKind::FnPtrToPtr
137             | CastKind::PtrToPtr
138             | CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer),
139             operand,
140             _,
141         ) => check_operand(tcx, operand, span, body),
142         Rvalue::Cast(
143             CastKind::Pointer(
144                 PointerCast::UnsafeFnPointer | PointerCast::ClosureFnPointer(_) | PointerCast::ReifyFnPointer,
145             ),
146             _,
147             _,
148         ) => Err((span, "function pointer casts are not allowed in const fn".into())),
149         Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), op, cast_ty) => {
150             let pointee_ty = if let Some(deref_ty) = cast_ty.builtin_deref(true) {
151                 deref_ty.ty
152             } else {
153                 // We cannot allow this for now.
154                 return Err((span, "unsizing casts are only allowed for references right now".into()));
155             };
156             let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id));
157             if let ty::Slice(_) | ty::Str = unsized_ty.kind() {
158                 check_operand(tcx, op, span, body)?;
159                 // Casting/coercing things to slices is fine.
160                 Ok(())
161             } else {
162                 // We just can't allow trait objects until we have figured out trait method calls.
163                 Err((span, "unsizing casts are not allowed in const fn".into()))
164             }
165         },
166         Rvalue::Cast(CastKind::PointerExposeAddress, _, _) => {
167             Err((span, "casting pointers to ints is unstable in const fn".into()))
168         },
169         Rvalue::Cast(CastKind::DynStar, _, _) => {
170             // FIXME(dyn-star)
171             unimplemented!()
172         },
173         // binops are fine on integers
174         Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => {
175             check_operand(tcx, lhs, span, body)?;
176             check_operand(tcx, rhs, span, body)?;
177             let ty = lhs.ty(body, tcx);
178             if ty.is_integral() || ty.is_bool() || ty.is_char() {
179                 Ok(())
180             } else {
181                 Err((
182                     span,
183                     "only int, `bool` and `char` operations are stable in const fn".into(),
184                 ))
185             }
186         },
187         Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, _) | Rvalue::ShallowInitBox(_, _) => Ok(()),
188         Rvalue::UnaryOp(_, operand) => {
189             let ty = operand.ty(body, tcx);
190             if ty.is_integral() || ty.is_bool() {
191                 check_operand(tcx, operand, span, body)
192             } else {
193                 Err((span, "only int and `bool` operations are stable in const fn".into()))
194             }
195         },
196         Rvalue::Aggregate(_, operands) => {
197             for operand in operands {
198                 check_operand(tcx, operand, span, body)?;
199             }
200             Ok(())
201         },
202     }
203 }
204
205 fn check_statement<'tcx>(
206     tcx: TyCtxt<'tcx>,
207     body: &Body<'tcx>,
208     def_id: DefId,
209     statement: &Statement<'tcx>,
210 ) -> McfResult {
211     let span = statement.source_info.span;
212     match &statement.kind {
213         StatementKind::Assign(box (place, rval)) => {
214             check_place(tcx, *place, span, body)?;
215             check_rvalue(tcx, body, def_id, rval, span)
216         },
217
218         StatementKind::FakeRead(box (_, place)) => check_place(tcx, *place, span, body),
219         // just an assignment
220         StatementKind::SetDiscriminant { place, .. } | StatementKind::Deinit(place) => {
221             check_place(tcx, **place, span, body)
222         },
223
224         StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => check_operand(tcx, op, span, body),
225
226         StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping(
227             rustc_middle::mir::CopyNonOverlapping { dst, src, count },
228         )) => {
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>(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>(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::OpaqueCast(..)
269             | ProjectionElem::Downcast(..)
270             | ProjectionElem::Subslice { .. }
271             | ProjectionElem::Deref
272             | ProjectionElem::Index(_) => {},
273         }
274     }
275
276     Ok(())
277 }
278
279 fn check_terminator<'a, 'tcx>(
280     tcx: TyCtxt<'tcx>,
281     body: &'a Body<'tcx>,
282     terminator: &Terminator<'tcx>,
283     msrv: Option<RustcVersion>,
284 ) -> McfResult {
285     let span = terminator.source_info.span;
286     match &terminator.kind {
287         TerminatorKind::FalseEdge { .. }
288         | TerminatorKind::FalseUnwind { .. }
289         | TerminatorKind::Goto { .. }
290         | TerminatorKind::Return
291         | TerminatorKind::Resume
292         | TerminatorKind::Unreachable => Ok(()),
293
294         TerminatorKind::Drop { place, .. } => check_place(tcx, *place, span, body),
295         TerminatorKind::DropAndReplace { place, value, .. } => {
296             check_place(tcx, *place, span, body)?;
297             check_operand(tcx, value, span, body)
298         },
299
300         TerminatorKind::SwitchInt {
301             discr,
302             switch_ty: _,
303             targets: _,
304         } => 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: Option<RustcVersion>) -> 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                 crate::meets_msrv(
387                     msrv,
388                     RustcVersion::parse(since.as_str()).unwrap_or_else(|err| {
389                         panic!("`rustc_attr::StabilityLevel::Stable::since` is ill-formatted: `{since}`, {err:?}")
390                     }),
391                 )
392             } else {
393                 // Unstable const fn with the feature enabled.
394                 msrv.is_none()
395             }
396         })
397 }