Skip to main content

clippy_utils/
qualify_min_const_fn.rs

1// This code used to be a part of `rustc` but moved to Clippy as a result of
2// https://github.com/rust-lang/rust/issues/76618. Because of that, it contains unused code and some
3// of terminologies might not be relevant in the context of Clippy. Note that its behavior might
4// differ from the time of `rustc` even if the name stays the same.
5
6use 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    // impl trait is gone in MIR, so check the return type manually
51    check_ty(
52        cx,
53        cx.tcx
54            .fn_sig(def_id)
55            .instantiate_identity()
56            .skip_norm_wip()
57            .output()
58            .skip_binder(),
59        body.local_decls.iter().next().unwrap().source_info.span,
60        msrv,
61    )?;
62
63    for bb in &*body.basic_blocks {
64        // Cleanup blocks are ignored entirely by const eval, so we can too:
65        // https://github.com/rust-lang/rust/blob/1dea922ea6e74f99a0e97de5cdb8174e4dea0444/compiler/rustc_const_eval/src/transform/check_consts/check.rs#L382
66        if !bb.is_cleanup {
67            check_terminator(cx, body, bb.terminator(), msrv)?;
68            for stmt in &bb.statements {
69                check_statement(cx, body, def_id, stmt, msrv)?;
70            }
71        }
72    }
73    Ok(())
74}
75
76fn check_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span, msrv: Msrv) -> McfResult {
77    for arg in ty.walk() {
78        let ty = match arg.kind() {
79            GenericArgKind::Type(ty) => ty,
80
81            // No constraints on lifetimes or constants, except potentially
82            // constants' types, but `walk` will get to them as well.
83            GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
84        };
85
86        match ty.kind() {
87            ty::Ref(_, _, hir::Mutability::Mut) if !msrv.meets(cx, msrvs::CONST_MUT_REFS) => {
88                return Err((span, "mutable references in const fn are unstable".into()));
89            },
90            ty::Alias(ty::AliasTy {
91                kind: ty::Opaque { .. },
92                ..
93            }) => return Err((span, "`impl Trait` in const fn is unstable".into())),
94            ty::FnPtr(..) => {
95                return Err((span, "function pointers in const fn are unstable".into()));
96            },
97            ty::Dynamic(preds, _) => {
98                for pred in *preds {
99                    match pred.skip_binder() {
100                        ty::ExistentialPredicate::AutoTrait(_) | ty::ExistentialPredicate::Projection(_) => {
101                            return Err((
102                                span,
103                                "trait bounds other than `Sized` \
104                                 on const fn parameters are unstable"
105                                    .into(),
106                            ));
107                        },
108                        ty::ExistentialPredicate::Trait(trait_ref) => {
109                            if Some(trait_ref.def_id) != cx.tcx.lang_items().sized_trait() {
110                                return Err((
111                                    span,
112                                    "trait bounds other than `Sized` \
113                                     on const fn parameters are unstable"
114                                        .into(),
115                                ));
116                            }
117                        },
118                    }
119                }
120            },
121            _ => {},
122        }
123    }
124    Ok(())
125}
126
127fn check_rvalue<'tcx>(
128    cx: &LateContext<'tcx>,
129    body: &Body<'tcx>,
130    def_id: DefId,
131    rvalue: &Rvalue<'tcx>,
132    span: Span,
133    msrv: Msrv,
134) -> McfResult {
135    match rvalue {
136        Rvalue::ThreadLocalRef(_) => Err((span, "cannot access thread local storage in const fn".into())),
137        Rvalue::Discriminant(place)
138        | Rvalue::Ref(_, _, place)
139        | Rvalue::Reborrow(_, _, place)
140        | Rvalue::RawPtr(_, place)
141        | Rvalue::CopyForDeref(place) => check_place(cx, *place, span, body, msrv),
142        Rvalue::Repeat(operand, _)
143        | Rvalue::Use(operand, _)
144        | Rvalue::WrapUnsafeBinder(operand, _)
145        | Rvalue::Cast(
146            CastKind::PointerWithExposedProvenance
147            | CastKind::IntToInt
148            | CastKind::FloatToInt
149            | CastKind::IntToFloat
150            | CastKind::FloatToFloat
151            | CastKind::FnPtrToPtr
152            | CastKind::PtrToPtr
153            | CastKind::PointerCoercion(PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, _)
154            | CastKind::Subtype,
155            operand,
156            _,
157        ) => check_operand(cx, operand, span, body, msrv),
158        Rvalue::Cast(
159            CastKind::PointerCoercion(
160                PointerCoercion::UnsafeFnPointer
161                | PointerCoercion::ClosureFnPointer(_)
162                | PointerCoercion::ReifyFnPointer(_),
163                _,
164            ),
165            _,
166            _,
167        ) => Err((span, "function pointer casts are not allowed in const fn".into())),
168        Rvalue::Cast(CastKind::PointerCoercion(PointerCoercion::Unsize, _), op, cast_ty) => {
169            let Some(pointee_ty) = cast_ty.builtin_deref(true) else {
170                // We cannot allow this for now.
171                return Err((span, "unsizing casts are only allowed for references right now".into()));
172            };
173            let unsized_ty = cx
174                .tcx
175                .struct_tail_for_codegen(pointee_ty, ty::TypingEnv::post_analysis(cx.tcx, def_id));
176            if let ty::Slice(_) | ty::Str = unsized_ty.kind() {
177                check_operand(cx, op, span, body, msrv)?;
178                // Casting/coercing things to slices is fine.
179                Ok(())
180            } else {
181                // We just can't allow trait objects until we have figured out trait method calls.
182                Err((span, "unsizing casts are not allowed in const fn".into()))
183            }
184        },
185        Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => {
186            Err((span, "casting pointers to ints is unstable in const fn".into()))
187        },
188        Rvalue::Cast(CastKind::Transmute, _, _) => Err((
189            span,
190            "transmute can attempt to turn pointers into integers, so is unstable in const fn".into(),
191        )),
192        // binops are fine on integers
193        Rvalue::BinaryOp(_, box (lhs, rhs)) => {
194            check_operand(cx, lhs, span, body, msrv)?;
195            check_operand(cx, rhs, span, body, msrv)?;
196            let ty = lhs.ty(body, cx.tcx);
197            if ty.is_integral() || ty.is_bool() || ty.is_char() {
198                Ok(())
199            } else {
200                Err((
201                    span,
202                    "only int, `bool` and `char` operations are stable in const fn".into(),
203                ))
204            }
205        },
206        Rvalue::UnaryOp(_, operand) => {
207            let ty = operand.ty(body, cx.tcx);
208            if ty.is_integral() || ty.is_bool() {
209                check_operand(cx, operand, span, body, msrv)
210            } else {
211                Err((span, "only int and `bool` operations are stable in const fn".into()))
212            }
213        },
214        Rvalue::Aggregate(_, operands) => {
215            for operand in operands {
216                check_operand(cx, operand, span, body, msrv)?;
217            }
218            Ok(())
219        },
220    }
221}
222
223fn check_statement<'tcx>(
224    cx: &LateContext<'tcx>,
225    body: &Body<'tcx>,
226    def_id: DefId,
227    statement: &Statement<'tcx>,
228    msrv: Msrv,
229) -> McfResult {
230    let span = statement.source_info.span;
231    match &statement.kind {
232        StatementKind::Assign(box (place, rval)) => {
233            check_place(cx, *place, span, body, msrv)?;
234            check_rvalue(cx, body, def_id, rval, span, msrv)
235        },
236
237        StatementKind::FakeRead(box (_, place)) => check_place(cx, *place, span, body, msrv),
238        // just an assignment
239        StatementKind::SetDiscriminant { place, .. } => check_place(cx, **place, span, body, msrv),
240
241        StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => check_operand(cx, op, span, body, msrv),
242
243        StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping(
244            rustc_middle::mir::CopyNonOverlapping { dst, src, count },
245        )) => {
246            check_operand(cx, dst, span, body, msrv)?;
247            check_operand(cx, src, span, body, msrv)?;
248            check_operand(cx, count, span, body, msrv)
249        },
250        // These are all NOPs
251        StatementKind::StorageLive(_)
252        | StatementKind::StorageDead(_)
253        | StatementKind::AscribeUserType(..)
254        | StatementKind::PlaceMention(..)
255        | StatementKind::Coverage(..)
256        | StatementKind::ConstEvalCounter
257        | StatementKind::BackwardIncompatibleDropHint { .. }
258        | StatementKind::Nop => Ok(()),
259    }
260}
261
262fn check_operand<'tcx>(
263    cx: &LateContext<'tcx>,
264    operand: &Operand<'tcx>,
265    span: Span,
266    body: &Body<'tcx>,
267    msrv: Msrv,
268) -> McfResult {
269    match operand {
270        Operand::Move(place) => {
271            if !place.projection.as_ref().is_empty()
272                && !is_ty_const_destruct(cx.tcx, place.ty(&body.local_decls, cx.tcx).ty, body)
273            {
274                return Err((
275                    span,
276                    "cannot drop locals with a non constant destructor in const fn".into(),
277                ));
278            }
279
280            check_place(cx, *place, span, body, msrv)
281        },
282        Operand::Copy(place) => check_place(cx, *place, span, body, msrv),
283        Operand::Constant(c) => match c.check_static_ptr(cx.tcx) {
284            Some(_) => Err((span, "cannot access `static` items in const fn".into())),
285            None => Ok(()),
286        },
287        Operand::RuntimeChecks(..) => Ok(()),
288    }
289}
290
291fn check_place<'tcx>(
292    cx: &LateContext<'tcx>,
293    place: Place<'tcx>,
294    span: Span,
295    body: &Body<'tcx>,
296    msrv: Msrv,
297) -> McfResult {
298    for (base, elem) in place.as_ref().iter_projections() {
299        match elem {
300            ProjectionElem::Field(..) => {
301                if base.ty(body, cx.tcx).ty.is_union() && !msrv.meets(cx, msrvs::CONST_FN_UNION) {
302                    return Err((span, "accessing union fields is unstable".into()));
303                }
304            },
305            ProjectionElem::Deref => match base.ty(body, cx.tcx).ty.kind() {
306                ty::RawPtr(_, hir::Mutability::Mut) => {
307                    return Err((span, "dereferencing raw mut pointer in const fn is unstable".into()));
308                },
309                ty::RawPtr(_, hir::Mutability::Not) if !msrv.meets(cx, msrvs::CONST_RAW_PTR_DEREF) => {
310                    return Err((span, "dereferencing raw const pointer in const fn is unstable".into()));
311                },
312                _ => (),
313            },
314            ProjectionElem::ConstantIndex { .. }
315            | ProjectionElem::OpaqueCast(..)
316            | ProjectionElem::Downcast(..)
317            | ProjectionElem::Subslice { .. }
318            | ProjectionElem::Index(_)
319            | ProjectionElem::UnwrapUnsafeBinder(_) => {},
320        }
321    }
322
323    Ok(())
324}
325
326fn check_terminator<'tcx>(
327    cx: &LateContext<'tcx>,
328    body: &Body<'tcx>,
329    terminator: &Terminator<'tcx>,
330    msrv: Msrv,
331) -> McfResult {
332    let span = terminator.source_info.span;
333    match &terminator.kind {
334        TerminatorKind::FalseEdge { .. }
335        | TerminatorKind::FalseUnwind { .. }
336        | TerminatorKind::Goto { .. }
337        | TerminatorKind::Return
338        | TerminatorKind::UnwindResume
339        | TerminatorKind::UnwindTerminate(_)
340        | TerminatorKind::Unreachable => Ok(()),
341        TerminatorKind::Drop { place, .. } => {
342            if !is_ty_const_destruct(cx.tcx, place.ty(&body.local_decls, cx.tcx).ty, body) {
343                return Err((
344                    span,
345                    "cannot drop locals with a non constant destructor in const fn".into(),
346                ));
347            }
348            Ok(())
349        },
350        TerminatorKind::SwitchInt { discr, targets: _ } => check_operand(cx, discr, span, body, msrv),
351        TerminatorKind::CoroutineDrop | TerminatorKind::Yield { .. } => {
352            Err((span, "const fn coroutines are unstable".into()))
353        },
354        TerminatorKind::Call {
355            func,
356            args,
357            call_source: _,
358            destination: _,
359            target: _,
360            unwind: _,
361            fn_span: _,
362        }
363        | TerminatorKind::TailCall { func, args, fn_span: _ } => {
364            let fn_ty = func.ty(body, cx.tcx);
365            if let ty::FnDef(fn_def_id, fn_substs) = fn_ty.kind() {
366                // FIXME: when analyzing a function with generic parameters, we may not have enough information to
367                // resolve to an instance. However, we could check if a host effect predicate can guarantee that
368                // this can be made a `const` call.
369                let fn_def_id = match Instance::try_resolve(cx.tcx, cx.typing_env(), *fn_def_id, fn_substs) {
370                    Ok(Some(fn_inst)) => fn_inst.def_id(),
371                    Ok(None) => return Err((span, format!("cannot resolve instance for {func:?}").into())),
372                    Err(_) => return Err((span, format!("error during instance resolution of {func:?}").into())),
373                };
374                if !is_stable_const_fn(cx, fn_def_id, msrv) {
375                    return Err((
376                        span,
377                        format!(
378                            "can only call other `const fn` within a `const fn`, \
379                             but `{func:?}` is not stable as `const fn`",
380                        )
381                        .into(),
382                    ));
383                }
384
385                // HACK: This is to "unstabilize" the `transmute` intrinsic
386                // within const fns. `transmute` is allowed in all other const contexts.
387                // This won't really scale to more intrinsics or functions. Let's allow const
388                // transmutes in const fn before we add more hacks to this.
389                if cx.tcx.is_intrinsic(fn_def_id, sym::transmute) {
390                    return Err((
391                        span,
392                        "can only call `transmute` from const items, not `const fn`".into(),
393                    ));
394                }
395
396                check_operand(cx, func, span, body, msrv)?;
397
398                for arg in args {
399                    check_operand(cx, &arg.node, span, body, msrv)?;
400                }
401                Ok(())
402            } else {
403                Err((span, "can only call other const fns within const fn".into()))
404            }
405        },
406        TerminatorKind::Assert {
407            cond,
408            expected: _,
409            msg: _,
410            target: _,
411            unwind: _,
412        } => check_operand(cx, cond, span, body, msrv),
413        TerminatorKind::InlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())),
414    }
415}
416
417/// Checks if the given `def_id` is a stable const fn, in respect to the given MSRV.
418pub fn is_stable_const_fn(cx: &LateContext<'_>, def_id: DefId, msrv: Msrv) -> bool {
419    cx.tcx.is_const_fn(def_id)
420        && cx
421            .tcx
422            .lookup_const_stability(def_id)
423            .or_else(|| {
424                cx.tcx
425                    .trait_of_assoc(def_id)
426                    .and_then(|trait_def_id| cx.tcx.lookup_const_stability(trait_def_id))
427            })
428            .is_none_or(|const_stab| {
429                if let rustc_hir::StabilityLevel::Stable { since, .. } = const_stab.level {
430                    // Checking MSRV is manually necessary because `rustc` has no such concept. This entire
431                    // function could be removed if `rustc` provided a MSRV-aware version of `is_stable_const_fn`.
432                    // as a part of an unimplemented MSRV check https://github.com/rust-lang/rust/issues/65262.
433
434                    let const_stab_rust_version = match since {
435                        StableSince::Version(version) => version,
436                        StableSince::Current => RustcVersion::CURRENT,
437                        StableSince::Err(_) => return false,
438                    };
439
440                    msrv.meets(cx, const_stab_rust_version)
441                } else {
442                    // Unstable const fn, check if the feature is enabled.
443                    cx.tcx.features().enabled(const_stab.feature) && msrv.current(cx).is_none()
444                }
445            })
446}
447
448fn is_ty_const_destruct<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, body: &Body<'tcx>) -> bool {
449    // FIXME(const_trait_impl, fee1-dead) revert to const destruct once it works again
450    #[expect(unused)]
451    fn is_ty_const_destruct_unused<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, body: &Body<'tcx>) -> bool {
452        // If this doesn't need drop at all, then don't select `[const] Destruct`.
453        if !ty.needs_drop(tcx, body.typing_env(tcx)) {
454            return false;
455        }
456
457        let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(body.typing_env(tcx));
458        // FIXME(const_trait_impl) constness
459        let obligation = Obligation::new(
460            tcx,
461            ObligationCause::dummy_with_span(body.span),
462            param_env,
463            TraitRef::new(tcx, tcx.require_lang_item(LangItem::Destruct, body.span), [ty]),
464        );
465
466        let mut selcx = SelectionContext::new(&infcx);
467        let Some(impl_src) = selcx.select(&obligation).ok().flatten() else {
468            return false;
469        };
470
471        if !matches!(
472            impl_src,
473            ImplSource::Builtin(BuiltinImplSource::Misc, _) | ImplSource::Param(_)
474        ) {
475            return false;
476        }
477
478        let ocx = ObligationCtxt::new(&infcx);
479        ocx.register_obligations(impl_src.nested_obligations());
480        ocx.evaluate_obligations_error_on_ambiguity().is_empty()
481    }
482
483    !ty.needs_drop(tcx, ConstCx::new(tcx, body).typing_env)
484}