1 use rustc::hir::def_id::DefId;
4 use rustc::ty::{self, Predicate, TyCtxt};
5 use rustc_target::spec::abi;
9 type McfResult = Result<(), (Span, Cow<'static, str>)>;
11 pub fn is_min_const_fn(
12 tcx: TyCtxt<'a, 'tcx, 'tcx>,
16 let mut current = def_id;
18 let predicates = tcx.predicates_of(current);
19 for (predicate, _) in &predicates.predicates {
21 | Predicate::RegionOutlives(_)
22 | Predicate::TypeOutlives(_)
23 | Predicate::WellFormed(_)
24 | Predicate::ConstEvaluatable(..) => continue,
25 | Predicate::ObjectSafe(_) => {
26 bug!("object safe predicate on function: {:#?}", predicate)
28 Predicate::ClosureKind(..) => {
29 bug!("closure kind predicate on function: {:#?}", predicate)
31 Predicate::Subtype(_) => bug!("subtype predicate on function: {:#?}", predicate),
32 Predicate::Projection(_) => {
33 let span = tcx.def_span(current);
34 // we'll hit a `Predicate::Trait` later which will report an error
36 .delay_span_bug(span, "projection without trait bound");
39 Predicate::Trait(pred) => {
40 if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
43 match pred.skip_binder().self_ty().sty {
45 let generics = tcx.generics_of(current);
46 let def = generics.type_param(p, tcx);
47 let span = tcx.def_span(def.def_id);
50 "trait bounds other than `Sized` \
51 on const fn parameters are unstable"
55 // other kinds of bounds are either tautologies
56 // or cause errors in other passes
62 match predicates.parent {
63 Some(parent) => current = parent,
68 for local in mir.vars_iter() {
70 mir.local_decls[local].source_info.span,
71 "local variables in const fn are unstable".into(),
74 for local in &mir.local_decls {
75 check_ty(tcx, local.ty, local.source_info.span)?;
77 // impl trait is gone in MIR, so check the return type manually
80 tcx.fn_sig(def_id).output().skip_binder(),
81 mir.local_decls.iter().next().unwrap().source_info.span,
84 for bb in mir.basic_blocks() {
85 check_terminator(tcx, mir, bb.terminator())?;
86 for stmt in &bb.statements {
87 check_statement(tcx, mir, stmt)?;
94 tcx: TyCtxt<'a, 'tcx, 'tcx>,
100 ty::Ref(_, _, hir::Mutability::MutMutable) => return Err((
102 "mutable references in const fn are unstable".into(),
104 ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
106 return Err((span, "function pointers in const fn are unstable".into()))
108 ty::Dynamic(preds, _) => {
109 for pred in preds.iter() {
110 match pred.skip_binder() {
111 | ty::ExistentialPredicate::AutoTrait(_)
112 | ty::ExistentialPredicate::Projection(_) => {
115 "trait bounds other than `Sized` \
116 on const fn parameters are unstable"
120 ty::ExistentialPredicate::Trait(trait_ref) => {
121 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
124 "trait bounds other than `Sized` \
125 on const fn parameters are unstable"
140 tcx: TyCtxt<'a, 'tcx, 'tcx>,
142 rvalue: &Rvalue<'tcx>,
146 Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
147 check_operand(tcx, mir, operand, span)
149 Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) => {
150 check_place(tcx, mir, place, span, PlaceMode::Read)
152 Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
153 use rustc::ty::cast::CastTy;
154 let cast_in = CastTy::from_ty(operand.ty(mir, tcx)).expect("bad input type for cast");
155 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
156 match (cast_in, cast_out) {
157 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => Err((
159 "casting pointers to ints is unstable in const fn".into(),
161 (CastTy::RPtr(_), CastTy::Float) => bug!(),
162 (CastTy::RPtr(_), CastTy::Int(_)) => bug!(),
163 (CastTy::Ptr(_), CastTy::RPtr(_)) => bug!(),
164 _ => check_operand(tcx, mir, operand, span),
167 Rvalue::Cast(CastKind::UnsafeFnPointer, _, _) |
168 Rvalue::Cast(CastKind::ClosureFnPointer, _, _) |
169 Rvalue::Cast(CastKind::ReifyFnPointer, _, _) => Err((
171 "function pointer casts are not allowed in const fn".into(),
173 Rvalue::Cast(CastKind::Unsize, _, _) => Err((
175 "unsizing casts are not allowed in const fn".into(),
177 // binops are fine on integers
178 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
179 check_operand(tcx, mir, lhs, span)?;
180 check_operand(tcx, mir, rhs, span)?;
181 let ty = lhs.ty(mir, tcx);
182 if ty.is_integral() || ty.is_bool() || ty.is_char() {
187 "only int, `bool` and `char` operations are stable in const fn".into(),
191 Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
192 Rvalue::NullaryOp(NullOp::Box, _) => Err((
194 "heap allocations are not allowed in const fn".into(),
196 Rvalue::UnaryOp(_, operand) => {
197 let ty = operand.ty(mir, tcx);
198 if ty.is_integral() || ty.is_bool() {
199 check_operand(tcx, mir, operand, span)
203 "only int and `bool` operations are stable in const fn".into(),
207 Rvalue::Aggregate(_, operands) => {
208 for operand in operands {
209 check_operand(tcx, mir, operand, span)?;
222 tcx: TyCtxt<'a, 'tcx, 'tcx>,
224 statement: &Statement<'tcx>,
226 let span = statement.source_info.span;
227 match &statement.kind {
228 StatementKind::Assign(place, rval) => {
229 check_place(tcx, mir, place, span, PlaceMode::Assign)?;
230 check_rvalue(tcx, mir, rval, span)
233 StatementKind::FakeRead(_, place) => check_place(tcx, mir, place, span, PlaceMode::Read),
235 // just an assignment
236 StatementKind::SetDiscriminant { .. } => Ok(()),
238 | StatementKind::InlineAsm { .. } => {
239 Err((span, "cannot use inline assembly in const fn".into()))
242 // These are all NOPs
243 | StatementKind::StorageLive(_)
244 | StatementKind::StorageDead(_)
245 | StatementKind::Retag { .. }
246 | StatementKind::AscribeUserType(..)
247 | StatementKind::Nop => Ok(()),
252 tcx: TyCtxt<'a, 'tcx, 'tcx>,
254 operand: &Operand<'tcx>,
258 Operand::Move(place) | Operand::Copy(place) => {
259 check_place(tcx, mir, place, span, PlaceMode::Read)
261 Operand::Constant(_) => Ok(()),
266 tcx: TyCtxt<'a, 'tcx, 'tcx>,
273 Place::Local(l) => match mode {
274 PlaceMode::Assign => match mir.local_kind(*l) {
275 LocalKind::Temp | LocalKind::ReturnPointer => Ok(()),
276 LocalKind::Arg | LocalKind::Var => {
277 Err((span, "assignments in const fn are unstable".into()))
280 PlaceMode::Read => Ok(()),
282 // promoteds are always fine, they are essentially constants
283 Place::Promoted(_) => Ok(()),
284 Place::Static(_) => Err((span, "cannot access `static` items in const fn".into())),
285 Place::Projection(proj) => {
287 | ProjectionElem::Deref | ProjectionElem::Field(..) | ProjectionElem::Index(_) => {
288 check_place(tcx, mir, &proj.base, span, mode)
290 // slice patterns are unstable
291 | ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
292 return Err((span, "slice patterns in const fn are unstable".into()))
294 | ProjectionElem::Downcast(..) => {
295 Err((span, "`match` or `if let` in `const fn` is unstable".into()))
303 tcx: TyCtxt<'a, 'tcx, 'tcx>,
305 terminator: &Terminator<'tcx>,
307 let span = terminator.source_info.span;
308 match &terminator.kind {
309 | TerminatorKind::Goto { .. }
310 | TerminatorKind::Return
311 | TerminatorKind::Resume => Ok(()),
313 TerminatorKind::Drop { location, .. } => {
314 check_place(tcx, mir, location, span, PlaceMode::Read)
316 TerminatorKind::DropAndReplace { location, value, .. } => {
317 check_place(tcx, mir, location, span, PlaceMode::Read)?;
318 check_operand(tcx, mir, value, span)
321 TerminatorKind::FalseEdges { .. } | TerminatorKind::SwitchInt { .. } => Err((
323 "`if`, `match`, `&&` and `||` are not stable in const fn".into(),
325 | TerminatorKind::Abort | TerminatorKind::Unreachable => {
326 Err((span, "const fn with unreachable code is not stable".into()))
328 | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
329 Err((span, "const fn generators are unstable".into()))
332 TerminatorKind::Call {
339 let fn_ty = func.ty(mir, tcx);
340 if let ty::FnDef(def_id, _) = fn_ty.sty {
342 // some intrinsics are waved through if called inside the
343 // standard library. Users never need to call them directly
344 match tcx.fn_sig(def_id).abi() {
345 abi::Abi::RustIntrinsic => match &tcx.item_name(def_id).as_str()[..] {
352 "can only call a curated list of intrinsics in `min_const_fn`".into(),
355 abi::Abi::Rust if tcx.is_min_const_fn(def_id) => {},
356 abi::Abi::Rust => return Err((
358 "can only call other `min_const_fn` within a `min_const_fn`".into(),
363 "cannot call functions with `{}` abi in `min_const_fn`",
369 check_operand(tcx, mir, func, span)?;
372 check_operand(tcx, mir, arg, span)?;
376 Err((span, "can only call other const fns within const fn".into()))
380 TerminatorKind::Assert {
386 } => check_operand(tcx, mir, cond, span),
388 TerminatorKind::FalseUnwind { .. } => {
389 Err((span, "loops are not allowed in const fn".into()))