Skip to main content

rustc_const_eval/check_consts/
ops.rs

1//! Concrete error types for all operations which may be invalid in a certain const context.
2
3use hir::ConstContext;
4use rustc_errors::codes::*;
5use rustc_errors::{Applicability, Diag, MultiSpan, msg};
6use rustc_hir as hir;
7use rustc_hir::attrs::lang_items::LangItem;
8use rustc_hir::def_id::DefId;
9use rustc_infer::infer::TyCtxtInferExt;
10use rustc_infer::traits::{ImplSource, Obligation, ObligationCause};
11use rustc_middle::mir::CallSource;
12use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths};
13use rustc_middle::ty::{
14    self, AssocContainer, Closure, FnDef, FnPtr, GenericArgKind, GenericArgsRef, Param, TraitRef,
15    Ty, suggest_constraining_type_param,
16};
17use rustc_session::diagnostics::add_feature_diagnostics;
18use rustc_span::{BytePos, Pos, Span, Symbol, span_bug, sym};
19use rustc_trait_selection::error_reporting::traits::call_kind::{
20    CallDesugaringKind, CallKind, call_kind,
21};
22use rustc_trait_selection::traits::SelectionContext;
23use tracing::debug;
24
25use super::ConstCx;
26use crate::diagnostics;
27
28#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Status { }
#[automatically_derived]
impl ::core::clone::Clone for Status {
    #[inline]
    fn clone(&self) -> Status {
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Status { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Status {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Status::Unstable {
                gate: __self_0,
                gate_already_checked: __self_1,
                safe_to_expose_on_stable: __self_2,
                is_function_call: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "Unstable", "gate", __self_0, "gate_already_checked",
                    __self_1, "safe_to_expose_on_stable", __self_2,
                    "is_function_call", &__self_3),
            Status::Forbidden =>
                ::core::fmt::Formatter::write_str(f, "Forbidden"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for Status { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Status {
    #[inline]
    fn eq(&self, other: &Status) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Status::Unstable {
                    gate: __self_0,
                    gate_already_checked: __self_1,
                    safe_to_expose_on_stable: __self_2,
                    is_function_call: __self_3 }, Status::Unstable {
                    gate: __arg1_0,
                    gate_already_checked: __arg1_1,
                    safe_to_expose_on_stable: __arg1_2,
                    is_function_call: __arg1_3 }) =>
                    __self_1 == __arg1_1 && __self_2 == __arg1_2 &&
                            __self_3 == __arg1_3 && __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Status {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Symbol>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq)]
29pub enum Status {
30    Unstable {
31        /// The feature that must be enabled to use this operation.
32        gate: Symbol,
33        /// Whether the feature gate was already checked (because the logic is a bit more
34        /// complicated than just checking a single gate).
35        gate_already_checked: bool,
36        /// Whether it is allowed to use this operation from stable `const fn`.
37        /// This will usually be `false`.
38        safe_to_expose_on_stable: bool,
39        /// We indicate whether this is a function call, since we can use targeted
40        /// diagnostics for "callee is not safe to expose om stable".
41        is_function_call: bool,
42    },
43    Forbidden,
44}
45
46#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DiagImportance { }
#[automatically_derived]
impl ::core::clone::Clone for DiagImportance {
    #[inline]
    fn clone(&self) -> DiagImportance { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DiagImportance { }Copy)]
47pub enum DiagImportance {
48    /// An operation that must be removed for const-checking to pass.
49    Primary,
50
51    /// An operation that causes const-checking to fail, but is usually a side-effect of a `Primary` operation elsewhere.
52    Secondary,
53}
54
55/// An operation that is *not allowed* in a const context.
56pub trait NonConstOp<'tcx>: std::fmt::Debug {
57    /// Returns an enum indicating whether this operation can be enabled with a feature gate.
58    fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status {
59        Status::Forbidden
60    }
61
62    fn importance(&self) -> DiagImportance {
63        DiagImportance::Primary
64    }
65
66    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx>;
67}
68
69/// A function call where the callee is a pointer.
70#[derive(#[automatically_derived]
impl ::core::fmt::Debug for FnCallIndirect {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "FnCallIndirect")
    }
}Debug)]
71pub(crate) struct FnCallIndirect;
72impl<'tcx> NonConstOp<'tcx> for FnCallIndirect {
73    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
74        ccx.dcx().create_err(diagnostics::UnallowedFnPointerCall { span, kind: ccx.const_kind() })
75    }
76}
77
78/// A c-variadic function call.
79#[derive(#[automatically_derived]
impl ::core::fmt::Debug for FnCallCVariadic {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "FnCallCVariadic")
    }
}Debug)]
80pub(crate) struct FnCallCVariadic;
81impl<'tcx> NonConstOp<'tcx> for FnCallCVariadic {
82    fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status {
83        Status::Unstable {
84            gate: sym::const_c_variadic,
85            gate_already_checked: false,
86            safe_to_expose_on_stable: false,
87            is_function_call: true,
88        }
89    }
90
91    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
92        ccx.tcx.sess.create_feature_err(
93            diagnostics::NonConstCVariadicCall { span, kind: ccx.const_kind() },
94            sym::const_c_variadic,
95        )
96    }
97}
98
99/// A call to a function that is in a trait, or has trait bounds that make it conditionally-const.
100#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ConditionallyConstCall<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "ConditionallyConstCall", "callee", &self.callee, "args",
            &self.args, "span", &self.span, "call_source", &&self.call_source)
    }
}Debug)]
101pub(crate) struct ConditionallyConstCall<'tcx> {
102    pub callee: DefId,
103    pub args: GenericArgsRef<'tcx>,
104    pub span: Span,
105    pub call_source: CallSource,
106}
107
108impl<'tcx> NonConstOp<'tcx> for ConditionallyConstCall<'tcx> {
109    fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status {
110        // We use the `const_trait_impl` gate for all conditionally-const calls.
111        Status::Unstable {
112            gate: sym::const_trait_impl,
113            gate_already_checked: false,
114            safe_to_expose_on_stable: false,
115            // We don't want the "mark the callee as `#[rustc_const_stable_indirect]`" hint
116            is_function_call: false,
117        }
118    }
119
120    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, _: Span) -> Diag<'tcx> {
121        let mut diag = build_error_for_const_call(
122            ccx,
123            self.callee,
124            self.args,
125            self.span,
126            self.call_source,
127            "conditionally",
128            |_, _, _| {},
129        );
130
131        // Override code and mention feature.
132        diag.code(E0658);
133        add_feature_diagnostics(&mut diag, ccx.tcx.sess, sym::const_trait_impl);
134
135        diag
136    }
137}
138
139/// A function call where the callee is not marked as `const`.
140#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for FnCallNonConst<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "FnCallNonConst", "callee", &self.callee, "args", &self.args,
            "span", &self.span, "call_source", &&self.call_source)
    }
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for FnCallNonConst<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for FnCallNonConst<'tcx> {
    #[inline]
    fn clone(&self) -> FnCallNonConst<'tcx> {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<CallSource>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for FnCallNonConst<'tcx> { }Copy)]
