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