]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/const_evaluatable.rs
fmt
[rust.git] / compiler / rustc_trait_selection / src / traits / const_evaluatable.rs
1 //! Checking that constant values used in types can be successfully evaluated.
2 //!
3 //! For concrete constants, this is fairly simple as we can just try and evaluate it.
4 //!
5 //! When dealing with polymorphic constants, for example `std::mem::size_of::<T>() - 1`,
6 //! this is not as easy.
7 //!
8 //! In this case we try to build an abstract representation of this constant using
9 //! `thir_abstract_const` which can then be checked for structural equality with other
10 //! generic constants mentioned in the `caller_bounds` of the current environment.
11 use rustc_infer::infer::InferCtxt;
12 use rustc_middle::mir::interpret::ErrorHandled;
13
14 use rustc_middle::traits::ObligationCause;
15 use rustc_middle::ty::abstract_const::NotConstEvaluatable;
16 use rustc_middle::ty::{self, TyCtxt, TypeVisitable, TypeVisitor};
17
18 use rustc_span::Span;
19 use std::ops::ControlFlow;
20
21 use crate::traits::ObligationCtxt;
22
23 /// Check if a given constant can be evaluated.
24 #[instrument(skip(infcx), level = "debug")]
25 pub fn is_const_evaluatable<'tcx>(
26     infcx: &InferCtxt<'tcx>,
27     ct: ty::Const<'tcx>,
28     param_env: ty::ParamEnv<'tcx>,
29     span: Span,
30 ) -> Result<(), NotConstEvaluatable> {
31     let tcx = infcx.tcx;
32     let uv = match ct.kind() {
33         ty::ConstKind::Unevaluated(uv) => uv,
34         ty::ConstKind::Expr(_) => bug!("unexpected expr in `is_const_evaluatable: {ct:?}"),
35         ty::ConstKind::Param(_)
36         | ty::ConstKind::Bound(_, _)
37         | ty::ConstKind::Placeholder(_)
38         | ty::ConstKind::Value(_)
39         | ty::ConstKind::Error(_) => return Ok(()),
40         ty::ConstKind::Infer(_) => return Err(NotConstEvaluatable::MentionsInfer),
41     };
42
43     if tcx.features().generic_const_exprs {
44         if let Some(ct) = tcx.expand_abstract_consts(ct)? {
45             if satisfied_from_param_env(tcx, infcx, ct, param_env)? {
46                 return Ok(());
47             }
48             if ct.has_non_region_infer() {
49                 return Err(NotConstEvaluatable::MentionsInfer);
50             } else if ct.has_non_region_param() {
51                 return Err(NotConstEvaluatable::MentionsParam);
52             }
53         }
54         let concrete = infcx.const_eval_resolve(param_env, uv, Some(span));
55         match concrete {
56             Err(ErrorHandled::TooGeneric) => Err(NotConstEvaluatable::Error(
57                 infcx
58                     .tcx
59                     .sess
60                     .delay_span_bug(span, "Missing value for constant, but no error reported?"),
61             )),
62             Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
63             Ok(_) => Ok(()),
64         }
65     } else {
66         // FIXME: We should only try to evaluate a given constant here if it is fully concrete
67         // as we don't want to allow things like `[u8; std::mem::size_of::<*mut T>()]`.
68         //
69         // We previously did not check this, so we only emit a future compat warning if
70         // const evaluation succeeds and the given constant is still polymorphic for now
71         // and hopefully soon change this to an error.
72         //
73         // See #74595 for more details about this.
74         let concrete = infcx.const_eval_resolve(param_env, uv, Some(span));
75         match concrete {
76             // If we're evaluating a generic foreign constant, under a nightly compiler while
77             // the current crate does not enable `feature(generic_const_exprs)`, abort
78             // compilation with a useful error.
79             Err(_) if tcx.sess.is_nightly_build()
80                 && let Ok(Some(ac)) = tcx.expand_abstract_consts(ct)
81                 && let ty::ConstKind::Expr(_) = ac.kind() =>
82             {
83                 tcx.sess
84                     .struct_span_fatal(
85                         // Slightly better span than just using `span` alone
86                         if span == rustc_span::DUMMY_SP { tcx.def_span(uv.def.did) } else { span },
87                         "failed to evaluate generic const expression",
88                     )
89                     .note("the crate this constant originates from uses `#![feature(generic_const_exprs)]`")
90                     .span_suggestion_verbose(
91                         rustc_span::DUMMY_SP,
92                         "consider enabling this feature",
93                         "#![feature(generic_const_exprs)]\n",
94                         rustc_errors::Applicability::MaybeIncorrect,
95                     )
96                     .emit()
97             }
98
99             Err(ErrorHandled::TooGeneric) => {
100                 let err = if uv.has_non_region_infer() {
101                     NotConstEvaluatable::MentionsInfer
102                 } else if uv.has_non_region_param() {
103                     NotConstEvaluatable::MentionsParam
104                 } else {
105                     let guar = infcx.tcx.sess.delay_span_bug(span, format!("Missing value for constant, but no error reported?"));
106                     NotConstEvaluatable::Error(guar)
107                 };
108
109                 Err(err)
110             },
111             Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
112             Ok(_) => Ok(()),
113         }
114     }
115 }
116
117 #[instrument(skip(infcx, tcx), level = "debug")]
118 fn satisfied_from_param_env<'tcx>(
119     tcx: TyCtxt<'tcx>,
120     infcx: &InferCtxt<'tcx>,
121     ct: ty::Const<'tcx>,
122     param_env: ty::ParamEnv<'tcx>,
123 ) -> Result<bool, NotConstEvaluatable> {
124     // Try to unify with each subtree in the AbstractConst to allow for
125     // `N + 1` being const evaluatable even if theres only a `ConstEvaluatable`
126     // predicate for `(N + 1) * 2`
127     struct Visitor<'a, 'tcx> {
128         ct: ty::Const<'tcx>,
129         param_env: ty::ParamEnv<'tcx>,
130
131         infcx: &'a InferCtxt<'tcx>,
132     }
133     impl<'a, 'tcx> TypeVisitor<'tcx> for Visitor<'a, 'tcx> {
134         type BreakTy = ();
135         fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
136             if let Ok(()) = self.infcx.commit_if_ok(|_| {
137                 let ocx = ObligationCtxt::new_in_snapshot(self.infcx);
138                 if let Ok(()) = ocx.eq(&ObligationCause::dummy(), self.param_env, c.ty(), self.ct.ty())
139                     && let Ok(()) = ocx.eq(&ObligationCause::dummy(), self.param_env, c, self.ct)
140                     && ocx.select_all_or_error().is_empty()
141                 {
142                     Ok(())
143                 } else {
144                     Err(())
145                 }
146             }) {
147                 ControlFlow::BREAK
148             } else if let ty::ConstKind::Expr(e) = c.kind() {
149                 e.visit_with(self)
150             } else {
151                 ControlFlow::CONTINUE
152             }
153         }
154     }
155
156     for pred in param_env.caller_bounds() {
157         match pred.kind().skip_binder() {
158             ty::PredicateKind::ConstEvaluatable(ce) => {
159                 let ty::ConstKind::Unevaluated(_) = ce.kind() else {
160                     continue
161                 };
162                 let Some(b_ct) = tcx.expand_abstract_consts(ce)? else {
163                     continue
164                 };
165
166                 let mut v = Visitor { ct, infcx, param_env };
167                 let result = b_ct.visit_with(&mut v);
168
169                 if let ControlFlow::Break(()) = result {
170                     debug!("is_const_evaluatable: abstract_const ~~> ok");
171                     return Ok(true);
172                 }
173             }
174             _ => {} // don't care
175         }
176     }
177
178     Ok(false)
179 }