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, LangItem};
4use rustc_errors::codes::*;
5use rustc_errors::{Applicability, Diag};
6use rustc_hir as hir;
7use rustc_hir::def_id::DefId;
8use rustc_infer::infer::TyCtxtInferExt;
9use rustc_infer::traits::{ImplSource, Obligation, ObligationCause};
10use rustc_middle::mir::CallSource;
11use rustc_middle::span_bug;
12use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths};
13use rustc_middle::ty::{
14    self, Closure, FnDef, FnPtr, GenericArgKind, GenericArgsRef, Param, TraitRef, Ty,
15    suggest_constraining_type_param,
16};
17use rustc_session::parse::add_feature_diagnostics;
18use rustc_span::{BytePos, Pos, Span, Symbol, 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::{errors, fluent_generated};
27
28#[derive(Clone, Copy, Debug, PartialEq, 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(Clone, 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(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(errors::UnallowedFnPointerCall { span, kind: ccx.const_kind() })
75    }
76}
77
78/// A call to a function that is in a trait, or has trait bounds that make it conditionally-const.
79#[derive(Debug)]
80pub(crate) struct ConditionallyConstCall<'tcx> {
81    pub callee: DefId,
82    pub args: GenericArgsRef<'tcx>,
83    pub span: Span,
84    pub call_source: CallSource,
85}
86
87impl<'tcx> NonConstOp<'tcx> for ConditionallyConstCall<'tcx> {
88    fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status {
89        // We use the `const_trait_impl` gate for all conditionally-const calls.
90        Status::Unstable {
91            gate: sym::const_trait_impl,
92            gate_already_checked: false,
93            safe_to_expose_on_stable: false,
94            // We don't want the "mark the callee as `#[rustc_const_stable_indirect]`" hint
95            is_function_call: false,
96        }
97    }
98
99    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, _: Span) -> Diag<'tcx> {
100        let mut diag = build_error_for_const_call(
101            ccx,
102            self.callee,
103            self.args,
104            self.span,
105            self.call_source,
106            "conditionally",
107            |_, _, _| {},
108        );
109
110        // Override code and mention feature.
111        diag.code(E0658);
112        add_feature_diagnostics(&mut diag, ccx.tcx.sess, sym::const_trait_impl);
113
114        diag
115    }
116}
117
118/// A function call where the callee is not marked as `const`.
119#[derive(Debug, Clone, Copy)]
120pub(crate) struct FnCallNonConst<'tcx> {
121    pub callee: DefId,
122    pub args: GenericArgsRef<'tcx>,
123    pub span: Span,
124    pub call_source: CallSource,
125}
126
127impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
128    // FIXME: make this translatable
129    #[allow(rustc::diagnostic_outside_of_impl)]
130    #[allow(rustc::untranslatable_diagnostic)]
131    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, _: Span) -> Diag<'tcx> {
132        let tcx = ccx.tcx;
133        let caller = ccx.def_id();
134
135        let mut err = build_error_for_const_call(
136            ccx,
137            self.callee,
138            self.args,
139            self.span,
140            self.call_source,
141            "non",
142            |err, self_ty, trait_id| {
143                // FIXME(const_trait_impl): Do we need any of this on the non-const codepath?
144
145                let trait_ref = TraitRef::from_method(tcx, trait_id, self.args);
146
147                match self_ty.kind() {
148                    Param(param_ty) => {
149                        debug!(?param_ty);
150                        if let Some(generics) = tcx.hir_node_by_def_id(caller).generics() {
151                            let constraint = with_no_trimmed_paths!(format!(
152                                "~const {}",
153                                trait_ref.print_trait_sugared(),
154                            ));
155                            suggest_constraining_type_param(
156                                tcx,
157                                generics,
158                                err,
159                                param_ty.name.as_str(),
160                                &constraint,
161                                Some(trait_ref.def_id),
162                                None,
163                            );
164                        }
165                    }
166                    ty::Adt(..) => {
167                        let (infcx, param_env) =
168                            tcx.infer_ctxt().build_with_typing_env(ccx.typing_env);
169                        let obligation =
170                            Obligation::new(tcx, ObligationCause::dummy(), param_env, trait_ref);
171                        let mut selcx = SelectionContext::new(&infcx);
172                        let implsrc = selcx.select(&obligation);
173                        if let Ok(Some(ImplSource::UserDefined(data))) = implsrc {
174                            // FIXME(const_trait_impl) revisit this
175                            if !tcx.is_const_trait_impl(data.impl_def_id) {
176                                let span = tcx.def_span(data.impl_def_id);
177                                err.subdiagnostic(errors::NonConstImplNote { span });
178                            }
179                        }
180                    }
181                    _ => {}
182                }
183            },
184        );
185
186        if let ConstContext::Static(_) = ccx.const_kind() {
187            err.note(fluent_generated::const_eval_lazy_lock);
188        }
189
190        err
191    }
192}
193
194/// Build an error message reporting that a function call is not const (or only
195/// conditionally const). In case that this call is desugared (like an operator
196/// or sugar from something like a `for` loop), try to build a better error message
197/// that doesn't call it a method.
198fn build_error_for_const_call<'tcx>(
199    ccx: &ConstCx<'_, 'tcx>,
200    callee: DefId,
201    args: ty::GenericArgsRef<'tcx>,
202    span: Span,
203    call_source: CallSource,
204    non_or_conditionally: &'static str,
205    note_trait_if_possible: impl FnOnce(&mut Diag<'tcx>, Ty<'tcx>, DefId),
206) -> Diag<'tcx> {
207    let tcx = ccx.tcx;
208
209    let call_kind =
210        call_kind(tcx, ccx.typing_env, callee, args, span, call_source.from_hir_call(), None);
211
212    debug!(?call_kind);
213
214    let mut err = match call_kind {
215        CallKind::Normal { desugaring: Some((kind, self_ty)), .. } => {
216            macro_rules! error {
217                ($err:ident) => {
218                    tcx.dcx().create_err(errors::$err {
219                        span,
220                        ty: self_ty,
221                        kind: ccx.const_kind(),
222                        non_or_conditionally,
223                    })
224                };
225            }
226
227            // Don't point at the trait if this is a desugaring...
228            // FIXME(const_trait_impl): we could perhaps do this for `Iterator`.
229            match kind {
230                CallDesugaringKind::ForLoopIntoIter | CallDesugaringKind::ForLoopNext => {
231                    error!(NonConstForLoopIntoIter)
232                }
233                CallDesugaringKind::QuestionBranch => {
234                    error!(NonConstQuestionBranch)
235                }
236                CallDesugaringKind::QuestionFromResidual => {
237                    error!(NonConstQuestionFromResidual)
238                }
239                CallDesugaringKind::TryBlockFromOutput => {
240                    error!(NonConstTryBlockFromOutput)
241                }
242                CallDesugaringKind::Await => {
243                    error!(NonConstAwait)
244                }
245            }
246        }
247        CallKind::FnCall { fn_trait_id, self_ty } => {
248            let note = match self_ty.kind() {
249                FnDef(def_id, ..) => {
250                    let span = tcx.def_span(*def_id);
251                    if ccx.tcx.is_const_fn(*def_id) {
252                        span_bug!(span, "calling const FnDef errored when it shouldn't");
253                    }
254
255                    Some(errors::NonConstClosureNote::FnDef { span })
256                }
257                FnPtr(..) => Some(errors::NonConstClosureNote::FnPtr),
258                Closure(..) => Some(errors::NonConstClosureNote::Closure),
259                _ => None,
260            };
261
262            let mut err = tcx.dcx().create_err(errors::NonConstClosure {
263                span,
264                kind: ccx.const_kind(),
265                note,
266                non_or_conditionally,
267            });
268
269            note_trait_if_possible(&mut err, self_ty, fn_trait_id);
270            err
271        }
272        CallKind::Operator { trait_id, self_ty, .. } => {
273            let mut err = if let CallSource::MatchCmp = call_source {
274                tcx.dcx().create_err(errors::NonConstMatchEq {
275                    span,
276                    kind: ccx.const_kind(),
277                    ty: self_ty,
278                    non_or_conditionally,
279                })
280            } else {
281                let mut sugg = None;
282
283                if ccx.tcx.is_lang_item(trait_id, LangItem::PartialEq) {
284                    match (args[0].kind(), args[1].kind()) {
285                        (GenericArgKind::Type(self_ty), GenericArgKind::Type(rhs_ty))
286                            if self_ty == rhs_ty
287                                && self_ty.is_ref()
288                                && self_ty.peel_refs().is_primitive() =>
289                        {
290                            let mut num_refs = 0;
291                            let mut tmp_ty = self_ty;
292                            while let rustc_middle::ty::Ref(_, inner_ty, _) = tmp_ty.kind() {
293                                num_refs += 1;
294                                tmp_ty = *inner_ty;
295                            }
296                            let deref = "*".repeat(num_refs);
297
298                            if let Ok(call_str) = ccx.tcx.sess.source_map().span_to_snippet(span) {
299                                if let Some(eq_idx) = call_str.find("==") {
300                                    if let Some(rhs_idx) =
301                                        call_str[(eq_idx + 2)..].find(|c: char| !c.is_whitespace())
302                                    {
303                                        let rhs_pos =
304                                            span.lo() + BytePos::from_usize(eq_idx + 2 + rhs_idx);
305                                        let rhs_span = span.with_lo(rhs_pos).with_hi(rhs_pos);
306                                        sugg = Some(errors::ConsiderDereferencing {
307                                            deref,
308                                            span: span.shrink_to_lo(),
309                                            rhs_span,
310                                        });
311                                    }
312                                }
313                            }
314                        }
315                        _ => {}
316                    }
317                }
318                tcx.dcx().create_err(errors::NonConstOperator {
319                    span,
320                    kind: ccx.const_kind(),
321                    sugg,
322                    non_or_conditionally,
323                })
324            };
325
326            note_trait_if_possible(&mut err, self_ty, trait_id);
327            err
328        }
329        CallKind::DerefCoercion { deref_target_span, deref_target_ty, self_ty } => {
330            // Check first whether the source is accessible (issue #87060)
331            let target = if let Some(deref_target_span) = deref_target_span
332                && tcx.sess.source_map().is_span_accessible(deref_target_span)
333            {
334                Some(deref_target_span)
335            } else {
336                None
337            };
338
339            let mut err = tcx.dcx().create_err(errors::NonConstDerefCoercion {
340                span,
341                ty: self_ty,
342                kind: ccx.const_kind(),
343                target_ty: deref_target_ty,
344                deref_target: target,
345                non_or_conditionally,
346            });
347
348            note_trait_if_possible(&mut err, self_ty, tcx.require_lang_item(LangItem::Deref, span));
349            err
350        }
351        _ if tcx.opt_parent(callee) == tcx.get_diagnostic_item(sym::FmtArgumentsNew) => {
352            ccx.dcx().create_err(errors::NonConstFmtMacroCall {
353                span,
354                kind: ccx.const_kind(),
355                non_or_conditionally,
356            })
357        }
358        _ => ccx.dcx().create_err(errors::NonConstFnCall {
359            span,
360            def_descr: ccx.tcx.def_descr(callee),
361            def_path_str: ccx.tcx.def_path_str_with_args(callee, args),
362            kind: ccx.const_kind(),
363            non_or_conditionally,
364        }),
365    };
366
367    err.note(format!(
368        "calls in {}s are limited to constant functions, \
369             tuple structs and tuple variants",
370        ccx.const_kind(),
371    ));
372
373    err
374}
375
376/// A call to an `#[unstable]` const fn, `#[rustc_const_unstable]` function or trait.
377///
378/// Contains the name of the feature that would allow the use of this function/trait.
379#[derive(Debug)]
380pub(crate) struct CallUnstable {
381    pub def_id: DefId,
382    pub feature: Symbol,
383    /// If this is true, then the feature is enabled, but we need to still check if it is safe to
384    /// expose on stable.
385    pub feature_enabled: bool,
386    pub safe_to_expose_on_stable: bool,
387    pub suggestion_span: Option<Span>,
388    /// true if `def_id` is the function we are calling, false if `def_id` is an unstable trait.
389    pub is_function_call: bool,
390}
391
392impl<'tcx> NonConstOp<'tcx> for CallUnstable {
393    fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status {
394        Status::Unstable {
395            gate: self.feature,
396            gate_already_checked: self.feature_enabled,
397            safe_to_expose_on_stable: self.safe_to_expose_on_stable,
398            is_function_call: self.is_function_call,
399        }
400    }
401
402    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
403        assert!(!self.feature_enabled);
404        let mut err = if self.is_function_call {
405            ccx.dcx().create_err(errors::UnstableConstFn {
406                span,
407                def_path: ccx.tcx.def_path_str(self.def_id),
408            })
409        } else {
410            ccx.dcx().create_err(errors::UnstableConstTrait {
411                span,
412                def_path: ccx.tcx.def_path_str(self.def_id),
413            })
414        };
415        // FIXME: make this translatable
416        let msg = format!("add `#![feature({})]` to the crate attributes to enable", self.feature);
417        #[allow(rustc::untranslatable_diagnostic)]
418        if let Some(span) = self.suggestion_span {
419            err.span_suggestion_verbose(
420                span,
421                msg,
422                format!("#![feature({})]\n", self.feature),
423                Applicability::MachineApplicable,
424            );
425        } else {
426            err.help(msg);
427        }
428
429        err
430    }
431}
432
433/// A call to an intrinsic that is just not const-callable at all.
434#[derive(Debug)]
435pub(crate) struct IntrinsicNonConst {
436    pub name: Symbol,
437}
438
439impl<'tcx> NonConstOp<'tcx> for IntrinsicNonConst {
440    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
441        ccx.dcx().create_err(errors::NonConstIntrinsic {
442            span,
443            name: self.name,
444            kind: ccx.const_kind(),
445        })
446    }
447}
448
449/// A call to an intrinsic that is just not const-callable at all.
450#[derive(Debug)]
451pub(crate) struct IntrinsicUnstable {
452    pub name: Symbol,
453    pub feature: Symbol,
454    pub const_stable_indirect: bool,
455    pub suggestion: Option<Span>,
456}
457
458impl<'tcx> NonConstOp<'tcx> for IntrinsicUnstable {
459    fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status {
460        Status::Unstable {
461            gate: self.feature,
462            gate_already_checked: false,
463            safe_to_expose_on_stable: self.const_stable_indirect,
464            // We do *not* want to suggest to mark the intrinsic as `const_stable_indirect`,
465            // that's not a trivial change!
466            is_function_call: false,
467        }
468    }
469
470    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
471        ccx.dcx().create_err(errors::UnstableIntrinsic {
472            span,
473            name: self.name,
474            feature: self.feature,
475            suggestion: self.suggestion,
476            help: self.suggestion.is_none(),
477        })
478    }
479}
480
481#[derive(Debug)]
482pub(crate) struct Coroutine(pub hir::CoroutineKind);
483impl<'tcx> NonConstOp<'tcx> for Coroutine {
484    fn status_in_item(&self, _: &ConstCx<'_, 'tcx>) -> Status {
485        match self.0 {
486            hir::CoroutineKind::Desugared(
487                hir::CoroutineDesugaring::Async,
488                hir::CoroutineSource::Block,
489            )
490            // FIXME(coroutines): eventually we want to gate const coroutine coroutines behind a
491            // different feature.
492            | hir::CoroutineKind::Coroutine(_) => Status::Unstable {
493                gate: sym::const_async_blocks,
494                gate_already_checked: false,
495                safe_to_expose_on_stable: false,
496                is_function_call: false,
497            },
498            _ => Status::Forbidden,
499        }
500    }
501
502    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
503        let msg = format!("{} are not allowed in {}s", self.0.to_plural_string(), ccx.const_kind());
504        if let Status::Unstable { gate, .. } = self.status_in_item(ccx) {
505            ccx.tcx.sess.create_feature_err(errors::UnallowedOpInConstContext { span, msg }, gate)
506        } else {
507            ccx.dcx().create_err(errors::UnallowedOpInConstContext { span, msg })
508        }
509    }
510}
511
512#[derive(Debug)]
513pub(crate) struct HeapAllocation;
514impl<'tcx> NonConstOp<'tcx> for HeapAllocation {
515    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
516        ccx.dcx().create_err(errors::UnallowedHeapAllocations {
517            span,
518            kind: ccx.const_kind(),
519            teach: ccx.tcx.sess.teach(E0010),
520        })
521    }
522}
523
524#[derive(Debug)]
525pub(crate) struct InlineAsm;
526impl<'tcx> NonConstOp<'tcx> for InlineAsm {
527    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
528        ccx.dcx().create_err(errors::UnallowedInlineAsm { span, kind: ccx.const_kind() })
529    }
530}
531
532#[derive(Debug)]
533pub(crate) struct LiveDrop<'tcx> {
534    pub dropped_at: Span,
535    pub dropped_ty: Ty<'tcx>,
536    pub needs_non_const_drop: bool,
537}
538impl<'tcx> NonConstOp<'tcx> for LiveDrop<'tcx> {
539    fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status {
540        if self.needs_non_const_drop {
541            Status::Forbidden
542        } else {
543            Status::Unstable {
544                gate: sym::const_destruct,
545                gate_already_checked: false,
546                safe_to_expose_on_stable: false,
547                is_function_call: false,
548            }
549        }
550    }
551
552    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
553        if self.needs_non_const_drop {
554            ccx.dcx().create_err(errors::LiveDrop {
555                span,
556                dropped_ty: self.dropped_ty,
557                kind: ccx.const_kind(),
558                dropped_at: self.dropped_at,
559            })
560        } else {
561            ccx.tcx.sess.create_feature_err(
562                errors::LiveDrop {
563                    span,
564                    dropped_ty: self.dropped_ty,
565                    kind: ccx.const_kind(),
566                    dropped_at: self.dropped_at,
567                },
568                sym::const_destruct,
569            )
570        }
571    }
572}
573
574#[derive(Debug)]
575/// A borrow of a type that contains an `UnsafeCell` somewhere. The borrow might escape to
576/// the final value of the constant, and thus we cannot allow this (for now). We may allow
577/// it in the future for static items.
578pub(crate) struct EscapingCellBorrow;
579impl<'tcx> NonConstOp<'tcx> for EscapingCellBorrow {
580    fn importance(&self) -> DiagImportance {
581        // Most likely the code will try to do mutation with these borrows, which
582        // triggers its own errors. Only show this one if that does not happen.
583        DiagImportance::Secondary
584    }
585    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
586        ccx.dcx().create_err(errors::InteriorMutableRefEscaping {
587            span,
588            opt_help: matches!(ccx.const_kind(), hir::ConstContext::Static(_)),
589            kind: ccx.const_kind(),
590            teach: ccx.tcx.sess.teach(E0492),
591        })
592    }
593}
594
595#[derive(Debug)]
596/// This op is for `&mut` borrows in the trailing expression of a constant
597/// which uses the "enclosing scopes rule" to leak its locals into anonymous
598/// static or const items.
599pub(crate) struct EscapingMutBorrow(pub hir::BorrowKind);
600
601impl<'tcx> NonConstOp<'tcx> for EscapingMutBorrow {
602    fn status_in_item(&self, _ccx: &ConstCx<'_, 'tcx>) -> Status {
603        Status::Forbidden
604    }
605
606    fn importance(&self) -> DiagImportance {
607        // Most likely the code will try to do mutation with these borrows, which
608        // triggers its own errors. Only show this one if that does not happen.
609        DiagImportance::Secondary
610    }
611
612    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
613        match self.0 {
614            hir::BorrowKind::Raw => ccx.tcx.dcx().create_err(errors::MutableRawEscaping {
615                span,
616                kind: ccx.const_kind(),
617                teach: ccx.tcx.sess.teach(E0764),
618            }),
619            hir::BorrowKind::Ref => ccx.dcx().create_err(errors::MutableRefEscaping {
620                span,
621                kind: ccx.const_kind(),
622                teach: ccx.tcx.sess.teach(E0764),
623            }),
624        }
625    }
626}
627
628/// A call to a `panic()` lang item where the first argument is _not_ a `&str`.
629#[derive(Debug)]
630pub(crate) struct PanicNonStr;
631impl<'tcx> NonConstOp<'tcx> for PanicNonStr {
632    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
633        ccx.dcx().create_err(errors::PanicNonStrErr { span })
634    }
635}
636
637/// Comparing raw pointers for equality.
638/// Not currently intended to ever be allowed, even behind a feature gate: operation depends on
639/// allocation base addresses that are not known at compile-time.
640#[derive(Debug)]
641pub(crate) struct RawPtrComparison;
642impl<'tcx> NonConstOp<'tcx> for RawPtrComparison {
643    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
644        // FIXME(const_trait_impl): revert to span_bug?
645        ccx.dcx().create_err(errors::RawPtrComparisonErr { span })
646    }
647}
648
649/// Casting raw pointer or function pointer to an integer.
650/// Not currently intended to ever be allowed, even behind a feature gate: operation depends on
651/// allocation base addresses that are not known at compile-time.
652#[derive(Debug)]
653pub(crate) struct RawPtrToIntCast;
654impl<'tcx> NonConstOp<'tcx> for RawPtrToIntCast {
655    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
656        ccx.dcx().create_err(errors::RawPtrToIntErr { span })
657    }
658}
659
660/// An access to a thread-local `static`.
661#[derive(Debug)]
662pub(crate) struct ThreadLocalAccess;
663impl<'tcx> NonConstOp<'tcx> for ThreadLocalAccess {
664    fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> {
665        ccx.dcx().create_err(errors::ThreadLocalAccessErr { span })
666    }
667}