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