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.
6 use crate::msrvs::Msrv;
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,
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;
20 type McfResult = Result<(), (Span, Cow<'static, str>)>;
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;
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(..),
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:#?}"),
46 match predicates.parent {
47 Some(parent) => current = parent,
52 for local in &body.local_decls {
53 check_ty(tcx, local.ty, local.source_info.span)?;
55 // impl trait is gone in MIR, so check the return type manually
58 tcx.fn_sig(def_id).output().skip_binder(),
59 body.local_decls.iter().next().unwrap().source_info.span,
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)?;
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,
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,
82 ty::Ref(_, _, hir::Mutability::Mut) => {
83 return Err((span, "mutable references in const fn are unstable".into()));
85 ty::Alias(ty::Opaque, ..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
87 return Err((span, "function pointers in const fn are unstable".into()));
89 ty::Dynamic(preds, _, _) => {
90 for pred in preds.iter() {
91 match pred.skip_binder() {
92 ty::ExistentialPredicate::AutoTrait(_) | ty::ExistentialPredicate::Projection(_) => {
95 "trait bounds other than `Sized` \
96 on const fn parameters are unstable"
100 ty::ExistentialPredicate::Trait(trait_ref) => {
101 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
104 "trait bounds other than `Sized` \
105 on const fn parameters are unstable"
119 fn check_rvalue<'tcx>(
123 rvalue: &Rvalue<'tcx>,
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)
131 Rvalue::CopyForDeref(place) => check_place(tcx, *place, span, body),
132 Rvalue::Repeat(operand, _)
133 | Rvalue::Use(operand)
135 CastKind::PointerFromExposedAddress
137 | CastKind::FloatToInt
138 | CastKind::IntToFloat
139 | CastKind::FloatToFloat
140 | CastKind::FnPtrToPtr
142 | CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer),
145 ) => check_operand(tcx, operand, span, body),
148 PointerCast::UnsafeFnPointer | PointerCast::ClosureFnPointer(_) | PointerCast::ReifyFnPointer,
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) {
157 // We cannot allow this for now.
158 return Err((span, "unsizing casts are only allowed for references right now".into()));
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.
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()))
170 Rvalue::Cast(CastKind::PointerExposeAddress, _, _) => {
171 Err((span, "casting pointers to ints is unstable in const fn".into()))
173 Rvalue::Cast(CastKind::DynStar, _, _) => {
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() {
187 "only int, `bool` and `char` operations are stable in const fn".into(),
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)
197 Err((span, "only int and `bool` operations are stable in const fn".into()))
200 Rvalue::Aggregate(_, operands) => {
201 for operand in operands {
202 check_operand(tcx, operand, span, body)?;
209 fn check_statement<'tcx>(
213 statement: &Statement<'tcx>,
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)
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)
228 StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => check_operand(tcx, op, span, body),
230 StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping(
231 rustc_middle::mir::CopyNonOverlapping { dst, src, count },
233 check_operand(tcx, dst, span, body)?;
234 check_operand(tcx, src, span, body)?;
235 check_operand(tcx, count, span, body)
237 // These are all NOPs
238 StatementKind::StorageLive(_)
239 | StatementKind::StorageDead(_)
240 | StatementKind::Retag { .. }
241 | StatementKind::AscribeUserType(..)
242 | StatementKind::Coverage(..)
243 | StatementKind::Nop => Ok(()),
247 fn check_operand<'tcx>(tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult {
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())),
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 {
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`
267 return Err((span, "accessing union fields is unstable".into()));
271 ProjectionElem::ConstantIndex { .. }
272 | ProjectionElem::OpaqueCast(..)
273 | ProjectionElem::Downcast(..)
274 | ProjectionElem::Subslice { .. }
275 | ProjectionElem::Deref
276 | ProjectionElem::Index(_) => {},
283 fn check_terminator<'tcx>(
286 terminator: &Terminator<'tcx>,
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(()),
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)
304 TerminatorKind::SwitchInt { discr, targets: _ } => check_operand(tcx, discr, span, body),
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()))
311 TerminatorKind::Call {
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) {
326 "can only call other `const fn` within a `const fn`, \
327 but `{func:?}` is not stable as `const fn`",
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 {
340 "can only call `transmute` from const items, not `const fn`".into(),
344 check_operand(tcx, func, span, body)?;
347 check_operand(tcx, arg, span, body)?;
351 Err((span, "can only call other const fns within const fn".into()))
355 TerminatorKind::Assert {
361 } => check_operand(tcx, cond, span, body),
363 TerminatorKind::InlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())),
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.
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
378 let short_version = since
382 .expect("rustc_attr::StabilityLevel::Stable::since` is empty");
384 let since = rustc_span::Symbol::intern(short_version);
386 msrv.meets(RustcVersion::parse(since.as_str()).unwrap_or_else(|err| {
387 panic!("`rustc_attr::StabilityLevel::Stable::since` is ill-formatted: `{since}`, {err:?}")
390 // Unstable const fn with the feature enabled.
391 msrv.current().is_none()