141pub(crate) struct FnCallNonConst<'tcx> {
142    pub callee: DefId,
143    pub args: GenericArgsRef<'tcx>,
144    pub span: Span,
145    pub call_source: CallSource,
146}
147
148impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
149    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, _: Span) -> Diag<'tcx> {
150        let tcx = ccx.tcx;
151        let caller = ccx.def_id();
152
153        let mut err = build_error_for_const_call(
154            ccx,
155            self.callee,
156            self.args,
157            self.span,
158            self.call_source,
159            "non",
160            |err, self_ty, trait_id| {
161                // FIXME(const_trait_impl): Do we need any of this on the non-const codepath?
162
163                let trait_ref = TraitRef::from_assoc(tcx, trait_id, self.args);
164
165                match self_ty.kind() {
166                    Param(param_ty) => {
167                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/ops.rs:167",
                        "rustc_const_eval::check_consts::ops",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/ops.rs"),
                        ::tracing_core::__macro_support::Option::Some(167u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::check_consts::ops"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("param_ty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("param_ty");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_ty)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?param_ty);
168                        if let Some(generics) = tcx.hir_node_by_def_id(caller).generics() {
169                            let constraint = {
    let _guard = NoTrimmedGuard::new();
    ::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("[const] {0}",
                    trait_ref.print_trait_sugared()))
        })
}with_no_trimmed_paths!(format!(
170                                "[const] {}",
171                                trait_ref.print_trait_sugared(),
172                            ));
173                            suggest_constraining_type_param(
174                                tcx,
175                                generics,
176                                err,
177                                param_ty.name.as_str(),
178                                &constraint,
179                                Some(trait_ref.def_id),
180                                None,
181                            );
182                        }
183                    }
184                    ty::Adt(..) => {
185                        let (infcx, param_env) =
186                            tcx.infer_ctxt().build_with_typing_env(ccx.typing_env);
187                        let obligation =
188                            Obligation::new(tcx, ObligationCause::dummy(), param_env, trait_ref);
189                        let mut selcx = SelectionContext::new(&infcx);
190                        let implsrc = selcx.select(&obligation);
191                        if let Ok(Some(ImplSource::UserDefined(data))) = implsrc {
192                            // FIXME(const_trait_impl) revisit this
193                            if !tcx.is_const_trait_impl(data.impl_def_id) {
194                                let span = tcx.def_span(data.impl_def_id);
195                                err.subdiagnostic(diagnostics::NonConstImplNote { span });
196                            }
197                        }
198                    }
199                    _ => {}
200                }
201            },
202        );
203
204        if let ConstContext::Static(_) = ccx.const_kind() {
205            err.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider wrapping this expression in `std::sync::LazyLock::new(|| ...)`"))msg!(
206                "consider wrapping this expression in `std::sync::LazyLock::new(|| ...)`"
207            ));
208        }
209
210        err
211    }
212}
213
214/// Build an error message reporting that a function call is not const (or only
215/// conditionally const). In case that this call is desugared (like an operator
216/// or sugar from something like a `for` loop), try to build a better error message
217/// that doesn't call it a method.
218fn build_error_for_const_call<'tcx>(
219    ccx: &ConstCx<'_, 'tcx>,
220    callee: DefId,
221    args: ty::GenericArgsRef<'tcx>,
222    span: Span,
223    call_source: CallSource,
224    non_or_conditionally: &'static str,
225    note_trait_if_possible: impl FnOnce(&mut Diag<'tcx>, Ty<'tcx>, DefId),
226) -> Diag<'tcx> {
227    let tcx = ccx.tcx;
228
229    let call_kind =
230        call_kind(tcx, ccx.typing_env, callee, args, span, call_source.from_hir_call(), None);
231
232    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/ops.rs:232",
                        "rustc_const_eval::check_consts::ops",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_const_eval/src/check_consts/ops.rs"),
                        ::tracing_core::__macro_support::Option::Some(232u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::check_consts::ops"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("call_kind")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("call_kind");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&call_kind)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?call_kind);
233
234    let mut err = match call_kind {
235        CallKind::Normal { desugaring: Some((kind, self_ty)), .. } => {
236            macro_rules! error {
237                ($err:ident) => {
238                    tcx.dcx().create_err(diagnostics::$err {
239                        span,
240                        ty: self_ty,
241                        kind: ccx.const_kind(),
242                        non_or_conditionally,
243                    })
244                };
245            }
246
247            // Don't point at the trait if this is a desugaring...
248            // FIXME(const_trait_impl): we could perhaps do this for `Iterator`.
249            match kind {
250                CallDesugaringKind::ForLoopIntoIter
251                | CallDesugaringKind::ForLoopIntoAsyncIter
252                | CallDesugaringKind::ForLoopNext => {
253                    tcx.dcx().create_err(diagnostics::NonConstForLoopIntoIter {
        span,
        ty: self_ty,
        kind: ccx.const_kind(),
        non_or_conditionally,
    })error!(NonConstForLoopIntoIter)
254                }
255                CallDesugaringKind::QuestionBranch => {
256                    tcx.dcx().create_err(diagnostics::NonConstQuestionBranch {
        span,
        ty: self_ty,
        kind: ccx.const_kind(),
        non_or_conditionally,
    })error!(NonConstQuestionBranch)
257                }
258                CallDesugaringKind::QuestionFromResidual => {
259                    tcx.dcx().create_err(diagnostics::NonConstQuestionFromResidual {
        span,
        ty: self_ty,
        kind: ccx.const_kind(),
        non_or_conditionally,
    })error!(NonConstQuestionFromResidual)
260                }
261                CallDesugaringKind::TryBlockFromOutput => {
262                    tcx.dcx().create_err(diagnostics::NonConstTryBlockFromOutput {
        span,
        ty: self_ty,
        kind: ccx.const_kind(),
        non_or_conditionally,
    })error!(NonConstTryBlockFromOutput)
263                }
264                CallDesugaringKind::Await => {
265                    tcx.dcx().create_err(diagnostics::NonConstAwait {
        span,
        ty: self_ty,
        kind: ccx.const_kind(),
        non_or_conditionally,
    })error!(NonConstAwait)
266                }
267            }
268        }
269        CallKind::FnCall { fn_trait_id, self_ty } => {
270            let kind = ccx.const_kind();
271            let note = match self_ty.kind() {
272                FnDef(def_id, ..) => {
273                    let span = tcx.def_span(*def_id);
274                    if ccx.tcx.is_const_fn(*def_id) {
275                        bug_impl(Some(span),
    format_args!("calling const FnDef errored when it shouldn\'t"),
    Location::caller());span_bug!(span, "calling const FnDef errored when it shouldn't");
276                    }
277
278                    Some(diagnostics::NonConstClosureNote::FnDef { span })
279                }
280                FnPtr(..) => Some(diagnostics::NonConstClosureNote::FnPtr { kind }),
281                Closure(..) => Some(diagnostics::NonConstClosureNote::Closure { kind }),
282                _ => None,
283            };
284
285            let mut err = tcx.dcx().create_err(diagnostics::NonConstClosure {
286                span,
287                kind: ccx.const_kind(),
288                note,
289                non_or_conditionally,
290            });
291
292            note_trait_if_possible(&mut err, self_ty, fn_trait_id);
293            err
294        }
295        CallKind::Operator { trait_id, self_ty, .. } => {
296            let mut err = if let CallSource::MatchCmp = call_source {
297                tcx.dcx().create_err(diagnostics::NonConstMatchEq {
298                    span,
299                    kind: ccx.const_kind(),
300                    ty: self_ty,
301                    non_or_conditionally,
302                })
303            } else {
304                let mut sugg = None;
305
306                if ccx.tcx.is_lang_item(trait_id, LangItem::PartialEq) {
307                    match (args[0].kind(), args[1].kind()) {
308                        (GenericArgKind::Type(self_ty), GenericArgKind::Type(rhs_ty))
309                            if self_ty == rhs_ty
310                                && self_ty.is_ref()
311                                && self_ty.peel_refs().is_primitive() =>
312                        {
313                            let mut num_refs = 0;
314                            let mut tmp_ty = self_ty;
315                            while let rustc_middle::ty::Ref(_, inner_ty, _) = tmp_ty.kind() {
316                                num_refs += 1;
317                                tmp_ty = *inner_ty;
318                            }
319                            let deref = "*".repeat(num_refs);
320
321                            if let Ok(call_str) = ccx.tcx.sess.source_map().span_to_snippet(span)
322                                && let Some(eq_idx) = call_str.find("==")
323                                && let Some(rhs_idx) =
324                                    call_str[(eq_idx + 2)..].find(|c: char| !c.is_whitespace())
325                            {
326                                let rhs_pos = span.lo() + BytePos::from_usize(eq_idx + 2 + rhs_idx);
327                                let rhs_span = span.with_lo(rhs_pos).with_hi(rhs_pos);
328                                sugg = Some(diagnostics::ConsiderDereferencing {
329                                    deref,
330                                    span: span.shrink_to_lo(),
331                                    rhs_span,
332                                });
333                            }
334                        }
335                        _ => {}
336                    }
337                }
338                tcx.dcx().create_err(diagnostics::NonConstOperator {
339                    span,
340                    kind: ccx.const_kind(),
341                    sugg,
342                    non_or_conditionally,
343                })
344            };
345
346            note_trait_if_possible(&mut err, self_ty, trait_id);
347            err
348        }
349        CallKind::DerefCoercion { deref_target_span, deref_target_ty, self_ty } => {
350            // Check first whether the source is accessible (issue #87060)
351            let target = if let Some(deref_target_span) = deref_target_span
352                && tcx.sess.source_map().is_span_accessible(deref_target_span)
353            {
354                Some(deref_target_span)
355            } else {
356                None
357            };
358
359            let mut err = tcx.dcx().create_err(diagnostics::NonConstDerefCoercion {
360                span,
361                ty: self_ty,
362                kind: ccx.const_kind(),
363                target_ty: deref_target_ty,
364                deref_target: target,
365                non_or_conditionally,
366            });
367
368            note_trait_if_possible(&mut err, self_ty, tcx.require_lang_item(LangItem::Deref, span));
369            err
370        }
371        _ if tcx.opt_parent(callee) == tcx.get_diagnostic_item(sym::FmtArgumentsNew) => {
372            ccx.dcx().create_err(diagnostics::NonConstFmtMacroCall {
373                span,
374                kind: ccx.const_kind(),
375                non_or_conditionally,
376            })
377        }
378        _ => {
379            let def_descr = ccx.tcx.def_descr(callee);
380            let mut err = ccx.dcx().create_err(diagnostics::NonConstFnCall {
381                span,
382                def_descr,
383                def_path_str: ccx.tcx.def_path_str_with_args(callee, args),
384                kind: ccx.const_kind(),
385                non_or_conditionally,
386            });
387            if let Some(item) = ccx.tcx.opt_associated_item(callee) {
388                if let AssocContainer::Trait = item.container
389                    && let parent = item.container_id(ccx.tcx)
390                    && !ccx.tcx.is_const_trait(parent)
391                {
392                    let assoc_span = ccx.tcx.def_span(callee);
393                    let assoc_name = ccx.tcx.item_name(callee);
394                    let mut span: MultiSpan = ccx.tcx.def_span(parent).into();
395                    span.push_span_label(assoc_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this {0} is not const", def_descr))
    })format!("this {def_descr} is not const"));
396                    let trait_descr = ccx.tcx.def_descr(parent);
397                    let trait_span = ccx.tcx.def_span(parent);
398                    let trait_name = ccx.tcx.item_name(parent);
399                    span.push_span_label(trait_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this {0} is not const",
                trait_descr))
    })format!("this {trait_descr} is not const"));
