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