]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/qualify_min_const_fn.rs
d927553c72e8b4afdc1bd9eb2b31ba70688d9555
[rust.git] / src / librustc_mir / transform / qualify_min_const_fn.rs
1 use rustc::mir::*;
2 use rustc::ty::{self, adjustment::PointerCast, Predicate, Ty, TyCtxt};
3 use rustc_hir as hir;
4 use rustc_hir::def_id::DefId;
5 use rustc_span::symbol::{sym, Symbol};
6 use rustc_span::Span;
7 use std::borrow::Cow;
8 use syntax::attr;
9
10 type McfResult = Result<(), (Span, Cow<'static, str>)>;
11
12 pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>) -> McfResult {
13     let mut current = def_id;
14     loop {
15         let predicates = tcx.predicates_of(current);
16         for (predicate, _) in predicates.predicates {
17             match predicate {
18                 Predicate::RegionOutlives(_)
19                 | Predicate::TypeOutlives(_)
20                 | Predicate::WellFormed(_)
21                 | Predicate::Projection(_)
22                 | Predicate::ConstEvaluatable(..) => continue,
23                 Predicate::ObjectSafe(_) => {
24                     bug!("object safe predicate on function: {:#?}", predicate)
25                 }
26                 Predicate::ClosureKind(..) => {
27                     bug!("closure kind predicate on function: {:#?}", predicate)
28                 }
29                 Predicate::Subtype(_) => bug!("subtype predicate on function: {:#?}", predicate),
30                 Predicate::Trait(pred) => {
31                     if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
32                         continue;
33                     }
34                     match pred.skip_binder().self_ty().kind {
35                         ty::Param(ref p) => {
36                             let generics = tcx.generics_of(current);
37                             let def = generics.type_param(p, tcx);
38                             let span = tcx.def_span(def.def_id);
39                             return Err((
40                                 span,
41                                 "trait bounds other than `Sized` \
42                                  on const fn parameters are unstable"
43                                     .into(),
44                             ));
45                         }
46                         // other kinds of bounds are either tautologies
47                         // or cause errors in other passes
48                         _ => continue,
49                     }
50                 }
51             }
52         }
53         match predicates.parent {
54             Some(parent) => current = parent,
55             None => break,
56         }
57     }
58
59     for local in &body.local_decls {
60         check_ty(tcx, local.ty, local.source_info.span, def_id)?;
61     }
62     // impl trait is gone in MIR, so check the return type manually
63     check_ty(
64         tcx,
65         tcx.fn_sig(def_id).output().skip_binder(),
66         body.local_decls.iter().next().unwrap().source_info.span,
67         def_id,
68     )?;
69
70     for bb in body.basic_blocks() {
71         check_terminator(tcx, body, def_id, bb.terminator())?;
72         for stmt in &bb.statements {
73             check_statement(tcx, body, def_id, stmt)?;
74         }
75     }
76     Ok(())
77 }
78
79 fn check_ty(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span, fn_def_id: DefId) -> McfResult {
80     for ty in ty.walk() {
81         match ty.kind {
82             ty::Ref(_, _, hir::Mutability::Mut) => {
83                 if !feature_allowed(tcx, fn_def_id, sym::const_mut_refs) {
84                     return Err((span, "mutable references in const fn are unstable".into()));
85                 }
86             }
87             ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
88             ty::FnPtr(..) => {
89                 if !tcx.const_fn_is_allowed_fn_ptr(fn_def_id) {
90                     return Err((span, "function pointers in const fn are unstable".into()));
91                 }
92             }
93             ty::Dynamic(preds, _) => {
94                 for pred in preds.iter() {
95                     match pred.skip_binder() {
96                         ty::ExistentialPredicate::AutoTrait(_)
97                         | ty::ExistentialPredicate::Projection(_) => {
98                             return Err((
99                                 span,
100                                 "trait bounds other than `Sized` \
101                                  on const fn parameters are unstable"
102                                     .into(),
103                             ));
104                         }
105                         ty::ExistentialPredicate::Trait(trait_ref) => {
106                             if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
107                                 return Err((
108                                     span,
109                                     "trait bounds other than `Sized` \
110                                      on const fn parameters are unstable"
111                                         .into(),
112                                 ));
113                             }
114                         }
115                     }
116                 }
117             }
118             _ => {}
119         }
120     }
121     Ok(())
122 }
123
124 fn check_rvalue(
125     tcx: TyCtxt<'tcx>,
126     body: &Body<'tcx>,
127     def_id: DefId,
128     rvalue: &Rvalue<'tcx>,
129     span: Span,
130 ) -> McfResult {
131     match rvalue {
132         Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
133             check_operand(tcx, operand, span, def_id, body)
134         }
135         Rvalue::Len(place)
136         | Rvalue::Discriminant(place)
137         | Rvalue::Ref(_, _, place)
138         | Rvalue::AddressOf(_, place) => check_place(tcx, place, span, def_id, body),
139         Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
140             use rustc::ty::cast::CastTy;
141             let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
142             let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
143             match (cast_in, cast_out) {
144                 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
145                     Err((span, "casting pointers to ints is unstable in const fn".into()))
146                 }
147                 _ => check_operand(tcx, operand, span, def_id, body),
148             }
149         }
150         Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, _)
151         | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, _) => {
152             check_operand(tcx, operand, span, def_id, body)
153         }
154         Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), _, _)
155         | Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), _, _)
156         | Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), _, _) => {
157             Err((span, "function pointer casts are not allowed in const fn".into()))
158         }
159         Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), _, _) => {
160             Err((span, "unsizing casts are not allowed in const fn".into()))
161         }
162         // binops are fine on integers
163         Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
164             check_operand(tcx, lhs, span, def_id, body)?;
165             check_operand(tcx, rhs, span, def_id, body)?;
166             let ty = lhs.ty(body, tcx);
167             if ty.is_integral() || ty.is_bool() || ty.is_char() {
168                 Ok(())
169             } else {
170                 Err((span, "only int, `bool` and `char` operations are stable in const fn".into()))
171             }
172         }
173         Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
174         Rvalue::NullaryOp(NullOp::Box, _) => {
175             Err((span, "heap allocations are not allowed in const fn".into()))
176         }
177         Rvalue::UnaryOp(_, operand) => {
178             let ty = operand.ty(body, tcx);
179             if ty.is_integral() || ty.is_bool() {
180                 check_operand(tcx, operand, span, def_id, body)
181             } else {
182                 Err((span, "only int and `bool` operations are stable in const fn".into()))
183             }
184         }
185         Rvalue::Aggregate(_, operands) => {
186             for operand in operands {
187                 check_operand(tcx, operand, span, def_id, body)?;
188             }
189             Ok(())
190         }
191     }
192 }
193
194 fn check_statement(
195     tcx: TyCtxt<'tcx>,
196     body: &Body<'tcx>,
197     def_id: DefId,
198     statement: &Statement<'tcx>,
199 ) -> McfResult {
200     let span = statement.source_info.span;
201     match &statement.kind {
202         StatementKind::Assign(box (place, rval)) => {
203             check_place(tcx, place, span, def_id, body)?;
204             check_rvalue(tcx, body, def_id, rval, span)
205         }
206
207         StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _)
208             if !feature_allowed(tcx, def_id, sym::const_if_match) =>
209         {
210             Err((span, "loops and conditional expressions are not stable in const fn".into()))
211         }
212
213         StatementKind::FakeRead(_, place) => check_place(tcx, place, span, def_id, body),
214
215         // just an assignment
216         StatementKind::SetDiscriminant { place, .. } => check_place(tcx, place, span, def_id, body),
217
218         StatementKind::InlineAsm { .. } => {
219             Err((span, "cannot use inline assembly in const fn".into()))
220         }
221
222         // These are all NOPs
223         StatementKind::StorageLive(_)
224         | StatementKind::StorageDead(_)
225         | StatementKind::Retag { .. }
226         | StatementKind::AscribeUserType(..)
227         | StatementKind::Nop => Ok(()),
228     }
229 }
230
231 fn check_operand(
232     tcx: TyCtxt<'tcx>,
233     operand: &Operand<'tcx>,
234     span: Span,
235     def_id: DefId,
236     body: &Body<'tcx>,
237 ) -> McfResult {
238     match operand {
239         Operand::Move(place) | Operand::Copy(place) => check_place(tcx, place, span, def_id, body),
240         Operand::Constant(c) => match c.check_static_ptr(tcx) {
241             Some(_) => Err((span, "cannot access `static` items in const fn".into())),
242             None => Ok(()),
243         },
244     }
245 }
246
247 fn check_place(
248     tcx: TyCtxt<'tcx>,
249     place: &Place<'tcx>,
250     span: Span,
251     def_id: DefId,
252     body: &Body<'tcx>,
253 ) -> McfResult {
254     let mut cursor = place.projection.as_ref();
255     while let &[ref proj_base @ .., elem] = cursor {
256         cursor = proj_base;
257         match elem {
258             ProjectionElem::Downcast(..) if !feature_allowed(tcx, def_id, sym::const_if_match) => {
259                 return Err((span, "`match` or `if let` in `const fn` is unstable".into()));
260             }
261             ProjectionElem::Downcast(_symbol, _variant_index) => {}
262
263             ProjectionElem::Field(..) => {
264                 let base_ty = Place::ty_from(&place.local, &proj_base, body, tcx).ty;
265                 if let Some(def) = base_ty.ty_adt_def() {
266                     // No union field accesses in `const fn`
267                     if def.is_union() {
268                         if !feature_allowed(tcx, def_id, sym::const_fn_union) {
269                             return Err((span, "accessing union fields is unstable".into()));
270                         }
271                     }
272                 }
273             }
274             ProjectionElem::ConstantIndex { .. }
275             | ProjectionElem::Subslice { .. }
276             | ProjectionElem::Deref
277             | ProjectionElem::Index(_) => {}
278         }
279     }
280
281     Ok(())
282 }
283
284 /// Returns `true` if the given feature gate is allowed within the function with the given `DefId`.
285 fn feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
286     // All features require that the corresponding gate be enabled,
287     // even if the function has `#[allow_internal_unstable(the_gate)]`.
288     if !tcx.features().enabled(feature_gate) {
289         return false;
290     }
291
292     // If this crate is not using stability attributes, or this function is not claiming to be a
293     // stable `const fn`, that is all that is required.
294     if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
295         return true;
296     }
297
298     // However, we cannot allow stable `const fn`s to use unstable features without an explicit
299     // opt-in via `allow_internal_unstable`.
300     attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
301         .map_or(false, |mut features| features.any(|name| name == feature_gate))
302 }
303
304 fn check_terminator(
305     tcx: TyCtxt<'tcx>,
306     body: &'a Body<'tcx>,
307     def_id: DefId,
308     terminator: &Terminator<'tcx>,
309 ) -> McfResult {
310     let span = terminator.source_info.span;
311     match &terminator.kind {
312         TerminatorKind::FalseEdges { .. }
313         | TerminatorKind::FalseUnwind { .. }
314         | TerminatorKind::Goto { .. }
315         | TerminatorKind::Return
316         | TerminatorKind::Resume => Ok(()),
317
318         TerminatorKind::Drop { location, .. } => check_place(tcx, location, span, def_id, body),
319         TerminatorKind::DropAndReplace { location, value, .. } => {
320             check_place(tcx, location, span, def_id, body)?;
321             check_operand(tcx, value, span, def_id, body)
322         }
323
324         TerminatorKind::SwitchInt { .. } if !feature_allowed(tcx, def_id, sym::const_if_match) => {
325             Err((span, "loops and conditional expressions are not stable in const fn".into()))
326         }
327
328         TerminatorKind::SwitchInt { discr, switch_ty: _, values: _, targets: _ } => {
329             check_operand(tcx, discr, span, def_id, body)
330         }
331
332         // FIXME(ecstaticmorse): We probably want to allow `Unreachable` unconditionally.
333         TerminatorKind::Unreachable if feature_allowed(tcx, def_id, sym::const_if_match) => Ok(()),
334
335         TerminatorKind::Abort | TerminatorKind::Unreachable => {
336             Err((span, "const fn with unreachable code is not stable".into()))
337         }
338         TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
339             Err((span, "const fn generators are unstable".into()))
340         }
341
342         TerminatorKind::Call { func, args, from_hir_call: _, destination: _, cleanup: _ } => {
343             let fn_ty = func.ty(body, tcx);
344             if let ty::FnDef(def_id, _) = fn_ty.kind {
345                 if !crate::const_eval::is_min_const_fn(tcx, def_id) {
346                     return Err((
347                         span,
348                         format!(
349                             "can only call other `const fn` within a `const fn`, \
350                              but `{:?}` is not stable as `const fn`",
351                             func,
352                         )
353                         .into(),
354                     ));
355                 }
356
357                 check_operand(tcx, func, span, def_id, body)?;
358
359                 for arg in args {
360                     check_operand(tcx, arg, span, def_id, body)?;
361                 }
362                 Ok(())
363             } else {
364                 Err((span, "can only call other const fns within const fn".into()))
365             }
366         }
367
368         TerminatorKind::Assert { cond, expected: _, msg: _, target: _, cleanup: _ } => {
369             check_operand(tcx, cond, span, def_id, body)
370         }
371     }
372 }