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