1use 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 gate: Symbol,
33 gate_already_checked: bool,
36 safe_to_expose_on_stable: bool,
39 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 Primary,
50
51 Secondary,
53}
54
55pub trait NonConstOp<'tcx>: std::fmt::Debug {
57 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#[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#[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#[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 Status::Unstable {
112 gate: sym::const_trait_impl,
113 gate_already_checked: false,
114 safe_to_expose_on_stable: false,
115 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 diag.code(E0658);
133 add_feature_diagnostics(&mut diag, ccx.tcx.sess, sym::const_trait_impl);
134
135 diag
136 }
137}
138
139#[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 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(¶m_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 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
214fn 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 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 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#[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 pub feature_enabled: bool,
458 pub safe_to_expose_on_stable: bool,
459 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#[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#[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 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 | 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 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)]
644pub(crate) struct EscapingCellBorrow;
648impl<'tcx> NonConstOp<'tcx> for EscapingCellBorrow {
649 fn importance(&self) -> DiagImportance {
650 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)]
661pub(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 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#[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#[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 ccx.dcx().create_err(diagnostics::RawPtrComparisonErr { span })
700 }
701}
702
703#[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#[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}