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().as_local_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.ignore_quantifiers().skip_binder().kind() {
28 ty::PredicateKind::ForAll(_) => bug!("unexpected predicate: {:?}", predicate),
29 ty::PredicateKind::RegionOutlives(_)
30 | ty::PredicateKind::TypeOutlives(_)
31 | ty::PredicateKind::WellFormed(_)
32 | ty::PredicateKind::Projection(_)
33 | ty::PredicateKind::ConstEvaluatable(..)
34 | ty::PredicateKind::ConstEquate(..) => continue,
35 ty::PredicateKind::ObjectSafe(_) => {
36 bug!("object safe predicate on function: {:#?}", predicate)
38 ty::PredicateKind::ClosureKind(..) => {
39 bug!("closure kind predicate on function: {:#?}", predicate)
41 ty::PredicateKind::Subtype(_) => {
42 bug!("subtype predicate on function: {:#?}", predicate)
44 &ty::PredicateKind::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 = cast_ty.builtin_deref(true).unwrap().ty;
198 let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id));
199 if let ty::Slice(_) | ty::Str = unsized_ty.kind {
200 check_operand(tcx, op, span, def_id, body)?;
201 // Casting/coercing things to slices is fine.
204 // We just can't allow trait objects until we have figured out trait method calls.
205 Err((span, "unsizing casts are not allowed in const fn".into()))
208 // binops are fine on integers
209 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
210 check_operand(tcx, lhs, span, def_id, body)?;
211 check_operand(tcx, rhs, span, def_id, body)?;
212 let ty = lhs.ty(body, tcx);
213 if ty.is_integral() || ty.is_bool() || ty.is_char() {
216 Err((span, "only int, `bool` and `char` operations are stable in const fn".into()))
219 Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
220 Rvalue::NullaryOp(NullOp::Box, _) => {
221 Err((span, "heap allocations are not allowed in const fn".into()))
223 Rvalue::UnaryOp(_, operand) => {
224 let ty = operand.ty(body, tcx);
225 if ty.is_integral() || ty.is_bool() {
226 check_operand(tcx, operand, span, def_id, body)
228 Err((span, "only int and `bool` operations are stable in const fn".into()))
231 Rvalue::Aggregate(_, operands) => {
232 for operand in operands {
233 check_operand(tcx, operand, span, def_id, body)?;
244 statement: &Statement<'tcx>,
246 let span = statement.source_info.span;
247 match &statement.kind {
248 StatementKind::Assign(box (place, rval)) => {
249 check_place(tcx, *place, span, def_id, body)?;
250 check_rvalue(tcx, body, def_id, rval, span)
253 StatementKind::FakeRead(_, place) => check_place(tcx, **place, span, def_id, body),
255 // just an assignment
256 StatementKind::SetDiscriminant { place, .. } => {
257 check_place(tcx, **place, span, def_id, body)
260 StatementKind::LlvmInlineAsm { .. } => {
261 Err((span, "cannot use inline assembly in const fn".into()))
264 // These are all NOPs
265 StatementKind::StorageLive(_)
266 | StatementKind::StorageDead(_)
267 | StatementKind::Retag { .. }
268 | StatementKind::AscribeUserType(..)
269 | StatementKind::Nop => Ok(()),
275 operand: &Operand<'tcx>,
281 Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, def_id, body),
282 Operand::Constant(c) => match c.check_static_ptr(tcx) {
283 Some(_) => Err((span, "cannot access `static` items in const fn".into())),
296 let mut cursor = place.projection.as_ref();
297 while let &[ref proj_base @ .., elem] = cursor {
300 ProjectionElem::Field(..) => {
301 let base_ty = Place::ty_from(place.local, &proj_base, body, tcx).ty;
302 if let Some(def) = base_ty.ty_adt_def() {
303 // No union field accesses in `const fn`
305 if !feature_allowed(tcx, def_id, sym::const_fn_union) {
306 return Err((span, "accessing union fields is unstable".into()));
311 ProjectionElem::ConstantIndex { .. }
312 | ProjectionElem::Downcast(..)
313 | ProjectionElem::Subslice { .. }
314 | ProjectionElem::Deref
315 | ProjectionElem::Index(_) => {}
322 /// Returns `true` if the given feature gate is allowed within the function with the given `DefId`.
323 fn feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
324 // All features require that the corresponding gate be enabled,
325 // even if the function has `#[allow_internal_unstable(the_gate)]`.
326 if !tcx.features().enabled(feature_gate) {
330 // If this crate is not using stability attributes, or this function is not claiming to be a
331 // stable `const fn`, that is all that is required.
332 if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
336 // However, we cannot allow stable `const fn`s to use unstable features without an explicit
337 // opt-in via `allow_internal_unstable`.
338 attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
339 .map_or(false, |mut features| features.any(|name| name == feature_gate))
342 /// Returns `true` if the given library feature gate is allowed within the function with the given `DefId`.
343 pub fn lib_feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
344 // All features require that the corresponding gate be enabled,
345 // even if the function has `#[allow_internal_unstable(the_gate)]`.
346 if !tcx.features().declared_lib_features.iter().any(|&(sym, _)| sym == feature_gate) {
350 // If this crate is not using stability attributes, or this function is not claiming to be a
351 // stable `const fn`, that is all that is required.
352 if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
356 // However, we cannot allow stable `const fn`s to use unstable features without an explicit
357 // opt-in via `allow_internal_unstable`.
358 attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
359 .map_or(false, |mut features| features.any(|name| name == feature_gate))
364 body: &'a Body<'tcx>,
366 terminator: &Terminator<'tcx>,
368 let span = terminator.source_info.span;
369 match &terminator.kind {
370 TerminatorKind::FalseEdge { .. }
371 | TerminatorKind::FalseUnwind { .. }
372 | TerminatorKind::Goto { .. }
373 | TerminatorKind::Return
374 | TerminatorKind::Resume
375 | TerminatorKind::Unreachable => Ok(()),
377 TerminatorKind::Drop { place, .. } => check_place(tcx, *place, span, def_id, body),
378 TerminatorKind::DropAndReplace { place, value, .. } => {
379 check_place(tcx, *place, span, def_id, body)?;
380 check_operand(tcx, value, span, def_id, body)
383 TerminatorKind::SwitchInt { discr, switch_ty: _, values: _, targets: _ } => {
384 check_operand(tcx, discr, span, def_id, body)
387 TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())),
388 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
389 Err((span, "const fn generators are unstable".into()))
392 TerminatorKind::Call {
400 let fn_ty = func.ty(body, tcx);
401 if let ty::FnDef(fn_def_id, _) = fn_ty.kind {
402 // Allow unstable const if we opt in by using #[allow_internal_unstable]
403 // on function or macro declaration.
404 if !crate::const_eval::is_min_const_fn(tcx, fn_def_id)
405 && !crate::const_eval::is_unstable_const_fn(tcx, fn_def_id)
407 span.allows_unstable(feature)
408 || lib_feature_allowed(tcx, def_id, feature)
415 "can only call other `const fn` within a `const fn`, \
416 but `{:?}` is not stable as `const fn`",
423 // HACK: This is to "unstabilize" the `transmute` intrinsic
424 // within const fns. `transmute` is allowed in all other const contexts.
425 // This won't really scale to more intrinsics or functions. Let's allow const
426 // transmutes in const fn before we add more hacks to this.
427 if tcx.fn_sig(fn_def_id).abi() == RustIntrinsic
428 && tcx.item_name(fn_def_id) == sym::transmute
429 && !feature_allowed(tcx, def_id, sym::const_fn_transmute)
433 "can only call `transmute` from const items, not `const fn`".into(),
437 check_operand(tcx, func, span, fn_def_id, body)?;
440 check_operand(tcx, arg, span, fn_def_id, body)?;
444 Err((span, "can only call other const fns within const fn".into()))
448 TerminatorKind::Assert { cond, expected: _, msg: _, target: _, cleanup: _ } => {
449 check_operand(tcx, cond, span, def_id, body)
452 TerminatorKind::InlineAsm { .. } => {
453 Err((span, "cannot use inline assembly in const fn".into()))