1mod check_match;
4mod const_to_pat;
5mod migration;
6
7use std::cmp::Ordering;
8use std::sync::Arc;
9
10use rustc_abi::{FieldIdx, Integer};
11use rustc_errors::codes::*;
12use rustc_hir::def::{CtorOf, DefKind, Res};
13use rustc_hir::pat_util::EnumerateAndAdjustIterator;
14use rustc_hir::{self as hir, LangItem, RangeEnd};
15use rustc_index::Idx;
16use rustc_infer::infer::TyCtxtInferExt;
17use rustc_middle::mir::interpret::LitToConstInput;
18use rustc_middle::thir::{
19 Ascription, 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, TypingMode};
24use rustc_middle::{bug, span_bug};
25use rustc_span::def_id::DefId;
26use rustc_span::{ErrorGuaranteed, Span};
27use tracing::{debug, instrument};
28
29pub(crate) use self::check_match::check_match;
30use self::migration::PatMigration;
31use crate::errors::*;
32
33struct PatCtxt<'a, 'tcx> {
34 tcx: TyCtxt<'tcx>,
35 typing_env: ty::TypingEnv<'tcx>,
36 typeck_results: &'a ty::TypeckResults<'tcx>,
37
38 rust_2024_migration: Option<PatMigration<'a>>,
40}
41
42pub(super) fn pat_from_hir<'a, 'tcx>(
43 tcx: TyCtxt<'tcx>,
44 typing_env: ty::TypingEnv<'tcx>,
45 typeck_results: &'a ty::TypeckResults<'tcx>,
46 pat: &'tcx hir::Pat<'tcx>,
47) -> Box<Pat<'tcx>> {
48 let mut pcx = PatCtxt {
49 tcx,
50 typing_env,
51 typeck_results,
52 rust_2024_migration: typeck_results
53 .rust_2024_migration_desugared_pats()
54 .get(pat.hir_id)
55 .map(PatMigration::new),
56 };
57 let result = pcx.lower_pattern(pat);
58 debug!("pat_from_hir({:?}) = {:?}", pat, result);
59 if let Some(m) = pcx.rust_2024_migration {
60 m.emit(tcx, pat.hir_id);
61 }
62 result
63}
64
65impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
66 fn lower_pattern(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Box<Pat<'tcx>> {
67 let adjustments: &[PatAdjustment<'tcx>] =
68 self.typeck_results.pat_adjustments().get(pat.hir_id).map_or(&[], |v| &**v);
69
70 let mut opt_old_mode_span = None;
74 if let Some(s) = &mut self.rust_2024_migration
75 && adjustments.iter().any(|adjust| adjust.kind == PatAdjust::BuiltinDeref)
76 {
77 opt_old_mode_span = s.visit_implicit_derefs(pat.span, adjustments);
78 }
79
80 let unadjusted_pat = match pat.kind {
100 hir::PatKind::Ref(inner, _)
101 if self.typeck_results.skipped_ref_pats().contains(pat.hir_id) =>
102 {
103 self.lower_pattern(inner)
104 }
105 _ => self.lower_pattern_unadjusted(pat),
106 };
107
108 let adjusted_pat = adjustments.iter().rev().fold(unadjusted_pat, |thir_pat, adjust| {
109 debug!("{:?}: wrapping pattern with adjustment {:?}", thir_pat, adjust);
110 let span = thir_pat.span;
111 let kind = match adjust.kind {
112 PatAdjust::BuiltinDeref => PatKind::Deref { subpattern: thir_pat },
113 PatAdjust::OverloadedDeref => {
114 let borrow = self.typeck_results.deref_pat_borrow_mode(adjust.source, pat);
115 PatKind::DerefPattern { subpattern: thir_pat, borrow }
116 }
117 };
118 Box::new(Pat { span, ty: adjust.source, kind })
119 });
120
121 if let Some(s) = &mut self.rust_2024_migration
122 && adjustments.iter().any(|adjust| adjust.kind == PatAdjust::BuiltinDeref)
123 {
124 s.leave_ref(opt_old_mode_span);
125 }
126
127 adjusted_pat
128 }
129
130 fn lower_pattern_range_endpoint(
131 &mut self,
132 expr: Option<&'tcx hir::PatExpr<'tcx>>,
133 ascriptions: &mut Vec<Ascription<'tcx>>,
135 expanded_consts: &mut Vec<DefId>,
136 ) -> Result<Option<PatRangeBoundary<'tcx>>, ErrorGuaranteed> {
137 let Some(expr) = expr else { return Ok(None) };
138
139 let mut kind: PatKind<'tcx> = self.lower_pat_expr(expr, None);
142
143 loop {
145 match kind {
146 PatKind::AscribeUserType { ascription, subpattern } => {
147 ascriptions.push(ascription);
148 kind = subpattern.kind;
149 }
150 PatKind::ExpandedConstant { def_id, subpattern } => {
151 expanded_consts.push(def_id);
152 kind = subpattern.kind;
153 }
154 _ => break,
155 }
156 }
157
158 let PatKind::Constant { value } = kind else {
160 let msg =
161 format!("found bad range pattern endpoint `{expr:?}` outside of error recovery");
162 return Err(self.tcx.dcx().span_delayed_bug(expr.span, msg));
163 };
164
165 Ok(Some(PatRangeBoundary::Finite(value)))
166 }
167
168 fn error_on_literal_overflow(
174 &self,
175 expr: Option<&'tcx hir::PatExpr<'tcx>>,
176 ty: Ty<'tcx>,
177 ) -> Result<(), ErrorGuaranteed> {
178 use rustc_ast::ast::LitKind;
179
180 let Some(expr) = expr else {
181 return Ok(());
182 };
183 let span = expr.span;
184
185 let hir::PatExprKind::Lit { lit, negated } = expr.kind else {
189 return Ok(());
190 };
191 let LitKind::Int(lit_val, _) = lit.node else {
192 return Ok(());
193 };
194 let (min, max): (i128, u128) = match ty.kind() {
195 ty::Int(ity) => {
196 let size = Integer::from_int_ty(&self.tcx, *ity).size();
197 (size.signed_int_min(), size.signed_int_max() as u128)
198 }
199 ty::Uint(uty) => {
200 let size = Integer::from_uint_ty(&self.tcx, *uty).size();
201 (0, size.unsigned_int_max())
202 }
203 _ => {
204 return Ok(());
205 }
206 };
207 if (negated && lit_val > max + 1) || (!negated && lit_val > max) {
210 return Err(self.tcx.dcx().emit_err(LiteralOutOfRange { span, ty, min, max }));
211 }
212 Ok(())
213 }
214
215 fn lower_pattern_range(
216 &mut self,
217 lo_expr: Option<&'tcx hir::PatExpr<'tcx>>,
218 hi_expr: Option<&'tcx hir::PatExpr<'tcx>>,
219 end: RangeEnd,
220 ty: Ty<'tcx>,
221 span: Span,
222 ) -> Result<PatKind<'tcx>, ErrorGuaranteed> {
223 if lo_expr.is_none() && hi_expr.is_none() {
224 let msg = "found twice-open range pattern (`..`) outside of error recovery";
225 self.tcx.dcx().span_bug(span, msg);
226 }
227
228 let mut ascriptions = vec![];
230 let mut expanded_consts = vec![];
231
232 let mut lower_endpoint =
233 |expr| self.lower_pattern_range_endpoint(expr, &mut ascriptions, &mut expanded_consts);
234
235 let lo = lower_endpoint(lo_expr)?.unwrap_or(PatRangeBoundary::NegInfinity);
236 let hi = lower_endpoint(hi_expr)?.unwrap_or(PatRangeBoundary::PosInfinity);
237
238 let cmp = lo.compare_with(hi, ty, self.tcx, self.typing_env);
239 let mut kind = PatKind::Range(Arc::new(PatRange { lo, hi, end, ty }));
240 match (end, cmp) {
241 (RangeEnd::Excluded, Some(Ordering::Less)) => {}
243 (RangeEnd::Included, Some(Ordering::Less)) => {}
245 (RangeEnd::Included, Some(Ordering::Equal)) if lo.is_finite() && hi.is_finite() => {
247 kind = PatKind::Constant { value: lo.as_finite().unwrap() };
248 }
249 (RangeEnd::Included, Some(Ordering::Equal)) if !lo.is_finite() => {}
251 (RangeEnd::Included, Some(Ordering::Equal)) if !hi.is_finite() => {}
254 _ => {
256 self.error_on_literal_overflow(lo_expr, ty)?;
258 self.error_on_literal_overflow(hi_expr, ty)?;
259 let e = match end {
260 RangeEnd::Included => {
261 self.tcx.dcx().emit_err(LowerRangeBoundMustBeLessThanOrEqualToUpper {
262 span,
263 teach: self.tcx.sess.teach(E0030),
264 })
265 }
266 RangeEnd::Excluded => {
267 self.tcx.dcx().emit_err(LowerRangeBoundMustBeLessThanUpper { span })
268 }
269 };
270 return Err(e);
271 }
272 }
273
274 for ascription in ascriptions {
278 let subpattern = Box::new(Pat { span, ty, kind });
279 kind = PatKind::AscribeUserType { ascription, subpattern };
280 }
281 for def_id in expanded_consts {
282 let subpattern = Box::new(Pat { span, ty, kind });
283 kind = PatKind::ExpandedConstant { def_id, subpattern };
284 }
285 Ok(kind)
286 }
287
288 #[instrument(skip(self), level = "debug")]
289 fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Box<Pat<'tcx>> {
290 let mut ty = self.typeck_results.node_type(pat.hir_id);
291 let mut span = pat.span;
292
293 let kind = match pat.kind {
294 hir::PatKind::Missing => PatKind::Missing,
295
296 hir::PatKind::Wild => PatKind::Wild,
297
298 hir::PatKind::Never => PatKind::Never,
299
300 hir::PatKind::Expr(value) => self.lower_pat_expr(value, Some(ty)),
301
302 hir::PatKind::Range(ref lo_expr, ref hi_expr, end) => {
303 let (lo_expr, hi_expr) = (lo_expr.as_deref(), hi_expr.as_deref());
304 self.lower_pattern_range(lo_expr, hi_expr, end, ty, span)
305 .unwrap_or_else(PatKind::Error)
306 }
307
308 hir::PatKind::Deref(subpattern) => {
309 let borrow = self.typeck_results.deref_pat_borrow_mode(ty, subpattern);
310 PatKind::DerefPattern { subpattern: self.lower_pattern(subpattern), borrow }
311 }
312 hir::PatKind::Ref(subpattern, _) => {
313 let opt_old_mode_span =
315 self.rust_2024_migration.as_mut().and_then(|s| s.visit_explicit_deref());
316 let subpattern = self.lower_pattern(subpattern);
317 if let Some(s) = &mut self.rust_2024_migration {
318 s.leave_ref(opt_old_mode_span);
319 }
320 PatKind::Deref { subpattern }
321 }
322 hir::PatKind::Box(subpattern) => {
323 PatKind::Deref { subpattern: self.lower_pattern(subpattern) }
324 }
325
326 hir::PatKind::Slice(prefix, slice, suffix) => {
327 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix)
328 }
329
330 hir::PatKind::Tuple(pats, ddpos) => {
331 let ty::Tuple(tys) = ty.kind() else {
332 span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty);
333 };
334 let subpatterns = self.lower_tuple_subpats(pats, tys.len(), ddpos);
335 PatKind::Leaf { subpatterns }
336 }
337
338 hir::PatKind::Binding(explicit_ba, id, ident, sub) => {
339 if let Some(ident_span) = ident.span.find_ancestor_inside(span) {
340 span = span.with_hi(ident_span.hi());
341 }
342
343 let mode = *self
344 .typeck_results
345 .pat_binding_modes()
346 .get(pat.hir_id)
347 .expect("missing binding mode");
348
349 if let Some(s) = &mut self.rust_2024_migration {
350 s.visit_binding(pat.span, mode, explicit_ba, ident);
351 }
352
353 let var_ty = ty;
356 if let hir::ByRef::Yes(_) = mode.0 {
357 if let ty::Ref(_, rty, _) = ty.kind() {
358 ty = *rty;
359 } else {
360 bug!("`ref {}` has wrong type {}", ident, ty);
361 }
362 };
363
364 PatKind::Binding {
365 mode,
366 name: ident.name,
367 var: LocalVarId(id),
368 ty: var_ty,
369 subpattern: self.lower_opt_pattern(sub),
370 is_primary: id == pat.hir_id,
371 }
372 }
373
374 hir::PatKind::TupleStruct(ref qpath, pats, ddpos) => {
375 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
376 let ty::Adt(adt_def, _) = ty.kind() else {
377 span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty);
378 };
379 let variant_def = adt_def.variant_of_res(res);
380 let subpatterns = self.lower_tuple_subpats(pats, variant_def.fields.len(), ddpos);
381 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
382 }
383
384 hir::PatKind::Struct(ref qpath, fields, _) => {
385 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
386 let subpatterns = fields
387 .iter()
388 .map(|field| FieldPat {
389 field: self.typeck_results.field_index(field.hir_id),
390 pattern: *self.lower_pattern(field.pat),
391 })
392 .collect();
393
394 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
395 }
396
397 hir::PatKind::Or(pats) => PatKind::Or { pats: self.lower_patterns(pats) },
398
399 hir::PatKind::Guard(pat, _) => self.lower_pattern(pat).kind,
401
402 hir::PatKind::Err(guar) => PatKind::Error(guar),
403 };
404
405 Box::new(Pat { span, ty, kind })
406 }
407
408 fn lower_tuple_subpats(
409 &mut self,
410 pats: &'tcx [hir::Pat<'tcx>],
411 expected_len: usize,
412 gap_pos: hir::DotDotPos,
413 ) -> Vec<FieldPat<'tcx>> {
414 pats.iter()
415 .enumerate_and_adjust(expected_len, gap_pos)
416 .map(|(i, subpattern)| FieldPat {
417 field: FieldIdx::new(i),
418 pattern: *self.lower_pattern(subpattern),
419 })
420 .collect()
421 }
422
423 fn lower_patterns(&mut self, pats: &'tcx [hir::Pat<'tcx>]) -> Box<[Pat<'tcx>]> {
424 pats.iter().map(|p| *self.lower_pattern(p)).collect()
425 }
426
427 fn lower_opt_pattern(&mut self, pat: Option<&'tcx hir::Pat<'tcx>>) -> Option<Box<Pat<'tcx>>> {
428 pat.map(|p| self.lower_pattern(p))
429 }
430
431 fn slice_or_array_pattern(
432 &mut self,
433 span: Span,
434 ty: Ty<'tcx>,
435 prefix: &'tcx [hir::Pat<'tcx>],
436 slice: Option<&'tcx hir::Pat<'tcx>>,
437 suffix: &'tcx [hir::Pat<'tcx>],
438 ) -> PatKind<'tcx> {
439 let prefix = self.lower_patterns(prefix);
440 let slice = self.lower_opt_pattern(slice);
441 let suffix = self.lower_patterns(suffix);
442 match ty.kind() {
443 ty::Slice(..) => PatKind::Slice { prefix, slice, suffix },
445 ty::Array(_, len) => {
447 let len = len
448 .try_to_target_usize(self.tcx)
449 .expect("expected len of array pat to be definite");
450 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
451 PatKind::Array { prefix, slice, suffix }
452 }
453 _ => span_bug!(span, "bad slice pattern type {:?}", ty),
454 }
455 }
456
457 fn lower_variant_or_leaf(
458 &mut self,
459 res: Res,
460 hir_id: hir::HirId,
461 span: Span,
462 ty: Ty<'tcx>,
463 subpatterns: Vec<FieldPat<'tcx>>,
464 ) -> PatKind<'tcx> {
465 let res = match res {
466 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
467 let variant_id = self.tcx.parent(variant_ctor_id);
468 Res::Def(DefKind::Variant, variant_id)
469 }
470 res => res,
471 };
472
473 let mut kind = match res {
474 Res::Def(DefKind::Variant, variant_id) => {
475 let enum_id = self.tcx.parent(variant_id);
476 let adt_def = self.tcx.adt_def(enum_id);
477 if adt_def.is_enum() {
478 let args = match ty.kind() {
479 ty::Adt(_, args) | ty::FnDef(_, args) => args,
480 ty::Error(e) => {
481 return PatKind::Error(*e);
483 }
484 _ => bug!("inappropriate type for def: {:?}", ty),
485 };
486 PatKind::Variant {
487 adt_def,
488 args,
489 variant_index: adt_def.variant_index_with_id(variant_id),
490 subpatterns,
491 }
492 } else {
493 PatKind::Leaf { subpatterns }
494 }
495 }
496
497 Res::Def(
498 DefKind::Struct
499 | DefKind::Ctor(CtorOf::Struct, ..)
500 | DefKind::Union
501 | DefKind::TyAlias
502 | DefKind::AssocTy,
503 _,
504 )
505 | Res::SelfTyParam { .. }
506 | Res::SelfTyAlias { .. }
507 | Res::SelfCtor(..) => PatKind::Leaf { subpatterns },
508 _ => {
509 let e = match res {
510 Res::Def(DefKind::ConstParam, def_id) => {
511 let const_span = self.tcx.def_span(def_id);
512 self.tcx.dcx().emit_err(ConstParamInPattern { span, const_span })
513 }
514 Res::Def(DefKind::Static { .. }, def_id) => {
515 let static_span = self.tcx.def_span(def_id);
516 self.tcx.dcx().emit_err(StaticInPattern { span, static_span })
517 }
518 _ => self.tcx.dcx().emit_err(NonConstPath { span }),
519 };
520 PatKind::Error(e)
521 }
522 };
523
524 if let Some(user_ty) = self.user_args_applied_to_ty_of_hir_id(hir_id) {
525 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
526 let annotation = CanonicalUserTypeAnnotation {
527 user_ty: Box::new(user_ty),
528 span,
529 inferred_ty: self.typeck_results.node_type(hir_id),
530 };
531 kind = PatKind::AscribeUserType {
532 subpattern: Box::new(Pat { span, ty, kind }),
533 ascription: Ascription { annotation, variance: ty::Covariant },
534 };
535 }
536
537 kind
538 }
539
540 fn user_args_applied_to_ty_of_hir_id(
541 &self,
542 hir_id: hir::HirId,
543 ) -> Option<ty::CanonicalUserType<'tcx>> {
544 crate::thir::util::user_args_applied_to_ty_of_hir_id(self.tcx, self.typeck_results, hir_id)
545 }
546
547 #[instrument(skip(self), level = "debug")]
551 fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Box<Pat<'tcx>> {
552 let ty = self.typeck_results.node_type(id);
553 let res = self.typeck_results.qpath_res(qpath, id);
554
555 let (def_id, user_ty) = match res {
556 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
557 (def_id, self.typeck_results.user_provided_types().get(id))
558 }
559
560 _ => {
561 let kind = self.lower_variant_or_leaf(res, id, span, ty, vec![]);
564 return Box::new(Pat { span, ty, kind });
565 }
566 };
567
568 let args = self.typeck_results.node_args(id);
570 let c = ty::Const::new_unevaluated(self.tcx, ty::UnevaluatedConst { def: def_id, args });
573 let mut pattern = self.const_to_pat(c, ty, id, span);
574
575 if let Some(&user_ty) = user_ty {
578 let annotation = CanonicalUserTypeAnnotation {
579 user_ty: Box::new(user_ty),
580 span,
581 inferred_ty: self.typeck_results.node_type(id),
582 };
583 let kind = PatKind::AscribeUserType {
584 subpattern: pattern,
585 ascription: Ascription {
586 annotation,
587 variance: ty::Contravariant,
590 },
591 };
592 pattern = Box::new(Pat { span, kind, ty });
593 }
594
595 pattern
596 }
597
598 fn lower_inline_const(
600 &mut self,
601 block: &'tcx hir::ConstBlock,
602 id: hir::HirId,
603 span: Span,
604 ) -> PatKind<'tcx> {
605 let tcx = self.tcx;
606 let def_id = block.def_id;
607 let ty = tcx.typeck(def_id).node_type(block.hir_id);
608
609 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
610 let parent_args = ty::GenericArgs::identity_for_item(tcx, typeck_root_def_id);
611 let args = ty::InlineConstArgs::new(tcx, ty::InlineConstArgsParts { parent_args, ty }).args;
612
613 let ct = ty::UnevaluatedConst { def: def_id.to_def_id(), args };
614 let c = ty::Const::new_unevaluated(self.tcx, ct);
615 let pattern = self.const_to_pat(c, ty, id, span);
616
617 let annotation = {
619 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
620 let args = ty::InlineConstArgs::new(
621 tcx,
622 ty::InlineConstArgsParts { parent_args, ty: infcx.next_ty_var(span) },
623 )
624 .args;
625 infcx.canonicalize_user_type_annotation(ty::UserType::new(ty::UserTypeKind::TypeOf(
626 def_id.to_def_id(),
627 ty::UserArgs { args, user_self_ty: None },
628 )))
629 };
630 let annotation =
631 CanonicalUserTypeAnnotation { user_ty: Box::new(annotation), span, inferred_ty: ty };
632 PatKind::AscribeUserType {
633 subpattern: pattern,
634 ascription: Ascription {
635 annotation,
636 variance: ty::Contravariant,
639 },
640 }
641 }
642
643 fn lower_pat_expr(
648 &mut self,
649 expr: &'tcx hir::PatExpr<'tcx>,
650 pat_ty: Option<Ty<'tcx>>,
651 ) -> PatKind<'tcx> {
652 match &expr.kind {
653 hir::PatExprKind::Path(qpath) => self.lower_path(qpath, expr.hir_id, expr.span).kind,
654 hir::PatExprKind::ConstBlock(anon_const) => {
655 self.lower_inline_const(anon_const, expr.hir_id, expr.span)
656 }
657 hir::PatExprKind::Lit { lit, negated } => {
658 let ct_ty = match pat_ty {
668 Some(pat_ty)
669 if let ty::Adt(def, _) = *pat_ty.kind()
670 && self.tcx.is_lang_item(def.did(), LangItem::String) =>
671 {
672 if !self.tcx.features().string_deref_patterns() {
673 span_bug!(
674 expr.span,
675 "matching on `String` went through without enabling string_deref_patterns"
676 );
677 }
678 self.typeck_results.node_type(expr.hir_id)
679 }
680 Some(pat_ty) => pat_ty,
681 None => self.typeck_results.node_type(expr.hir_id),
682 };
683 let lit_input = LitToConstInput { lit: &lit.node, ty: ct_ty, neg: *negated };
684 let constant = self.tcx.at(expr.span).lit_to_const(lit_input);
685 self.const_to_pat(constant, ct_ty, expr.hir_id, lit.span).kind
686 }
687 }
688 }
689}