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