400                    err.span_note(
401                        span,
402                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}` is not const because {2} `{3}` is not const",
                def_descr, assoc_name, trait_descr, trait_name))
    })format!(
403                            "{def_descr} `{assoc_name}` is not const because {trait_descr} \
404                            `{trait_name}` is not const",
405                        ),
406                    );
407                    if let Some(parent) = parent.as_local()
408                        && ccx.tcx.sess.is_nightly_build()
409                    {
410                        if !ccx.tcx.features().const_trait_impl() {
411                            err.help(
412                                "add `#![feature(const_trait_impl)]` to the crate attributes to \
413                                 enable const traits",
414                            );
415                        }
416                        let span = ccx.tcx.hir_expect_item(parent).vis_span;
417                        let span = ccx.tcx.sess.source_map().span_extend_while_whitespace(span);
418                        err.span_suggestion_verbose(
419                            span.shrink_to_hi(),
420                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider making trait `{0}` const",
                trait_name))
    })format!("consider making trait `{trait_name}` const"),
421                            "const ".to_owned(),
422                            Applicability::MaybeIncorrect,
423                        );
424                    } else if !ccx.tcx.sess.is_nightly_build() {
425                        err.help("const traits are not yet supported on stable Rust");
426                    }
427                }
428            } else if !#[allow(non_exhaustive_omitted_patterns)] match ccx.tcx.constness(callee) {
    hir::Constness::Const { always: false } => true,
    _ => false,
}matches!(ccx.tcx.constness(callee), hir::Constness::Const { always: false })
429            {
430                let name = ccx.tcx.item_name(callee);
431                err.span_note(
432                    ccx.tcx.def_span(callee),
433                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}` is not const", def_descr,
                name))
    })format!("{def_descr} `{name}` is not const"),
434                );
435            }
436            err
437        }
438    };
439
440    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("calls in {0}s are limited to constant functions, tuple structs and tuple variants",
                ccx.const_kind()))
    })format!(
441        "calls in {}s are limited to constant functions, tuple structs and tuple variants",
442        ccx.const_kind(),
443    ));
444
445    err
446}
447
448/// A call to an `#[unstable]` const fn, `#[rustc_const_unstable]` function or trait.
449///
450/// Contains the name of the feature that would allow the use of this function/trait.
451#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CallUnstable {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f, "CallUnstable",
            "def_id", &self.def_id, "feature", &self.feature,
            "feature_enabled", &self.feature_enabled,
            "safe_to_expose_on_stable", &self.safe_to_expose_on_stable,
            "is_function_call", &&self.is_function_call)
    }
}Debug)]
452pub(crate) struct CallUnstable {
453    pub def_id: DefId,
454    pub feature: Symbol,
455    /// If this is true, then the feature is enabled, but we need to still check if it is safe to
456    /// expose on stable.
457    pub feature_enabled: bool,
458    pub safe_to_expose_on_stable: bool,
459    /// true if `def_id` is the function we are calling, false if `def_id` is an unstable trait.
460    pub is_function_call: bool,
461}
462
463impl<'tcx> NonConstOp<'tcx> for CallUnstable {
464    fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status {
465        Status::Unstable {
466            gate: self.feature,
467            gate_already_checked: self.feature_enabled,
468            safe_to_expose_on_stable: self.safe_to_expose_on_stable,
469            is_function_call: self.is_function_call,
470        }
471    }
472
473    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
474        if !!self.feature_enabled {
    ::core::panicking::panic("assertion failed: !self.feature_enabled")
};assert!(!self.feature_enabled);
475        let mut err = if self.is_function_call {
476            ccx.dcx().create_err(diagnostics::UnstableConstFn {
477                span,
478                def_path: ccx.tcx.def_path_str(self.def_id),
479            })
480        } else {
481            ccx.dcx().create_err(diagnostics::UnstableConstTrait {
482                span,
483                def_path: ccx.tcx.def_path_str(self.def_id),
484            })
485        };
486        ccx.tcx.disabled_nightly_features(&mut err, [(String::new(), self.feature)]);
487        err
488    }
489}
490
491/// A call to an intrinsic that is just not const-callable at all.
492#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IntrinsicNonConst {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "IntrinsicNonConst", "name", &&self.name)
    }
}Debug)]
493pub(crate) struct IntrinsicNonConst {
494    pub name: Symbol,
495}
496
497impl<'tcx> NonConstOp<'tcx> for IntrinsicNonConst {
498    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
499        ccx.dcx().create_err(diagnostics::NonConstIntrinsic {
500            span,
501            name: self.name,
502            kind: ccx.const_kind(),
503        })
504    }
505}
506
507/// A call to an intrinsic that is just not const-callable at all.
508#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IntrinsicUnstable {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "IntrinsicUnstable", "name", &self.name, "feature", &self.feature,
            "const_stable_indirect", &&self.const_stable_indirect)
    }
}Debug)]
509pub(crate) struct IntrinsicUnstable {
510    pub name: Symbol,
511    pub feature: Symbol,
512    pub const_stable_indirect: bool,
513}
514
515impl<'tcx> NonConstOp<'tcx> for IntrinsicUnstable {
516    fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status {
517        Status::Unstable {
518            gate: self.feature,
519            gate_already_checked: false,
520            safe_to_expose_on_stable: self.const_stable_indirect,
521            // We do *not* want to suggest to mark the intrinsic as `const_stable_indirect`,
522            // that's not a trivial change!
523            is_function_call: false,
524        }
525    }
526
527    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
528        ccx.dcx().create_err(diagnostics::UnstableIntrinsic {
529            span,
530            name: self.name,
531            feature: self.feature,
532            suggestion: ccx.tcx.crate_level_attribute_injection_span(),
533        })
534    }
535}
536
537#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Coroutine {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Coroutine",
            &&self.0)
    }
}Debug)]
538pub(crate) struct Coroutine(pub hir::CoroutineKind);
539impl<'tcx> NonConstOp<'tcx> for Coroutine {
540    fn status_in_item(&self, _: &ConstCx<'_, 'tcx>) -> Status {
541        match self.0 {
542            hir::CoroutineKind::Desugared(
543                hir::CoroutineDesugaring::Async,
544                hir::CoroutineSource::Block,
545            )
546            // FIXME(coroutines): eventually we want to gate const coroutine coroutines behind a
547            // different feature.
548            | hir::CoroutineKind::Coroutine(_) => Status::Unstable {
549                gate: sym::const_async_blocks,
550                gate_already_checked: false,
551                safe_to_expose_on_stable: false,
552                is_function_call: false,
553            },
554            _ => Status::Forbidden,
555        }
556    }
557
558    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
559        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} are not allowed in {1}s",
                self.0.to_plural_string(), ccx.const_kind()))
    })format!("{} are not allowed in {}s", self.0.to_plural_string(), ccx.const_kind());
