Skip to main content

rustc_ast_lowering/
pat.rs

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