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