560        if let Status::Unstable { gate, .. } = self.status_in_item(ccx) {
561            ccx.tcx
562                .sess
563                .create_feature_err(diagnostics::UnallowedOpInConstContext { span, msg }, gate)
564        } else {
565            ccx.dcx().create_err(diagnostics::UnallowedOpInConstContext { span, msg })
566        }
567    }
568}
569
570#[derive(#[automatically_derived]
impl ::core::fmt::Debug for InlineAsm {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "InlineAsm")
    }
}Debug)]
571pub(crate) struct InlineAsm;
572impl<'tcx> NonConstOp<'tcx> for InlineAsm {
573    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
574        ccx.dcx().create_err(diagnostics::UnallowedInlineAsm { span, kind: ccx.const_kind() })
575    }
576}
577
578#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for LiveDrop<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "LiveDrop",
            "dropped_at", &self.dropped_at, "dropped_ty", &self.dropped_ty,
            "needs_non_const_drop", &&self.needs_non_const_drop)
    }
}Debug)]
579pub(crate) struct LiveDrop<'tcx> {
580    pub dropped_at: Span,
581    pub dropped_ty: Ty<'tcx>,
582    pub needs_non_const_drop: bool,
583}
584impl<'tcx> NonConstOp<'tcx> for LiveDrop<'tcx> {
585    fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status {
586        if self.needs_non_const_drop {
587            Status::Forbidden
588        } else {
589            Status::Unstable {
590                gate: sym::const_destruct,
591                gate_already_checked: false,
592                safe_to_expose_on_stable: false,
593                is_function_call: false,
594            }
595        }
596    }
597
598    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
599        let mut err = if self.needs_non_const_drop {
600            ccx.dcx().create_err(diagnostics::LiveDrop {
601                span,
602                dropped_ty: self.dropped_ty,
603                kind: ccx.const_kind(),
604                dropped_at: self.dropped_at,
605            })
606        } else {
607            ccx.tcx.sess.create_feature_err(
608                diagnostics::LiveDrop {
609                    span,
610                    dropped_ty: self.dropped_ty,
611                    kind: ccx.const_kind(),
612                    dropped_at: self.dropped_at,
613                },
614                sym::const_destruct,
615            )
616        };
617
618        // If the dropped type is a type parameter, suggest adding a `[const] Destruct` bound.
619        // The suggestion is only offered on nightly, since `[const]` bounds are unstable.
620        if let Param(param_ty) = self.dropped_ty.kind()
621            && ccx.tcx.sess.is_nightly_build()
622        {
623            let tcx = ccx.tcx;
624            let caller = ccx.def_id();
625            if let Some(generics) = tcx.hir_node_by_def_id(caller).generics() {
626                let destruct_def_id = tcx.lang_items().destruct_trait();
627                suggest_constraining_type_param(
628                    tcx,
629                    generics,
630                    &mut err,
631                    param_ty.name.as_str(),
632                    "[const] Destruct",
633                    destruct_def_id,
634                    None,
635                );
636            }
637        }
638
639        err
640    }
641}
642
643#[derive(#[automatically_derived]
impl ::core::fmt::Debug for EscapingCellBorrow {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "EscapingCellBorrow")
    }
}Debug)]
644/// A borrow of a type that contains an `UnsafeCell` somewhere. The borrow might escape to
645/// the final value of the constant, and thus we cannot allow this (for now). We may allow
646/// it in the future for static items.
647pub(crate) struct EscapingCellBorrow;
648impl<'tcx> NonConstOp<'tcx> for EscapingCellBorrow {
649    fn importance(&self) -> DiagImportance {
650        // Most likely the code will try to do mutation with these borrows, which
651        // triggers its own errors. Only show this one if that does not happen.
652        DiagImportance::Secondary
653    }
654    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
655        ccx.dcx()
656            .create_err(diagnostics::InteriorMutableBorrowEscaping { span, kind: ccx.const_kind() })
657    }
658}
659
660#[derive(#[automatically_derived]
impl ::core::fmt::Debug for EscapingMutBorrow {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "EscapingMutBorrow")
    }
}Debug)]
661/// This op is for `&mut` borrows in the trailing expression of a constant
662/// which uses the "enclosing scopes rule" to leak its locals into anonymous
663/// static or const items.
664pub(crate) struct EscapingMutBorrow;
665
666impl<'tcx> NonConstOp<'tcx> for EscapingMutBorrow {
667    fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status {
668        Status::Forbidden
669    }
670
671    fn importance(&self) -> DiagImportance {
672        // Most likely the code will try to do mutation with these borrows, which
673        // triggers its own errors. Only show this one if that does not happen.
674        DiagImportance::Secondary
675    }
676
677    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
678        ccx.dcx().create_err(diagnostics::MutableBorrowEscaping { span, kind: ccx.const_kind() })
679    }
680}
681
682/// A call to a `panic()` lang item where the first argument is _not_ a `&str`.
683#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PanicNonStr {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "PanicNonStr")
    }
}Debug)]
684pub(crate) struct PanicNonStr;
685impl<'tcx> NonConstOp<'tcx> for PanicNonStr {
686    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
687        ccx.dcx().create_err(diagnostics::PanicNonStrErr { span })
688    }
689}
690
691/// Comparing raw pointers for equality.
692/// Not currently intended to ever be allowed, even behind a feature gate: operation depends on
693/// allocation base addresses that are not known at compile-time.
694#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RawPtrComparison {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "RawPtrComparison")
    }
}Debug)]
695pub(crate) struct RawPtrComparison;
696impl<'tcx> NonConstOp<'tcx> for RawPtrComparison {
697    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
698        // FIXME(const_trait_impl): revert to span_bug?
699        ccx.dcx().create_err(diagnostics::RawPtrComparisonErr { span })
700    }
701}
702
703/// Casting raw pointer or function pointer to an integer.
704/// Not currently intended to ever be allowed, even behind a feature gate: operation depends on
705/// allocation base addresses that are not known at compile-time.
706#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RawPtrToIntCast {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "RawPtrToIntCast")
    }
}Debug)]
707pub(crate) struct RawPtrToIntCast;
708impl<'tcx> NonConstOp<'tcx> for RawPtrToIntCast {
709    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
710        ccx.dcx().create_err(diagnostics::RawPtrToIntErr { span })
711    }
712}
713
714/// An access to a thread-local `static`.
715#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ThreadLocalAccess {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "ThreadLocalAccess")
    }
}Debug)]
716pub(crate) struct ThreadLocalAccess;
717impl<'tcx> NonConstOp<'tcx> for ThreadLocalAccess {
718    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
719        ccx.dcx().create_err(diagnostics::ThreadLocalAccessErr { span })
720    }
721}