1mod check_match;
4mod const_to_pat;
5mod migration;
6
7use std::assert_matches::assert_matches;
8use std::cmp::Ordering;
9use std::sync::Arc;
10
11use rustc_abi::{FieldIdx, Integer};
12use rustc_errors::codes::*;
13use rustc_hir::def::{CtorOf, DefKind, Res};
14use rustc_hir::pat_util::EnumerateAndAdjustIterator;
15use rustc_hir::{self as hir, RangeEnd};
16use rustc_index::Idx;
17use rustc_middle::mir::interpret::LitToConstInput;
18use rustc_middle::thir::{
19 Ascription, DerefPatBorrowMode, FieldPat, LocalVarId, Pat, PatKind, PatRange, PatRangeBoundary,
20};
21use rustc_middle::ty::adjustment::{PatAdjust, PatAdjustment};
22use rustc_middle::ty::layout::IntegerExt;
23use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt};
24use rustc_middle::{bug, span_bug};
25use rustc_span::ErrorGuaranteed;
26use tracing::{debug, instrument};
27
28pub(crate) use self::check_match::check_match;
29use self::migration::PatMigration;
30use crate::errors::*;
31
32struct PatCtxt<'tcx> {
34 tcx: TyCtxt<'tcx>,
35 typing_env: ty::TypingEnv<'tcx>,
36 typeck_results: &'tcx ty::TypeckResults<'tcx>,
37
38 rust_2024_migration: Option<PatMigration<'tcx>>,
40}
41
42#[instrument(level = "debug", skip(tcx, typing_env, typeck_results), ret)]
43pub(super) fn pat_from_hir<'tcx>(
44 tcx: TyCtxt<'tcx>,
45 typing_env: ty::TypingEnv<'tcx>,
46 typeck_results: &'tcx ty::TypeckResults<'tcx>,
47 pat: &'tcx hir::Pat<'tcx>,
48 let_stmt_type: Option<&hir::Ty<'tcx>>,
50) -> Box<Pat<'tcx>> {
51 let mut pcx = PatCtxt {
52 tcx,
53 typing_env,
54 typeck_results,
55 rust_2024_migration: typeck_results
56 .rust_2024_migration_desugared_pats()
57 .get(pat.hir_id)
58 .map(PatMigration::new),
59 };
60
61 let mut thir_pat = pcx.lower_pattern(pat);
62
63 if let Some(let_stmt_type) = let_stmt_type
66 && let Some(&user_ty) = typeck_results.user_provided_types().get(let_stmt_type.hir_id)
67 {
68 debug!(?user_ty);
69 let annotation = CanonicalUserTypeAnnotation {
70 user_ty: Box::new(user_ty),
71 span: let_stmt_type.span,
72 inferred_ty: typeck_results.node_type(let_stmt_type.hir_id),
73 };
74 thir_pat = Box::new(Pat {
75 ty: thir_pat.ty,
76 span: thir_pat.span,
77 kind: PatKind::AscribeUserType {
78 ascription: Ascription { annotation, variance: ty::Covariant },
79 subpattern: thir_pat,
80 },
81 });
82 }
83
84 if let Some(m) = pcx.rust_2024_migration {
85 m.emit(tcx, pat.hir_id);
86 }
87
88 thir_pat
89}
90
91impl<'tcx> PatCtxt<'tcx> {
92 fn lower_pattern(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Box<Pat<'tcx>> {
93 let adjustments: &[PatAdjustment<'tcx>] =
94 self.typeck_results.pat_adjustments().get(pat.hir_id).map_or(&[], |v| &**v);
95
96 let mut opt_old_mode_span = None;
100 if let Some(s) = &mut self.rust_2024_migration
101 && adjustments.iter().any(|adjust| adjust.kind == PatAdjust::BuiltinDeref)
102 {
103 opt_old_mode_span = s.visit_implicit_derefs(pat.span, adjustments);
104 }
105
106 let unadjusted_pat = match pat.kind {
126 hir::PatKind::Ref(inner, _, _)
127 if self.typeck_results.skipped_ref_pats().contains(pat.hir_id) =>
128 {
129 self.lower_pattern(inner)
130 }
131 _ => self.lower_pattern_unadjusted(pat),
132 };
133
134 let adjusted_pat = adjustments.iter().rev().fold(unadjusted_pat, |thir_pat, adjust| {
135 debug!("{:?}: wrapping pattern with adjustment {:?}", thir_pat, adjust);
136 let span = thir_pat.span;
137 let kind = match adjust.kind {
138 PatAdjust::BuiltinDeref => PatKind::Deref { subpattern: thir_pat },
139 PatAdjust::OverloadedDeref => {
140 let borrow = self.typeck_results.deref_pat_borrow_mode(adjust.source, pat);
141 PatKind::DerefPattern { subpattern: thir_pat, borrow }
142 }
143 PatAdjust::PinDeref => PatKind::Deref { subpattern: thir_pat },
144 };
145 Box::new(Pat { span, ty: adjust.source, kind })
146 });
147
148 if let Some(s) = &mut self.rust_2024_migration
149 && adjustments.iter().any(|adjust| adjust.kind == PatAdjust::BuiltinDeref)
150 {
151 s.leave_ref(opt_old_mode_span);
152 }
153
154 adjusted_pat
155 }
156
157 fn lower_pattern_range_endpoint(
158 &mut self,
159 pat: &'tcx hir::Pat<'tcx>, expr: Option<&'tcx hir::PatExpr<'tcx>>,
161 ascriptions: &mut Vec<Ascription<'tcx>>,
163 ) -> Result<Option<PatRangeBoundary<'tcx>>, ErrorGuaranteed> {
164 assert_matches!(pat.kind, hir::PatKind::Range(..));
165
166 let Some(expr) = expr else { return Ok(None) };
169
170 let mut kind: PatKind<'tcx> = self.lower_pat_expr(pat, expr);
173
174 loop {
176 match kind {
177 PatKind::AscribeUserType { ascription, subpattern } => {
178 ascriptions.push(ascription);
179 kind = subpattern.kind;
180 }
181 PatKind::ExpandedConstant { def_id: _, subpattern } => {
182 kind = subpattern.kind;
186 }
187 _ => break,
188 }
189 }
190
191 let PatKind::Constant { value } = kind else {
193 let msg =
194 format!("found bad range pattern endpoint `{expr:?}` outside of error recovery");
195 return Err(self.tcx.dcx().span_delayed_bug(expr.span, msg));
196 };
197 Ok(Some(PatRangeBoundary::Finite(value.valtree)))
198 }
199
200 fn error_on_literal_overflow(
206 &self,
207 expr: Option<&'tcx hir::PatExpr<'tcx>>,
208 ty: Ty<'tcx>,
209 ) -> Result<(), ErrorGuaranteed> {
210 use rustc_ast::ast::LitKind;
211
212 let Some(expr) = expr else {
213 return Ok(());
214 };
215 let span = expr.span;
216
217 let hir::PatExprKind::Lit { lit, negated } = expr.kind else {
221 return Ok(());
222 };
223 let LitKind::Int(lit_val, _) = lit.node else {
224 return Ok(());
225 };
226 let (min, max): (i128, u128) = match ty.kind() {
227 ty::Int(ity) => {
228 let size = Integer::from_int_ty(&self.tcx, *ity).size();
229 (size.signed_int_min(), size.signed_int_max() as u128)
230 }
231 ty::Uint(uty) => {
232 let size = Integer::from_uint_ty(&self.tcx, *uty).size();
233 (0, size.unsigned_int_max())
234 }
235 _ => {
236 return Ok(());
237 }
238 };
239 if (negated && lit_val > max + 1) || (!negated && lit_val > max) {
242 return Err(self.tcx.dcx().emit_err(LiteralOutOfRange { span, ty, min, max }));
243 }
244 Ok(())
245 }
246
247 fn lower_pattern_range(
248 &mut self,
249 pat: &'tcx hir::Pat<'tcx>,
250 lo_expr: Option<&'tcx hir::PatExpr<'tcx>>,
251 hi_expr: Option<&'tcx hir::PatExpr<'tcx>>,
252 end: RangeEnd,
253 ) -> Result<PatKind<'tcx>, ErrorGuaranteed> {
254 let ty = self.typeck_results.node_type(pat.hir_id);
255 let span = pat.span;
256
257 if lo_expr.is_none() && hi_expr.is_none() {
258 let msg = "found twice-open range pattern (`..`) outside of error recovery";
259 self.tcx.dcx().span_bug(span, msg);
260 }
261
262 let mut ascriptions = vec![];
264 let mut lower_endpoint =
265 |expr| self.lower_pattern_range_endpoint(pat, expr, &mut ascriptions);
266
267 let lo = lower_endpoint(lo_expr)?.unwrap_or(PatRangeBoundary::NegInfinity);
268 let hi = lower_endpoint(hi_expr)?.unwrap_or(PatRangeBoundary::PosInfinity);
269
270 let cmp = lo.compare_with(hi, ty, self.tcx);
271 let mut kind = PatKind::Range(Arc::new(PatRange { lo, hi, end, ty }));
272 match (end, cmp) {
273 (RangeEnd::Excluded, Some(Ordering::Less)) => {}
275 (RangeEnd::Included, Some(Ordering::Less)) => {}
277 (RangeEnd::Included, Some(Ordering::Equal)) if lo.is_finite() && hi.is_finite() => {
279 let value = ty::Value { ty, valtree: lo.as_finite().unwrap() };
280 kind = PatKind::Constant { value };
281 }
282 (RangeEnd::Included, Some(Ordering::Equal)) if !lo.is_finite() => {}
284 (RangeEnd::Included, Some(Ordering::Equal)) if !hi.is_finite() => {}
287 _ => {
289 self.error_on_literal_overflow(lo_expr, ty)?;
291 self.error_on_literal_overflow(hi_expr, ty)?;
292 let e = match end {
293 RangeEnd::Included => {
294 self.tcx.dcx().emit_err(LowerRangeBoundMustBeLessThanOrEqualToUpper {
295 span,
296 teach: self.tcx.sess.teach(E0030),
297 })
298 }
299 RangeEnd::Excluded if lo_expr.is_none() => {
300 self.tcx.dcx().emit_err(UpperRangeBoundCannotBeMin { span })
301 }
302 RangeEnd::Excluded => {
303 self.tcx.dcx().emit_err(LowerRangeBoundMustBeLessThanUpper { span })
304 }
305 };
306 return Err(e);
307 }
308 }
309
310 for ascription in ascriptions {
314 let subpattern = Box::new(Pat { span, ty, kind });
315 kind = PatKind::AscribeUserType { ascription, subpattern };
316 }
317 Ok(kind)
323 }
324
325 #[instrument(skip(self), level = "debug")]
326 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Box<Pat<'tcx>> {
327 let mut ty = self.typeck_results.node_type(pat.hir_id);
328 let mut span = pat.span;
329
330 let kind = match pat.kind {
331 hir::PatKind::Missing => PatKind::Missing,
332
333 hir::PatKind::Wild => PatKind::Wild,
334
335 hir::PatKind::Never => PatKind::Never,
336
337 hir::PatKind::Expr(value) => self.lower_pat_expr(pat, value),
338
339 hir::PatKind::Range(lo_expr, hi_expr, end) => {
340 self.lower_pattern_range(pat, lo_expr, hi_expr, end).unwrap_or_else(PatKind::Error)
341 }
342
343 hir::PatKind::Deref(subpattern) => {
344 let borrow = self.typeck_results.deref_pat_borrow_mode(ty, subpattern);
345 PatKind::DerefPattern { subpattern: self.lower_pattern(subpattern), borrow }
346 }
347 hir::PatKind::Ref(subpattern, _, _) => {
348 let opt_old_mode_span =
350 self.rust_2024_migration.as_mut().and_then(|s| s.visit_explicit_deref());
351 let subpattern = self.lower_pattern(subpattern);
352 if let Some(s) = &mut self.rust_2024_migration {
353 s.leave_ref(opt_old_mode_span);
354 }
355 PatKind::Deref { subpattern }
356 }
357 hir::PatKind::Box(subpattern) => PatKind::DerefPattern {
358 subpattern: self.lower_pattern(subpattern),
359 borrow: DerefPatBorrowMode::Box,
360 },
361
362 hir::PatKind::Slice(prefix, slice, suffix) => {
363 self.slice_or_array_pattern(pat, prefix, slice, suffix)
364 }
365
366 hir::PatKind::Tuple(pats, ddpos) => {
367 let ty::Tuple(tys) = ty.kind() else {
368 span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty);
369 };
370 let subpatterns = self.lower_tuple_subpats(pats, tys.len(), ddpos);
371 PatKind::Leaf { subpatterns }
372 }
373
374 hir::PatKind::Binding(explicit_ba, id, ident, sub) => {
375 if let Some(ident_span) = ident.span.find_ancestor_inside(span) {
376 span = span.with_hi(ident_span.hi());
377 }
378
379 let mode = *self
380 .typeck_results
381 .pat_binding_modes()
382 .get(pat.hir_id)
383 .expect("missing binding mode");
384
385 if let Some(s) = &mut self.rust_2024_migration {
386 s.visit_binding(pat.span, mode, explicit_ba, ident);
387 }
388
389 let var_ty = ty;
392 if let hir::ByRef::Yes(pinnedness, _) = mode.0 {
393 match pinnedness {
394 hir::Pinnedness::Pinned
395 if let Some(pty) = ty.pinned_ty()
396 && let &ty::Ref(_, rty, _) = pty.kind() =>
397 {
398 ty = rty;
399 }
400 hir::Pinnedness::Not if let &ty::Ref(_, rty, _) = ty.kind() => {
401 ty = rty;
402 }
403 _ => bug!("`ref {}` has wrong type {}", ident, ty),
404 }
405 };
406
407 PatKind::Binding {
408 mode,
409 name: ident.name,
410 var: LocalVarId(id),
411 ty: var_ty,
412 subpattern: self.lower_opt_pattern(sub),
413 is_primary: id == pat.hir_id,
414 is_shorthand: false,
415 }
416 }
417
418 hir::PatKind::TupleStruct(ref qpath, pats, ddpos) => {
419 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
420 let ty::Adt(adt_def, _) = ty.kind() else {
421 span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty);
422 };
423 let variant_def = adt_def.variant_of_res(res);
424 let subpatterns = self.lower_tuple_subpats(pats, variant_def.fields.len(), ddpos);
425 self.lower_variant_or_leaf(pat, None, res, subpatterns)
426 }
427
428 hir::PatKind::Struct(ref qpath, fields, _) => {
429 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
430 let subpatterns = fields
431 .iter()
432 .map(|field| {
433 let mut pattern = *self.lower_pattern(field.pat);
434 if let PatKind::Binding { ref mut is_shorthand, .. } = pattern.kind {
435 *is_shorthand = field.is_shorthand;
436 }
437 let field = self.typeck_results.field_index(field.hir_id);
438 FieldPat { field, pattern }
439 })
440 .collect();
441
442 self.lower_variant_or_leaf(pat, None, res, subpatterns)
443 }
444
445 hir::PatKind::Or(pats) => PatKind::Or { pats: self.lower_patterns(pats) },
446
447 hir::PatKind::Guard(pat, _) => self.lower_pattern(pat).kind,
449
450 hir::PatKind::Err(guar) => PatKind::Error(guar),
451 };
452
453 Box::new(Pat { span, ty, kind })
454 }
455
456 fn lower_tuple_subpats(
457 &mut self,
458 pats: &'tcx [hir::Pat<'tcx>],
459 expected_len: usize,
460 gap_pos: hir::DotDotPos,
461 ) -> Vec<FieldPat<'tcx>> {
462 pats.iter()
463 .enumerate_and_adjust(expected_len, gap_pos)
464 .map(|(i, subpattern)| FieldPat {
465 field: FieldIdx::new(i),
466 pattern: *self.lower_pattern(subpattern),
467 })
468 .collect()
469 }
470
471 fn lower_patterns(&mut self, pats: &'tcx [hir::Pat<'tcx>]) -> Box<[Pat<'tcx>]> {
472 pats.iter().map(|p| *self.lower_pattern(p)).collect()
473 }
474
475 fn lower_opt_pattern(&mut self, pat: Option<&'tcx hir::Pat<'tcx>>) -> Option<Box<Pat<'tcx>>> {
476 pat.map(|p| self.lower_pattern(p))
477 }
478
479 fn slice_or_array_pattern(
480 &mut self,
481 pat: &'tcx hir::Pat<'tcx>,
482 prefix: &'tcx [hir::Pat<'tcx>],
483 slice: Option<&'tcx hir::Pat<'tcx>>,
484 suffix: &'tcx [hir::Pat<'tcx>],
485 ) -> PatKind<'tcx> {
486 let ty = self.typeck_results.node_type(pat.hir_id);
487
488 let prefix = self.lower_patterns(prefix);
489 let slice = self.lower_opt_pattern(slice);
490 let suffix = self.lower_patterns(suffix);
491 match ty.kind() {
492 ty::Slice(..) => PatKind::Slice { prefix, slice, suffix },
494 ty::Array(_, len) => {
496 let len = len
497 .try_to_target_usize(self.tcx)
498 .expect("expected len of array pat to be definite");
499 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
500 PatKind::Array { prefix, slice, suffix }
501 }
502 _ => span_bug!(pat.span, "bad slice pattern type {ty:?}"),
503 }
504 }
505
506 fn lower_variant_or_leaf(
507 &mut self,
508 pat: &'tcx hir::Pat<'tcx>,
509 expr: Option<&'tcx hir::PatExpr<'tcx>>,
510 res: Res,
511 subpatterns: Vec<FieldPat<'tcx>>,
512 ) -> PatKind<'tcx> {
513 assert_matches!(
515 (pat.kind, expr),
516 (hir::PatKind::Expr(..) | hir::PatKind::Range(..), Some(_))
517 | (hir::PatKind::Struct(..) | hir::PatKind::TupleStruct(..), None)
518 );
519
520 let (hir_id, span) = match expr {
523 Some(expr) => (expr.hir_id, expr.span),
524 None => (pat.hir_id, pat.span),
525 };
526 let ty = self.typeck_results.node_type(hir_id);
527
528 let res = match res {
529 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
530 let variant_id = self.tcx.parent(variant_ctor_id);
531 Res::Def(DefKind::Variant, variant_id)
532 }
533 res => res,
534 };
535
536 let mut kind = match res {
537 Res::Def(DefKind::Variant, variant_id) => {
538 let enum_id = self.tcx.parent(variant_id);
539 let adt_def = self.tcx.adt_def(enum_id);
540 if adt_def.is_enum() {
541 let args = match ty.kind() {
542 ty::Adt(_, args) | ty::FnDef(_, args) => args,
543 ty::Error(e) => {
544 return PatKind::Error(*e);
546 }
547 _ => bug!("inappropriate type for def: {:?}", ty),
548 };
549 PatKind::Variant {
550 adt_def,
551 args,
552 variant_index: adt_def.variant_index_with_id(variant_id),
553 subpatterns,
554 }
555 } else {
556 PatKind::Leaf { subpatterns }
557 }
558 }
559
560 Res::Def(
561 DefKind::Struct
562 | DefKind::Ctor(CtorOf::Struct, ..)
563 | DefKind::Union
564 | DefKind::TyAlias
565 | DefKind::AssocTy,
566 _,
567 )
568 | Res::SelfTyParam { .. }
569 | Res::SelfTyAlias { .. }
570 | Res::SelfCtor(..) => PatKind::Leaf { subpatterns },
571 _ => {
572 let e = match res {
573 Res::Def(DefKind::ConstParam, def_id) => {
574 let const_span = self.tcx.def_span(def_id);
575 self.tcx.dcx().emit_err(ConstParamInPattern { span, const_span })
576 }
577 Res::Def(DefKind::Static { .. }, def_id) => {
578 let static_span = self.tcx.def_span(def_id);
579 self.tcx.dcx().emit_err(StaticInPattern { span, static_span })
580 }
581 _ => self.tcx.dcx().emit_err(NonConstPath { span }),
582 };
583 PatKind::Error(e)
584 }
585 };
586
587 if let Some(user_ty) = self.user_args_applied_to_ty_of_hir_id(hir_id) {
588 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
589 let annotation = CanonicalUserTypeAnnotation {
590 user_ty: Box::new(user_ty),
591 span,
592 inferred_ty: self.typeck_results.node_type(hir_id),
593 };
594 kind = PatKind::AscribeUserType {
595 subpattern: Box::new(Pat { span, ty, kind }),
596 ascription: Ascription { annotation, variance: ty::Covariant },
597 };
598 }
599
600 kind
601 }
602
603 fn user_args_applied_to_ty_of_hir_id(
604 &self,
605 hir_id: hir::HirId,
606 ) -> Option<ty::CanonicalUserType<'tcx>> {
607 crate::thir::util::user_args_applied_to_ty_of_hir_id(self.tcx, self.typeck_results, hir_id)
608 }
609
610 #[instrument(skip(self), level = "debug")]
614 fn lower_path(
615 &mut self,
616 pat: &'tcx hir::Pat<'tcx>, expr: &'tcx hir::PatExpr<'tcx>,
618 qpath: &hir::QPath<'_>,
619 ) -> Box<Pat<'tcx>> {
620 assert_matches!(pat.kind, hir::PatKind::Expr(..) | hir::PatKind::Range(..));
621
622 let id = expr.hir_id;
623 let span = expr.span;
624 let ty = self.typeck_results.node_type(id);
625 let res = self.typeck_results.qpath_res(qpath, id);
626
627 let (def_id, user_ty) = match res {
628 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
629 (def_id, self.typeck_results.user_provided_types().get(id))
630 }
631
632 _ => {
633 let kind = self.lower_variant_or_leaf(pat, Some(expr), res, vec![]);
636 return Box::new(Pat { span, ty, kind });
637 }
638 };
639
640 let args = self.typeck_results.node_args(id);
642 let c = ty::Const::new_unevaluated(self.tcx, ty::UnevaluatedConst { def: def_id, args });
645 let mut pattern = self.const_to_pat(c, ty, id, span);
646
647 if let Some(&user_ty) = user_ty {
650 let annotation = CanonicalUserTypeAnnotation {
651 user_ty: Box::new(user_ty),
652 span,
653 inferred_ty: self.typeck_results.node_type(id),
654 };
655 let kind = PatKind::AscribeUserType {
656 subpattern: pattern,
657 ascription: Ascription {
658 annotation,
659 variance: ty::Contravariant,
662 },
663 };
664 pattern = Box::new(Pat { span, kind, ty });
665 }
666
667 pattern
668 }
669
670 fn lower_pat_expr(
674 &mut self,
675 pat: &'tcx hir::Pat<'tcx>, expr: &'tcx hir::PatExpr<'tcx>,
677 ) -> PatKind<'tcx> {
678 assert_matches!(pat.kind, hir::PatKind::Expr(..) | hir::PatKind::Range(..));
679 match &expr.kind {
680 hir::PatExprKind::Path(qpath) => self.lower_path(pat, expr, qpath).kind,
681 hir::PatExprKind::Lit { lit, negated } => {
682 let pat_ty = self.typeck_results.node_type(pat.hir_id);
692 let lit_input = LitToConstInput { lit: lit.node, ty: pat_ty, neg: *negated };
693 let constant = self.tcx.at(expr.span).lit_to_const(lit_input);
694 self.const_to_pat(constant, pat_ty, expr.hir_id, lit.span).kind
695 }
696 }
697 }
698}