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) => PatKind::DerefPattern {
323 subpattern: self.lower_pattern(subpattern),
324 borrow: hir::ByRef::No,
325 },
326
327 hir::PatKind::Slice(prefix, slice, suffix) => {
328 self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix)
329 }
330
331 hir::PatKind::Tuple(pats, ddpos) => {
332 let ty::Tuple(tys) = ty.kind() else {
333 span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", ty);
334 };
335 let subpatterns = self.lower_tuple_subpats(pats, tys.len(), ddpos);
336 PatKind::Leaf { subpatterns }
337 }
338
339 hir::PatKind::Binding(explicit_ba, id, ident, sub) => {
340 if let Some(ident_span) = ident.span.find_ancestor_inside(span) {
341 span = span.with_hi(ident_span.hi());
342 }
343
344 let mode = *self
345 .typeck_results
346 .pat_binding_modes()
347 .get(pat.hir_id)
348 .expect("missing binding mode");
349
350 if let Some(s) = &mut self.rust_2024_migration {
351 s.visit_binding(pat.span, mode, explicit_ba, ident);
352 }
353
354 let var_ty = ty;
357 if let hir::ByRef::Yes(_) = mode.0 {
358 if let ty::Ref(_, rty, _) = ty.kind() {
359 ty = *rty;
360 } else {
361 bug!("`ref {}` has wrong type {}", ident, ty);
362 }
363 };
364
365 PatKind::Binding {
366 mode,
367 name: ident.name,
368 var: LocalVarId(id),
369 ty: var_ty,
370 subpattern: self.lower_opt_pattern(sub),
371 is_primary: id == pat.hir_id,
372 }
373 }
374
375 hir::PatKind::TupleStruct(ref qpath, pats, ddpos) => {
376 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
377 let ty::Adt(adt_def, _) = ty.kind() else {
378 span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty);
379 };
380 let variant_def = adt_def.variant_of_res(res);
381 let subpatterns = self.lower_tuple_subpats(pats, variant_def.fields.len(), ddpos);
382 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
383 }
384
385 hir::PatKind::Struct(ref qpath, fields, _) => {
386 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
387 let subpatterns = fields
388 .iter()
389 .map(|field| FieldPat {
390 field: self.typeck_results.field_index(field.hir_id),
391 pattern: *self.lower_pattern(field.pat),
392 })
393 .collect();
394
395 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
396 }
397
398 hir::PatKind::Or(pats) => PatKind::Or { pats: self.lower_patterns(pats) },
399
400 hir::PatKind::Guard(pat, _) => self.lower_pattern(pat).kind,
402
403 hir::PatKind::Err(guar) => PatKind::Error(guar),
404 };
405
406 Box::new(Pat { span, ty, kind })
407 }
408
409 fn lower_tuple_subpats(
410 &mut self,
411 pats: &'tcx [hir::Pat<'tcx>],
412 expected_len: usize,
413 gap_pos: hir::DotDotPos,
414 ) -> Vec<FieldPat<'tcx>> {
415 pats.iter()
416 .enumerate_and_adjust(expected_len, gap_pos)
417 .map(|(i, subpattern)| FieldPat {
418 field: FieldIdx::new(i),
419 pattern: *self.lower_pattern(subpattern),
420 })
421 .collect()
422 }
423
424 fn lower_patterns(&mut self, pats: &'tcx [hir::Pat<'tcx>]) -> Box<[Pat<'tcx>]> {
425 pats.iter().map(|p| *self.lower_pattern(p)).collect()
426 }
427
428 fn lower_opt_pattern(&mut self, pat: Option<&'tcx hir::Pat<'tcx>>) -> Option<Box<Pat<'tcx>>> {
429 pat.map(|p| self.lower_pattern(p))
430 }
431
432 fn slice_or_array_pattern(
433 &mut self,
434 span: Span,
435 ty: Ty<'tcx>,
436 prefix: &'tcx [hir::Pat<'tcx>],
437 slice: Option<&'tcx hir::Pat<'tcx>>,
438 suffix: &'tcx [hir::Pat<'tcx>],
439 ) -> PatKind<'tcx> {
440 let prefix = self.lower_patterns(prefix);
441 let slice = self.lower_opt_pattern(slice);
442 let suffix = self.lower_patterns(suffix);
443 match ty.kind() {
444 ty::Slice(..) => PatKind::Slice { prefix, slice, suffix },
446 ty::Array(_, len) => {
448 let len = len
449 .try_to_target_usize(self.tcx)
450 .expect("expected len of array pat to be definite");
451 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
452 PatKind::Array { prefix, slice, suffix }
453 }
454 _ => span_bug!(span, "bad slice pattern type {:?}", ty),
455 }
456 }
457
458 fn lower_variant_or_leaf(
459 &mut self,
460 res: Res,
461 hir_id: hir::HirId,
462 span: Span,
463 ty: Ty<'tcx>,
464 subpatterns: Vec<FieldPat<'tcx>>,
465 ) -> PatKind<'tcx> {
466 let res = match res {
467 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
468 let variant_id = self.tcx.parent(variant_ctor_id);
469 Res::Def(DefKind::Variant, variant_id)
470 }
471 res => res,
472 };
473
474 let mut kind = match res {
475 Res::Def(DefKind::Variant, variant_id) => {
476 let enum_id = self.tcx.parent(variant_id);
477 let adt_def = self.tcx.adt_def(enum_id);
478 if adt_def.is_enum() {
479 let args = match ty.kind() {
480 ty::Adt(_, args) | ty::FnDef(_, args) => args,
481 ty::Error(e) => {
482 return PatKind::Error(*e);
484 }
485 _ => bug!("inappropriate type for def: {:?}", ty),
486 };
487 PatKind::Variant {
488 adt_def,
489 args,
490 variant_index: adt_def.variant_index_with_id(variant_id),
491 subpatterns,
492 }
493 } else {
494 PatKind::Leaf { subpatterns }
495 }
496 }
497
498 Res::Def(
499 DefKind::Struct
500 | DefKind::Ctor(CtorOf::Struct, ..)
501 | DefKind::Union
502 | DefKind::TyAlias
503 | DefKind::AssocTy,
504 _,
505 )
506 | Res::SelfTyParam { .. }
507 | Res::SelfTyAlias { .. }
508 | Res::SelfCtor(..) => PatKind::Leaf { subpatterns },
509 _ => {
510 let e = match res {
511 Res::Def(DefKind::ConstParam, def_id) => {
512 let const_span = self.tcx.def_span(def_id);
513 self.tcx.dcx().emit_err(ConstParamInPattern { span, const_span })
514 }
515 Res::Def(DefKind::Static { .. }, def_id) => {
516 let static_span = self.tcx.def_span(def_id);
517 self.tcx.dcx().emit_err(StaticInPattern { span, static_span })
518 }
519 _ => self.tcx.dcx().emit_err(NonConstPath { span }),
520 };
521 PatKind::Error(e)
522 }
523 };
524
525 if let Some(user_ty) = self.user_args_applied_to_ty_of_hir_id(hir_id) {
526 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
527 let annotation = CanonicalUserTypeAnnotation {
528 user_ty: Box::new(user_ty),
529 span,
530 inferred_ty: self.typeck_results.node_type(hir_id),
531 };
532 kind = PatKind::AscribeUserType {
533 subpattern: Box::new(Pat { span, ty, kind }),
534 ascription: Ascription { annotation, variance: ty::Covariant },
535 };
536 }
537
538 kind
539 }
540
541 fn user_args_applied_to_ty_of_hir_id(
542 &self,
543 hir_id: hir::HirId,
544 ) -> Option<ty::CanonicalUserType<'tcx>> {
545 crate::thir::util::user_args_applied_to_ty_of_hir_id(self.tcx, self.typeck_results, hir_id)
546 }
547
548 #[instrument(skip(self), level = "debug")]
552 fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Box<Pat<'tcx>> {
553 let ty = self.typeck_results.node_type(id);
554 let res = self.typeck_results.qpath_res(qpath, id);
555
556 let (def_id, user_ty) = match res {
557 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
558 (def_id, self.typeck_results.user_provided_types().get(id))
559 }
560
561 _ => {
562 let kind = self.lower_variant_or_leaf(res, id, span, ty, vec![]);
565 return Box::new(Pat { span, ty, kind });
566 }
567 };
568
569 let args = self.typeck_results.node_args(id);
571 let c = ty::Const::new_unevaluated(self.tcx, ty::UnevaluatedConst { def: def_id, args });
574 let mut pattern = self.const_to_pat(c, ty, id, span);
575
576 if let Some(&user_ty) = user_ty {
579 let annotation = CanonicalUserTypeAnnotation {
580 user_ty: Box::new(user_ty),
581 span,
582 inferred_ty: self.typeck_results.node_type(id),
583 };
584 let kind = PatKind::AscribeUserType {
585 subpattern: pattern,
586 ascription: Ascription {
587 annotation,
588 variance: ty::Contravariant,
591 },
592 };
593 pattern = Box::new(Pat { span, kind, ty });
594 }
595
596 pattern
597 }
598
599 fn lower_inline_const(
601 &mut self,
602 block: &'tcx hir::ConstBlock,
603 id: hir::HirId,
604 span: Span,
605 ) -> PatKind<'tcx> {
606 let tcx = self.tcx;
607 let def_id = block.def_id;
608 let ty = tcx.typeck(def_id).node_type(block.hir_id);
609
610 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
611 let parent_args = ty::GenericArgs::identity_for_item(tcx, typeck_root_def_id);
612 let args = ty::InlineConstArgs::new(tcx, ty::InlineConstArgsParts { parent_args, ty }).args;
613
614 let ct = ty::UnevaluatedConst { def: def_id.to_def_id(), args };
615 let c = ty::Const::new_unevaluated(self.tcx, ct);
616 let pattern = self.const_to_pat(c, ty, id, span);
617
618 let annotation = {
620 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
621 let args = ty::InlineConstArgs::new(
622 tcx,
623 ty::InlineConstArgsParts { parent_args, ty: infcx.next_ty_var(span) },
624 )
625 .args;
626 infcx.canonicalize_user_type_annotation(ty::UserType::new(ty::UserTypeKind::TypeOf(
627 def_id.to_def_id(),
628 ty::UserArgs { args, user_self_ty: None },
629 )))
630 };
631 let annotation =
632 CanonicalUserTypeAnnotation { user_ty: Box::new(annotation), span, inferred_ty: ty };
633 PatKind::AscribeUserType {
634 subpattern: pattern,
635 ascription: Ascription {
636 annotation,
637 variance: ty::Contravariant,
640 },
641 }
642 }
643
644 fn lower_pat_expr(
649 &mut self,
650 expr: &'tcx hir::PatExpr<'tcx>,
651 pat_ty: Option<Ty<'tcx>>,
652 ) -> PatKind<'tcx> {
653 match &expr.kind {
654 hir::PatExprKind::Path(qpath) => self.lower_path(qpath, expr.hir_id, expr.span).kind,
655 hir::PatExprKind::ConstBlock(anon_const) => {
656 self.lower_inline_const(anon_const, expr.hir_id, expr.span)
657 }
658 hir::PatExprKind::Lit { lit, negated } => {
659 let ct_ty = match pat_ty {
669 Some(pat_ty)
670 if let ty::Adt(def, _) = *pat_ty.kind()
671 && self.tcx.is_lang_item(def.did(), LangItem::String) =>
672 {
673 if !self.tcx.features().string_deref_patterns() {
674 span_bug!(
675 expr.span,
676 "matching on `String` went through without enabling string_deref_patterns"
677 );
678 }
679 self.typeck_results.node_type(expr.hir_id)
680 }
681 Some(pat_ty) => pat_ty,
682 None => self.typeck_results.node_type(expr.hir_id),
683 };
684 let lit_input = LitToConstInput { lit: lit.node, ty: ct_ty, neg: *negated };
685 let constant = self.tcx.at(expr.span).lit_to_const(lit_input);
686 self.const_to_pat(constant, ct_ty, expr.hir_id, lit.span).kind
687 }
688 }
689 }
690}