rustc_ast_lowering/
pat.rs

1use std::sync::Arc;
2
3use rustc_ast::*;
4use rustc_data_structures::stack::ensure_sufficient_stack;
5use rustc_hir::def::{DefKind, Res};
6use rustc_hir::{self as hir, LangItem, Target};
7use rustc_middle::span_bug;
8use rustc_span::source_map::{Spanned, respan};
9use rustc_span::{DesugaringKind, Ident, Span};
10
11use super::errors::{
12    ArbitraryExpressionInPattern, ExtraDoubleDot, MisplacedDoubleDot, SubTupleBinding,
13};
14use super::{ImplTraitContext, LoweringContext, ParamMode, ResolverAstLoweringExt};
15use crate::{AllowReturnTypeNotation, ImplTraitPosition};
16
17impl<'a, 'hir> LoweringContext<'a, 'hir> {
18    pub(crate) fn lower_pat(&mut self, pattern: &Pat) -> &'hir hir::Pat<'hir> {
19        self.arena.alloc(self.lower_pat_mut(pattern))
20    }
21
22    fn lower_pat_mut(&mut self, mut pattern: &Pat) -> hir::Pat<'hir> {
23        ensure_sufficient_stack(|| {
24            // loop here to avoid recursion
25            let pat_hir_id = self.lower_node_id(pattern.id);
26            let node = loop {
27                match &pattern.kind {
28                    PatKind::Missing => break hir::PatKind::Missing,
29                    PatKind::Wild => break hir::PatKind::Wild,
30                    PatKind::Never => break hir::PatKind::Never,
31                    PatKind::Ident(binding_mode, ident, sub) => {
32                        let lower_sub = |this: &mut Self| sub.as_ref().map(|s| this.lower_pat(s));
33                        break self.lower_pat_ident(
34                            pattern,
35                            *binding_mode,
36                            *ident,
37                            pat_hir_id,
38                            lower_sub,
39                        );
40                    }
41                    PatKind::Expr(e) => {
42                        break hir::PatKind::Expr(self.lower_expr_within_pat(e, false));
43                    }
44                    PatKind::TupleStruct(qself, path, pats) => {
45                        let qpath = self.lower_qpath(
46                            pattern.id,
47                            qself,
48                            path,
49                            ParamMode::Optional,
50                            AllowReturnTypeNotation::No,
51                            ImplTraitContext::Disallowed(ImplTraitPosition::Path),
52                            None,
53                        );
54                        let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple struct");
55                        break hir::PatKind::TupleStruct(qpath, pats, ddpos);
56                    }
57                    PatKind::Or(pats) => {
58                        break hir::PatKind::Or(
59                            self.arena.alloc_from_iter(pats.iter().map(|x| self.lower_pat_mut(x))),
60                        );
61                    }
62                    PatKind::Path(qself, path) => {
63                        let qpath = self.lower_qpath(
64                            pattern.id,
65                            qself,
66                            path,
67                            ParamMode::Optional,
68                            AllowReturnTypeNotation::No,
69                            ImplTraitContext::Disallowed(ImplTraitPosition::Path),
70                            None,
71                        );
72                        let kind = hir::PatExprKind::Path(qpath);
73                        let span = self.lower_span(pattern.span);
74                        let expr = hir::PatExpr { hir_id: pat_hir_id, span, kind };
75                        let expr = self.arena.alloc(expr);
76                        return hir::Pat {
77                            hir_id: self.next_id(),
78                            kind: hir::PatKind::Expr(expr),
79                            span,
80                            default_binding_modes: true,
81                        };
82                    }
83                    PatKind::Struct(qself, path, fields, etc) => {
84                        let qpath = self.lower_qpath(
85                            pattern.id,
86                            qself,
87                            path,
88                            ParamMode::Optional,
89                            AllowReturnTypeNotation::No,
90                            ImplTraitContext::Disallowed(ImplTraitPosition::Path),
91                            None,
92                        );
93
94                        let fs = self.arena.alloc_from_iter(fields.iter().map(|f| {
95                            let hir_id = self.lower_node_id(f.id);
96                            self.lower_attrs(hir_id, &f.attrs, f.span, Target::PatField);
97
98                            hir::PatField {
99                                hir_id,
100                                ident: self.lower_ident(f.ident),
101                                pat: self.lower_pat(&f.pat),
102                                is_shorthand: f.is_shorthand,
103                                span: self.lower_span(f.span),
104                            }
105                        }));
106                        break hir::PatKind::Struct(
107                            qpath,
108                            fs,
109                            match etc {
110                                ast::PatFieldsRest::Rest(sp) => Some(self.lower_span(*sp)),
111                                ast::PatFieldsRest::Recovered(_) => Some(Span::default()),
112                                _ => None,
113                            },
114                        );
115                    }
116                    PatKind::Tuple(pats) => {
117                        let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple");
118                        break hir::PatKind::Tuple(pats, ddpos);
119                    }
120                    PatKind::Box(inner) => {
121                        break hir::PatKind::Box(self.lower_pat(inner));
122                    }
123                    PatKind::Deref(inner) => {
124                        break hir::PatKind::Deref(self.lower_pat(inner));
125                    }
126                    PatKind::Ref(inner, mutbl) => {
127                        break hir::PatKind::Ref(self.lower_pat(inner), *mutbl);
128                    }
129                    PatKind::Range(e1, e2, Spanned { node: end, .. }) => {
130                        break hir::PatKind::Range(
131                            e1.as_deref().map(|e| self.lower_expr_within_pat(e, true)),
132                            e2.as_deref().map(|e| self.lower_expr_within_pat(e, true)),
133                            self.lower_range_end(end, e2.is_some()),
134                        );
135                    }
136                    PatKind::Guard(inner, cond) => {
137                        break hir::PatKind::Guard(self.lower_pat(inner), self.lower_expr(cond));
138                    }
139                    PatKind::Slice(pats) => break self.lower_pat_slice(pats),
140                    PatKind::Rest => {
141                        // If we reach here the `..` pattern is not semantically allowed.
142                        break self.ban_illegal_rest_pat(pattern.span);
143                    }
144                    // return inner to be processed in next loop
145                    PatKind::Paren(inner) => pattern = inner,
146                    PatKind::MacCall(_) => {
147                        panic!("{pattern:#?} shouldn't exist here")
148                    }
149                    PatKind::Err(guar) => break hir::PatKind::Err(*guar),
150                }
151            };
152
153            self.pat_with_node_id_of(pattern, node, pat_hir_id)
154        })
155    }
156
157    fn lower_pat_tuple(
158        &mut self,
159        pats: &[Pat],
160        ctx: &str,
161    ) -> (&'hir [hir::Pat<'hir>], hir::DotDotPos) {
162        let mut elems = Vec::with_capacity(pats.len());
163        let mut rest = None;
164
165        let mut iter = pats.iter().enumerate();
166        for (idx, pat) in iter.by_ref() {
167            // Interpret the first `..` pattern as a sub-tuple pattern.
168            // Note that unlike for slice patterns,
169            // where `xs @ ..` is a legal sub-slice pattern,
170            // it is not a legal sub-tuple pattern.
171            match &pat.kind {
172                // Found a sub-tuple rest pattern
173                PatKind::Rest => {
174                    rest = Some((idx, pat.span));
175                    break;
176                }
177                // Found a sub-tuple pattern `$binding_mode $ident @ ..`.
178                // This is not allowed as a sub-tuple pattern
179                PatKind::Ident(_, ident, Some(sub)) if sub.is_rest() => {
180                    let sp = pat.span;
181                    self.dcx().emit_err(SubTupleBinding {
182                        span: sp,
183                        ident_name: ident.name,
184                        ident: *ident,
185                        ctx,
186                    });
187                }
188                _ => {}
189            }
190
191            // It was not a sub-tuple pattern so lower it normally.
192            elems.push(self.lower_pat_mut(pat));
193        }
194
195        for (_, pat) in iter {
196            // There was a previous sub-tuple pattern; make sure we don't allow more...
197            if pat.is_rest() {
198                // ...but there was one again, so error.
199                self.ban_extra_rest_pat(pat.span, rest.unwrap().1, ctx);
200            } else {
201                elems.push(self.lower_pat_mut(pat));
202            }
203        }
204
205        (self.arena.alloc_from_iter(elems), hir::DotDotPos::new(rest.map(|(ddpos, _)| ddpos)))
206    }
207
208    /// Lower a slice pattern of form `[pat_0, ..., pat_n]` into
209    /// `hir::PatKind::Slice(before, slice, after)`.
210    ///
211    /// When encountering `($binding_mode $ident @)? ..` (`slice`),
212    /// this is interpreted as a sub-slice pattern semantically.
213    /// Patterns that follow, which are not like `slice` -- or an error occurs, are in `after`.
214    fn lower_pat_slice(&mut self, pats: &[Pat]) -> hir::PatKind<'hir> {
215        let mut before = Vec::new();
216        let mut after = Vec::new();
217        let mut slice = None;
218        let mut prev_rest_span = None;
219
220        // Lowers `$bm $ident @ ..` to `$bm $ident @ _`.
221        let lower_rest_sub = |this: &mut Self, pat: &Pat, &ann, &ident, sub: &Pat| {
222            let sub_hir_id = this.lower_node_id(sub.id);
223            let lower_sub = |this: &mut Self| Some(this.pat_wild_with_node_id_of(sub, sub_hir_id));
224            let pat_hir_id = this.lower_node_id(pat.id);
225            let node = this.lower_pat_ident(pat, ann, ident, pat_hir_id, lower_sub);
226            this.pat_with_node_id_of(pat, node, pat_hir_id)
227        };
228
229        let mut iter = pats.iter();
230        // Lower all the patterns until the first occurrence of a sub-slice pattern.
231        for pat in iter.by_ref() {
232            match &pat.kind {
233                // Found a sub-slice pattern `..`. Record, lower it to `_`, and stop here.
234                PatKind::Rest => {
235                    prev_rest_span = Some(pat.span);
236                    let hir_id = self.lower_node_id(pat.id);
237                    slice = Some(self.pat_wild_with_node_id_of(pat, hir_id));
238                    break;
239                }
240                // Found a sub-slice pattern `$binding_mode $ident @ ..`.
241                // Record, lower it to `$binding_mode $ident @ _`, and stop here.
242                PatKind::Ident(ann, ident, Some(sub)) if sub.is_rest() => {
243                    prev_rest_span = Some(sub.span);
244                    slice = Some(self.arena.alloc(lower_rest_sub(self, pat, ann, ident, sub)));
245                    break;
246                }
247                // It was not a subslice pattern so lower it normally.
248                _ => before.push(self.lower_pat_mut(pat)),
249            }
250        }
251
252        // Lower all the patterns after the first sub-slice pattern.
253        for pat in iter {
254            // There was a previous subslice pattern; make sure we don't allow more.
255            let rest_span = match &pat.kind {
256                PatKind::Rest => Some(pat.span),
257                PatKind::Ident(ann, ident, Some(sub)) if sub.is_rest() => {
258                    // #69103: Lower into `binding @ _` as above to avoid ICEs.
259                    after.push(lower_rest_sub(self, pat, ann, ident, sub));
260                    Some(sub.span)
261                }
262                _ => None,
263            };
264            if let Some(rest_span) = rest_span {
265                // We have e.g., `[a, .., b, ..]`. That's no good, error!
266                self.ban_extra_rest_pat(rest_span, prev_rest_span.unwrap(), "slice");
267            } else {
268                // Lower the pattern normally.
269                after.push(self.lower_pat_mut(pat));
270            }
271        }
272
273        hir::PatKind::Slice(
274            self.arena.alloc_from_iter(before),
275            slice,
276            self.arena.alloc_from_iter(after),
277        )
278    }
279
280    fn lower_pat_ident(
281        &mut self,
282        p: &Pat,
283        annotation: BindingMode,
284        ident: Ident,
285        hir_id: hir::HirId,
286        lower_sub: impl FnOnce(&mut Self) -> Option<&'hir hir::Pat<'hir>>,
287    ) -> hir::PatKind<'hir> {
288        match self.resolver.get_partial_res(p.id).map(|d| d.expect_full_res()) {
289            // `None` can occur in body-less function signatures
290            res @ (None | Some(Res::Local(_))) => {
291                let binding_id = match res {
292                    Some(Res::Local(id)) => {
293                        // In `Or` patterns like `VariantA(s) | VariantB(s, _)`, multiple identifier patterns
294                        // will be resolved to the same `Res::Local`. Thus they just share a single
295                        // `HirId`.
296                        if id == p.id {
297                            self.ident_and_label_to_local_id.insert(id, hir_id.local_id);
298                            hir_id
299                        } else {
300                            hir::HirId {
301                                owner: self.current_hir_id_owner,
302                                local_id: self.ident_and_label_to_local_id[&id],
303                            }
304                        }
305                    }
306                    _ => {
307                        self.ident_and_label_to_local_id.insert(p.id, hir_id.local_id);
308                        hir_id
309                    }
310                };
311                hir::PatKind::Binding(
312                    annotation,
313                    binding_id,
314                    self.lower_ident(ident),
315                    lower_sub(self),
316                )
317            }
318            Some(res) => {
319                let res = self.lower_res(res);
320                let span = self.lower_span(ident.span);
321                hir::PatKind::Expr(self.arena.alloc(hir::PatExpr {
322                    kind: hir::PatExprKind::Path(hir::QPath::Resolved(
323                        None,
324                        self.arena.alloc(hir::Path {
325                            span,
326                            res,
327                            segments: arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), self.next_id(), res)],
328                        }),
329                    )),
330                    hir_id: self.next_id(),
331                    span,
332                }))
333            }
334        }
335    }
336
337    fn pat_wild_with_node_id_of(&mut self, p: &Pat, hir_id: hir::HirId) -> &'hir hir::Pat<'hir> {
338        self.arena.alloc(self.pat_with_node_id_of(p, hir::PatKind::Wild, hir_id))
339    }
340
341    /// Construct a `Pat` with the `HirId` of `p.id` already lowered.
342    fn pat_with_node_id_of(
343        &mut self,
344        p: &Pat,
345        kind: hir::PatKind<'hir>,
346        hir_id: hir::HirId,
347    ) -> hir::Pat<'hir> {
348        hir::Pat { hir_id, kind, span: self.lower_span(p.span), default_binding_modes: true }
349    }
350
351    /// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern.
352    pub(crate) fn ban_extra_rest_pat(&self, sp: Span, prev_sp: Span, ctx: &str) {
353        self.dcx().emit_err(ExtraDoubleDot { span: sp, prev_span: prev_sp, ctx });
354    }
355
356    /// Used to ban the `..` pattern in places it shouldn't be semantically.
357    fn ban_illegal_rest_pat(&self, sp: Span) -> hir::PatKind<'hir> {
358        self.dcx().emit_err(MisplacedDoubleDot { span: sp });
359
360        // We're not in a list context so `..` can be reasonably treated
361        // as `_` because it should always be valid and roughly matches the
362        // intent of `..` (notice that the rest of a single slot is that slot).
363        hir::PatKind::Wild
364    }
365
366    fn lower_range_end(&mut self, e: &RangeEnd, has_end: bool) -> hir::RangeEnd {
367        match *e {
368            RangeEnd::Excluded if has_end => hir::RangeEnd::Excluded,
369            // No end; so `X..` behaves like `RangeFrom`.
370            RangeEnd::Excluded | RangeEnd::Included(_) => hir::RangeEnd::Included,
371        }
372    }
373
374    /// Matches `'-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus)`,
375    /// or paths for ranges.
376    //
377    // FIXME: do we want to allow `expr -> pattern` conversion to create path expressions?
378    // That means making this work:
379    //
380    // ```rust,ignore (FIXME)
381    // struct S;
382    // macro_rules! m {
383    //     ($a:expr) => {
384    //         let $a = S;
385    //     }
386    // }
387    // m!(S);
388    // ```
389    fn lower_expr_within_pat(
390        &mut self,
391        expr: &Expr,
392        allow_paths: bool,
393    ) -> &'hir hir::PatExpr<'hir> {
394        let span = self.lower_span(expr.span);
395        let err =
396            |guar| hir::PatExprKind::Lit { lit: respan(span, LitKind::Err(guar)), negated: false };
397        let kind = match &expr.kind {
398            ExprKind::Lit(lit) => {
399                hir::PatExprKind::Lit { lit: self.lower_lit(lit, span), negated: false }
400            }
401            ExprKind::ConstBlock(c) => hir::PatExprKind::ConstBlock(self.lower_const_block(c)),
402            ExprKind::IncludedBytes(byte_sym) => hir::PatExprKind::Lit {
403                lit: respan(span, LitKind::ByteStr(*byte_sym, StrStyle::Cooked)),
404                negated: false,
405            },
406            ExprKind::Err(guar) => err(*guar),
407            ExprKind::Dummy => span_bug!(span, "lowered ExprKind::Dummy"),
408            ExprKind::Path(qself, path) if allow_paths => hir::PatExprKind::Path(self.lower_qpath(
409                expr.id,
410                qself,
411                path,
412                ParamMode::Optional,
413                AllowReturnTypeNotation::No,
414                ImplTraitContext::Disallowed(ImplTraitPosition::Path),
415                None,
416            )),
417            ExprKind::Unary(UnOp::Neg, inner) if let ExprKind::Lit(lit) = &inner.kind => {
418                hir::PatExprKind::Lit { lit: self.lower_lit(lit, span), negated: true }
419            }
420            _ => {
421                let pattern_from_macro = expr.is_approximately_pattern();
422                let guar = self.dcx().emit_err(ArbitraryExpressionInPattern {
423                    span,
424                    pattern_from_macro_note: pattern_from_macro,
425                });
426                err(guar)
427            }
428        };
429        self.arena.alloc(hir::PatExpr { hir_id: self.lower_node_id(expr.id), span, kind })
430    }
431
432    pub(crate) fn lower_ty_pat(
433        &mut self,
434        pattern: &TyPat,
435        base_type: Span,
436    ) -> &'hir hir::TyPat<'hir> {
437        self.arena.alloc(self.lower_ty_pat_mut(pattern, base_type))
438    }
439
440    fn lower_ty_pat_mut(&mut self, pattern: &TyPat, base_type: Span) -> hir::TyPat<'hir> {
441        // loop here to avoid recursion
442        let pat_hir_id = self.lower_node_id(pattern.id);
443        let node = match &pattern.kind {
444            TyPatKind::Range(e1, e2, Spanned { node: end, span }) => hir::TyPatKind::Range(
445                e1.as_deref().map(|e| self.lower_anon_const_to_const_arg(e)).unwrap_or_else(|| {
446                    self.lower_ty_pat_range_end(
447                        hir::LangItem::RangeMin,
448                        span.shrink_to_lo(),
449                        base_type,
450                    )
451                }),
452                e2.as_deref()
453                    .map(|e| match end {
454                        RangeEnd::Included(..) => self.lower_anon_const_to_const_arg(e),
455                        RangeEnd::Excluded => self.lower_excluded_range_end(e),
456                    })
457                    .unwrap_or_else(|| {
458                        self.lower_ty_pat_range_end(
459                            hir::LangItem::RangeMax,
460                            span.shrink_to_hi(),
461                            base_type,
462                        )
463                    }),
464            ),
465            TyPatKind::NotNull => hir::TyPatKind::NotNull,
466            TyPatKind::Or(variants) => {
467                hir::TyPatKind::Or(self.arena.alloc_from_iter(
468                    variants.iter().map(|pat| self.lower_ty_pat_mut(pat, base_type)),
469                ))
470            }
471            TyPatKind::Err(guar) => hir::TyPatKind::Err(*guar),
472        };
473
474        hir::TyPat { hir_id: pat_hir_id, kind: node, span: self.lower_span(pattern.span) }
475    }
476
477    /// Lowers the range end of an exclusive range (`2..5`) to an inclusive range 2..=(5 - 1).
478    /// This way the type system doesn't have to handle the distinction between inclusive/exclusive ranges.
479    fn lower_excluded_range_end(&mut self, e: &AnonConst) -> &'hir hir::ConstArg<'hir> {
480        let span = self.lower_span(e.value.span);
481        let unstable_span = self.mark_span_with_reason(
482            DesugaringKind::PatTyRange,
483            span,
484            Some(Arc::clone(&self.allow_pattern_type)),
485        );
486        let anon_const = self.with_new_scopes(span, |this| {
487            let def_id = this.local_def_id(e.id);
488            let hir_id = this.lower_node_id(e.id);
489            let body = this.lower_body(|this| {
490                // Need to use a custom function as we can't just subtract `1` from a `char`.
491                let kind = hir::ExprKind::Path(this.make_lang_item_qpath(
492                    hir::LangItem::RangeSub,
493                    unstable_span,
494                    None,
495                ));
496                let fn_def = this.arena.alloc(hir::Expr { hir_id: this.next_id(), kind, span });
497                let args = this.arena.alloc([this.lower_expr_mut(&e.value)]);
498                (
499                    &[],
500                    hir::Expr {
501                        hir_id: this.next_id(),
502                        kind: hir::ExprKind::Call(fn_def, args),
503                        span,
504                    },
505                )
506            });
507            hir::AnonConst { def_id, hir_id, body, span }
508        });
509        self.arena.alloc(hir::ConstArg {
510            hir_id: self.next_id(),
511            kind: hir::ConstArgKind::Anon(self.arena.alloc(anon_const)),
512        })
513    }
514
515    /// When a range has no end specified (`1..` or `1..=`) or no start specified (`..5` or `..=5`),
516    /// we instead use a constant of the MAX/MIN of the type.
517    /// This way the type system does not have to handle the lack of a start/end.
518    fn lower_ty_pat_range_end(
519        &mut self,
520        lang_item: LangItem,
521        span: Span,
522        base_type: Span,
523    ) -> &'hir hir::ConstArg<'hir> {
524        let node_id = self.next_node_id();
525
526        // Add a definition for the in-band const def.
527        // We're generating a range end that didn't exist in the AST,
528        // so the def collector didn't create the def ahead of time. That's why we have to do
529        // it here.
530        let def_id = self.create_def(node_id, None, DefKind::AnonConst, span);
531        let hir_id = self.lower_node_id(node_id);
532
533        let unstable_span = self.mark_span_with_reason(
534            DesugaringKind::PatTyRange,
535            self.lower_span(span),
536            Some(Arc::clone(&self.allow_pattern_type)),
537        );
538        let span = self.lower_span(base_type);
539
540        let path_expr = hir::Expr {
541            hir_id: self.next_id(),
542            kind: hir::ExprKind::Path(self.make_lang_item_qpath(lang_item, unstable_span, None)),
543            span,
544        };
545
546        let ct = self.with_new_scopes(span, |this| {
547            self.arena.alloc(hir::AnonConst {
548                def_id,
549                hir_id,
550                body: this.lower_body(|_this| (&[], path_expr)),
551                span,
552            })
553        });
554        let hir_id = self.next_id();
555        self.arena.alloc(hir::ConstArg { kind: hir::ConstArgKind::Anon(ct), hir_id })
556    }
557}