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, UnOp,
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::UnaryOp(UnOp::PtrMetadata, operand)
146        | Rvalue::Cast(
147            CastKind::PointerWithExposedProvenance
148            | CastKind::IntToInt
149            | CastKind::FloatToInt
150            | CastKind::IntToFloat
151            | CastKind::FloatToFloat
152            | CastKind::FnPtrToPtr
153            | CastKind::PtrToPtr
154            | CastKind::PointerCoercion(PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, _)
155            | CastKind::Subtype,
156            operand,
157            _,
158        ) => check_operand(cx, operand, span, body, msrv),
159        Rvalue::Cast(
160            CastKind::PointerCoercion(
161                PointerCoercion::UnsafeFnPointer
162                | PointerCoercion::ClosureFnPointer(_)
163                | PointerCoercion::ReifyFnPointer(_),
164                _,
165            ),
166            _,
167            _,
168        ) => Err((span, "function pointer casts are not allowed in const fn".into())),
169        Rvalue::Cast(CastKind::PointerCoercion(PointerCoercion::Unsize, _), op, cast_ty) => {
170            let Some(pointee_ty) = cast_ty.builtin_deref(true) else {
171                // We cannot allow this for now.
172                return Err((span, "unsizing casts are only allowed for references right now".into()));
173            };
174            let unsized_ty = cx
175                .tcx
176                .struct_tail_for_codegen(pointee_ty, ty::TypingEnv::post_analysis(cx.tcx, def_id));
177            if let ty::Slice(_) | ty::Str = unsized_ty.kind() {
178                check_operand(cx, op, span, body, msrv)?;
179                // Casting/coercing things to slices is fine.
180                Ok(())
181            } else {
182                // We just can't allow trait objects until we have figured out trait method calls.
183                Err((span, "unsizing casts are not allowed in const fn".into()))
184            }
185        },
186        Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => {
187            Err((span, "casting pointers to ints is unstable in const fn".into()))
188        },
189        Rvalue::Cast(CastKind::Transmute, _, _) => Err((
190            span,
191            "transmute can attempt to turn pointers into integers, so is unstable in const fn".into(),
192        )),
193        // binops are fine on integers
194        Rvalue::BinaryOp(_, box (lhs, rhs)) => {
195            check_operand(cx, lhs, span, body, msrv)?;
196            check_operand(cx, rhs, span, body, msrv)?;
197            let ty = lhs.ty(body, cx.tcx);
198            if ty.is_integral() || ty.is_bool() || ty.is_char() {
199                Ok(())
200            } else {
201                Err((
202                    span,
203                    "only int, `bool` and `char` operations are stable in const fn".into(),
204                ))
205            }
206        },
207        Rvalue::UnaryOp(_, operand) => {
208            let ty = operand.ty(body, cx.tcx);
209            if ty.is_integral() | ty.is_bool() {
210                check_operand(cx, operand, span, body, msrv)
211            } else {
212                Err((
213                    span,
214                    "only int, `bool`, and pointer metadata operations are stable in const fn".into(),
215                ))
216            }
217        },
218        Rvalue::Aggregate(_, operands) => {
219            for operand in operands {
220                check_operand(cx, operand, span, body, msrv)?;
221            }
222            Ok(())
223        },
224    }
225}
226
227fn check_statement<'tcx>(
228    cx: &LateContext<'tcx>,
229    body: &Body<'tcx>,
230    def_id: DefId,
231    statement: &Statement<'tcx>,
232    msrv: Msrv,
233) -> McfResult {
234    let span = statement.source_info.span;
235    match &statement.kind {
236        StatementKind::Assign(box (place, rval)) => {
237            check_place(cx, *place, span, body, msrv)?;
238            check_rvalue(cx, body, def_id, rval, span, msrv)
239        },
240
241        StatementKind::FakeRead(box (_, place)) => check_place(cx, *place, span, body, msrv),
242        // just an assignment
243        StatementKind::SetDiscriminant { place, .. } => check_place(cx, **place, span, body, msrv),
244
245        StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => check_operand(cx, op, span, body, msrv),
246
247        StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping(
248            rustc_middle::mir::CopyNonOverlapping { dst, src, count },
249        )) => {
250            check_operand(cx, dst, span, body, msrv)?;
251            check_operand(cx, src, span, body, msrv)?;
252            check_operand(cx, count, span, body, msrv)
253        },
254        // These are all NOPs
255        StatementKind::StorageLive(_)
256        | StatementKind::StorageDead(_)
257        | StatementKind::AscribeUserType(..)
258        | StatementKind::PlaceMention(..)
259        | StatementKind::Coverage(..)
260        | StatementKind::ConstEvalCounter
261        | StatementKind::BackwardIncompatibleDropHint { .. }
262        | StatementKind::Nop => Ok(()),
263    }
264}
265
266fn check_operand<'tcx>(
267    cx: &LateContext<'tcx>,
268    operand: &Operand<'tcx>,
269    span: Span,
270    body: &Body<'tcx>,
271    msrv: Msrv,
272) -> McfResult {
273    match operand {
274        Operand::Move(place) => {
275            if !place.projection.as_ref().is_empty()
276                && !is_ty_const_destruct(cx.tcx, place.ty(&body.local_decls, cx.tcx).ty, body)
277            {
278                return Err((
279                    span,
280                    "cannot drop locals with a non constant destructor in const fn".into(),
281                ));
282            }
283
284            check_place(cx, *place, span, body, msrv)
285        },
286        Operand::Copy(place) => check_place(cx, *place, span, body, msrv),
287        Operand::Constant(c) => match c.check_static_ptr(cx.tcx) {
288            Some(_) => Err((span, "cannot access `static` items in const fn".into())),
289            None => Ok(()),
290        },
291        Operand::RuntimeChecks(..) => Ok(()),
292    }
293}
294
295fn check_place<'tcx>(
296    cx: &LateContext<'tcx>,
297    place: Place<'tcx>,
298    span: Span,
299    body: &Body<'tcx>,
300    msrv: Msrv,
301) -> McfResult {
302    for (base, elem) in place.as_ref().iter_projections() {
303        match elem {
304            ProjectionElem::Field(..) => {
305                if base.ty(body, cx.tcx).ty.is_union() && !msrv.meets(cx, msrvs::CONST_FN_UNION) {
306                    return Err((span, "accessing union fields is unstable".into()));
307                }
308            },
309            ProjectionElem::Deref => match base.ty(body, cx.tcx).ty.kind() {
310                ty::RawPtr(_, hir::Mutability::Mut) => {
311                    return Err((span, "dereferencing raw mut pointer in const fn is unstable".into()));
312                },
313                ty::RawPtr(_, hir::Mutability::Not) if !msrv.meets(cx, msrvs::CONST_RAW_PTR_DEREF) => {
314                    return Err((span, "dereferencing raw const pointer in const fn is unstable".into()));
315                },
316                _ => (),
317            },
318            ProjectionElem::ConstantIndex { .. }
319            | ProjectionElem::OpaqueCast(..)
320            | ProjectionElem::Downcast(..)
321            | ProjectionElem::Subslice { .. }
322            | ProjectionElem::Index(_)
323            | ProjectionElem::UnwrapUnsafeBinder(_) => {},
324        }
325    }
326
327    Ok(())
328}
329
330fn check_terminator<'tcx>(
331    cx: &LateContext<'tcx>,
332    body: &Body<'tcx>,
333    terminator: &Terminator<'tcx>,
334    msrv: Msrv,
335) -> McfResult {
336    let span = terminator.source_info.span;
337    match &terminator.kind {
338        TerminatorKind::FalseEdge { .. }
339        | TerminatorKind::FalseUnwind { .. }
340        | TerminatorKind::Goto { .. }
341        | TerminatorKind::Return
342        | TerminatorKind::UnwindResume
343        | TerminatorKind::UnwindTerminate(_)
344        | TerminatorKind::Unreachable => Ok(()),
345        TerminatorKind::Drop { place, .. } => {
346            if !is_ty_const_destruct(cx.tcx, place.ty(&body.local_decls, cx.tcx).ty, body) {
347                return Err((
348                    span,
349                    "cannot drop locals with a non constant destructor in const fn".into(),
350                ));
351            }
352            Ok(())
353        },
354        TerminatorKind::SwitchInt { discr, targets: _ } => check_operand(cx, discr, span, body, msrv),
355        TerminatorKind::CoroutineDrop | TerminatorKind::Yield { .. } => {
356            Err((span, "const fn coroutines are unstable".into()))
357        },
358        TerminatorKind::Call {
359            func,
360            args,
361            call_source: _,
362            destination: _,
363            target: _,
364            unwind: _,
365            fn_span: _,
366        }
367        | TerminatorKind::TailCall { func, args, fn_span: _ } => {
368            let fn_ty = func.ty(body, cx.tcx);
369            if let ty::FnDef(fn_def_id, fn_substs) = fn_ty.kind() {
370                // FIXME: when analyzing a function with generic parameters, we may not have enough information to
371                // resolve to an instance. However, we could check if a host effect predicate can guarantee that
372                // this can be made a `const` call.
373                let fn_def_id = match Instance::try_resolve(cx.tcx, cx.typing_env(), *fn_def_id, fn_substs) {
374                    Ok(Some(fn_inst)) => fn_inst.def_id(),
375                    Ok(None) => return Err((span, format!("cannot resolve instance for {func:?}").into())),
376                    Err(_) => return Err((span, format!("error during instance resolution of {func:?}").into())),
377                };
378                if !is_stable_const_fn(cx, fn_def_id, msrv) {
379                    return Err((
380                        span,
381                        format!(
382                            "can only call other `const fn` within a `const fn`, \
383                             but `{func:?}` is not stable as `const fn`",
384                        )
385                        .into(),
386                    ));
387                }
388
389                // HACK: This is to "unstabilize" the `transmute` intrinsic
390                // within const fns. `transmute` is allowed in all other const contexts.
391                // This won't really scale to more intrinsics or functions. Let's allow const
392                // transmutes in const fn before we add more hacks to this.
393                if cx.tcx.is_intrinsic(fn_def_id, sym::transmute) {
394                    return Err((
395                        span,
396                        "can only call `transmute` from const items, not `const fn`".into(),
397                    ));
398                }
399
400                check_operand(cx, func, span, body, msrv)?;
401
402                for arg in args {
403                    check_operand(cx, &arg.node, span, body, msrv)?;
404                }
405                Ok(())
406            } else {
407                Err((span, "can only call other const fns within const fn".into()))
408            }
409        },
410        TerminatorKind::Assert {
411            cond,
412            expected: _,
413            msg: _,
414            target: _,
415            unwind: _,
416        } => check_operand(cx, cond, span, body, msrv),
417        TerminatorKind::InlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())),
418    }
419}
420
421/// Checks if the given `def_id` is a stable const fn, in respect to the given MSRV.
422pub fn is_stable_const_fn(cx: &LateContext<'_>, def_id: DefId, msrv: Msrv) -> bool {
423    cx.tcx.is_const_fn(def_id)
424        && cx
425            .tcx
426            .lookup_const_stability(def_id)
427            .or_else(|| {
428                cx.tcx
429                    .trait_of_assoc(def_id)
430                    .and_then(|trait_def_id| cx.tcx.lookup_const_stability(trait_def_id))
431            })
432            .is_none_or(|const_stab| {
433                if let rustc_hir::StabilityLevel::Stable { since, .. } = const_stab.level {
434                    // Checking MSRV is manually necessary because `rustc` has no such concept. This entire
435                    // function could be removed if `rustc` provided a MSRV-aware version of `is_stable_const_fn`.
436                    // as a part of an unimplemented MSRV check https://github.com/rust-lang/rust/issues/65262.
437
438                    let const_stab_rust_version = match since {
439                        StableSince::Version(version) => version,
440                        StableSince::Current => RustcVersion::CURRENT,
441                        StableSince::Err(_) => return false,
442                    };
443
444                    msrv.meets(cx, const_stab_rust_version)
445                } else {
446                    // Unstable const fn, check if the feature is enabled.
447                    cx.tcx.features().enabled(const_stab.feature) && msrv.current(cx).is_none()
448                }
449            })
450}
451
452fn is_ty_const_destruct<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, body: &Body<'tcx>) -> bool {
453    // FIXME(const_trait_impl, fee1-dead) revert to const destruct once it works again
454    #[expect(unused)]
455    fn is_ty_const_destruct_unused<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, body: &Body<'tcx>) -> bool {
456        // If this doesn't need drop at all, then don't select `[const] Destruct`.
457        if !ty.needs_drop(tcx, body.typing_env(tcx)) {
458            return false;
459        }
460
461        let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(body.typing_env(tcx));
462        // FIXME(const_trait_impl) constness
463        let obligation = Obligation::new(
464            tcx,
465            ObligationCause::dummy_with_span(body.span),
466            param_env,
467            TraitRef::new(tcx, tcx.require_lang_item(LangItem::Destruct, body.span), [ty]),
468        );
469
470        let mut selcx = SelectionContext::new(&infcx);
471        let Some(impl_src) = selcx.select(&obligation).ok().flatten() else {
472            return false;
473        };
474
475        if !matches!(
476            impl_src,
477            ImplSource::Builtin(BuiltinImplSource::Misc, _) | ImplSource::Param(_)
478        ) {
479            return false;
480        }
481
482        let ocx = ObligationCtxt::new(&infcx);
483        ocx.register_obligations(impl_src.nested_obligations());
484        ocx.evaluate_obligations_error_on_ambiguity().is_empty()
485    }
486
487    !ty.needs_drop(tcx, ConstCx::new(tcx, body).typing_env)
488}