]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/qualify_min_const_fn.rs
Rollup merge of #55013 - matthewjasper:propagate-generator-bounds, r=nikomatsakis
[rust.git] / src / librustc_mir / transform / qualify_min_const_fn.rs
1 use rustc::hir::def_id::DefId;
2 use rustc::hir;
3 use rustc::mir::*;
4 use rustc::ty::{self, Predicate, TyCtxt};
5 use std::borrow::Cow;
6 use syntax_pos::Span;
7
8 type McfResult = Result<(), (Span, Cow<'static, str>)>;
9
10 pub fn is_min_const_fn(
11     tcx: TyCtxt<'a, 'tcx, 'tcx>,
12     def_id: DefId,
13     mir: &'a Mir<'tcx>,
14 ) -> McfResult {
15     let mut current = def_id;
16     loop {
17         let predicates = tcx.predicates_of(current);
18         for (predicate, _) in &predicates.predicates {
19             match predicate {
20                 | Predicate::RegionOutlives(_)
21                 | Predicate::TypeOutlives(_)
22                 | Predicate::WellFormed(_)
23                 | Predicate::ConstEvaluatable(..) => continue,
24                 | Predicate::ObjectSafe(_) => {
25                     bug!("object safe predicate on function: {:#?}", predicate)
26                 }
27                 Predicate::ClosureKind(..) => {
28                     bug!("closure kind predicate on function: {:#?}", predicate)
29                 }
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
34                     tcx.sess
35                         .delay_span_bug(span, "projection without trait bound");
36                     continue;
37                 }
38                 Predicate::Trait(pred) => {
39                     if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
40                         continue;
41                     }
42                     match pred.skip_binder().self_ty().sty {
43                         ty::Param(ref p) => {
44                             let generics = tcx.generics_of(current);
45                             let def = generics.type_param(p, tcx);
46                             let span = tcx.def_span(def.def_id);
47                             return Err((
48                                 span,
49                                 "trait bounds other than `Sized` \
50                                  on const fn parameters are unstable"
51                                     .into(),
52                             ));
53                         }
54                         // other kinds of bounds are either tautologies
55                         // or cause errors in other passes
56                         _ => continue,
57                     }
58                 }
59             }
60         }
61         match predicates.parent {
62             Some(parent) => current = parent,
63             None => break,
64         }
65     }
66
67     for local in mir.vars_iter() {
68         return Err((
69             mir.local_decls[local].source_info.span,
70             "local variables in const fn are unstable".into(),
71         ));
72     }
73     for local in &mir.local_decls {
74         check_ty(tcx, local.ty, local.source_info.span)?;
75     }
76     // impl trait is gone in MIR, so check the return type manually
77     check_ty(
78         tcx,
79         tcx.fn_sig(def_id).output().skip_binder(),
80         mir.local_decls.iter().next().unwrap().source_info.span,
81     )?;
82
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)?;
87         }
88     }
89     Ok(())
90 }
91
92 fn check_ty(
93     tcx: TyCtxt<'a, 'tcx, 'tcx>,
94     ty: ty::Ty<'tcx>,
95     span: Span,
96 ) -> McfResult {
97     for ty in ty.walk() {
98         match ty.sty {
99             ty::Ref(_, _, hir::Mutability::MutMutable) => return Err((
100                 span,
101                 "mutable references in const fn are unstable".into(),
102             )),
103             ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
104             ty::FnPtr(..) => {
105                 return Err((span, "function pointers in const fn are unstable".into()))
106             }
107             ty::Dynamic(preds, _) => {
108                 for pred in preds.iter() {
109                     match pred.skip_binder() {
110                         | ty::ExistentialPredicate::AutoTrait(_)
111                         | ty::ExistentialPredicate::Projection(_) => {
112                             return Err((
113                                 span,
114                                 "trait bounds other than `Sized` \
115                                  on const fn parameters are unstable"
116                                     .into(),
117                             ))
118                         }
119                         ty::ExistentialPredicate::Trait(trait_ref) => {
120                             if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
121                                 return Err((
122                                     span,
123                                     "trait bounds other than `Sized` \
124                                      on const fn parameters are unstable"
125                                         .into(),
126                                 ));
127                             }
128                         }
129                     }
130                 }
131             }
132             _ => {}
133         }
134     }
135     Ok(())
136 }
137
138 fn check_rvalue(
139     tcx: TyCtxt<'a, 'tcx, 'tcx>,
140     mir: &'a Mir<'tcx>,
141     rvalue: &Rvalue<'tcx>,
142     span: Span,
143 ) -> McfResult {
144     match rvalue {
145         Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
146             check_operand(tcx, mir, operand, span)
147         }
148         Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) => {
149             check_place(tcx, mir, place, span, PlaceMode::Read)
150         }
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((
157                     span,
158                     "casting pointers to ints is unstable in const fn".into(),
159                 )),
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),
164             }
165         }
166         Rvalue::Cast(CastKind::UnsafeFnPointer, _, _) |
167         Rvalue::Cast(CastKind::ClosureFnPointer, _, _) |
168         Rvalue::Cast(CastKind::ReifyFnPointer, _, _) => Err((
169             span,
170             "function pointer casts are not allowed in const fn".into(),
171         )),
172         Rvalue::Cast(CastKind::Unsize, _, _) => Err((
173             span,
174             "unsizing casts are not allowed in const fn".into(),
175         )),
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() {
182                 Ok(())
183             } else {
184                 Err((
185                     span,
186                     "only int, `bool` and `char` operations are stable in const fn".into(),
187                 ))
188             }
189         }
190         Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
191         Rvalue::NullaryOp(NullOp::Box, _) => Err((
192             span,
193             "heap allocations are not allowed in const fn".into(),
194         )),
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)
199             } else {
200                 Err((
201                     span,
202                     "only int and `bool` operations are stable in const fn".into(),
203                 ))
204             }
205         }
206         Rvalue::Aggregate(_, operands) => {
207             for operand in operands {
208                 check_operand(tcx, mir, operand, span)?;
209             }
210             Ok(())
211         }
212     }
213 }
214
215 enum PlaceMode {
216     Assign,
217     Read,
218 }
219
220 fn check_statement(
221     tcx: TyCtxt<'a, 'tcx, 'tcx>,
222     mir: &'a Mir<'tcx>,
223     statement: &Statement<'tcx>,
224 ) -> McfResult {
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)
230         }
231
232         StatementKind::FakeRead(..) => Err((span, "match in const fn is unstable".into())),
233
234         // just an assignment
235         StatementKind::SetDiscriminant { .. } => Ok(()),
236
237         | StatementKind::InlineAsm { .. } => {
238             Err((span, "cannot use inline assembly in const fn".into()))
239         }
240
241         // These are all NOPs
242         | StatementKind::StorageLive(_)
243         | StatementKind::StorageDead(_)
244         | StatementKind::Validate(..)
245         | StatementKind::EndRegion(_)
246         | StatementKind::AscribeUserType(..)
247         | StatementKind::Nop => Ok(()),
248     }
249 }
250
251 fn check_operand(
252     tcx: TyCtxt<'a, 'tcx, 'tcx>,
253     mir: &'a Mir<'tcx>,
254     operand: &Operand<'tcx>,
255     span: Span,
256 ) -> McfResult {
257     match operand {
258         Operand::Move(place) | Operand::Copy(place) => {
259             check_place(tcx, mir, place, span, PlaceMode::Read)
260         }
261         Operand::Constant(_) => Ok(()),
262     }
263 }
264
265 fn check_place(
266     tcx: TyCtxt<'a, 'tcx, 'tcx>,
267     mir: &'a Mir<'tcx>,
268     place: &Place<'tcx>,
269     span: Span,
270     mode: PlaceMode,
271 ) -> McfResult {
272     match place {
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()))
278                 }
279             },
280             PlaceMode::Read => Ok(()),
281         },
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) => {
286             match proj.elem {
287                 | ProjectionElem::Deref | ProjectionElem::Field(..) | ProjectionElem::Index(_) => {
288                     check_place(tcx, mir, &proj.base, span, mode)
289                 }
290                 // slice patterns are unstable
291                 | ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
292                     return Err((span, "slice patterns in const fn are unstable".into()))
293                 }
294                 | ProjectionElem::Downcast(..) => {
295                     Err((span, "`match` or `if let` in `const fn` is unstable".into()))
296                 }
297             }
298         }
299     }
300 }
301
302 fn check_terminator(
303     tcx: TyCtxt<'a, 'tcx, 'tcx>,
304     mir: &'a Mir<'tcx>,
305     terminator: &Terminator<'tcx>,
306 ) -> McfResult {
307     let span = terminator.source_info.span;
308     match &terminator.kind {
309         | TerminatorKind::Goto { .. }
310         | TerminatorKind::Return
311         | TerminatorKind::Resume => Ok(()),
312
313         TerminatorKind::Drop { location, .. } => {
314             check_place(tcx, mir, location, span, PlaceMode::Read)
315         }
316         TerminatorKind::DropAndReplace { location, value, .. } => {
317             check_place(tcx, mir, location, span, PlaceMode::Read)?;
318             check_operand(tcx, mir, value, span)
319         },
320         TerminatorKind::SwitchInt { .. } => Err((
321             span,
322             "`if`, `match`, `&&` and `||` are not stable in const fn".into(),
323         )),
324         | TerminatorKind::Abort | TerminatorKind::Unreachable => {
325             Err((span, "const fn with unreachable code is not stable".into()))
326         }
327         | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
328             Err((span, "const fn generators are unstable".into()))
329         }
330
331         TerminatorKind::Call {
332             func,
333             args,
334             from_hir_call: _,
335             destination: _,
336             cleanup: _,
337         } => {
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)?;
342
343                     for arg in args {
344                         check_operand(tcx, mir, arg, span)?;
345                     }
346                     Ok(())
347                 } else {
348                     Err((
349                         span,
350                         "can only call other `min_const_fn` within a `min_const_fn`".into(),
351                     ))
352                 }
353             } else {
354                 Err((span, "can only call other const fns within const fn".into()))
355             }
356         }
357
358         TerminatorKind::Assert {
359             cond,
360             expected: _,
361             msg: _,
362             target: _,
363             cleanup: _,
364         } => check_operand(tcx, mir, cond, span),
365
366         | TerminatorKind::FalseEdges { .. } | TerminatorKind::FalseUnwind { .. } => span_bug!(
367             terminator.source_info.span,
368             "min_const_fn encountered `{:#?}`",
369             terminator
370         ),
371     }
372 }