1 use rustc::hir::def_id::DefId;
4 use rustc::ty::{self, Predicate, Ty, TyCtxt, adjustment::{PointerCast}};
5 use rustc_target::spec::abi;
8 use syntax::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 let mut current = def_id;
16 let predicates = tcx.predicates_of(current);
17 for (predicate, _) in predicates.predicates {
19 | Predicate::RegionOutlives(_)
20 | Predicate::TypeOutlives(_)
21 | Predicate::WellFormed(_)
22 | Predicate::Projection(_)
23 | Predicate::ConstEvaluatable(..) => continue,
24 | Predicate::ObjectSafe(_) => {
25 bug!("object safe predicate on function: {:#?}", predicate)
27 Predicate::ClosureKind(..) => {
28 bug!("closure kind predicate on function: {:#?}", predicate)
30 Predicate::Subtype(_) => bug!("subtype predicate on function: {:#?}", predicate),
31 Predicate::Trait(pred) => {
32 if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
35 match pred.skip_binder().self_ty().kind {
37 let generics = tcx.generics_of(current);
38 let def = generics.type_param(p, tcx);
39 let span = tcx.def_span(def.def_id);
42 "trait bounds other than `Sized` \
43 on const fn parameters are unstable"
47 // other kinds of bounds are either tautologies
48 // or cause errors in other passes
54 match predicates.parent {
55 Some(parent) => current = parent,
60 for local in &body.local_decls {
61 check_ty(tcx, local.ty, local.source_info.span, def_id)?;
63 // impl trait is gone in MIR, so check the return type manually
66 tcx.fn_sig(def_id).output().skip_binder(),
67 body.local_decls.iter().next().unwrap().source_info.span,
71 for bb in body.basic_blocks() {
72 check_terminator(tcx, body, def_id, bb.terminator())?;
73 for stmt in &bb.statements {
74 check_statement(tcx, body, def_id, stmt)?;
80 fn check_ty(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span, fn_def_id: DefId) -> McfResult {
83 ty::Ref(_, _, hir::Mutability::Mutable) => return Err((
85 "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)
135 Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) => {
136 check_place(tcx, place, span, def_id, body)
138 Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
139 use rustc::ty::cast::CastTy;
140 let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
141 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
142 match (cast_in, cast_out) {
143 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => Err((
145 "casting pointers to ints is unstable in const fn".into(),
147 (CastTy::RPtr(_), CastTy::Float) => bug!(),
148 (CastTy::RPtr(_), CastTy::Int(_)) => bug!(),
149 (CastTy::Ptr(_), CastTy::RPtr(_)) => bug!(),
150 _ => check_operand(tcx, operand, span, def_id, body),
153 Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, _)
154 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, _) => {
155 check_operand(tcx, operand, span, def_id, body)
157 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), _, _) |
158 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), _, _) |
159 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), _, _) => Err((
161 "function pointer casts are not allowed in const fn".into(),
163 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), _, _) => Err((
165 "unsizing casts are not allowed in const fn".into(),
167 // binops are fine on integers
168 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
169 check_operand(tcx, lhs, span, def_id, body)?;
170 check_operand(tcx, rhs, span, def_id, body)?;
171 let ty = lhs.ty(body, tcx);
172 if ty.is_integral() || ty.is_bool() || ty.is_char() {
177 "only int, `bool` and `char` operations are stable in const fn".into(),
181 Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
182 Rvalue::NullaryOp(NullOp::Box, _) => Err((
184 "heap allocations are not allowed in const fn".into(),
186 Rvalue::UnaryOp(_, operand) => {
187 let ty = operand.ty(body, tcx);
188 if ty.is_integral() || ty.is_bool() {
189 check_operand(tcx, operand, span, def_id, body)
193 "only int and `bool` operations are stable in const fn".into(),
197 Rvalue::Aggregate(_, operands) => {
198 for operand in operands {
199 check_operand(tcx, operand, span, def_id, body)?;
210 statement: &Statement<'tcx>,
212 let span = statement.source_info.span;
213 match &statement.kind {
214 StatementKind::Assign(box(place, rval)) => {
215 check_place(tcx, place, span, def_id, body)?;
216 check_rvalue(tcx, body, def_id, rval, span)
219 | StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _)
220 if !tcx.features().const_if_match
222 Err((span, "loops and conditional expressions are not stable in const fn".into()))
225 StatementKind::FakeRead(_, place) => check_place(tcx, place, span, def_id, body),
227 // just an assignment
228 StatementKind::SetDiscriminant { .. } => Ok(()),
230 | StatementKind::InlineAsm { .. } => {
231 Err((span, "cannot use inline assembly in const fn".into()))
234 // These are all NOPs
235 | StatementKind::StorageLive(_)
236 | StatementKind::StorageDead(_)
237 | StatementKind::Retag { .. }
238 | StatementKind::AscribeUserType(..)
239 | StatementKind::Nop => Ok(()),
245 operand: &Operand<'tcx>,
251 Operand::Move(place) | Operand::Copy(place) => {
252 check_place(tcx, place, span, def_id, body)
254 Operand::Constant(_) => Ok(()),
265 let mut cursor = place.projection.as_ref();
266 while let &[ref proj_base @ .., elem] = cursor {
269 ProjectionElem::Downcast(..) => {
270 return Err((span, "`match` or `if let` in `const fn` is unstable".into()));
272 ProjectionElem::Field(..) => {
273 let base_ty = Place::ty_from(&place.base, &proj_base, body, tcx).ty;
274 if let Some(def) = base_ty.ty_adt_def() {
275 // No union field accesses in `const fn`
277 if !feature_allowed(tcx, def_id, sym::const_fn_union) {
278 return Err((span, "accessing union fields is unstable".into()));
283 ProjectionElem::ConstantIndex { .. }
284 | ProjectionElem::Subslice { .. }
285 | ProjectionElem::Deref
286 | ProjectionElem::Index(_) => {}
291 PlaceBase::Static(box Static { kind: StaticKind::Static, .. }) => {
292 Err((span, "cannot access `static` items in const fn".into()))
295 | PlaceBase::Static(box Static { kind: StaticKind::Promoted(_, _), .. }) => Ok(()),
299 /// Returns whether `allow_internal_unstable(..., <feature_gate>, ...)` is present.
303 feature_gate: Symbol,
305 attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
306 .map_or(false, |mut features| features.any(|name| name == feature_gate))
311 body: &'a Body<'tcx>,
313 terminator: &Terminator<'tcx>,
315 let span = terminator.source_info.span;
316 match &terminator.kind {
317 | TerminatorKind::Goto { .. }
318 | TerminatorKind::Return
319 | TerminatorKind::Resume => Ok(()),
321 TerminatorKind::Drop { location, .. } => {
322 check_place(tcx, location, span, def_id, body)
324 TerminatorKind::DropAndReplace { location, value, .. } => {
325 check_place(tcx, location, span, def_id, body)?;
326 check_operand(tcx, value, span, def_id, body)
329 | TerminatorKind::FalseEdges { .. }
330 | TerminatorKind::SwitchInt { .. }
331 if !tcx.features().const_if_match
334 "loops and conditional expressions are not stable in const fn".into(),
337 TerminatorKind::FalseEdges { .. } => Ok(()),
338 TerminatorKind::SwitchInt { discr, switch_ty: _, values: _, targets: _ } => {
339 check_operand(tcx, discr, span, def_id, body)
342 | TerminatorKind::Abort | TerminatorKind::Unreachable => {
343 Err((span, "const fn with unreachable code is not stable".into()))
345 | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
346 Err((span, "const fn generators are unstable".into()))
349 TerminatorKind::Call {
356 let fn_ty = func.ty(body, tcx);
357 if let ty::FnDef(def_id, _) = fn_ty.kind {
359 // some intrinsics are waved through if called inside the
360 // standard library. Users never need to call them directly
361 match tcx.fn_sig(def_id).abi() {
362 abi::Abi::RustIntrinsic => if !is_intrinsic_whitelisted(tcx, def_id) {
365 "can only call a curated list of intrinsics in `min_const_fn`".into(),
368 abi::Abi::Rust if tcx.is_min_const_fn(def_id) => {},
369 abi::Abi::Rust => return Err((
372 "can only call other `const fn` within a `const fn`, \
373 but `{:?}` is not stable as `const fn`",
381 "cannot call functions with `{}` abi in `min_const_fn`",
387 check_operand(tcx, func, span, def_id, body)?;
390 check_operand(tcx, arg, span, def_id, body)?;
394 Err((span, "can only call other const fns within const fn".into()))
398 TerminatorKind::Assert {
404 } => check_operand(tcx, cond, span, def_id, body),
406 TerminatorKind::FalseUnwind { .. } => {
407 Err((span, "loops are not allowed in const fn".into()))
412 /// Returns `true` if the `def_id` refers to an intrisic which we've whitelisted
413 /// for being called from stable `const fn`s (`min_const_fn`).
415 /// Adding more intrinsics requires sign-off from @rust-lang/lang.
416 fn is_intrinsic_whitelisted(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
417 match &*tcx.item_name(def_id).as_str() {
422 | "add_with_overflow" // ~> .overflowing_add
423 | "sub_with_overflow" // ~> .overflowing_sub
424 | "mul_with_overflow" // ~> .overflowing_mul
425 | "wrapping_add" // ~> .wrapping_add
426 | "wrapping_sub" // ~> .wrapping_sub
427 | "wrapping_mul" // ~> .wrapping_mul
428 | "saturating_add" // ~> .saturating_add
429 | "saturating_sub" // ~> .saturating_sub
430 | "unchecked_shl" // ~> .wrapping_shl
431 | "unchecked_shr" // ~> .wrapping_shr
432 | "rotate_left" // ~> .rotate_left
433 | "rotate_right" // ~> .rotate_right
434 | "ctpop" // ~> .count_ones
435 | "ctlz" // ~> .leading_zeros
436 | "cttz" // ~> .trailing_zeros
437 | "bswap" // ~> .swap_bytes
438 | "bitreverse" // ~> .reverse_bits