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<'a, 'tcx>(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::Coerce(_) => panic!("coerce predicate on function: {:#?}", predicate),
40 ty::PredicateKind::Trait(pred) => {
41 if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
44 match pred.self_ty().kind() {
46 let generics = tcx.generics_of(current);
47 let def = generics.type_param(p, tcx);
48 let span = tcx.def_span(def.def_id);
51 "trait bounds other than `Sized` \
52 on const fn parameters are unstable"
56 // other kinds of bounds are either tautologies
57 // or cause errors in other passes
63 match predicates.parent {
64 Some(parent) => current = parent,
69 for local in &body.local_decls {
70 check_ty(tcx, local.ty, local.source_info.span)?;
72 // impl trait is gone in MIR, so check the return type manually
75 tcx.fn_sig(def_id).output().skip_binder(),
76 body.local_decls.iter().next().unwrap().source_info.span,
79 for bb in body.basic_blocks() {
80 check_terminator(tcx, body, bb.terminator(), msrv)?;
81 for stmt in &bb.statements {
82 check_statement(tcx, body, def_id, stmt)?;
88 fn check_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) -> McfResult {
89 for arg in ty.walk() {
90 let ty = match arg.unpack() {
91 GenericArgKind::Type(ty) => ty,
93 // No constraints on lifetimes or constants, except potentially
94 // constants' types, but `walk` will get to them as well.
95 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
99 ty::Ref(_, _, hir::Mutability::Mut) => {
100 return Err((span, "mutable references in const fn are unstable".into()));
102 ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
104 return Err((span, "function pointers in const fn are unstable".into()));
106 ty::Dynamic(preds, _) => {
107 for pred in preds.iter() {
108 match pred.skip_binder() {
109 ty::ExistentialPredicate::AutoTrait(_) | ty::ExistentialPredicate::Projection(_) => {
112 "trait bounds other than `Sized` \
113 on const fn parameters are unstable"
117 ty::ExistentialPredicate::Trait(trait_ref) => {
118 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
121 "trait bounds other than `Sized` \
122 on const fn parameters are unstable"
136 fn check_rvalue<'tcx>(
140 rvalue: &Rvalue<'tcx>,
144 Rvalue::ThreadLocalRef(_) => Err((span, "cannot access thread local storage in const fn".into())),
145 Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => check_operand(tcx, operand, span, body),
146 Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
147 check_place(tcx, *place, span, body)
149 Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
150 use rustc_middle::ty::cast::CastTy;
151 let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
152 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
153 match (cast_in, cast_out) {
154 (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
155 Err((span, "casting pointers to ints is unstable in const fn".into()))
157 _ => check_operand(tcx, operand, span, body),
160 Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer), operand, _) => {
161 check_operand(tcx, operand, span, body)
165 PointerCast::UnsafeFnPointer | PointerCast::ClosureFnPointer(_) | PointerCast::ReifyFnPointer,
169 ) => Err((span, "function pointer casts are not allowed in const fn".into())),
170 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), op, cast_ty) => {
171 let pointee_ty = if let Some(deref_ty) = cast_ty.builtin_deref(true) {
174 // We cannot allow this for now.
175 return Err((span, "unsizing casts are only allowed for references right now".into()));
177 let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id));
178 if let ty::Slice(_) | ty::Str = unsized_ty.kind() {
179 check_operand(tcx, op, span, body)?;
180 // Casting/coercing things to slices is fine.
183 // We just can't allow trait objects until we have figured out trait method calls.
184 Err((span, "unsizing casts are not allowed in const fn".into()))
187 // binops are fine on integers
188 Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => {
189 check_operand(tcx, lhs, span, body)?;
190 check_operand(tcx, rhs, span, body)?;
191 let ty = lhs.ty(body, tcx);
192 if ty.is_integral() || ty.is_bool() || ty.is_char() {
197 "only int, `bool` and `char` operations are stable in const fn".into(),
201 Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, _) | Rvalue::ShallowInitBox(_, _) => Ok(()),
202 Rvalue::UnaryOp(_, operand) => {
203 let ty = operand.ty(body, tcx);
204 if ty.is_integral() || ty.is_bool() {
205 check_operand(tcx, operand, span, body)
207 Err((span, "only int and `bool` operations are stable in const fn".into()))
210 Rvalue::Aggregate(_, operands) => {
211 for operand in operands {
212 check_operand(tcx, operand, span, body)?;
219 fn check_statement<'tcx>(
223 statement: &Statement<'tcx>,
225 let span = statement.source_info.span;
226 match &statement.kind {
227 StatementKind::Assign(box (place, rval)) => {
228 check_place(tcx, *place, span, body)?;
229 check_rvalue(tcx, body, def_id, rval, span)
232 StatementKind::FakeRead(box (_, place)) => check_place(tcx, *place, span, body),
233 // just an assignment
234 StatementKind::SetDiscriminant { place, .. } => check_place(tcx, **place, span, body),
236 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping { dst, src, count }) => {
237 check_operand(tcx, dst, span, body)?;
238 check_operand(tcx, src, span, body)?;
239 check_operand(tcx, count, span, body)
241 // These are all NOPs
242 StatementKind::StorageLive(_)
243 | StatementKind::StorageDead(_)
244 | StatementKind::Retag { .. }
245 | StatementKind::AscribeUserType(..)
246 | StatementKind::Coverage(..)
247 | StatementKind::Nop => Ok(()),
251 fn check_operand<'tcx>(tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult {
253 Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, body),
254 Operand::Constant(c) => match c.check_static_ptr(tcx) {
255 Some(_) => Err((span, "cannot access `static` items in const fn".into())),
261 fn check_place<'tcx>(tcx: TyCtxt<'tcx>, place: Place<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult {
262 let mut cursor = place.projection.as_ref();
263 while let [ref proj_base @ .., elem] = *cursor {
266 ProjectionElem::Field(..) => {
267 let base_ty = Place::ty_from(place.local, proj_base, body, tcx).ty;
268 if let Some(def) = base_ty.ty_adt_def() {
269 // No union field accesses in `const fn`
271 return Err((span, "accessing union fields is unstable".into()));
275 ProjectionElem::ConstantIndex { .. }
276 | ProjectionElem::Downcast(..)
277 | ProjectionElem::Subslice { .. }
278 | ProjectionElem::Deref
279 | ProjectionElem::Index(_) => {},
286 fn check_terminator<'a, 'tcx>(
288 body: &'a Body<'tcx>,
289 terminator: &Terminator<'tcx>,
290 msrv: Option<&RustcVersion>,
292 let span = terminator.source_info.span;
293 match &terminator.kind {
294 TerminatorKind::FalseEdge { .. }
295 | TerminatorKind::FalseUnwind { .. }
296 | TerminatorKind::Goto { .. }
297 | TerminatorKind::Return
298 | TerminatorKind::Resume
299 | TerminatorKind::Unreachable => Ok(()),
301 TerminatorKind::Drop { place, .. } => check_place(tcx, *place, span, body),
302 TerminatorKind::DropAndReplace { place, value, .. } => {
303 check_place(tcx, *place, span, body)?;
304 check_operand(tcx, value, span, body)
307 TerminatorKind::SwitchInt {
311 } => check_operand(tcx, discr, span, body),
313 TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())),
314 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
315 Err((span, "const fn generators are unstable".into()))
318 TerminatorKind::Call {
326 let fn_ty = func.ty(body, tcx);
327 if let ty::FnDef(fn_def_id, _) = *fn_ty.kind() {
328 if !is_const_fn(tcx, fn_def_id, msrv) {
332 "can only call other `const fn` within a `const fn`, \
333 but `{:?}` is not stable as `const fn`",
340 // HACK: This is to "unstabilize" the `transmute` intrinsic
341 // within const fns. `transmute` is allowed in all other const contexts.
342 // This won't really scale to more intrinsics or functions. Let's allow const
343 // transmutes in const fn before we add more hacks to this.
344 if tcx.fn_sig(fn_def_id).abi() == RustIntrinsic && tcx.item_name(fn_def_id) == sym::transmute {
347 "can only call `transmute` from const items, not `const fn`".into(),
351 check_operand(tcx, func, span, body)?;
354 check_operand(tcx, arg, span, body)?;
358 Err((span, "can only call other const fns within const fn".into()))
362 TerminatorKind::Assert {
368 } => check_operand(tcx, cond, span, body),
370 TerminatorKind::InlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())),
374 fn is_const_fn(tcx: TyCtxt<'_>, def_id: DefId, msrv: Option<&RustcVersion>) -> bool {
375 tcx.is_const_fn(def_id)
376 && tcx.lookup_const_stability(def_id).map_or(true, |const_stab| {
377 if let rustc_attr::StabilityLevel::Stable { since } = const_stab.level {
378 // Checking MSRV is manually necessary because `rustc` has no such concept. This entire
379 // function could be removed if `rustc` provided a MSRV-aware version of `is_const_fn`.
380 // as a part of an unimplemented MSRV check https://github.com/rust-lang/rust/issues/65262.
383 &RustcVersion::parse(since.as_str())
384 .expect("`rustc_attr::StabilityLevel::Stable::since` is ill-formatted"),
387 // Unstable const fn with the feature enabled.