]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/qualify_min_const_fn.rs
Auto merge of #53830 - davidtwco:issue-53228, 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::Anon(..) => 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(_, 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         // 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() {
172                 Ok(())
173             } else {
174                 Err((
175                     span,
176                     "only int, `bool` and `char` operations are stable in const fn".into(),
177                 ))
178             }
179         }
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)
186             } else {
187                 Err((
188                     span,
189                     "only int and `bool` operations are stable in const fn".into(),
190                 ))
191             }
192         }
193         Rvalue::Aggregate(_, operands) => {
194             for operand in operands {
195                 check_operand(tcx, mir, operand, span)?;
196             }
197             Ok(())
198         }
199     }
200 }
201
202 enum PlaceMode {
203     Assign,
204     Read,
205 }
206
207 fn check_statement(
208     tcx: TyCtxt<'a, 'tcx, 'tcx>,
209     mir: &'a Mir<'tcx>,
210     statement: &Statement<'tcx>,
211 ) -> McfResult {
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)
217         }
218
219         StatementKind::ReadForMatch(_) => Err((span, "match in const fn is unstable".into())),
220
221         // just an assignment
222         StatementKind::SetDiscriminant { .. } => Ok(()),
223
224         | StatementKind::InlineAsm { .. } => {
225             Err((span, "cannot use inline assembly in const fn".into()))
226         }
227
228         // These are all NOPs
229         | StatementKind::StorageLive(_)
230         | StatementKind::StorageDead(_)
231         | StatementKind::Validate(..)
232         | StatementKind::EndRegion(_)
233         | StatementKind::UserAssertTy(..)
234         | StatementKind::Nop => Ok(()),
235     }
236 }
237
238 fn check_operand(
239     tcx: TyCtxt<'a, 'tcx, 'tcx>,
240     mir: &'a Mir<'tcx>,
241     operand: &Operand<'tcx>,
242     span: Span,
243 ) -> McfResult {
244     match operand {
245         Operand::Move(place) | Operand::Copy(place) => {
246             check_place(tcx, mir, place, span, PlaceMode::Read)
247         }
248         Operand::Constant(_) => Ok(()),
249     }
250 }
251
252 fn check_place(
253     tcx: TyCtxt<'a, 'tcx, 'tcx>,
254     mir: &'a Mir<'tcx>,
255     place: &Place<'tcx>,
256     span: Span,
257     mode: PlaceMode,
258 ) -> McfResult {
259     match place {
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()))
265                 }
266             },
267             PlaceMode::Read => Ok(()),
268         },
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) => {
273             match proj.elem {
274                 | ProjectionElem::Deref | ProjectionElem::Field(..) | ProjectionElem::Index(_) => {
275                     check_place(tcx, mir, &proj.base, span, mode)
276                 }
277                 // slice patterns are unstable
278                 | ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {
279                     return Err((span, "slice patterns in const fn are unstable".into()))
280                 }
281                 | ProjectionElem::Downcast(..) => {
282                     Err((span, "`match` or `if let` in `const fn` is unstable".into()))
283                 }
284             }
285         }
286     }
287 }
288
289 fn check_terminator(
290     tcx: TyCtxt<'a, 'tcx, 'tcx>,
291     mir: &'a Mir<'tcx>,
292     terminator: &Terminator<'tcx>,
293 ) -> McfResult {
294     let span = terminator.source_info.span;
295     match &terminator.kind {
296         | TerminatorKind::Goto { .. }
297         | TerminatorKind::Return
298         | TerminatorKind::Resume => Ok(()),
299
300         TerminatorKind::Drop { location, .. } => {
301             check_place(tcx, mir, location, span, PlaceMode::Read)
302         }
303         TerminatorKind::DropAndReplace { location, value, .. } => {
304             check_place(tcx, mir, location, span, PlaceMode::Read)?;
305             check_operand(tcx, mir, value, span)
306         },
307         TerminatorKind::SwitchInt { .. } => Err((
308             span,
309             "`if`, `match`, `&&` and `||` are not stable in const fn".into(),
310         )),
311         | TerminatorKind::Abort | TerminatorKind::Unreachable => {
312             Err((span, "const fn with unreachable code is not stable".into()))
313         }
314         | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
315             Err((span, "const fn generators are unstable".into()))
316         }
317
318         TerminatorKind::Call {
319             func,
320             args,
321             destination: _,
322             cleanup: _,
323         } => {
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)?;
328
329                     for arg in args {
330                         check_operand(tcx, mir, arg, span)?;
331                     }
332                     Ok(())
333                 } else {
334                     Err((
335                         span,
336                         "can only call other `min_const_fn` within a `min_const_fn`".into(),
337                     ))
338                 }
339             } else {
340                 Err((span, "can only call other const fns within const fn".into()))
341             }
342         }
343
344         TerminatorKind::Assert {
345             cond,
346             expected: _,
347             msg: _,
348             target: _,
349             cleanup: _,
350         } => check_operand(tcx, mir, cond, span),
351
352         | TerminatorKind::FalseEdges { .. } | TerminatorKind::FalseUnwind { .. } => span_bug!(
353             terminator.source_info.span,
354             "min_const_fn encountered `{:#?}`",
355             terminator
356         ),
357     }
358 }