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::Anon(..) => 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(_, 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 // binops are fine on integers
167 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
168 check_operand(tcx, mir, lhs, span)?;
169 check_operand(tcx, mir, rhs, span)?;
170 let ty = lhs.ty(mir, tcx);
171 if ty.is_integral() || ty.is_bool() || ty.is_char() {
176 "only int, `bool` and `char` operations are stable in const fn".into(),
180 // checked by regular const fn checks
181 Rvalue::NullaryOp(..) => Ok(()),
182 Rvalue::UnaryOp(_, operand) => {
183 let ty = operand.ty(mir, tcx);
184 if ty.is_integral() || ty.is_bool() {
185 check_operand(tcx, mir, operand, span)
189 "only int and `bool` operations are stable in const fn".into(),
193 Rvalue::Aggregate(_, operands) => {
194 for operand in operands {
195 check_operand(tcx, mir, operand, span)?;
208 tcx: TyCtxt<'a, 'tcx, 'tcx>,
210 statement: &Statement<'tcx>,
212 let span = statement.source_info.span;
213 match &statement.kind {
214 StatementKind::Assign(place, rval) => {
215 check_place(tcx, mir, place, span, PlaceMode::Assign)?;
216 check_rvalue(tcx, mir, rval, span)
219 StatementKind::ReadForMatch(_) => Err((span, "match in const fn is unstable".into())),
221 // just an assignment
222 StatementKind::SetDiscriminant { .. } => Ok(()),
224 | StatementKind::InlineAsm { .. } => {
225 Err((span, "cannot use inline assembly in const fn".into()))
228 // These are all NOPs
229 | StatementKind::StorageLive(_)
230 | StatementKind::StorageDead(_)
231 | StatementKind::Validate(..)
232 | StatementKind::EndRegion(_)
233 | StatementKind::UserAssertTy(..)
234 | StatementKind::Nop => Ok(()),
239 tcx: TyCtxt<'a, 'tcx, 'tcx>,
241 operand: &Operand<'tcx>,
245 Operand::Move(place) | Operand::Copy(place) => {
246 check_place(tcx, mir, place, span, PlaceMode::Read)
248 Operand::Constant(_) => Ok(()),
253 tcx: TyCtxt<'a, 'tcx, 'tcx>,
260 Place::Local(l) => match mode {
261 PlaceMode::Assign => match mir.local_kind(*l) {
262 LocalKind::Temp | LocalKind::ReturnPointer => Ok(()),
263 LocalKind::Arg | LocalKind::Var => {
264 Err((span, "assignments in const fn are unstable".into()))
267 PlaceMode::Read => Ok(()),
269 // promoteds are always fine, they are essentially constants
270 Place::Promoted(_) => Ok(()),
271 Place::Static(_) => Err((span, "cannot access `static` items in const fn".into())),
272 Place::Projection(proj) => {
274 | ProjectionElem::Deref | ProjectionElem::Field(..) | ProjectionElem::Index(_) => {
275 check_place(tcx, mir, &proj.base, span, mode)
277 // slice patterns are unstable
278 | ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
279 return Err((span, "slice patterns in const fn are unstable".into()))
281 | ProjectionElem::Downcast(..) => {
282 Err((span, "`match` or `if let` in `const fn` is unstable".into()))
290 tcx: TyCtxt<'a, 'tcx, 'tcx>,
292 terminator: &Terminator<'tcx>,
294 let span = terminator.source_info.span;
295 match &terminator.kind {
296 | TerminatorKind::Goto { .. }
297 | TerminatorKind::Return
298 | TerminatorKind::Resume => Ok(()),
300 TerminatorKind::Drop { location, .. } => {
301 check_place(tcx, mir, location, span, PlaceMode::Read)
303 TerminatorKind::DropAndReplace { location, value, .. } => {
304 check_place(tcx, mir, location, span, PlaceMode::Read)?;
305 check_operand(tcx, mir, value, span)
307 TerminatorKind::SwitchInt { .. } => Err((
309 "`if`, `match`, `&&` and `||` are not stable in const fn".into(),
311 | TerminatorKind::Abort | TerminatorKind::Unreachable => {
312 Err((span, "const fn with unreachable code is not stable".into()))
314 | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
315 Err((span, "const fn generators are unstable".into()))
318 TerminatorKind::Call {
324 let fn_ty = func.ty(mir, tcx);
325 if let ty::FnDef(def_id, _) = fn_ty.sty {
326 if tcx.is_min_const_fn(def_id) {
327 check_operand(tcx, mir, func, span)?;
330 check_operand(tcx, mir, arg, span)?;
336 "can only call other `min_const_fn` within a `min_const_fn`".into(),
340 Err((span, "can only call other const fns within const fn".into()))
344 TerminatorKind::Assert {
350 } => check_operand(tcx, mir, cond, span),
352 | TerminatorKind::FalseEdges { .. } | TerminatorKind::FalseUnwind { .. } => span_bug!(
353 terminator.source_info.span,
354 "min_const_fn encountered `{:#?}`",