1 use rustc_attr as attr;
3 use rustc_hir::def_id::DefId;
4 use rustc_middle::mir::*;
5 use rustc_middle::ty::subst::GenericArgKind;
6 use rustc_middle::ty::{self, adjustment::PointerCast, Ty, TyCtxt};
7 use rustc_span::symbol::{sym, Symbol};
9 use rustc_target::spec::abi::Abi::RustIntrinsic;
12 type McfResult = Result<(), (Span, Cow<'static, str>)>;
14 pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>) -> McfResult {
15 // Prevent const trait methods from being annotated as `stable`.
16 if tcx.features().staged_api {
17 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
18 if crate::const_eval::is_parent_const_impl_raw(tcx, hir_id) {
19 return Err((body.span, "trait methods cannot be stable const fn".into()));
23 let mut current = def_id;
25 let predicates = tcx.predicates_of(current);
26 for (predicate, _) in predicates.predicates {
27 match predicate.skip_binders() {
28 ty::PredicateAtom::RegionOutlives(_)
29 | ty::PredicateAtom::TypeOutlives(_)
30 | ty::PredicateAtom::WellFormed(_)
31 | ty::PredicateAtom::Projection(_)
32 | ty::PredicateAtom::ConstEvaluatable(..)
33 | ty::PredicateAtom::ConstEquate(..)
34 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => continue,
35 ty::PredicateAtom::ObjectSafe(_) => {
36 bug!("object safe predicate on function: {:#?}", predicate)
38 ty::PredicateAtom::ClosureKind(..) => {
39 bug!("closure kind predicate on function: {:#?}", predicate)
41 ty::PredicateAtom::Subtype(_) => {
42 bug!("subtype predicate on function: {:#?}", predicate)
44 ty::PredicateAtom::Trait(pred, constness) => {
45 if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
48 match pred.self_ty().kind() {
50 // Allow `T: ?const Trait`
51 if constness == hir::Constness::NotConst
52 && feature_allowed(tcx, def_id, sym::const_trait_bound_opt_out)
57 let generics = tcx.generics_of(current);
58 let def = generics.type_param(p, tcx);
59 let span = tcx.def_span(def.def_id);
62 "trait bounds other than `Sized` \
63 on const fn parameters are unstable"
67 // other kinds of bounds are either tautologies
68 // or cause errors in other passes
74 match predicates.parent {
75 Some(parent) => current = parent,
80 for local in &body.local_decls {
81 check_ty(tcx, local.ty, local.source_info.span, def_id)?;
83 // impl trait is gone in MIR, so check the return type manually
86 tcx.fn_sig(def_id).output().skip_binder(),
87 body.local_decls.iter().next().unwrap().source_info.span,
91 for bb in body.basic_blocks() {
92 check_terminator(tcx, body, def_id, bb.terminator())?;
93 for stmt in &bb.statements {
94 check_statement(tcx, body, def_id, stmt)?;
100 fn check_ty(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span, fn_def_id: DefId) -> McfResult {
101 for arg in ty.walk() {
102 let ty = match arg.unpack() {
103 GenericArgKind::Type(ty) => ty,
105 // No constraints on lifetimes or constants, except potentially
106 // constants' types, but `walk` will get to them as well.
107 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
111 ty::Ref(_, _, hir::Mutability::Mut) => {
112 if !feature_allowed(tcx, fn_def_id, sym::const_mut_refs) {
113 return Err((span, "mutable references in const fn are unstable".into()));
116 ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
118 if !tcx.const_fn_is_allowed_fn_ptr(fn_def_id) {
119 return Err((span, "function pointers in const fn are unstable".into()));
122 ty::Dynamic(preds, _) => {
123 for pred in preds.iter() {
124 match pred.skip_binder() {
125 ty::ExistentialPredicate::AutoTrait(_)
126 | ty::ExistentialPredicate::Projection(_) => {
129 "trait bounds other than `Sized` \
130 on const fn parameters are unstable"
134 ty::ExistentialPredicate::Trait(trait_ref) => {
135 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
138 "trait bounds other than `Sized` \
139 on const fn parameters are unstable"
157 rvalue: &Rvalue<'tcx>,
161 Rvalue::ThreadLocalRef(_) => {
162 Err((span, "cannot access thread local storage in const fn".into()))
164 Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
165 check_operand(tcx, operand, span, def_id, body)
168 | Rvalue::Discriminant(place)
169 | Rvalue::Ref(_, _, place)
170 | Rvalue::AddressOf(_, place) => check_place(tcx, *place, span, def_id, body),
171 Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
172 use rustc_middle::ty::cast::CastTy;
173 let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
174 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
175 match (cast_in, cast_out) {
176 (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
177 Err((span, "casting pointers to ints is unstable in const fn".into()))
179 _ => check_operand(tcx, operand, span, def_id, body),
183 CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer),
186 ) => check_operand(tcx, operand, span, def_id, body),
189 PointerCast::UnsafeFnPointer
190 | PointerCast::ClosureFnPointer(_)
191 | PointerCast::ReifyFnPointer,
195 ) => Err((span, "function pointer casts are not allowed in const fn".into())),
196 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), op, cast_ty) => {
197 let pointee_ty = if let Some(deref_ty) = cast_ty.builtin_deref(true) {
200 // We cannot allow this for now.
203 "unsizing casts are only allowed for references right now".into(),
206 let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id));
207 if let ty::Slice(_) | ty::Str = unsized_ty.kind() {
208 check_operand(tcx, op, span, def_id, body)?;
209 // Casting/coercing things to slices is fine.
212 // We just can't allow trait objects until we have figured out trait method calls.
213 Err((span, "unsizing casts are not allowed in const fn".into()))
216 // binops are fine on integers
217 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
218 check_operand(tcx, lhs, span, def_id, body)?;
219 check_operand(tcx, rhs, span, def_id, body)?;
220 let ty = lhs.ty(body, tcx);
221 if ty.is_integral() || ty.is_bool() || ty.is_char() {
224 Err((span, "only int, `bool` and `char` operations are stable in const fn".into()))
227 Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
228 Rvalue::NullaryOp(NullOp::Box, _) => {
229 Err((span, "heap allocations are not allowed in const fn".into()))
231 Rvalue::UnaryOp(_, operand) => {
232 let ty = operand.ty(body, tcx);
233 if ty.is_integral() || ty.is_bool() {
234 check_operand(tcx, operand, span, def_id, body)
236 Err((span, "only int and `bool` operations are stable in const fn".into()))
239 Rvalue::Aggregate(_, operands) => {
240 for operand in operands {
241 check_operand(tcx, operand, span, def_id, body)?;
252 statement: &Statement<'tcx>,
254 let span = statement.source_info.span;
255 match &statement.kind {
256 StatementKind::Assign(box (place, rval)) => {
257 check_place(tcx, *place, span, def_id, body)?;
258 check_rvalue(tcx, body, def_id, rval, span)
261 StatementKind::FakeRead(_, place) => check_place(tcx, **place, span, def_id, body),
263 // just an assignment
264 StatementKind::SetDiscriminant { place, .. } => {
265 check_place(tcx, **place, span, def_id, body)
268 StatementKind::LlvmInlineAsm { .. } => {
269 Err((span, "cannot use inline assembly in const fn".into()))
272 // These are all NOPs
273 StatementKind::StorageLive(_)
274 | StatementKind::StorageDead(_)
275 | StatementKind::Retag { .. }
276 | StatementKind::AscribeUserType(..)
277 | StatementKind::Coverage(..)
278 | StatementKind::Nop => Ok(()),
284 operand: &Operand<'tcx>,
290 Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, def_id, body),
291 Operand::Constant(c) => match c.check_static_ptr(tcx) {
292 Some(_) => Err((span, "cannot access `static` items in const fn".into())),
305 let mut cursor = place.projection.as_ref();
306 while let &[ref proj_base @ .., elem] = cursor {
309 ProjectionElem::Field(..) => {
310 let base_ty = Place::ty_from(place.local, &proj_base, body, tcx).ty;
311 if let Some(def) = base_ty.ty_adt_def() {
312 // No union field accesses in `const fn`
314 if !feature_allowed(tcx, def_id, sym::const_fn_union) {
315 return Err((span, "accessing union fields is unstable".into()));
320 ProjectionElem::ConstantIndex { .. }
321 | ProjectionElem::Downcast(..)
322 | ProjectionElem::Subslice { .. }
323 | ProjectionElem::Deref
324 | ProjectionElem::Index(_) => {}
331 /// Returns `true` if the given feature gate is allowed within the function with the given `DefId`.
332 fn feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
333 // All features require that the corresponding gate be enabled,
334 // even if the function has `#[allow_internal_unstable(the_gate)]`.
335 if !tcx.features().enabled(feature_gate) {
339 // If this crate is not using stability attributes, or this function is not claiming to be a
340 // stable `const fn`, that is all that is required.
341 if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
345 // However, we cannot allow stable `const fn`s to use unstable features without an explicit
346 // opt-in via `allow_internal_unstable`.
347 attr::allow_internal_unstable(&tcx.sess, &tcx.get_attrs(def_id))
348 .map_or(false, |mut features| features.any(|name| name == feature_gate))
351 /// Returns `true` if the given library feature gate is allowed within the function with the given `DefId`.
352 pub fn lib_feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
353 // All features require that the corresponding gate be enabled,
354 // even if the function has `#[allow_internal_unstable(the_gate)]`.
355 if !tcx.features().declared_lib_features.iter().any(|&(sym, _)| sym == feature_gate) {
359 // If this crate is not using stability attributes, or this function is not claiming to be a
360 // stable `const fn`, that is all that is required.
361 if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
365 // However, we cannot allow stable `const fn`s to use unstable features without an explicit
366 // opt-in via `allow_internal_unstable`.
367 attr::allow_internal_unstable(&tcx.sess, &tcx.get_attrs(def_id))
368 .map_or(false, |mut features| features.any(|name| name == feature_gate))
373 body: &'a Body<'tcx>,
375 terminator: &Terminator<'tcx>,
377 let span = terminator.source_info.span;
378 match &terminator.kind {
379 TerminatorKind::FalseEdge { .. }
380 | TerminatorKind::FalseUnwind { .. }
381 | TerminatorKind::Goto { .. }
382 | TerminatorKind::Return
383 | TerminatorKind::Resume
384 | TerminatorKind::Unreachable => Ok(()),
386 TerminatorKind::Drop { place, .. } => check_place(tcx, *place, span, def_id, body),
387 TerminatorKind::DropAndReplace { place, value, .. } => {
388 check_place(tcx, *place, span, def_id, body)?;
389 check_operand(tcx, value, span, def_id, body)
392 TerminatorKind::SwitchInt { discr, switch_ty: _, values: _, targets: _ } => {
393 check_operand(tcx, discr, span, def_id, body)
396 TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())),
397 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
398 Err((span, "const fn generators are unstable".into()))
401 TerminatorKind::Call {
409 let fn_ty = func.ty(body, tcx);
410 if let ty::FnDef(fn_def_id, _) = *fn_ty.kind() {
411 // Allow unstable const if we opt in by using #[allow_internal_unstable]
412 // on function or macro declaration.
413 if !crate::const_eval::is_min_const_fn(tcx, fn_def_id)
414 && !crate::const_eval::is_unstable_const_fn(tcx, fn_def_id)
416 span.allows_unstable(feature)
417 || lib_feature_allowed(tcx, def_id, feature)
424 "can only call other `const fn` within a `const fn`, \
425 but `{:?}` is not stable as `const fn`",
432 // HACK: This is to "unstabilize" the `transmute` intrinsic
433 // within const fns. `transmute` is allowed in all other const contexts.
434 // This won't really scale to more intrinsics or functions. Let's allow const
435 // transmutes in const fn before we add more hacks to this.
436 if tcx.fn_sig(fn_def_id).abi() == RustIntrinsic
437 && tcx.item_name(fn_def_id) == sym::transmute
438 && !feature_allowed(tcx, def_id, sym::const_fn_transmute)
442 "can only call `transmute` from const items, not `const fn`".into(),
446 check_operand(tcx, func, span, fn_def_id, body)?;
449 check_operand(tcx, arg, span, fn_def_id, body)?;
453 Err((span, "can only call other const fns within const fn".into()))
457 TerminatorKind::Assert { cond, expected: _, msg: _, target: _, cleanup: _ } => {
458 check_operand(tcx, cond, span, def_id, body)
461 TerminatorKind::InlineAsm { .. } => {
462 Err((span, "cannot use inline assembly in const fn".into()))