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.
7 use rustc_hir::def_id::DefId;
8 use rustc_middle::mir::{
9 Body, CastKind, NullOp, Operand, Place, ProjectionElem, Rvalue, Statement, StatementKind, Terminator,
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;
17 use rustc_target::spec::abi::Abi::RustIntrinsic;
20 type McfResult = Result<(), (Span, Cow<'static, str>)>;
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;
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() {
43 match pred.self_ty().kind() {
45 let generics = tcx.generics_of(current);
46 let def = generics.type_param(p, tcx);
47 let span = tcx.def_span(def.def_id);
50 "trait bounds other than `Sized` \
51 on const fn parameters are unstable"
55 // other kinds of bounds are either tautologies
56 // or cause errors in other passes
62 match predicates.parent {
63 Some(parent) => current = parent,
68 for local in &body.local_decls {
69 check_ty(tcx, local.ty, local.source_info.span)?;
71 // impl trait is gone in MIR, so check the return type manually
74 tcx.fn_sig(def_id).output().skip_binder(),
75 body.local_decls.iter().next().unwrap().source_info.span,
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)?;
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,
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,
98 ty::Ref(_, _, hir::Mutability::Mut) => {
99 return Err((span, "mutable references in const fn are unstable".into()));
101 ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
103 return Err((span, "function pointers in const fn are unstable".into()));
105 ty::Dynamic(preds, _) => {
106 for pred in preds.iter() {
107 match pred.skip_binder() {
108 ty::ExistentialPredicate::AutoTrait(_) | ty::ExistentialPredicate::Projection(_) => {
111 "trait bounds other than `Sized` \
112 on const fn parameters are unstable"
116 ty::ExistentialPredicate::Trait(trait_ref) => {
117 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
120 "trait bounds other than `Sized` \
121 on const fn parameters are unstable"
135 fn check_rvalue(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, def_id: DefId, rvalue: &Rvalue<'tcx>, span: Span) -> McfResult {
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)
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()))
150 _ => check_operand(tcx, operand, span, body),
153 Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer), operand, _) => {
154 check_operand(tcx, operand, span, body)
158 PointerCast::UnsafeFnPointer | PointerCast::ClosureFnPointer(_) | PointerCast::ReifyFnPointer,
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) {
167 // We cannot allow this for now.
168 return Err((span, "unsizing casts are only allowed for references right now".into()));
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.
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()))
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() {
190 "only int, `bool` and `char` operations are stable in const fn".into(),
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)
201 Err((span, "only int and `bool` operations are stable in const fn".into()))
204 Rvalue::Aggregate(_, operands) => {
205 for operand in operands {
206 check_operand(tcx, operand, span, body)?;
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)
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),
225 StatementKind::LlvmInlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())),
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)
232 // These are all NOPs
233 StatementKind::StorageLive(_)
234 | StatementKind::StorageDead(_)
235 | StatementKind::Retag { .. }
236 | StatementKind::AscribeUserType(..)
237 | StatementKind::Coverage(..)
238 | StatementKind::Nop => Ok(()),
242 fn check_operand(tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult {
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())),
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 {
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`
262 return Err((span, "accessing union fields is unstable".into()));
266 ProjectionElem::ConstantIndex { .. }
267 | ProjectionElem::Downcast(..)
268 | ProjectionElem::Subslice { .. }
269 | ProjectionElem::Deref
270 | ProjectionElem::Index(_) => {},
279 body: &'a Body<'tcx>,
280 terminator: &Terminator<'tcx>,
281 msrv: Option<&RustcVersion>,
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(()),
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)
298 TerminatorKind::SwitchInt {
302 } => check_operand(tcx, discr, span, body),
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()))
309 TerminatorKind::Call {
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) {
323 "can only call other `const fn` within a `const fn`, \
324 but `{:?}` is not stable as `const fn`",
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 {
338 "can only call `transmute` from const items, not `const fn`".into(),
342 check_operand(tcx, func, span, body)?;
345 check_operand(tcx, arg, span, body)?;
349 Err((span, "can only call other const fns within const fn".into()))
353 TerminatorKind::Assert {
359 } => check_operand(tcx, cond, span, body),
361 TerminatorKind::InlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())),
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 && if let Some(const_stab) = tcx.lookup_const_stability(def_id) {
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.
374 &RustcVersion::parse(&since.as_str())
375 .expect("`rustc_attr::StabilityLevel::Stable::since` is ill-formatted"),
378 // `rustc_mir::const_eval::is_const_fn` should return false for unstably const functions.