]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir_build/hair/pattern/const_to_pat.rs
Auto merge of #67133 - oli-obk:it_must_be_a_sign, r=eddyb
[rust.git] / src / librustc_mir_build / hair / pattern / const_to_pat.rs
1 use rustc::lint;
2 use rustc::mir::Field;
3 use rustc::ty::{self, Ty, TyCtxt};
4 use rustc_hir as hir;
5 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
6 use rustc_trait_selection::traits::predicate_for_trait_def;
7 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
8 use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligation};
9
10 use rustc_index::vec::Idx;
11
12 use rustc_span::Span;
13
14 use std::cell::Cell;
15
16 use super::{FieldPat, Pat, PatCtxt, PatKind};
17
18 impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
19     /// Converts an evaluated constant to a pattern (if possible).
20     /// This means aggregate values (like structs and enums) are converted
21     /// to a pattern that matches the value (as if you'd compared via structural equality).
22     pub(super) fn const_to_pat(
23         &self,
24         cv: &'tcx ty::Const<'tcx>,
25         id: hir::HirId,
26         span: Span,
27     ) -> Pat<'tcx> {
28         debug!("const_to_pat: cv={:#?} id={:?}", cv, id);
29         debug!("const_to_pat: cv.ty={:?} span={:?}", cv.ty, span);
30
31         self.tcx.infer_ctxt().enter(|infcx| {
32             let mut convert = ConstToPat::new(self, id, span, infcx);
33             convert.to_pat(cv)
34         })
35     }
36 }
37
38 struct ConstToPat<'a, 'tcx> {
39     id: hir::HirId,
40     span: Span,
41     param_env: ty::ParamEnv<'tcx>,
42
43     // This tracks if we signal some hard error for a given const value, so that
44     // we will not subsequently issue an irrelevant lint for the same const
45     // value.
46     saw_const_match_error: Cell<bool>,
47
48     // inference context used for checking `T: Structural` bounds.
49     infcx: InferCtxt<'a, 'tcx>,
50
51     include_lint_checks: bool,
52 }
53
54 impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
55     fn new(
56         pat_ctxt: &PatCtxt<'_, 'tcx>,
57         id: hir::HirId,
58         span: Span,
59         infcx: InferCtxt<'a, 'tcx>,
60     ) -> Self {
61         ConstToPat {
62             id,
63             span,
64             infcx,
65             param_env: pat_ctxt.param_env,
66             include_lint_checks: pat_ctxt.include_lint_checks,
67             saw_const_match_error: Cell::new(false),
68         }
69     }
70
71     fn tcx(&self) -> TyCtxt<'tcx> {
72         self.infcx.tcx
73     }
74
75     fn search_for_structural_match_violation(
76         &self,
77         ty: Ty<'tcx>,
78     ) -> Option<traits::NonStructuralMatchTy<'tcx>> {
79         traits::search_for_structural_match_violation(self.id, self.span, self.tcx(), ty)
80     }
81
82     fn type_marked_structural(&self, ty: Ty<'tcx>) -> bool {
83         traits::type_marked_structural(self.id, self.span, &self.infcx, ty)
84     }
85
86     fn to_pat(&mut self, cv: &'tcx ty::Const<'tcx>) -> Pat<'tcx> {
87         // This method is just a wrapper handling a validity check; the heavy lifting is
88         // performed by the recursive `recur` method, which is not meant to be
89         // invoked except by this method.
90         //
91         // once indirect_structural_match is a full fledged error, this
92         // level of indirection can be eliminated
93
94         let inlined_const_as_pat = self.recur(cv);
95
96         if self.include_lint_checks && !self.saw_const_match_error.get() {
97             // If we were able to successfully convert the const to some pat,
98             // double-check that all types in the const implement `Structural`.
99
100             let structural = self.search_for_structural_match_violation(cv.ty);
101             debug!(
102                 "search_for_structural_match_violation cv.ty: {:?} returned: {:?}",
103                 cv.ty, structural
104             );
105             if let Some(non_sm_ty) = structural {
106                 let adt_def = match non_sm_ty {
107                     traits::NonStructuralMatchTy::Adt(adt_def) => adt_def,
108                     traits::NonStructuralMatchTy::Param => {
109                         bug!("use of constant whose type is a parameter inside a pattern")
110                     }
111                 };
112                 let path = self.tcx().def_path_str(adt_def.did);
113
114                 let make_msg = || -> String {
115                     format!(
116                         "to use a constant of type `{}` in a pattern, \
117                          `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
118                         path, path,
119                     )
120                 };
121
122                 // double-check there even *is* a semantic `PartialEq` to dispatch to.
123                 //
124                 // (If there isn't, then we can safely issue a hard
125                 // error, because that's never worked, due to compiler
126                 // using `PartialEq::eq` in this scenario in the past.)
127                 //
128                 // Note: To fix rust-lang/rust#65466, one could lift this check
129                 // *before* any structural-match checking, and unconditionally error
130                 // if `PartialEq` is not implemented. However, that breaks stable
131                 // code at the moment, because types like `for <'a> fn(&'a ())` do
132                 // not *yet* implement `PartialEq`. So for now we leave this here.
133                 let ty_is_partial_eq: bool = {
134                     let partial_eq_trait_id = self.tcx().lang_items().eq_trait().unwrap();
135                     let obligation: PredicateObligation<'_> = predicate_for_trait_def(
136                         self.tcx(),
137                         self.param_env,
138                         ObligationCause::misc(self.span, self.id),
139                         partial_eq_trait_id,
140                         0,
141                         cv.ty,
142                         &[],
143                     );
144                     // FIXME: should this call a `predicate_must_hold` variant instead?
145                     self.infcx.predicate_may_hold(&obligation)
146                 };
147
148                 if !ty_is_partial_eq {
149                     // span_fatal avoids ICE from resolution of non-existent method (rare case).
150                     self.tcx().sess.span_fatal(self.span, &make_msg());
151                 } else {
152                     self.tcx().struct_span_lint_hir(
153                         lint::builtin::INDIRECT_STRUCTURAL_MATCH,
154                         self.id,
155                         self.span,
156                         |lint| lint.build(&make_msg()).emit(),
157                     );
158                 }
159             }
160         }
161
162         inlined_const_as_pat
163     }
164
165     // Recursive helper for `to_pat`; invoke that (instead of calling this directly).
166     fn recur(&self, cv: &'tcx ty::Const<'tcx>) -> Pat<'tcx> {
167         let id = self.id;
168         let span = self.span;
169         let tcx = self.tcx();
170         let param_env = self.param_env;
171
172         let field_pats = |vals: &[&'tcx ty::Const<'tcx>]| {
173             vals.iter()
174                 .enumerate()
175                 .map(|(idx, val)| {
176                     let field = Field::new(idx);
177                     FieldPat { field, pattern: self.recur(val) }
178                 })
179                 .collect()
180         };
181
182         let kind = match cv.ty.kind {
183             ty::Float(_) => {
184                 tcx.struct_span_lint_hir(
185                     ::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
186                     id,
187                     span,
188                     |lint| lint.build("floating-point types cannot be used in patterns").emit(),
189                 );
190                 PatKind::Constant { value: cv }
191             }
192             ty::Adt(adt_def, _) if adt_def.is_union() => {
193                 // Matching on union fields is unsafe, we can't hide it in constants
194                 self.saw_const_match_error.set(true);
195                 tcx.sess.span_err(span, "cannot use unions in constant patterns");
196                 PatKind::Wild
197             }
198             // keep old code until future-compat upgraded to errors.
199             ty::Adt(adt_def, _) if !self.type_marked_structural(cv.ty) => {
200                 debug!("adt_def {:?} has !type_marked_structural for cv.ty: {:?}", adt_def, cv.ty);
201                 let path = tcx.def_path_str(adt_def.did);
202                 let msg = format!(
203                     "to use a constant of type `{}` in a pattern, \
204                      `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
205                     path, path,
206                 );
207                 self.saw_const_match_error.set(true);
208                 tcx.sess.span_err(span, &msg);
209                 PatKind::Wild
210             }
211             // keep old code until future-compat upgraded to errors.
212             ty::Ref(_, adt_ty @ ty::TyS { kind: ty::Adt(_, _), .. }, _)
213                 if !self.type_marked_structural(adt_ty) =>
214             {
215                 let adt_def =
216                     if let ty::Adt(adt_def, _) = adt_ty.kind { adt_def } else { unreachable!() };
217
218                 debug!(
219                     "adt_def {:?} has !type_marked_structural for adt_ty: {:?}",
220                     adt_def, adt_ty
221                 );
222
223                 // HACK(estebank): Side-step ICE #53708, but anything other than erroring here
224                 // would be wrong. Returnging `PatKind::Wild` is not technically correct.
225                 let path = tcx.def_path_str(adt_def.did);
226                 let msg = format!(
227                     "to use a constant of type `{}` in a pattern, \
228                      `{}` must be annotated with `#[derive(PartialEq, Eq)]`",
229                     path, path,
230                 );
231                 self.saw_const_match_error.set(true);
232                 tcx.sess.span_err(span, &msg);
233                 PatKind::Wild
234             }
235             ty::Adt(adt_def, substs) if adt_def.is_enum() => {
236                 let destructured = tcx.destructure_const(param_env.and(cv));
237                 PatKind::Variant {
238                     adt_def,
239                     substs,
240                     variant_index: destructured.variant,
241                     subpatterns: field_pats(destructured.fields),
242                 }
243             }
244             ty::Adt(_, _) => {
245                 let destructured = tcx.destructure_const(param_env.and(cv));
246                 PatKind::Leaf { subpatterns: field_pats(destructured.fields) }
247             }
248             ty::Tuple(_) => {
249                 let destructured = tcx.destructure_const(param_env.and(cv));
250                 PatKind::Leaf { subpatterns: field_pats(destructured.fields) }
251             }
252             ty::Array(..) => PatKind::Array {
253                 prefix: tcx
254                     .destructure_const(param_env.and(cv))
255                     .fields
256                     .iter()
257                     .map(|val| self.recur(val))
258                     .collect(),
259                 slice: None,
260                 suffix: Vec::new(),
261             },
262             _ => PatKind::Constant { value: cv },
263         };
264
265         Pat { span, ty: cv.ty, kind: Box::new(kind) }
266     }
267 }