2 use rustc::ty::{self, adjustment::PointerCast, Predicate, Ty, TyCtxt};
4 use rustc_hir::def_id::DefId;
5 use rustc_span::symbol::{sym, Symbol};
10 type McfResult = Result<(), (Span, Cow<'static, str>)>;
12 pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>) -> McfResult {
13 let mut current = def_id;
15 let predicates = tcx.predicates_of(current);
16 for (predicate, _) in predicates.predicates {
18 Predicate::RegionOutlives(_)
19 | Predicate::TypeOutlives(_)
20 | Predicate::WellFormed(_)
21 | Predicate::Projection(_)
22 | Predicate::ConstEvaluatable(..) => continue,
23 Predicate::ObjectSafe(_) => {
24 bug!("object safe predicate on function: {:#?}", predicate)
26 Predicate::ClosureKind(..) => {
27 bug!("closure kind predicate on function: {:#?}", predicate)
29 Predicate::Subtype(_) => bug!("subtype predicate on function: {:#?}", predicate),
30 Predicate::Trait(pred) => {
31 if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
34 match pred.skip_binder().self_ty().kind {
36 let generics = tcx.generics_of(current);
37 let def = generics.type_param(p, tcx);
38 let span = tcx.def_span(def.def_id);
41 "trait bounds other than `Sized` \
42 on const fn parameters are unstable"
46 // other kinds of bounds are either tautologies
47 // or cause errors in other passes
53 match predicates.parent {
54 Some(parent) => current = parent,
59 for local in &body.local_decls {
60 check_ty(tcx, local.ty, local.source_info.span, def_id)?;
62 // impl trait is gone in MIR, so check the return type manually
65 tcx.fn_sig(def_id).output().skip_binder(),
66 body.local_decls.iter().next().unwrap().source_info.span,
70 for bb in body.basic_blocks() {
71 check_terminator(tcx, body, def_id, bb.terminator())?;
72 for stmt in &bb.statements {
73 check_statement(tcx, body, def_id, stmt)?;
79 fn check_ty(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span, fn_def_id: DefId) -> McfResult {
82 ty::Ref(_, _, hir::Mutability::Mut) => {
83 if !feature_allowed(tcx, fn_def_id, sym::const_mut_refs) {
84 return Err((span, "mutable references in const fn are unstable".into()));
87 ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
89 if !tcx.const_fn_is_allowed_fn_ptr(fn_def_id) {
90 return Err((span, "function pointers in const fn are unstable".into()));
93 ty::Dynamic(preds, _) => {
94 for pred in preds.iter() {
95 match pred.skip_binder() {
96 ty::ExistentialPredicate::AutoTrait(_)
97 | ty::ExistentialPredicate::Projection(_) => {
100 "trait bounds other than `Sized` \
101 on const fn parameters are unstable"
105 ty::ExistentialPredicate::Trait(trait_ref) => {
106 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
109 "trait bounds other than `Sized` \
110 on const fn parameters are unstable"
128 rvalue: &Rvalue<'tcx>,
132 Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
133 check_operand(tcx, operand, span, def_id, body)
136 | Rvalue::Discriminant(place)
137 | Rvalue::Ref(_, _, place)
138 | Rvalue::AddressOf(_, place) => check_place(tcx, place, span, def_id, body),
139 Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
140 use rustc::ty::cast::CastTy;
141 let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
142 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
143 match (cast_in, cast_out) {
144 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
145 Err((span, "casting pointers to ints is unstable in const fn".into()))
147 _ => check_operand(tcx, operand, span, def_id, body),
150 Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, _)
151 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, _) => {
152 check_operand(tcx, operand, span, def_id, body)
154 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), _, _)
155 | Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), _, _)
156 | Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), _, _) => {
157 Err((span, "function pointer casts are not allowed in const fn".into()))
159 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), _, _) => {
160 Err((span, "unsizing casts are not allowed in const fn".into()))
162 // binops are fine on integers
163 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
164 check_operand(tcx, lhs, span, def_id, body)?;
165 check_operand(tcx, rhs, span, def_id, body)?;
166 let ty = lhs.ty(body, tcx);
167 if ty.is_integral() || ty.is_bool() || ty.is_char() {
170 Err((span, "only int, `bool` and `char` operations are stable in const fn".into()))
173 Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
174 Rvalue::NullaryOp(NullOp::Box, _) => {
175 Err((span, "heap allocations are not allowed in const fn".into()))
177 Rvalue::UnaryOp(_, operand) => {
178 let ty = operand.ty(body, tcx);
179 if ty.is_integral() || ty.is_bool() {
180 check_operand(tcx, operand, span, def_id, body)
182 Err((span, "only int and `bool` operations are stable in const fn".into()))
185 Rvalue::Aggregate(_, operands) => {
186 for operand in operands {
187 check_operand(tcx, operand, span, def_id, body)?;
198 statement: &Statement<'tcx>,
200 let span = statement.source_info.span;
201 match &statement.kind {
202 StatementKind::Assign(box (place, rval)) => {
203 check_place(tcx, place, span, def_id, body)?;
204 check_rvalue(tcx, body, def_id, rval, span)
207 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _)
208 if !feature_allowed(tcx, def_id, sym::const_if_match) =>
210 Err((span, "loops and conditional expressions are not stable in const fn".into()))
213 StatementKind::FakeRead(_, place) => check_place(tcx, place, span, def_id, body),
215 // just an assignment
216 StatementKind::SetDiscriminant { place, .. } => check_place(tcx, place, span, def_id, body),
218 StatementKind::InlineAsm { .. } => {
219 Err((span, "cannot use inline assembly in const fn".into()))
222 // These are all NOPs
223 StatementKind::StorageLive(_)
224 | StatementKind::StorageDead(_)
225 | StatementKind::Retag { .. }
226 | StatementKind::AscribeUserType(..)
227 | StatementKind::Nop => Ok(()),
233 operand: &Operand<'tcx>,
239 Operand::Move(place) | Operand::Copy(place) => check_place(tcx, place, span, def_id, body),
240 Operand::Constant(c) => match c.check_static_ptr(tcx) {
241 Some(_) => Err((span, "cannot access `static` items in const fn".into())),
254 let mut cursor = place.projection.as_ref();
255 while let &[ref proj_base @ .., elem] = cursor {
258 ProjectionElem::Downcast(..) if !feature_allowed(tcx, def_id, sym::const_if_match) => {
259 return Err((span, "`match` or `if let` in `const fn` is unstable".into()));
261 ProjectionElem::Downcast(_symbol, _variant_index) => {}
263 ProjectionElem::Field(..) => {
264 let base_ty = Place::ty_from(&place.local, &proj_base, body, tcx).ty;
265 if let Some(def) = base_ty.ty_adt_def() {
266 // No union field accesses in `const fn`
268 if !feature_allowed(tcx, def_id, sym::const_fn_union) {
269 return Err((span, "accessing union fields is unstable".into()));
274 ProjectionElem::ConstantIndex { .. }
275 | ProjectionElem::Subslice { .. }
276 | ProjectionElem::Deref
277 | ProjectionElem::Index(_) => {}
284 /// Returns `true` if the given feature gate is allowed within the function with the given `DefId`.
285 fn feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
286 // All features require that the corresponding gate be enabled,
287 // even if the function has `#[allow_internal_unstable(the_gate)]`.
288 if !tcx.features().enabled(feature_gate) {
292 // If this crate is not using stability attributes, or this function is not claiming to be a
293 // stable `const fn`, that is all that is required.
294 if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
298 // However, we cannot allow stable `const fn`s to use unstable features without an explicit
299 // opt-in via `allow_internal_unstable`.
300 attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
301 .map_or(false, |mut features| features.any(|name| name == feature_gate))
306 body: &'a Body<'tcx>,
308 terminator: &Terminator<'tcx>,
310 let span = terminator.source_info.span;
311 match &terminator.kind {
312 TerminatorKind::FalseEdges { .. }
313 | TerminatorKind::FalseUnwind { .. }
314 | TerminatorKind::Goto { .. }
315 | TerminatorKind::Return
316 | TerminatorKind::Resume => Ok(()),
318 TerminatorKind::Drop { location, .. } => check_place(tcx, location, span, def_id, body),
319 TerminatorKind::DropAndReplace { location, value, .. } => {
320 check_place(tcx, location, span, def_id, body)?;
321 check_operand(tcx, value, span, def_id, body)
324 TerminatorKind::SwitchInt { .. } if !feature_allowed(tcx, def_id, sym::const_if_match) => {
325 Err((span, "loops and conditional expressions are not stable in const fn".into()))
328 TerminatorKind::SwitchInt { discr, switch_ty: _, values: _, targets: _ } => {
329 check_operand(tcx, discr, span, def_id, body)
332 // FIXME(ecstaticmorse): We probably want to allow `Unreachable` unconditionally.
333 TerminatorKind::Unreachable if feature_allowed(tcx, def_id, sym::const_if_match) => Ok(()),
335 TerminatorKind::Abort | TerminatorKind::Unreachable => {
336 Err((span, "const fn with unreachable code is not stable".into()))
338 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
339 Err((span, "const fn generators are unstable".into()))
342 TerminatorKind::Call { func, args, from_hir_call: _, destination: _, cleanup: _ } => {
343 let fn_ty = func.ty(body, tcx);
344 if let ty::FnDef(def_id, _) = fn_ty.kind {
345 if !crate::const_eval::is_min_const_fn(tcx, def_id) {
349 "can only call other `const fn` within a `const fn`, \
350 but `{:?}` is not stable as `const fn`",
357 check_operand(tcx, func, span, def_id, body)?;
360 check_operand(tcx, arg, span, def_id, body)?;
364 Err((span, "can only call other const fns within const fn".into()))
368 TerminatorKind::Assert { cond, expected: _, msg: _, target: _, cleanup: _ } => {
369 check_operand(tcx, cond, span, def_id, body)