rustc_mir_build/builder/matches/
match_pair.rs

1use std::sync::Arc;
2
3use rustc_abi::FieldIdx;
4use rustc_middle::mir::*;
5use rustc_middle::span_bug;
6use rustc_middle::thir::*;
7use rustc_middle::ty::{self, Ty, TypeVisitableExt};
8
9use crate::builder::Builder;
10use crate::builder::expr::as_place::{PlaceBase, PlaceBuilder};
11use crate::builder::matches::{
12    FlatPat, MatchPairTree, PatConstKind, PatternExtraData, SliceLenOp, TestableCase,
13};
14
15impl<'a, 'tcx> Builder<'a, 'tcx> {
16    /// Builds and pushes [`MatchPairTree`] subtrees, one for each pattern in
17    /// `subpatterns`, representing the fields of a [`PatKind::Variant`] or
18    /// [`PatKind::Leaf`].
19    ///
20    /// Used internally by [`MatchPairTree::for_pattern`].
21    fn field_match_pairs(
22        &mut self,
23        match_pairs: &mut Vec<MatchPairTree<'tcx>>,
24        extra_data: &mut PatternExtraData<'tcx>,
25        place: PlaceBuilder<'tcx>,
26        subpatterns: &[FieldPat<'tcx>],
27    ) {
28        for fieldpat in subpatterns {
29            let place = place.clone_project(PlaceElem::Field(fieldpat.field, fieldpat.pattern.ty));
30            MatchPairTree::for_pattern(place, &fieldpat.pattern, self, match_pairs, extra_data);
31        }
32    }
33
34    /// Builds [`MatchPairTree`] subtrees for the prefix/middle/suffix parts of an
35    /// array pattern or slice pattern, and adds those trees to `match_pairs`.
36    ///
37    /// Used internally by [`MatchPairTree::for_pattern`].
38    fn prefix_slice_suffix(
39        &mut self,
40        match_pairs: &mut Vec<MatchPairTree<'tcx>>,
41        extra_data: &mut PatternExtraData<'tcx>,
42        place: &PlaceBuilder<'tcx>,
43        prefix: &[Pat<'tcx>],
44        opt_slice: &Option<Box<Pat<'tcx>>>,
45        suffix: &[Pat<'tcx>],
46    ) {
47        let tcx = self.tcx;
48        let (min_length, exact_size) = if let Some(place_resolved) = place.try_to_place(self) {
49            let place_ty = place_resolved.ty(&self.local_decls, tcx).ty;
50            match place_ty.kind() {
51                ty::Array(_, length) => {
52                    if let Some(length) = length.try_to_target_usize(tcx) {
53                        (length, true)
54                    } else {
55                        // This can happen when the array length is a generic const
56                        // expression that couldn't be evaluated (e.g., due to an error).
57                        // Since there's already a compilation error, we use a fallback
58                        // to avoid an ICE.
59                        tcx.dcx().span_delayed_bug(
60                            tcx.def_span(self.def_id),
61                            "array length in pattern couldn't be evaluated",
62                        );
63                        ((prefix.len() + suffix.len()).try_into().unwrap(), false)
64                    }
65                }
66                _ => ((prefix.len() + suffix.len()).try_into().unwrap(), false),
67            }
68        } else {
69            ((prefix.len() + suffix.len()).try_into().unwrap(), false)
70        };
71
72        for (idx, subpattern) in prefix.iter().enumerate() {
73            let elem =
74                ProjectionElem::ConstantIndex { offset: idx as u64, min_length, from_end: false };
75            let place = place.clone_project(elem);
76            MatchPairTree::for_pattern(place, subpattern, self, match_pairs, extra_data)
77        }
78
79        if let Some(subslice_pat) = opt_slice {
80            let suffix_len = suffix.len() as u64;
81            let subslice = place.clone_project(PlaceElem::Subslice {
82                from: prefix.len() as u64,
83                to: if exact_size { min_length - suffix_len } else { suffix_len },
84                from_end: !exact_size,
85            });
86            MatchPairTree::for_pattern(subslice, subslice_pat, self, match_pairs, extra_data);
87        }
88
89        for (idx, subpattern) in suffix.iter().rev().enumerate() {
90            let end_offset = (idx + 1) as u64;
91            let elem = ProjectionElem::ConstantIndex {
92                offset: if exact_size { min_length - end_offset } else { end_offset },
93                min_length,
94                from_end: !exact_size,
95            };
96            let place = place.clone_project(elem);
97            MatchPairTree::for_pattern(place, subpattern, self, match_pairs, extra_data)
98        }
99    }
100}
101
102impl<'tcx> MatchPairTree<'tcx> {
103    /// Recursively builds a match pair tree for the given pattern and its
104    /// subpatterns.
105    pub(super) fn for_pattern(
106        mut place_builder: PlaceBuilder<'tcx>,
107        pattern: &Pat<'tcx>,
108        cx: &mut Builder<'_, 'tcx>,
109        match_pairs: &mut Vec<Self>, // Newly-created nodes are added to this vector
110        extra_data: &mut PatternExtraData<'tcx>, // Bindings/ascriptions are added here
111    ) {
112        // Force the place type to the pattern's type.
113        // FIXME(oli-obk): can we use this to simplify slice/array pattern hacks?
114        if let Some(resolved) = place_builder.resolve_upvar(cx) {
115            place_builder = resolved;
116        }
117
118        if !cx.tcx.next_trait_solver_globally() {
119            // Only add the OpaqueCast projection if the given place is an opaque type and the
120            // expected type from the pattern is not.
121            let may_need_cast = match place_builder.base() {
122                PlaceBase::Local(local) => {
123                    let ty =
124                        Place::ty_from(local, place_builder.projection(), &cx.local_decls, cx.tcx)
125                            .ty;
126                    ty != pattern.ty && ty.has_opaque_types()
127                }
128                _ => true,
129            };
130            if may_need_cast {
131                place_builder = place_builder.project(ProjectionElem::OpaqueCast(pattern.ty));
132            }
133        }
134
135        let place = place_builder.try_to_place(cx);
136        let mut subpairs = Vec::new();
137        let testable_case = match pattern.kind {
138            PatKind::Missing | PatKind::Wild | PatKind::Error(_) => None,
139
140            PatKind::Or { ref pats } => {
141                let pats: Box<[FlatPat<'tcx>]> =
142                    pats.iter().map(|pat| FlatPat::new(place_builder.clone(), pat, cx)).collect();
143                if !pats[0].extra_data.bindings.is_empty() {
144                    // Hold a place for any bindings established in (possibly-nested) or-patterns.
145                    // By only holding a place when bindings are present, we skip over any
146                    // or-patterns that will be simplified by `merge_trivial_subcandidates`. In
147                    // other words, we can assume this expands into subcandidates.
148                    // FIXME(@dianne): this needs updating/removing if we always merge or-patterns
149                    extra_data.bindings.push(super::SubpatternBindings::FromOrPattern);
150                }
151                Some(TestableCase::Or { pats })
152            }
153
154            PatKind::Range(ref range) => {
155                if range.is_full_range(cx.tcx) == Some(true) {
156                    None
157                } else {
158                    Some(TestableCase::Range(Arc::clone(range)))
159                }
160            }
161
162            PatKind::Constant { value } => {
163                // CAUTION: The type of the pattern node (`pattern.ty`) is
164                // _often_ the same as the type of the const value (`value.ty`),
165                // but there are some cases where those types differ
166                // (e.g. when `deref!(..)` patterns interact with `String`).
167
168                // Classify the constant-pattern into further kinds, to
169                // reduce the number of ad-hoc type tests needed later on.
170                let pat_ty = pattern.ty;
171                let const_kind = if pat_ty.is_bool() {
172                    PatConstKind::Bool
173                } else if pat_ty.is_integral() || pat_ty.is_char() {
174                    PatConstKind::IntOrChar
175                } else if pat_ty.is_floating_point() {
176                    PatConstKind::Float
177                } else if pat_ty.is_str() {
178                    // Deref-patterns can cause string-literal patterns to have
179                    // type `str` instead of the usual `&str`.
180                    if !cx.tcx.features().deref_patterns() {
181                        span_bug!(
182                            pattern.span,
183                            "const pattern has type `str` but deref_patterns is not enabled"
184                        );
185                    }
186                    PatConstKind::String
187                } else if pat_ty.is_imm_ref_str() {
188                    PatConstKind::String
189                } else {
190                    // FIXME(Zalathar): This still covers several different
191                    // categories (e.g. raw pointer, pattern-type)
192                    // which could be split out into their own kinds.
193                    PatConstKind::Other
194                };
195                Some(TestableCase::Constant { value, kind: const_kind })
196            }
197
198            PatKind::AscribeUserType {
199                ascription: Ascription { ref annotation, variance },
200                ref subpattern,
201                ..
202            } => {
203                MatchPairTree::for_pattern(
204                    place_builder,
205                    subpattern,
206                    cx,
207                    &mut subpairs,
208                    extra_data,
209                );
210
211                // Apply the type ascription to the value at `match_pair.place`
212                if let Some(source) = place {
213                    let annotation = annotation.clone();
214                    extra_data.ascriptions.push(super::Ascription { source, annotation, variance });
215                }
216
217                None
218            }
219
220            PatKind::Binding { mode, var, is_shorthand, ref subpattern, .. } => {
221                // In order to please the borrow checker, when lowering a pattern
222                // like `x @ subpat` we must establish any bindings in `subpat`
223                // before establishing the binding for `x`.
224                //
225                // For example (from #69971):
226                //
227                // ```ignore (illustrative)
228                // struct NonCopyStruct {
229                //     copy_field: u32,
230                // }
231                //
232                // fn foo1(x: NonCopyStruct) {
233                //     let y @ NonCopyStruct { copy_field: z } = x;
234                //     // the above should turn into
235                //     let z = x.copy_field;
236                //     let y = x;
237                // }
238                // ```
239
240                // First, recurse into the subpattern, if any.
241                if let Some(subpattern) = subpattern.as_ref() {
242                    // this is the `x @ P` case; have to keep matching against `P` now
243                    MatchPairTree::for_pattern(
244                        place_builder,
245                        subpattern,
246                        cx,
247                        &mut subpairs,
248                        extra_data,
249                    );
250                }
251
252                // Then push this binding, after any bindings in the subpattern.
253                if let Some(source) = place {
254                    extra_data.bindings.push(super::SubpatternBindings::One(super::Binding {
255                        span: pattern.span,
256                        source,
257                        var_id: var,
258                        binding_mode: mode,
259                        is_shorthand,
260                    }));
261                }
262
263                None
264            }
265
266            PatKind::ExpandedConstant { subpattern: ref pattern, .. } => {
267                MatchPairTree::for_pattern(place_builder, pattern, cx, &mut subpairs, extra_data);
268                None
269            }
270
271            PatKind::Array { ref prefix, ref slice, ref suffix } => {
272                cx.prefix_slice_suffix(
273                    &mut subpairs,
274                    extra_data,
275                    &place_builder,
276                    prefix,
277                    slice,
278                    suffix,
279                );
280                None
281            }
282            PatKind::Slice { ref prefix, ref slice, ref suffix } => {
283                cx.prefix_slice_suffix(
284                    &mut subpairs,
285                    extra_data,
286                    &place_builder,
287                    prefix,
288                    slice,
289                    suffix,
290                );
291
292                if prefix.is_empty() && slice.is_some() && suffix.is_empty() {
293                    // This pattern is shaped like `[..]`. It can match a slice
294                    // of any length, so no length test is needed.
295                    None
296                } else {
297                    // Any other shape of slice pattern requires a length test.
298                    // Slice patterns with a `..` subpattern require a minimum
299                    // length; those without `..` require an exact length.
300                    Some(TestableCase::Slice {
301                        len: u64::try_from(prefix.len() + suffix.len()).unwrap(),
302                        op: if slice.is_some() {
303                            SliceLenOp::GreaterOrEqual
304                        } else {
305                            SliceLenOp::Equal
306                        },
307                    })
308                }
309            }
310
311            PatKind::Variant { adt_def, variant_index, args, ref subpatterns } => {
312                let downcast_place = place_builder.downcast(adt_def, variant_index); // `(x as Variant)`
313                cx.field_match_pairs(&mut subpairs, extra_data, downcast_place, subpatterns);
314
315                let irrefutable = adt_def.variants().iter_enumerated().all(|(i, v)| {
316                    i == variant_index
317                        || !v.inhabited_predicate(cx.tcx, adt_def).instantiate(cx.tcx, args).apply(
318                            cx.tcx,
319                            cx.infcx.typing_env(cx.param_env),
320                            cx.def_id.into(),
321                        )
322                }) && !adt_def.variant_list_has_applicable_non_exhaustive();
323                if irrefutable {
324                    None
325                } else {
326                    Some(TestableCase::Variant { adt_def, variant_index })
327                }
328            }
329
330            PatKind::Leaf { ref subpatterns } => {
331                cx.field_match_pairs(&mut subpairs, extra_data, place_builder, subpatterns);
332                None
333            }
334
335            // FIXME: Pin-patterns should probably have their own pattern kind,
336            // instead of overloading `PatKind::Deref` via the pattern type.
337            PatKind::Deref { ref subpattern }
338                if let Some(ref_ty) = pattern.ty.pinned_ty()
339                    && ref_ty.is_ref() =>
340            {
341                MatchPairTree::for_pattern(
342                    place_builder.field(FieldIdx::ZERO, ref_ty).deref(),
343                    subpattern,
344                    cx,
345                    &mut subpairs,
346                    extra_data,
347                );
348                None
349            }
350
351            PatKind::Deref { ref subpattern }
352            | PatKind::DerefPattern { ref subpattern, borrow: DerefPatBorrowMode::Box } => {
353                MatchPairTree::for_pattern(
354                    place_builder.deref(),
355                    subpattern,
356                    cx,
357                    &mut subpairs,
358                    extra_data,
359                );
360                None
361            }
362
363            PatKind::DerefPattern {
364                ref subpattern,
365                borrow: DerefPatBorrowMode::Borrow(mutability),
366            } => {
367                // Create a new temporary for each deref pattern.
368                // FIXME(deref_patterns): dedup temporaries to avoid multiple `deref()` calls?
369                let temp = cx.temp(
370                    Ty::new_ref(cx.tcx, cx.tcx.lifetimes.re_erased, subpattern.ty, mutability),
371                    pattern.span,
372                );
373                MatchPairTree::for_pattern(
374                    PlaceBuilder::from(temp).deref(),
375                    subpattern,
376                    cx,
377                    &mut subpairs,
378                    extra_data,
379                );
380                Some(TestableCase::Deref { temp, mutability })
381            }
382
383            PatKind::Never => Some(TestableCase::Never),
384        };
385
386        if let Some(testable_case) = testable_case {
387            // This pattern is refutable, so push a new match-pair node.
388            //
389            // Note: unless test_case is TestCase::Or, place must not be None.
390            // This means that the closure capture analysis in
391            // rustc_hir_typeck::upvar, and in particular the pattern handling
392            // code of ExprUseVisitor, must capture all of the places we'll use.
393            // Make sure to keep these two parts in sync!
394            match_pairs.push(MatchPairTree {
395                place,
396                testable_case,
397                subpairs,
398                pattern_ty: pattern.ty,
399                pattern_span: pattern.span,
400            })
401        } else {
402            // This pattern is irrefutable, so it doesn't need its own match-pair node.
403            // Just push its refutable subpatterns instead, if any.
404            match_pairs.extend(subpairs);
405        }
406    }
407}