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