]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/qualify_min_const_fn.rs
Rollup merge of #57278 - mati865:config_clippy, r=alexcrichton
[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 rustc_target::spec::abi;
6 use std::borrow::Cow;
7 use syntax_pos::Span;
8
9 type McfResult = Result<(), (Span, Cow<'static, str>)>;
10
11 pub fn is_min_const_fn(
12     tcx: TyCtxt<'a, 'tcx, 'tcx>,
13     def_id: DefId,
14     mir: &'a Mir<'tcx>,
15 ) -> McfResult {
16     let mut current = def_id;
17     loop {
18         let predicates = tcx.predicates_of(current);
19         for (predicate, _) in &predicates.predicates {
20             match predicate {
21                 | Predicate::RegionOutlives(_)
22                 | Predicate::TypeOutlives(_)
23                 | Predicate::WellFormed(_)
24                 | Predicate::ConstEvaluatable(..) => continue,
25                 | Predicate::ObjectSafe(_) => {
26                     bug!("object safe predicate on function: {:#?}", predicate)
27                 }
28                 Predicate::ClosureKind(..) => {
29                     bug!("closure kind predicate on function: {:#?}", predicate)
30                 }
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
35                     tcx.sess
36                         .delay_span_bug(span, "projection without trait bound");
37                     continue;
38                 }
39                 Predicate::Trait(pred) => {
40                     if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
41                         continue;
42                     }
43                     match pred.skip_binder().self_ty().sty {
44                         ty::Param(ref p) => {
45                             let generics = tcx.generics_of(current);
46                             let def = generics.type_param(p, tcx);
47                             let span = tcx.def_span(def.def_id);
48                             return Err((
49                                 span,
50                                 "trait bounds other than `Sized` \
51                                  on const fn parameters are unstable"
52                                     .into(),
53                             ));
54                         }
55                         // other kinds of bounds are either tautologies
56                         // or cause errors in other passes
57                         _ => continue,
58                     }
59                 }
60             }
61         }
62         match predicates.parent {
63             Some(parent) => current = parent,
64             None => break,
65         }
66     }
67
68     for local in mir.vars_iter() {
69         return Err((
70             mir.local_decls[local].source_info.span,
71             "local variables in const fn are unstable".into(),
72         ));
73     }
74     for local in &mir.local_decls {
75         check_ty(tcx, local.ty, local.source_info.span)?;
76     }
77     // impl trait is gone in MIR, so check the return type manually
78     check_ty(
79         tcx,
80         tcx.fn_sig(def_id).output().skip_binder(),
81         mir.local_decls.iter().next().unwrap().source_info.span,
82     )?;
83
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)?;
88         }
89     }
90     Ok(())
91 }
92
93 fn check_ty(
94     tcx: TyCtxt<'a, 'tcx, 'tcx>,
95     ty: ty::Ty<'tcx>,
96     span: Span,
97 ) -> McfResult {
98     for ty in ty.walk() {
99         match ty.sty {
100             ty::Ref(_, _, hir::Mutability::MutMutable) => return Err((
101                 span,
102                 "mutable references in const fn are unstable".into(),
103             )),
104             ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
105             ty::FnPtr(..) => {
106                 return Err((span, "function pointers in const fn are unstable".into()))
107             }
108             ty::Dynamic(preds, _) => {
109                 for pred in preds.iter() {
110                     match pred.skip_binder() {
111                         | ty::ExistentialPredicate::AutoTrait(_)
112                         | ty::ExistentialPredicate::Projection(_) => {
113                             return Err((
114                                 span,
115                                 "trait bounds other than `Sized` \
116                                  on const fn parameters are unstable"
117                                     .into(),
118                             ))
119                         }
120                         ty::ExistentialPredicate::Trait(trait_ref) => {
121                             if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
122                                 return Err((
123                                     span,
124                                     "trait bounds other than `Sized` \
125                                      on const fn parameters are unstable"
126                                         .into(),
127                                 ));
128                             }
129                         }
130                     }
131                 }
132             }
133             _ => {}
134         }
135     }
136     Ok(())
137 }
138
139 fn check_rvalue(
140     tcx: TyCtxt<'a, 'tcx, 'tcx>,
141     mir: &'a Mir<'tcx>,
142     rvalue: &Rvalue<'tcx>,
143     span: Span,
144 ) -> McfResult {
145     match rvalue {
146         Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
147             check_operand(tcx, mir, operand, span)
148         }
149         Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) => {
150             check_place(tcx, mir, place, span, PlaceMode::Read)
151         }
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((
158                     span,
159                     "casting pointers to ints is unstable in const fn".into(),
160                 )),
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),
165             }
166         }
167         Rvalue::Cast(CastKind::UnsafeFnPointer, _, _) |
168         Rvalue::Cast(CastKind::ClosureFnPointer, _, _) |
169         Rvalue::Cast(CastKind::ReifyFnPointer, _, _) => Err((
170             span,
171             "function pointer casts are not allowed in const fn".into(),
172         )),
173         Rvalue::Cast(CastKind::Unsize, _, _) => Err((
174             span,
175             "unsizing casts are not allowed in const fn".into(),
176         )),
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() {
183                 Ok(())
184             } else {
185                 Err((
186                     span,
187                     "only int, `bool` and `char` operations are stable in const fn".into(),
188                 ))
189             }
190         }
191         Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
192         Rvalue::NullaryOp(NullOp::Box, _) => Err((
193             span,
194             "heap allocations are not allowed in const fn".into(),
195         )),
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)
200             } else {
201                 Err((
202                     span,
203                     "only int and `bool` operations are stable in const fn".into(),
204                 ))
205             }
206         }
207         Rvalue::Aggregate(_, operands) => {
208             for operand in operands {
209                 check_operand(tcx, mir, operand, span)?;
210             }
211             Ok(())
212         }
213     }
214 }
215
216 enum PlaceMode {
217     Assign,
218     Read,
219 }
220
221 fn check_statement(
222     tcx: TyCtxt<'a, 'tcx, 'tcx>,
223     mir: &'a Mir<'tcx>,
224     statement: &Statement<'tcx>,
225 ) -> McfResult {
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)
231         }
232
233         StatementKind::FakeRead(_, place) => check_place(tcx, mir, place, span, PlaceMode::Read),
234
235         // just an assignment
236         StatementKind::SetDiscriminant { .. } => Ok(()),
237
238         | StatementKind::InlineAsm { .. } => {
239             Err((span, "cannot use inline assembly in const fn".into()))
240         }
241
242         // These are all NOPs
243         | StatementKind::StorageLive(_)
244         | StatementKind::StorageDead(_)
245         | StatementKind::Retag { .. }
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
321         TerminatorKind::FalseEdges { .. } | TerminatorKind::SwitchInt { .. } => Err((
322             span,
323             "`if`, `match`, `&&` and `||` are not stable in const fn".into(),
324         )),
325         | TerminatorKind::Abort | TerminatorKind::Unreachable => {
326             Err((span, "const fn with unreachable code is not stable".into()))
327         }
328         | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
329             Err((span, "const fn generators are unstable".into()))
330         }
331
332         TerminatorKind::Call {
333             func,
334             args,
335             from_hir_call: _,
336             destination: _,
337             cleanup: _,
338         } => {
339             let fn_ty = func.ty(mir, tcx);
340             if let ty::FnDef(def_id, _) = fn_ty.sty {
341
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()[..] {
346                         | "size_of"
347                         | "min_align_of"
348                         | "needs_drop"
349                         => {},
350                         _ => return Err((
351                             span,
352                             "can only call a curated list of intrinsics in `min_const_fn`".into(),
353                         )),
354                     },
355                     abi::Abi::Rust if tcx.is_min_const_fn(def_id) => {},
356                     abi::Abi::Rust => return Err((
357                         span,
358                         "can only call other `min_const_fn` within a `min_const_fn`".into(),
359                     )),
360                     abi => return Err((
361                         span,
362                         format!(
363                             "cannot call functions with `{}` abi in `min_const_fn`",
364                             abi,
365                         ).into(),
366                     )),
367                 }
368
369                 check_operand(tcx, mir, func, span)?;
370
371                 for arg in args {
372                     check_operand(tcx, mir, arg, span)?;
373                 }
374                 Ok(())
375             } else {
376                 Err((span, "can only call other const fns within const fn".into()))
377             }
378         }
379
380         TerminatorKind::Assert {
381             cond,
382             expected: _,
383             msg: _,
384             target: _,
385             cleanup: _,
386         } => check_operand(tcx, mir, cond, span),
387
388         TerminatorKind::FalseUnwind { .. } => {
389             Err((span, "loops are not allowed in const fn".into()))
390         },
391     }
392 }