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