1 use rustc::hir::def_id::DefId;
4 use rustc::ty::{self, Predicate, TyCtxt};
8 type McfResult = Result<(), (Span, Cow<'static, str>)>;
10 pub fn is_min_const_fn(
11 tcx: TyCtxt<'a, 'tcx, 'tcx>,
15 let mut current = def_id;
17 let predicates = tcx.predicates_of(current);
18 for (predicate, _) in &predicates.predicates {
20 | Predicate::RegionOutlives(_)
21 | Predicate::TypeOutlives(_)
22 | Predicate::WellFormed(_)
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::Projection(_) => {
32 let span = tcx.def_span(current);
33 // we'll hit a `Predicate::Trait` later which will report an error
35 .delay_span_bug(span, "projection without trait bound");
38 Predicate::Trait(pred) => {
39 if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
42 match pred.skip_binder().self_ty().sty {
44 let generics = tcx.generics_of(current);
45 let def = generics.type_param(p, tcx);
46 let span = tcx.def_span(def.def_id);
49 "trait bounds other than `Sized` \
50 on const fn parameters are unstable"
54 // other kinds of bounds are either tautologies
55 // or cause errors in other passes
61 match predicates.parent {
62 Some(parent) => current = parent,
67 for local in mir.vars_iter() {
69 mir.local_decls[local].source_info.span,
70 "local variables in const fn are unstable".into(),
73 for local in &mir.local_decls {
74 check_ty(tcx, local.ty, local.source_info.span)?;
76 // impl trait is gone in MIR, so check the return type manually
79 tcx.fn_sig(def_id).output().skip_binder(),
80 mir.local_decls.iter().next().unwrap().source_info.span,
83 for bb in mir.basic_blocks() {
84 check_terminator(tcx, mir, bb.terminator())?;
85 for stmt in &bb.statements {
86 check_statement(tcx, mir, stmt)?;
93 tcx: TyCtxt<'a, 'tcx, 'tcx>,
99 ty::Ref(_, _, hir::Mutability::MutMutable) => return Err((
101 "mutable references in const fn are unstable".into(),
103 ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
105 return Err((span, "function pointers in const fn are unstable".into()))
107 ty::Dynamic(preds, _) => {
108 for pred in preds.iter() {
109 match pred.skip_binder() {
110 | ty::ExistentialPredicate::AutoTrait(_)
111 | ty::ExistentialPredicate::Projection(_) => {
114 "trait bounds other than `Sized` \
115 on const fn parameters are unstable"
119 ty::ExistentialPredicate::Trait(trait_ref) => {
120 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
123 "trait bounds other than `Sized` \
124 on const fn parameters are unstable"
139 tcx: TyCtxt<'a, 'tcx, 'tcx>,
141 rvalue: &Rvalue<'tcx>,
145 Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
146 check_operand(tcx, mir, operand, span)
148 Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) => {
149 check_place(tcx, mir, place, span, PlaceMode::Read)
151 Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
152 use rustc::ty::cast::CastTy;
153 let cast_in = CastTy::from_ty(operand.ty(mir, tcx)).expect("bad input type for cast");
154 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
155 match (cast_in, cast_out) {
156 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => Err((
158 "casting pointers to ints is unstable in const fn".into(),
160 (CastTy::RPtr(_), CastTy::Float) => bug!(),
161 (CastTy::RPtr(_), CastTy::Int(_)) => bug!(),
162 (CastTy::Ptr(_), CastTy::RPtr(_)) => bug!(),
163 _ => check_operand(tcx, mir, operand, span),
166 Rvalue::Cast(CastKind::UnsafeFnPointer, _, _) |
167 Rvalue::Cast(CastKind::ClosureFnPointer, _, _) |
168 Rvalue::Cast(CastKind::ReifyFnPointer, _, _) => Err((
170 "function pointer casts are not allowed in const fn".into(),
172 Rvalue::Cast(CastKind::Unsize, _, _) => Err((
174 "unsizing casts are not allowed in const fn".into(),
176 // binops are fine on integers
177 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
178 check_operand(tcx, mir, lhs, span)?;
179 check_operand(tcx, mir, rhs, span)?;
180 let ty = lhs.ty(mir, tcx);
181 if ty.is_integral() || ty.is_bool() || ty.is_char() {
186 "only int, `bool` and `char` operations are stable in const fn".into(),
190 Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
191 Rvalue::NullaryOp(NullOp::Box, _) => Err((
193 "heap allocations are not allowed in const fn".into(),
195 Rvalue::UnaryOp(_, operand) => {
196 let ty = operand.ty(mir, tcx);
197 if ty.is_integral() || ty.is_bool() {
198 check_operand(tcx, mir, operand, span)
202 "only int and `bool` operations are stable in const fn".into(),
206 Rvalue::Aggregate(_, operands) => {
207 for operand in operands {
208 check_operand(tcx, mir, operand, span)?;
221 tcx: TyCtxt<'a, 'tcx, 'tcx>,
223 statement: &Statement<'tcx>,
225 let span = statement.source_info.span;
226 match &statement.kind {
227 StatementKind::Assign(place, rval) => {
228 check_place(tcx, mir, place, span, PlaceMode::Assign)?;
229 check_rvalue(tcx, mir, rval, span)
232 StatementKind::FakeRead(..) => Err((span, "match in const fn is unstable".into())),
234 // just an assignment
235 StatementKind::SetDiscriminant { .. } => Ok(()),
237 | StatementKind::InlineAsm { .. } => {
238 Err((span, "cannot use inline assembly in const fn".into()))
241 // These are all NOPs
242 | StatementKind::StorageLive(_)
243 | StatementKind::StorageDead(_)
244 | StatementKind::Validate(..)
245 | StatementKind::EndRegion(_)
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)
320 TerminatorKind::SwitchInt { .. } => Err((
322 "`if`, `match`, `&&` and `||` are not stable in const fn".into(),
324 | TerminatorKind::Abort | TerminatorKind::Unreachable => {
325 Err((span, "const fn with unreachable code is not stable".into()))
327 | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
328 Err((span, "const fn generators are unstable".into()))
331 TerminatorKind::Call {
338 let fn_ty = func.ty(mir, tcx);
339 if let ty::FnDef(def_id, _) = fn_ty.sty {
340 if tcx.is_min_const_fn(def_id) {
341 check_operand(tcx, mir, func, span)?;
344 check_operand(tcx, mir, arg, span)?;
350 "can only call other `min_const_fn` within a `min_const_fn`".into(),
354 Err((span, "can only call other const fns within const fn".into()))
358 TerminatorKind::Assert {
364 } => check_operand(tcx, mir, cond, span),
366 | TerminatorKind::FalseEdges { .. } | TerminatorKind::FalseUnwind { .. } => span_bug!(
367 terminator.source_info.span,
368 "min_const_fn encountered `{:#?}`",