Skip to main content

rustc_ast_lowering/
pat.rs

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