]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/qualify_min_const_fn.rs
Rollup merge of #76695 - iximeow:trait-generic-bound-suggestion, r=estebank
[rust.git] / compiler / rustc_mir / src / 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().local_def_id_to_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(..)
34                 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => continue,
35                 ty::PredicateAtom::ObjectSafe(_) => {
36                     bug!("object safe predicate on function: {:#?}", predicate)
37                 }
38                 ty::PredicateAtom::ClosureKind(..) => {
39                     bug!("closure kind predicate on function: {:#?}", predicate)
40                 }
41                 ty::PredicateAtom::Subtype(_) => {
42                     bug!("subtype predicate on function: {:#?}", predicate)
43                 }
44                 ty::PredicateAtom::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 = if let Some(deref_ty) = cast_ty.builtin_deref(true) {
198                 deref_ty.ty
199             } else {
200                 // We cannot allow this for now.
201                 return Err((
202                     span,
203                     "unsizing casts are only allowed for references right now".into(),
204                 ));
205             };
206             let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id));
207             if let ty::Slice(_) | ty::Str = unsized_ty.kind() {
208                 check_operand(tcx, op, span, def_id, body)?;
209                 // Casting/coercing things to slices is fine.
210                 Ok(())
211             } else {
212                 // We just can't allow trait objects until we have figured out trait method calls.
213                 Err((span, "unsizing casts are not allowed in const fn".into()))
214             }
215         }
216         // binops are fine on integers
217         Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
218             check_operand(tcx, lhs, span, def_id, body)?;
219             check_operand(tcx, rhs, span, def_id, body)?;
220             let ty = lhs.ty(body, tcx);
221             if ty.is_integral() || ty.is_bool() || ty.is_char() {
222                 Ok(())
223             } else {
224                 Err((span, "only int, `bool` and `char` operations are stable in const fn".into()))
225             }
226         }
227         Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
228         Rvalue::NullaryOp(NullOp::Box, _) => {
229             Err((span, "heap allocations are not allowed in const fn".into()))
230         }
231         Rvalue::UnaryOp(_, operand) => {
232             let ty = operand.ty(body, tcx);
233             if ty.is_integral() || ty.is_bool() {
234                 check_operand(tcx, operand, span, def_id, body)
235             } else {
236                 Err((span, "only int and `bool` operations are stable in const fn".into()))
237             }
238         }
239         Rvalue::Aggregate(_, operands) => {
240             for operand in operands {
241                 check_operand(tcx, operand, span, def_id, body)?;
242             }
243             Ok(())
244         }
245     }
246 }
247
248 fn check_statement(
249     tcx: TyCtxt<'tcx>,
250     body: &Body<'tcx>,
251     def_id: DefId,
252     statement: &Statement<'tcx>,
253 ) -> McfResult {
254     let span = statement.source_info.span;
255     match &statement.kind {
256         StatementKind::Assign(box (place, rval)) => {
257             check_place(tcx, *place, span, def_id, body)?;
258             check_rvalue(tcx, body, def_id, rval, span)
259         }
260
261         StatementKind::FakeRead(_, place) => check_place(tcx, **place, span, def_id, body),
262
263         // just an assignment
264         StatementKind::SetDiscriminant { place, .. } => {
265             check_place(tcx, **place, span, def_id, body)
266         }
267
268         StatementKind::LlvmInlineAsm { .. } => {
269             Err((span, "cannot use inline assembly in const fn".into()))
270         }
271
272         // These are all NOPs
273         StatementKind::StorageLive(_)
274         | StatementKind::StorageDead(_)
275         | StatementKind::Retag { .. }
276         | StatementKind::AscribeUserType(..)
277         | StatementKind::Coverage(..)
278         | StatementKind::Nop => Ok(()),
279     }
280 }
281
282 fn check_operand(
283     tcx: TyCtxt<'tcx>,
284     operand: &Operand<'tcx>,
285     span: Span,
286     def_id: DefId,
287     body: &Body<'tcx>,
288 ) -> McfResult {
289     match operand {
290         Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, def_id, body),
291         Operand::Constant(c) => match c.check_static_ptr(tcx) {
292             Some(_) => Err((span, "cannot access `static` items in const fn".into())),
293             None => Ok(()),
294         },
295     }
296 }
297
298 fn check_place(
299     tcx: TyCtxt<'tcx>,
300     place: Place<'tcx>,
301     span: Span,
302     def_id: DefId,
303     body: &Body<'tcx>,
304 ) -> McfResult {
305     let mut cursor = place.projection.as_ref();
306     while let &[ref proj_base @ .., elem] = cursor {
307         cursor = proj_base;
308         match elem {
309             ProjectionElem::Field(..) => {
310                 let base_ty = Place::ty_from(place.local, &proj_base, body, tcx).ty;
311                 if let Some(def) = base_ty.ty_adt_def() {
312                     // No union field accesses in `const fn`
313                     if def.is_union() {
314                         if !feature_allowed(tcx, def_id, sym::const_fn_union) {
315                             return Err((span, "accessing union fields is unstable".into()));
316                         }
317                     }
318                 }
319             }
320             ProjectionElem::ConstantIndex { .. }
321             | ProjectionElem::Downcast(..)
322             | ProjectionElem::Subslice { .. }
323             | ProjectionElem::Deref
324             | ProjectionElem::Index(_) => {}
325         }
326     }
327
328     Ok(())
329 }
330
331 /// Returns `true` if the given feature gate is allowed within the function with the given `DefId`.
332 fn feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
333     // All features require that the corresponding gate be enabled,
334     // even if the function has `#[allow_internal_unstable(the_gate)]`.
335     if !tcx.features().enabled(feature_gate) {
336         return false;
337     }
338
339     // If this crate is not using stability attributes, or this function is not claiming to be a
340     // stable `const fn`, that is all that is required.
341     if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
342         return true;
343     }
344
345     // However, we cannot allow stable `const fn`s to use unstable features without an explicit
346     // opt-in via `allow_internal_unstable`.
347     attr::allow_internal_unstable(&tcx.sess, &tcx.get_attrs(def_id))
348         .map_or(false, |mut features| features.any(|name| name == feature_gate))
349 }
350
351 /// Returns `true` if the given library feature gate is allowed within the function with the given `DefId`.
352 pub fn lib_feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
353     // All features require that the corresponding gate be enabled,
354     // even if the function has `#[allow_internal_unstable(the_gate)]`.
355     if !tcx.features().declared_lib_features.iter().any(|&(sym, _)| sym == feature_gate) {
356         return false;
357     }
358
359     // If this crate is not using stability attributes, or this function is not claiming to be a
360     // stable `const fn`, that is all that is required.
361     if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
362         return true;
363     }
364
365     // However, we cannot allow stable `const fn`s to use unstable features without an explicit
366     // opt-in via `allow_internal_unstable`.
367     attr::allow_internal_unstable(&tcx.sess, &tcx.get_attrs(def_id))
368         .map_or(false, |mut features| features.any(|name| name == feature_gate))
369 }
370
371 fn check_terminator(
372     tcx: TyCtxt<'tcx>,
373     body: &'a Body<'tcx>,
374     def_id: DefId,
375     terminator: &Terminator<'tcx>,
376 ) -> McfResult {
377     let span = terminator.source_info.span;
378     match &terminator.kind {
379         TerminatorKind::FalseEdge { .. }
380         | TerminatorKind::FalseUnwind { .. }
381         | TerminatorKind::Goto { .. }
382         | TerminatorKind::Return
383         | TerminatorKind::Resume
384         | TerminatorKind::Unreachable => Ok(()),
385
386         TerminatorKind::Drop { place, .. } => check_place(tcx, *place, span, def_id, body),
387         TerminatorKind::DropAndReplace { place, value, .. } => {
388             check_place(tcx, *place, span, def_id, body)?;
389             check_operand(tcx, value, span, def_id, body)
390         }
391
392         TerminatorKind::SwitchInt { discr, switch_ty: _, values: _, targets: _ } => {
393             check_operand(tcx, discr, span, def_id, body)
394         }
395
396         TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())),
397         TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
398             Err((span, "const fn generators are unstable".into()))
399         }
400
401         TerminatorKind::Call {
402             func,
403             args,
404             from_hir_call: _,
405             destination: _,
406             cleanup: _,
407             fn_span: _,
408         } => {
409             let fn_ty = func.ty(body, tcx);
410             if let ty::FnDef(fn_def_id, _) = *fn_ty.kind() {
411                 // Allow unstable const if we opt in by using #[allow_internal_unstable]
412                 // on function or macro declaration.
413                 if !crate::const_eval::is_min_const_fn(tcx, fn_def_id)
414                     && !crate::const_eval::is_unstable_const_fn(tcx, fn_def_id)
415                         .map(|feature| {
416                             span.allows_unstable(feature)
417                                 || lib_feature_allowed(tcx, def_id, feature)
418                         })
419                         .unwrap_or(false)
420                 {
421                     return Err((
422                         span,
423                         format!(
424                             "can only call other `const fn` within a `const fn`, \
425                              but `{:?}` is not stable as `const fn`",
426                             func,
427                         )
428                         .into(),
429                     ));
430                 }
431
432                 // HACK: This is to "unstabilize" the `transmute` intrinsic
433                 // within const fns. `transmute` is allowed in all other const contexts.
434                 // This won't really scale to more intrinsics or functions. Let's allow const
435                 // transmutes in const fn before we add more hacks to this.
436                 if tcx.fn_sig(fn_def_id).abi() == RustIntrinsic
437                     && tcx.item_name(fn_def_id) == sym::transmute
438                     && !feature_allowed(tcx, def_id, sym::const_fn_transmute)
439                 {
440                     return Err((
441                         span,
442                         "can only call `transmute` from const items, not `const fn`".into(),
443                     ));
444                 }
445
446                 check_operand(tcx, func, span, fn_def_id, body)?;
447
448                 for arg in args {
449                     check_operand(tcx, arg, span, fn_def_id, body)?;
450                 }
451                 Ok(())
452             } else {
453                 Err((span, "can only call other const fns within const fn".into()))
454             }
455         }
456
457         TerminatorKind::Assert { cond, expected: _, msg: _, target: _, cleanup: _ } => {
458             check_operand(tcx, cond, span, def_id, body)
459         }
460
461         TerminatorKind::InlineAsm { .. } => {
462             Err((span, "cannot use inline assembly in const fn".into()))
463         }
464     }
465 }