]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/const_evaluatable.rs
Rollup merge of #102854 - semarie:openbsd-immutablestack, r=m-ou-se
[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_errors::ErrorGuaranteed;
12 use rustc_hir::def::DefKind;
13 use rustc_infer::infer::InferCtxt;
14 use rustc_middle::mir::interpret::ErrorHandled;
15 use rustc_middle::ty::abstract_const::{
16     walk_abstract_const, AbstractConst, FailureKind, Node, NotConstEvaluatable,
17 };
18 use rustc_middle::ty::{self, TyCtxt, TypeVisitable};
19 use rustc_session::lint;
20 use rustc_span::Span;
21
22 use std::iter;
23 use std::ops::ControlFlow;
24
25 pub struct ConstUnifyCtxt<'tcx> {
26     pub tcx: TyCtxt<'tcx>,
27     pub param_env: ty::ParamEnv<'tcx>,
28 }
29
30 impl<'tcx> ConstUnifyCtxt<'tcx> {
31     // Substitutes generics repeatedly to allow AbstractConsts to unify where a
32     // ConstKind::Unevaluated could be turned into an AbstractConst that would unify e.g.
33     // Param(N) should unify with Param(T), substs: [Unevaluated("T2", [Unevaluated("T3", [Param(N)])])]
34     #[inline]
35     #[instrument(skip(self), level = "debug")]
36     fn try_replace_substs_in_root(
37         &self,
38         mut abstr_const: AbstractConst<'tcx>,
39     ) -> Option<AbstractConst<'tcx>> {
40         while let Node::Leaf(ct) = abstr_const.root(self.tcx) {
41             match AbstractConst::from_const(self.tcx, ct) {
42                 Ok(Some(act)) => abstr_const = act,
43                 Ok(None) => break,
44                 Err(_) => return None,
45             }
46         }
47
48         Some(abstr_const)
49     }
50
51     /// Tries to unify two abstract constants using structural equality.
52     #[instrument(skip(self), level = "debug")]
53     pub fn try_unify(&self, a: AbstractConst<'tcx>, b: AbstractConst<'tcx>) -> bool {
54         let a = if let Some(a) = self.try_replace_substs_in_root(a) {
55             a
56         } else {
57             return true;
58         };
59
60         let b = if let Some(b) = self.try_replace_substs_in_root(b) {
61             b
62         } else {
63             return true;
64         };
65
66         let a_root = a.root(self.tcx);
67         let b_root = b.root(self.tcx);
68         debug!(?a_root, ?b_root);
69
70         match (a_root, b_root) {
71             (Node::Leaf(a_ct), Node::Leaf(b_ct)) => {
72                 let a_ct = a_ct.eval(self.tcx, self.param_env);
73                 debug!("a_ct evaluated: {:?}", a_ct);
74                 let b_ct = b_ct.eval(self.tcx, self.param_env);
75                 debug!("b_ct evaluated: {:?}", b_ct);
76
77                 if a_ct.ty() != b_ct.ty() {
78                     return false;
79                 }
80
81                 match (a_ct.kind(), b_ct.kind()) {
82                     // We can just unify errors with everything to reduce the amount of
83                     // emitted errors here.
84                     (ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
85                     (ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
86                         a_param == b_param
87                     }
88                     (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
89                     // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
90                     // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
91                     // means that we only allow inference variables if they are equal.
92                     (ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => a_val == b_val,
93                     // We expand generic anonymous constants at the start of this function, so this
94                     // branch should only be taking when dealing with associated constants, at
95                     // which point directly comparing them seems like the desired behavior.
96                     //
97                     // FIXME(generic_const_exprs): This isn't actually the case.
98                     // We also take this branch for concrete anonymous constants and
99                     // expand generic anonymous constants with concrete substs.
100                     (ty::ConstKind::Unevaluated(a_uv), ty::ConstKind::Unevaluated(b_uv)) => {
101                         a_uv == b_uv
102                     }
103                     // FIXME(generic_const_exprs): We may want to either actually try
104                     // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
105                     // this, for now we just return false here.
106                     _ => false,
107                 }
108             }
109             (Node::Binop(a_op, al, ar), Node::Binop(b_op, bl, br)) if a_op == b_op => {
110                 self.try_unify(a.subtree(al), b.subtree(bl))
111                     && self.try_unify(a.subtree(ar), b.subtree(br))
112             }
113             (Node::UnaryOp(a_op, av), Node::UnaryOp(b_op, bv)) if a_op == b_op => {
114                 self.try_unify(a.subtree(av), b.subtree(bv))
115             }
116             (Node::FunctionCall(a_f, a_args), Node::FunctionCall(b_f, b_args))
117                 if a_args.len() == b_args.len() =>
118             {
119                 self.try_unify(a.subtree(a_f), b.subtree(b_f))
120                     && iter::zip(a_args, b_args)
121                         .all(|(&an, &bn)| self.try_unify(a.subtree(an), b.subtree(bn)))
122             }
123             (Node::Cast(a_kind, a_operand, a_ty), Node::Cast(b_kind, b_operand, b_ty))
124                 if (a_ty == b_ty) && (a_kind == b_kind) =>
125             {
126                 self.try_unify(a.subtree(a_operand), b.subtree(b_operand))
127             }
128             // use this over `_ => false` to make adding variants to `Node` less error prone
129             (Node::Cast(..), _)
130             | (Node::FunctionCall(..), _)
131             | (Node::UnaryOp(..), _)
132             | (Node::Binop(..), _)
133             | (Node::Leaf(..), _) => false,
134         }
135     }
136 }
137
138 #[instrument(skip(tcx), level = "debug")]
139 pub fn try_unify_abstract_consts<'tcx>(
140     tcx: TyCtxt<'tcx>,
141     (a, b): (ty::UnevaluatedConst<'tcx>, ty::UnevaluatedConst<'tcx>),
142     param_env: ty::ParamEnv<'tcx>,
143 ) -> bool {
144     (|| {
145         if let Some(a) = AbstractConst::new(tcx, a)? {
146             if let Some(b) = AbstractConst::new(tcx, b)? {
147                 let const_unify_ctxt = ConstUnifyCtxt { tcx, param_env };
148                 return Ok(const_unify_ctxt.try_unify(a, b));
149             }
150         }
151
152         Ok(false)
153     })()
154     .unwrap_or_else(|_: ErrorGuaranteed| true)
155     // FIXME(generic_const_exprs): We should instead have this
156     // method return the resulting `ty::Const` and return `ConstKind::Error`
157     // on `ErrorGuaranteed`.
158 }
159
160 /// Check if a given constant can be evaluated.
161 #[instrument(skip(infcx), level = "debug")]
162 pub fn is_const_evaluatable<'tcx>(
163     infcx: &InferCtxt<'tcx>,
164     uv: ty::UnevaluatedConst<'tcx>,
165     param_env: ty::ParamEnv<'tcx>,
166     span: Span,
167 ) -> Result<(), NotConstEvaluatable> {
168     let tcx = infcx.tcx;
169
170     if tcx.features().generic_const_exprs {
171         if let Some(ct) = AbstractConst::new(tcx, uv)? {
172             if satisfied_from_param_env(tcx, ct, param_env)? {
173                 return Ok(());
174             }
175             match ct.unify_failure_kind(tcx) {
176                 FailureKind::MentionsInfer => {
177                     return Err(NotConstEvaluatable::MentionsInfer);
178                 }
179                 FailureKind::MentionsParam => {
180                     return Err(NotConstEvaluatable::MentionsParam);
181                 }
182                 // returned below
183                 FailureKind::Concrete => {}
184             }
185         }
186         let concrete = infcx.const_eval_resolve(param_env, uv, Some(span));
187         match concrete {
188             Err(ErrorHandled::TooGeneric) => {
189                 Err(NotConstEvaluatable::Error(infcx.tcx.sess.delay_span_bug(
190                     span,
191                     format!("Missing value for constant, but no error reported?"),
192                 )))
193             }
194             Err(ErrorHandled::Linted) => {
195                 let reported = infcx
196                     .tcx
197                     .sess
198                     .delay_span_bug(span, "constant in type had error reported as lint");
199                 Err(NotConstEvaluatable::Error(reported))
200             }
201             Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
202             Ok(_) => Ok(()),
203         }
204     } else {
205         // FIXME: We should only try to evaluate a given constant here if it is fully concrete
206         // as we don't want to allow things like `[u8; std::mem::size_of::<*mut T>()]`.
207         //
208         // We previously did not check this, so we only emit a future compat warning if
209         // const evaluation succeeds and the given constant is still polymorphic for now
210         // and hopefully soon change this to an error.
211         //
212         // See #74595 for more details about this.
213         let concrete = infcx.const_eval_resolve(param_env, uv, Some(span));
214
215         match concrete {
216           // If we're evaluating a foreign constant, under a nightly compiler without generic
217           // const exprs, AND it would've passed if that expression had been evaluated with
218           // generic const exprs, then suggest using generic const exprs.
219           Err(_) if tcx.sess.is_nightly_build()
220             && let Ok(Some(ct)) = AbstractConst::new(tcx, uv)
221             && satisfied_from_param_env(tcx, ct, param_env) == Ok(true) => {
222               tcx.sess
223                   .struct_span_fatal(
224                       // Slightly better span than just using `span` alone
225                       if span == rustc_span::DUMMY_SP { tcx.def_span(uv.def.did) } else { span },
226                       "failed to evaluate generic const expression",
227                   )
228                   .note("the crate this constant originates from uses `#![feature(generic_const_exprs)]`")
229                   .span_suggestion_verbose(
230                       rustc_span::DUMMY_SP,
231                       "consider enabling this feature",
232                       "#![feature(generic_const_exprs)]\n",
233                       rustc_errors::Applicability::MaybeIncorrect,
234                   )
235                   .emit()
236             }
237
238             Err(ErrorHandled::TooGeneric) => {
239                 let err = if uv.has_non_region_infer() {
240                     NotConstEvaluatable::MentionsInfer
241                 } else if uv.has_non_region_param() {
242                     NotConstEvaluatable::MentionsParam
243                 } else {
244                     let guar = infcx.tcx.sess.delay_span_bug(span, format!("Missing value for constant, but no error reported?"));
245                     NotConstEvaluatable::Error(guar)
246                 };
247
248                 Err(err)
249             },
250             Err(ErrorHandled::Linted) => {
251                 let reported =
252                     infcx.tcx.sess.delay_span_bug(span, "constant in type had error reported as lint");
253                 Err(NotConstEvaluatable::Error(reported))
254             }
255             Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
256             Ok(_) => {
257                 if uv.substs.has_non_region_param() {
258                     assert!(matches!(infcx.tcx.def_kind(uv.def.did), DefKind::AnonConst));
259                     let mir_body = infcx.tcx.mir_for_ctfe_opt_const_arg(uv.def);
260
261                     if mir_body.is_polymorphic {
262                         let Some(local_def_id) = uv.def.did.as_local() else { return Ok(()) };
263                         tcx.struct_span_lint_hir(
264                             lint::builtin::CONST_EVALUATABLE_UNCHECKED,
265                             tcx.hir().local_def_id_to_hir_id(local_def_id),
266                             span,
267                             "cannot use constants which depend on generic parameters in types",
268                             |err| err
269                         )
270                     }
271                 }
272
273                 Ok(())
274             },
275         }
276     }
277 }
278
279 #[instrument(skip(tcx), level = "debug")]
280 fn satisfied_from_param_env<'tcx>(
281     tcx: TyCtxt<'tcx>,
282     ct: AbstractConst<'tcx>,
283     param_env: ty::ParamEnv<'tcx>,
284 ) -> Result<bool, NotConstEvaluatable> {
285     for pred in param_env.caller_bounds() {
286         match pred.kind().skip_binder() {
287             ty::PredicateKind::ConstEvaluatable(uv) => {
288                 if let Some(b_ct) = AbstractConst::new(tcx, uv)? {
289                     let const_unify_ctxt = ConstUnifyCtxt { tcx, param_env };
290
291                     // Try to unify with each subtree in the AbstractConst to allow for
292                     // `N + 1` being const evaluatable even if theres only a `ConstEvaluatable`
293                     // predicate for `(N + 1) * 2`
294                     let result = walk_abstract_const(tcx, b_ct, |b_ct| {
295                         match const_unify_ctxt.try_unify(ct, b_ct) {
296                             true => ControlFlow::BREAK,
297                             false => ControlFlow::CONTINUE,
298                         }
299                     });
300
301                     if let ControlFlow::Break(()) = result {
302                         debug!("is_const_evaluatable: abstract_const ~~> ok");
303                         return Ok(true);
304                     }
305                 }
306             }
307             _ => {} // don't care
308         }
309     }
310
311     Ok(false)
312 }