1use crate::msrvs::{self, Msrv};
7use hir::LangItem;
8use rustc_const_eval::check_consts::ConstCx;
9use rustc_hir as hir;
10use rustc_hir::def_id::DefId;
11use rustc_hir::{RustcVersion, StableSince};
12use rustc_infer::infer::TyCtxtInferExt;
13use rustc_infer::traits::Obligation;
14use rustc_lint::LateContext;
15use rustc_middle::mir::{
16 Body, CastKind, NonDivergingIntrinsic, Operand, Place, ProjectionElem, Rvalue, Statement, StatementKind,
17 Terminator, TerminatorKind,
18};
19use rustc_middle::traits::{BuiltinImplSource, ImplSource, ObligationCause};
20use rustc_middle::ty::adjustment::PointerCoercion;
21use rustc_middle::ty::{self, GenericArgKind, Instance, TraitRef, Ty, TyCtxt};
22use rustc_span::Span;
23use rustc_span::symbol::sym;
24use rustc_trait_selection::traits::{ObligationCtxt, SelectionContext};
25use std::borrow::Cow;
26
27type McfResult = Result<(), (Span, Cow<'static, str>)>;
28
29pub fn is_min_const_fn<'tcx>(cx: &LateContext<'tcx>, body: &Body<'tcx>, msrv: Msrv) -> McfResult {
30 let def_id = body.source.def_id();
31
32 for local in &body.local_decls {
33 check_ty(cx, local.ty, local.source_info.span, msrv)?;
34 }
35 if !msrv.meets(cx, msrvs::CONST_FN_TRAIT_BOUND)
36 && let Some(sized_did) = cx.tcx.lang_items().sized_trait()
37 && let Some(meta_sized_did) = cx.tcx.lang_items().meta_sized_trait()
38 && cx.tcx.param_env(def_id).caller_bounds().iter().any(|bound| {
39 bound.as_trait_clause().is_some_and(|clause| {
40 let did = clause.def_id();
41 did != sized_did && did != meta_sized_did
42 })
43 })
44 {
45 return Err((
46 body.span,
47 "non-`Sized` trait clause before `const_fn_trait_bound` is stabilized".into(),
48 ));
49 }
50 check_ty(
52 cx,
53 cx.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip().output().skip_binder(),
54 body.local_decls.iter().next().unwrap().source_info.span,
55 msrv,
56 )?;
57
58 for bb in &*body.basic_blocks {
59 if !bb.is_cleanup {
62 check_terminator(cx, body, bb.terminator(), msrv)?;
63 for stmt in &bb.statements {
64 check_statement(cx, body, def_id, stmt, msrv)?;
65 }
66 }
67 }
68 Ok(())
69}
70
71fn check_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span, msrv: Msrv) -> McfResult {
72 for arg in ty.walk() {
73 let ty = match arg.kind() {
74 GenericArgKind::Type(ty) => ty,
75
76 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
79 };
80
81 match ty.kind() {
82 ty::Ref(_, _, hir::Mutability::Mut) if !msrv.meets(cx, msrvs::CONST_MUT_REFS) => {
83 return Err((span, "mutable references in const fn are unstable".into()));
84 },
85 ty::Alias(ty::AliasTy {
86 kind: ty::Opaque { .. },
87 ..
88 }) => return Err((span, "`impl Trait` in const fn is unstable".into())),
89 ty::FnPtr(..) => {
90 return Err((span, "function pointers in const fn are unstable".into()));
91 },
92 ty::Dynamic(preds, _) => {
93 for pred in *preds {
94 match pred.skip_binder() {
95 ty::ExistentialPredicate::AutoTrait(_) | ty::ExistentialPredicate::Projection(_) => {
96 return Err((
97 span,
98 "trait bounds other than `Sized` \
99 on const fn parameters are unstable"
100 .into(),
101 ));
102 },
103 ty::ExistentialPredicate::Trait(trait_ref) => {
104 if Some(trait_ref.def_id) != cx.tcx.lang_items().sized_trait() {
105 return Err((
106 span,
107 "trait bounds other than `Sized` \
108 on const fn parameters are unstable"
109 .into(),
110 ));
111 }
112 },
113 }
114 }
115 },
116 _ => {},
117 }
118 }
119 Ok(())
120}
121
122fn check_rvalue<'tcx>(
123 cx: &LateContext<'tcx>,
124 body: &Body<'tcx>,
125 def_id: DefId,
126 rvalue: &Rvalue<'tcx>,
127 span: Span,
128 msrv: Msrv,
129) -> McfResult {
130 match rvalue {
131 Rvalue::ThreadLocalRef(_) => Err((span, "cannot access thread local storage in const fn".into())),
132 Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) | Rvalue::RawPtr(_, place) => {
133 check_place(cx, *place, span, body, msrv)
134 },
135 Rvalue::CopyForDeref(place) => check_place(cx, *place, span, body, msrv),
136 Rvalue::Repeat(operand, _)
137 | Rvalue::Use(operand)
138 | Rvalue::WrapUnsafeBinder(operand, _)
139 | Rvalue::Cast(
140 CastKind::PointerWithExposedProvenance
141 | CastKind::IntToInt
142 | CastKind::FloatToInt
143 | CastKind::IntToFloat
144 | CastKind::FloatToFloat
145 | CastKind::FnPtrToPtr
146 | CastKind::PtrToPtr
147 | CastKind::PointerCoercion(PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, _)
148 | CastKind::Subtype,
149 operand,
150 _,
151 ) => check_operand(cx, operand, span, body, msrv),
152 Rvalue::Cast(
153 CastKind::PointerCoercion(
154 PointerCoercion::UnsafeFnPointer
155 | PointerCoercion::ClosureFnPointer(_)
156 | PointerCoercion::ReifyFnPointer(_),
157 _,
158 ),
159 _,
160 _,
161 ) => Err((span, "function pointer casts are not allowed in const fn".into())),
162 Rvalue::Cast(CastKind::PointerCoercion(PointerCoercion::Unsize, _), op, cast_ty) => {
163 let Some(pointee_ty) = cast_ty.builtin_deref(true) else {
164 return Err((span, "unsizing casts are only allowed for references right now".into()));
166 };
167 let unsized_ty = cx
168 .tcx
169 .struct_tail_for_codegen(pointee_ty, ty::TypingEnv::post_analysis(cx.tcx, def_id));
170 if let ty::Slice(_) | ty::Str = unsized_ty.kind() {
171 check_operand(cx, op, span, body, msrv)?;
172 Ok(())
174 } else {
175 Err((span, "unsizing casts are not allowed in const fn".into()))
177 }
178 },
179 Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => {
180 Err((span, "casting pointers to ints is unstable in const fn".into()))
181 },
182 Rvalue::Cast(CastKind::Transmute, _, _) => Err((
183 span,
184 "transmute can attempt to turn pointers into integers, so is unstable in const fn".into(),
185 )),
186 Rvalue::BinaryOp(_, box (lhs, rhs)) => {
188 check_operand(cx, lhs, span, body, msrv)?;
189 check_operand(cx, rhs, span, body, msrv)?;
190 let ty = lhs.ty(body, cx.tcx);
191 if ty.is_integral() || ty.is_bool() || ty.is_char() {
192 Ok(())
193 } else {
194 Err((
195 span,
196 "only int, `bool` and `char` operations are stable in const fn".into(),
197 ))
198 }
199 },
200 Rvalue::UnaryOp(_, operand) => {
201 let ty = operand.ty(body, cx.tcx);
202 if ty.is_integral() || ty.is_bool() {
203 check_operand(cx, operand, span, body, msrv)
204 } else {
205 Err((span, "only int and `bool` operations are stable in const fn".into()))
206 }
207 },
208 Rvalue::Aggregate(_, operands) => {
209 for operand in operands {
210 check_operand(cx, operand, span, body, msrv)?;
211 }
212 Ok(())
213 },
214 }
215}
216
217fn check_statement<'tcx>(
218 cx: &LateContext<'tcx>,
219 body: &Body<'tcx>,
220 def_id: DefId,
221 statement: &Statement<'tcx>,
222 msrv: Msrv,
223) -> McfResult {
224 let span = statement.source_info.span;
225 match &statement.kind {
226 StatementKind::Assign(box (place, rval)) => {
227 check_place(cx, *place, span, body, msrv)?;
228 check_rvalue(cx, body, def_id, rval, span, msrv)
229 },
230
231 StatementKind::FakeRead(box (_, place)) => check_place(cx, *place, span, body, msrv),
232 StatementKind::SetDiscriminant { place, .. } => check_place(cx, **place, span, body, msrv),
234
235 StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => check_operand(cx, op, span, body, msrv),
236
237 StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping(
238 rustc_middle::mir::CopyNonOverlapping { dst, src, count },
239 )) => {
240 check_operand(cx, dst, span, body, msrv)?;
241 check_operand(cx, src, span, body, msrv)?;
242 check_operand(cx, count, span, body, msrv)
243 },
244 StatementKind::StorageLive(_)
246 | StatementKind::StorageDead(_)
247 | StatementKind::Retag { .. }
248 | StatementKind::AscribeUserType(..)
249 | StatementKind::PlaceMention(..)
250 | StatementKind::Coverage(..)
251 | StatementKind::ConstEvalCounter
252 | StatementKind::BackwardIncompatibleDropHint { .. }
253 | StatementKind::Nop => Ok(()),
254 }
255}
256
257fn check_operand<'tcx>(
258 cx: &LateContext<'tcx>,
259 operand: &Operand<'tcx>,
260 span: Span,
261 body: &Body<'tcx>,
262 msrv: Msrv,
263) -> McfResult {
264 match operand {
265 Operand::Move(place) => {
266 if !place.projection.as_ref().is_empty()
267 && !is_ty_const_destruct(cx.tcx, place.ty(&body.local_decls, cx.tcx).ty, body)
268 {
269 return Err((
270 span,
271 "cannot drop locals with a non constant destructor in const fn".into(),
272 ));
273 }
274
275 check_place(cx, *place, span, body, msrv)
276 },
277 Operand::Copy(place) => check_place(cx, *place, span, body, msrv),
278 Operand::Constant(c) => match c.check_static_ptr(cx.tcx) {
279 Some(_) => Err((span, "cannot access `static` items in const fn".into())),
280 None => Ok(()),
281 },
282 Operand::RuntimeChecks(..) => Ok(()),
283 }
284}
285
286fn check_place<'tcx>(
287 cx: &LateContext<'tcx>,
288 place: Place<'tcx>,
289 span: Span,
290 body: &Body<'tcx>,
291 msrv: Msrv,
292) -> McfResult {
293 for (base, elem) in place.as_ref().iter_projections() {
294 match elem {
295 ProjectionElem::Field(..) => {
296 if base.ty(body, cx.tcx).ty.is_union() && !msrv.meets(cx, msrvs::CONST_FN_UNION) {
297 return Err((span, "accessing union fields is unstable".into()));
298 }
299 },
300 ProjectionElem::Deref => match base.ty(body, cx.tcx).ty.kind() {
301 ty::RawPtr(_, hir::Mutability::Mut) => {
302 return Err((span, "dereferencing raw mut pointer in const fn is unstable".into()));
303 },
304 ty::RawPtr(_, hir::Mutability::Not) if !msrv.meets(cx, msrvs::CONST_RAW_PTR_DEREF) => {
305 return Err((span, "dereferencing raw const pointer in const fn is unstable".into()));
306 },
307 _ => (),
308 },
309 ProjectionElem::ConstantIndex { .. }
310 | ProjectionElem::OpaqueCast(..)
311 | ProjectionElem::Downcast(..)
312 | ProjectionElem::Subslice { .. }
313 | ProjectionElem::Index(_)
314 | ProjectionElem::UnwrapUnsafeBinder(_) => {},
315 }
316 }
317
318 Ok(())
319}
320
321fn check_terminator<'tcx>(
322 cx: &LateContext<'tcx>,
323 body: &Body<'tcx>,
324 terminator: &Terminator<'tcx>,
325 msrv: Msrv,
326) -> McfResult {
327 let span = terminator.source_info.span;
328 match &terminator.kind {
329 TerminatorKind::FalseEdge { .. }
330 | TerminatorKind::FalseUnwind { .. }
331 | TerminatorKind::Goto { .. }
332 | TerminatorKind::Return
333 | TerminatorKind::UnwindResume
334 | TerminatorKind::UnwindTerminate(_)
335 | TerminatorKind::Unreachable => Ok(()),
336 TerminatorKind::Drop { place, .. } => {
337 if !is_ty_const_destruct(cx.tcx, place.ty(&body.local_decls, cx.tcx).ty, body) {
338 return Err((
339 span,
340 "cannot drop locals with a non constant destructor in const fn".into(),
341 ));
342 }
343 Ok(())
344 },
345 TerminatorKind::SwitchInt { discr, targets: _ } => check_operand(cx, discr, span, body, msrv),
346 TerminatorKind::CoroutineDrop | TerminatorKind::Yield { .. } => {
347 Err((span, "const fn coroutines are unstable".into()))
348 },
349 TerminatorKind::Call {
350 func,
351 args,
352 call_source: _,
353 destination: _,
354 target: _,
355 unwind: _,
356 fn_span: _,
357 }
358 | TerminatorKind::TailCall { func, args, fn_span: _ } => {
359 let fn_ty = func.ty(body, cx.tcx);
360 if let ty::FnDef(fn_def_id, fn_substs) = fn_ty.kind() {
361 let fn_def_id = match Instance::try_resolve(cx.tcx, cx.typing_env(), *fn_def_id, fn_substs) {
365 Ok(Some(fn_inst)) => fn_inst.def_id(),
366 Ok(None) => return Err((span, format!("cannot resolve instance for {func:?}").into())),
367 Err(_) => return Err((span, format!("error during instance resolution of {func:?}").into())),
368 };
369 if !is_stable_const_fn(cx, fn_def_id, msrv) {
370 return Err((
371 span,
372 format!(
373 "can only call other `const fn` within a `const fn`, \
374 but `{func:?}` is not stable as `const fn`",
375 )
376 .into(),
377 ));
378 }
379
380 if cx.tcx.is_intrinsic(fn_def_id, sym::transmute) {
385 return Err((
386 span,
387 "can only call `transmute` from const items, not `const fn`".into(),
388 ));
389 }
390
391 check_operand(cx, func, span, body, msrv)?;
392
393 for arg in args {
394 check_operand(cx, &arg.node, span, body, msrv)?;
395 }
396 Ok(())
397 } else {
398 Err((span, "can only call other const fns within const fn".into()))
399 }
400 },
401 TerminatorKind::Assert {
402 cond,
403 expected: _,
404 msg: _,
405 target: _,
406 unwind: _,
407 } => check_operand(cx, cond, span, body, msrv),
408 TerminatorKind::InlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())),
409 }
410}
411
412pub fn is_stable_const_fn(cx: &LateContext<'_>, def_id: DefId, msrv: Msrv) -> bool {
414 cx.tcx.is_const_fn(def_id)
415 && cx
416 .tcx
417 .lookup_const_stability(def_id)
418 .or_else(|| {
419 cx.tcx
420 .trait_of_assoc(def_id)
421 .and_then(|trait_def_id| cx.tcx.lookup_const_stability(trait_def_id))
422 })
423 .is_none_or(|const_stab| {
424 if let rustc_hir::StabilityLevel::Stable { since, .. } = const_stab.level {
425 let const_stab_rust_version = match since {
430 StableSince::Version(version) => version,
431 StableSince::Current => RustcVersion::CURRENT,
432 StableSince::Err(_) => return false,
433 };
434
435 msrv.meets(cx, const_stab_rust_version)
436 } else {
437 cx.tcx.features().enabled(const_stab.feature) && msrv.current(cx).is_none()
439 }
440 })
441}
442
443fn is_ty_const_destruct<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, body: &Body<'tcx>) -> bool {
444 #[expect(unused)]
446 fn is_ty_const_destruct_unused<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, body: &Body<'tcx>) -> bool {
447 if !ty.needs_drop(tcx, body.typing_env(tcx)) {
449 return false;
450 }
451
452 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(body.typing_env(tcx));
453 let obligation = Obligation::new(
455 tcx,
456 ObligationCause::dummy_with_span(body.span),
457 param_env,
458 TraitRef::new(tcx, tcx.require_lang_item(LangItem::Destruct, body.span), [ty]),
459 );
460
461 let mut selcx = SelectionContext::new(&infcx);
462 let Some(impl_src) = selcx.select(&obligation).ok().flatten() else {
463 return false;
464 };
465
466 if !matches!(
467 impl_src,
468 ImplSource::Builtin(BuiltinImplSource::Misc, _) | ImplSource::Param(_)
469 ) {
470 return false;
471 }
472
473 let ocx = ObligationCtxt::new(&infcx);
474 ocx.register_obligations(impl_src.nested_obligations());
475 ocx.evaluate_obligations_error_on_ambiguity().is_empty()
476 }
477
478 !ty.needs_drop(tcx, ConstCx::new(tcx, body).typing_env)
479}