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};
11 type McfResult = Result<(), (Span, Cow<'static, str>)>;
13 pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>) -> McfResult {
14 // Prevent const trait methods from being annotated as `stable`.
15 if tcx.features().staged_api {
16 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
17 if crate::const_eval::is_parent_const_impl_raw(tcx, hir_id) {
18 return Err((body.span, "trait methods cannot be stable const fn".into()));
22 let mut current = def_id;
24 let predicates = tcx.predicates_of(current);
25 for (predicate, _) in predicates.predicates {
27 ty::PredicateKind::RegionOutlives(_)
28 | ty::PredicateKind::TypeOutlives(_)
29 | ty::PredicateKind::WellFormed(_)
30 | ty::PredicateKind::Projection(_)
31 | ty::PredicateKind::ConstEvaluatable(..)
32 | ty::PredicateKind::ConstEquate(..) => continue,
33 ty::PredicateKind::ObjectSafe(_) => {
34 bug!("object safe predicate on function: {:#?}", predicate)
36 ty::PredicateKind::ClosureKind(..) => {
37 bug!("closure kind predicate on function: {:#?}", predicate)
39 ty::PredicateKind::Subtype(_) => {
40 bug!("subtype predicate on function: {:#?}", predicate)
42 ty::PredicateKind::Trait(pred, constness) => {
43 if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
46 match pred.skip_binder().self_ty().kind {
48 // Allow `T: ?const Trait`
49 if *constness == hir::Constness::NotConst
50 && feature_allowed(tcx, def_id, sym::const_trait_bound_opt_out)
55 let generics = tcx.generics_of(current);
56 let def = generics.type_param(p, tcx);
57 let span = tcx.def_span(def.def_id);
60 "trait bounds other than `Sized` \
61 on const fn parameters are unstable"
65 // other kinds of bounds are either tautologies
66 // or cause errors in other passes
72 match predicates.parent {
73 Some(parent) => current = parent,
78 for local in &body.local_decls {
79 check_ty(tcx, local.ty, local.source_info.span, def_id)?;
81 // impl trait is gone in MIR, so check the return type manually
84 tcx.fn_sig(def_id).output().skip_binder(),
85 body.local_decls.iter().next().unwrap().source_info.span,
89 for bb in body.basic_blocks() {
90 check_terminator(tcx, body, def_id, bb.terminator())?;
91 for stmt in &bb.statements {
92 check_statement(tcx, body, def_id, stmt)?;
98 fn check_ty(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span, fn_def_id: DefId) -> McfResult {
99 for arg in ty.walk() {
100 let ty = match arg.unpack() {
101 GenericArgKind::Type(ty) => ty,
103 // No constraints on lifetimes or constants, except potentially
104 // constants' types, but `walk` will get to them as well.
105 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
109 ty::Ref(_, _, hir::Mutability::Mut) => {
110 if !feature_allowed(tcx, fn_def_id, sym::const_mut_refs) {
111 return Err((span, "mutable references in const fn are unstable".into()));
114 ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
116 if !tcx.const_fn_is_allowed_fn_ptr(fn_def_id) {
117 return Err((span, "function pointers in const fn are unstable".into()));
120 ty::Dynamic(preds, _) => {
121 for pred in preds.iter() {
122 match pred.skip_binder() {
123 ty::ExistentialPredicate::AutoTrait(_)
124 | ty::ExistentialPredicate::Projection(_) => {
127 "trait bounds other than `Sized` \
128 on const fn parameters are unstable"
132 ty::ExistentialPredicate::Trait(trait_ref) => {
133 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
136 "trait bounds other than `Sized` \
137 on const fn parameters are unstable"
155 rvalue: &Rvalue<'tcx>,
159 Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
160 check_operand(tcx, operand, span, def_id, body)
163 | Rvalue::Discriminant(place)
164 | Rvalue::Ref(_, _, place)
165 | Rvalue::AddressOf(_, place) => check_place(tcx, *place, span, def_id, body),
166 Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
167 use rustc_middle::ty::cast::CastTy;
168 let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
169 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
170 match (cast_in, cast_out) {
171 (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
172 Err((span, "casting pointers to ints is unstable in const fn".into()))
174 _ => check_operand(tcx, operand, span, def_id, body),
178 CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer),
181 ) => check_operand(tcx, operand, span, def_id, body),
184 PointerCast::UnsafeFnPointer
185 | PointerCast::ClosureFnPointer(_)
186 | PointerCast::ReifyFnPointer,
190 ) => Err((span, "function pointer casts are not allowed in const fn".into())),
191 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), _, _) => {
192 Err((span, "unsizing casts are not allowed in const fn".into()))
194 // binops are fine on integers
195 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
196 check_operand(tcx, lhs, span, def_id, body)?;
197 check_operand(tcx, rhs, span, def_id, body)?;
198 let ty = lhs.ty(body, tcx);
199 if ty.is_integral() || ty.is_bool() || ty.is_char() {
202 Err((span, "only int, `bool` and `char` operations are stable in const fn".into()))
205 Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
206 Rvalue::NullaryOp(NullOp::Box, _) => {
207 Err((span, "heap allocations are not allowed in const fn".into()))
209 Rvalue::UnaryOp(_, operand) => {
210 let ty = operand.ty(body, tcx);
211 if ty.is_integral() || ty.is_bool() {
212 check_operand(tcx, operand, span, def_id, body)
214 Err((span, "only int and `bool` operations are stable in const fn".into()))
217 Rvalue::Aggregate(_, operands) => {
218 for operand in operands {
219 check_operand(tcx, operand, span, def_id, body)?;
230 statement: &Statement<'tcx>,
232 let span = statement.source_info.span;
233 match &statement.kind {
234 StatementKind::Assign(box (place, rval)) => {
235 check_place(tcx, *place, span, def_id, body)?;
236 check_rvalue(tcx, body, def_id, rval, span)
239 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _)
240 if !feature_allowed(tcx, def_id, sym::const_if_match) =>
242 Err((span, "loops and conditional expressions are not stable in const fn".into()))
245 StatementKind::FakeRead(_, place) => check_place(tcx, **place, span, def_id, body),
247 // just an assignment
248 StatementKind::SetDiscriminant { place, .. } => {
249 check_place(tcx, **place, span, def_id, body)
252 StatementKind::LlvmInlineAsm { .. } => {
253 Err((span, "cannot use inline assembly in const fn".into()))
256 // These are all NOPs
257 StatementKind::StorageLive(_)
258 | StatementKind::StorageDead(_)
259 | StatementKind::Retag { .. }
260 | StatementKind::AscribeUserType(..)
261 | StatementKind::Nop => Ok(()),
267 operand: &Operand<'tcx>,
273 Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, def_id, body),
274 Operand::Constant(c) => match c.check_static_ptr(tcx) {
275 Some(_) => Err((span, "cannot access `static` items in const fn".into())),
288 let mut cursor = place.projection.as_ref();
289 while let &[ref proj_base @ .., elem] = cursor {
292 ProjectionElem::Field(..) => {
293 let base_ty = Place::ty_from(place.local, &proj_base, body, tcx).ty;
294 if let Some(def) = base_ty.ty_adt_def() {
295 // No union field accesses in `const fn`
297 if !feature_allowed(tcx, def_id, sym::const_fn_union) {
298 return Err((span, "accessing union fields is unstable".into()));
303 ProjectionElem::ConstantIndex { .. }
304 | ProjectionElem::Downcast(..)
305 | ProjectionElem::Subslice { .. }
306 | ProjectionElem::Deref
307 | ProjectionElem::Index(_) => {}
314 /// Returns `true` if the given feature gate is allowed within the function with the given `DefId`.
315 fn feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
316 // All features require that the corresponding gate be enabled,
317 // even if the function has `#[allow_internal_unstable(the_gate)]`.
318 if !tcx.features().enabled(feature_gate) {
322 // If this crate is not using stability attributes, or this function is not claiming to be a
323 // stable `const fn`, that is all that is required.
324 if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
328 // However, we cannot allow stable `const fn`s to use unstable features without an explicit
329 // opt-in via `allow_internal_unstable`.
330 attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
331 .map_or(false, |mut features| features.any(|name| name == feature_gate))
336 body: &'a Body<'tcx>,
338 terminator: &Terminator<'tcx>,
340 let span = terminator.source_info.span;
341 match &terminator.kind {
342 TerminatorKind::FalseEdges { .. }
343 | TerminatorKind::FalseUnwind { .. }
344 | TerminatorKind::Goto { .. }
345 | TerminatorKind::Return
346 | TerminatorKind::Resume
347 | TerminatorKind::Unreachable => Ok(()),
349 TerminatorKind::Drop { location, .. } => check_place(tcx, *location, span, def_id, body),
350 TerminatorKind::DropAndReplace { location, value, .. } => {
351 check_place(tcx, *location, span, def_id, body)?;
352 check_operand(tcx, value, span, def_id, body)
355 TerminatorKind::SwitchInt { .. } if !feature_allowed(tcx, def_id, sym::const_if_match) => {
356 Err((span, "loops and conditional expressions are not stable in const fn".into()))
359 TerminatorKind::SwitchInt { discr, switch_ty: _, values: _, targets: _ } => {
360 check_operand(tcx, discr, span, def_id, body)
363 TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())),
364 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
365 Err((span, "const fn generators are unstable".into()))
368 TerminatorKind::Call { func, args, from_hir_call: _, destination: _, cleanup: _ } => {
369 let fn_ty = func.ty(body, tcx);
370 if let ty::FnDef(def_id, _) = fn_ty.kind {
371 if !crate::const_eval::is_min_const_fn(tcx, def_id) {
375 "can only call other `const fn` within a `const fn`, \
376 but `{:?}` is not stable as `const fn`",
383 check_operand(tcx, func, span, def_id, body)?;
386 check_operand(tcx, arg, span, def_id, body)?;
390 Err((span, "can only call other const fns within const fn".into()))
394 TerminatorKind::Assert { cond, expected: _, msg: _, target: _, cleanup: _ } => {
395 check_operand(tcx, cond, span, def_id, body)
398 TerminatorKind::InlineAsm { .. } => {
399 Err((span, "cannot use inline assembly in const fn".into()))