1 use rustc_attr as attr;
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};
11 type McfResult = Result<(), (Span, Cow<'static, str>)>;
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()));
22 let mut current = def_id;
24 let predicates = tcx.predicates_of(current);
25 for (predicate, _) in predicates.predicates {
26 match predicate.kind() {
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)
36 ty::PredicateKind::ClosureKind(..) => {
37 bug!("closure kind predicate on function: {:#?}", predicate)
39 ty::PredicateKind::Subtype(_) => {
40 bug!("subtype predicate on function: {:#?}", predicate)
42 &ty::PredicateKind::Trait(pred, constness) => {
43 if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
46 match pred.skip_binder().self_ty().kind {
48 // Allow `T: ?const Trait`
49 if constness == hir::Constness::NotConst
50 && feature_allowed(tcx, def_id, sym::const_trait_bound_opt_out)
55 let generics = tcx.generics_of(current);
56 let def = generics.type_param(p, tcx);
57 let span = tcx.def_span(def.def_id);
60 "trait bounds other than `Sized` \
61 on const fn parameters are unstable"
65 // other kinds of bounds are either tautologies
66 // or cause errors in other passes
72 match predicates.parent {
73 Some(parent) => current = parent,
78 for local in &body.local_decls {
79 check_ty(tcx, local.ty, local.source_info.span, def_id)?;
81 // impl trait is gone in MIR, so check the return type manually
84 tcx.fn_sig(def_id).output().skip_binder(),
85 body.local_decls.iter().next().unwrap().source_info.span,
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)?;
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,
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,
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()));
114 ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
116 if !tcx.const_fn_is_allowed_fn_ptr(fn_def_id) {
117 return Err((span, "function pointers in const fn are unstable".into()));
120 ty::Dynamic(preds, _) => {
121 for pred in preds.iter() {
122 match pred.skip_binder() {
123 ty::ExistentialPredicate::AutoTrait(_)
124 | ty::ExistentialPredicate::Projection(_) => {
127 "trait bounds other than `Sized` \
128 on const fn parameters are unstable"
132 ty::ExistentialPredicate::Trait(trait_ref) => {
133 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
136 "trait bounds other than `Sized` \
137 on const fn parameters are unstable"
155 rvalue: &Rvalue<'tcx>,
159 Rvalue::ThreadLocalRef(_) => {
160 Err((span, "cannot access thread local storage in const fn".into()))
162 Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
163 check_operand(tcx, operand, span, def_id, body)
166 | Rvalue::Discriminant(place)
167 | Rvalue::Ref(_, _, place)
168 | Rvalue::AddressOf(_, place) => check_place(tcx, *place, span, def_id, body),
169 Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
170 use rustc_middle::ty::cast::CastTy;
171 let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
172 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
173 match (cast_in, cast_out) {
174 (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
175 Err((span, "casting pointers to ints is unstable in const fn".into()))
177 _ => check_operand(tcx, operand, span, def_id, body),
181 CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer),
184 ) => check_operand(tcx, operand, span, def_id, body),
187 PointerCast::UnsafeFnPointer
188 | PointerCast::ClosureFnPointer(_)
189 | PointerCast::ReifyFnPointer,
193 ) => Err((span, "function pointer casts are not allowed in const fn".into())),
194 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), op, cast_ty) => {
195 let pointee_ty = cast_ty.builtin_deref(true).unwrap().ty;
196 let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id));
197 if let ty::Slice(_) | ty::Str = unsized_ty.kind {
198 check_operand(tcx, op, span, def_id, body)?;
199 // Casting/coercing things to slices is fine.
202 // We just can't allow trait objects until we have figured out trait method calls.
203 Err((span, "unsizing casts are not allowed in const fn".into()))
206 // binops are fine on integers
207 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
208 check_operand(tcx, lhs, span, def_id, body)?;
209 check_operand(tcx, rhs, span, def_id, body)?;
210 let ty = lhs.ty(body, tcx);
211 if ty.is_integral() || ty.is_bool() || ty.is_char() {
214 Err((span, "only int, `bool` and `char` operations are stable in const fn".into()))
217 Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
218 Rvalue::NullaryOp(NullOp::Box, _) => {
219 Err((span, "heap allocations are not allowed in const fn".into()))
221 Rvalue::UnaryOp(_, operand) => {
222 let ty = operand.ty(body, tcx);
223 if ty.is_integral() || ty.is_bool() {
224 check_operand(tcx, operand, span, def_id, body)
226 Err((span, "only int and `bool` operations are stable in const fn".into()))
229 Rvalue::Aggregate(_, operands) => {
230 for operand in operands {
231 check_operand(tcx, operand, span, def_id, body)?;
242 statement: &Statement<'tcx>,
244 let span = statement.source_info.span;
245 match &statement.kind {
246 StatementKind::Assign(box (place, rval)) => {
247 check_place(tcx, *place, span, def_id, body)?;
248 check_rvalue(tcx, body, def_id, rval, span)
251 StatementKind::FakeRead(_, place) => check_place(tcx, **place, span, def_id, body),
253 // just an assignment
254 StatementKind::SetDiscriminant { place, .. } => {
255 check_place(tcx, **place, span, def_id, body)
258 StatementKind::LlvmInlineAsm { .. } => {
259 Err((span, "cannot use inline assembly in const fn".into()))
262 // These are all NOPs
263 StatementKind::StorageLive(_)
264 | StatementKind::StorageDead(_)
265 | StatementKind::Retag { .. }
266 | StatementKind::AscribeUserType(..)
267 | StatementKind::Nop => Ok(()),
273 operand: &Operand<'tcx>,
279 Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, def_id, body),
280 Operand::Constant(c) => match c.check_static_ptr(tcx) {
281 Some(_) => Err((span, "cannot access `static` items in const fn".into())),
294 let mut cursor = place.projection.as_ref();
295 while let &[ref proj_base @ .., elem] = cursor {
298 ProjectionElem::Field(..) => {
299 let base_ty = Place::ty_from(place.local, &proj_base, body, tcx).ty;
300 if let Some(def) = base_ty.ty_adt_def() {
301 // No union field accesses in `const fn`
303 if !feature_allowed(tcx, def_id, sym::const_fn_union) {
304 return Err((span, "accessing union fields is unstable".into()));
309 ProjectionElem::ConstantIndex { .. }
310 | ProjectionElem::Downcast(..)
311 | ProjectionElem::Subslice { .. }
312 | ProjectionElem::Deref
313 | ProjectionElem::Index(_) => {}
320 /// Returns `true` if the given feature gate is allowed within the function with the given `DefId`.
321 fn feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
322 // All features require that the corresponding gate be enabled,
323 // even if the function has `#[allow_internal_unstable(the_gate)]`.
324 if !tcx.features().enabled(feature_gate) {
328 // If this crate is not using stability attributes, or this function is not claiming to be a
329 // stable `const fn`, that is all that is required.
330 if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
334 // However, we cannot allow stable `const fn`s to use unstable features without an explicit
335 // opt-in via `allow_internal_unstable`.
336 attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
337 .map_or(false, |mut features| features.any(|name| name == feature_gate))
340 /// Returns `true` if the given library feature gate is allowed within the function with the given `DefId`.
341 pub fn lib_feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
342 // All features require that the corresponding gate be enabled,
343 // even if the function has `#[allow_internal_unstable(the_gate)]`.
344 if !tcx.features().declared_lib_features.iter().any(|&(sym, _)| sym == feature_gate) {
348 // If this crate is not using stability attributes, or this function is not claiming to be a
349 // stable `const fn`, that is all that is required.
350 if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
354 // However, we cannot allow stable `const fn`s to use unstable features without an explicit
355 // opt-in via `allow_internal_unstable`.
356 attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
357 .map_or(false, |mut features| features.any(|name| name == feature_gate))
362 body: &'a Body<'tcx>,
364 terminator: &Terminator<'tcx>,
366 let span = terminator.source_info.span;
367 match &terminator.kind {
368 TerminatorKind::FalseEdge { .. }
369 | TerminatorKind::FalseUnwind { .. }
370 | TerminatorKind::Goto { .. }
371 | TerminatorKind::Return
372 | TerminatorKind::Resume
373 | TerminatorKind::Unreachable => Ok(()),
375 TerminatorKind::Drop { place, .. } => check_place(tcx, *place, span, def_id, body),
376 TerminatorKind::DropAndReplace { place, value, .. } => {
377 check_place(tcx, *place, span, def_id, body)?;
378 check_operand(tcx, value, span, def_id, body)
381 TerminatorKind::SwitchInt { discr, switch_ty: _, values: _, targets: _ } => {
382 check_operand(tcx, discr, span, def_id, body)
385 TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())),
386 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
387 Err((span, "const fn generators are unstable".into()))
390 TerminatorKind::Call {
398 let fn_ty = func.ty(body, tcx);
399 if let ty::FnDef(fn_def_id, _) = fn_ty.kind {
400 // Allow unstable const if we opt in by using #[allow_internal_unstable]
401 // on function or macro declaration.
402 if !crate::const_eval::is_min_const_fn(tcx, fn_def_id)
403 && !crate::const_eval::is_unstable_const_fn(tcx, fn_def_id)
405 span.allows_unstable(feature)
406 || lib_feature_allowed(tcx, def_id, feature)
413 "can only call other `const fn` within a `const fn`, \
414 but `{:?}` is not stable as `const fn`",
421 check_operand(tcx, func, span, fn_def_id, body)?;
424 check_operand(tcx, arg, span, fn_def_id, body)?;
428 Err((span, "can only call other const fns within const fn".into()))
432 TerminatorKind::Assert { cond, expected: _, msg: _, target: _, cleanup: _ } => {
433 check_operand(tcx, cond, span, def_id, body)
436 TerminatorKind::InlineAsm { .. } => {
437 Err((span, "cannot use inline assembly in const fn".into()))