rustc_mir_build/thir/pattern/
mod.rs1mod 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 Ok(Some(PatRangeBoundary::Finite(value.valtree)))
165 }
166
167 fn error_on_literal_overflow(
173 &self,
174 expr: Option<&'tcx hir::PatExpr<'tcx>>,
175 ty: Ty<'tcx>,
176 ) -> Result<(), ErrorGuaranteed> {
177 use rustc_ast::ast::LitKind;
178
179 let Some(expr) = expr else {
180 return Ok(());
181 };
182 let span = expr.span;
183
184 let hir::PatExprKind::Lit { lit, negated } = expr.kind else {
188 return Ok(());
189 };
190 let LitKind::Int(lit_val, _) = lit.node else {
191 return Ok(());
192 };
193 let (min, max): (i128, u128) = match ty.kind() {
194 ty::Int(ity) => {
195 let size = Integer::from_int_ty(&self.tcx, *ity).size();
196 (size.signed_int_min(), size.signed_int_max() as u128)
197 }
198 ty::Uint(uty) => {
199 let size = Integer::from_uint_ty(&self.tcx, *uty).size();
200 (0, size.unsigned_int_max())
201 }
202 _ => {
203 return Ok(());
204 }
205 };
206 if (negated && lit_val > max + 1) || (!negated && lit_val > max) {
209 return Err(self.tcx.dcx().emit_err(LiteralOutOfRange { span, ty, min, max }));
210 }
211 Ok(())
212 }
213
214 fn lower_pattern_range(
215 &mut self,
216 lo_expr: Option<&'tcx hir::PatExpr<'tcx>>,
217 hi_expr: Option<&'tcx hir::PatExpr<'tcx>>,
218 end: RangeEnd,
219 ty: Ty<'tcx>,
220 span: Span,
221 ) -> Result<PatKind<'tcx>, ErrorGuaranteed> {
222 if lo_expr.is_none() && hi_expr.is_none() {
223 let msg = "found twice-open range pattern (`..`) outside of error recovery";
224 self.tcx.dcx().span_bug(span, msg);
225 }
226
227 let mut ascriptions = vec![];
229 let mut expanded_consts = vec![];
230
231 let mut lower_endpoint =
232 |expr| self.lower_pattern_range_endpoint(expr, &mut ascriptions, &mut expanded_consts);
233
234 let lo = lower_endpoint(lo_expr)?.unwrap_or(PatRangeBoundary::NegInfinity);
235 let hi = lower_endpoint(hi_expr)?.unwrap_or(PatRangeBoundary::PosInfinity);
236
237 let cmp = lo.compare_with(hi, ty, self.tcx);
238 let mut kind = PatKind::Range(Arc::new(PatRange { lo, hi, end, ty }));
239 match (end, cmp) {
240 (RangeEnd::Excluded, Some(Ordering::Less)) => {}
242 (RangeEnd::Included, Some(Ordering::Less)) => {}
244 (RangeEnd::Included, Some(Ordering::Equal)) if lo.is_finite() && hi.is_finite() => {
246 let value = ty::Value { ty, valtree: lo.as_finite().unwrap() };
247 kind = PatKind::Constant { value };
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 is_shorthand: false,
373 }
374 }
375
376 hir::PatKind::TupleStruct(ref qpath, pats, ddpos) => {
377 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
378 let ty::Adt(adt_def, _) = ty.kind() else {
379 span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty);
380 };
381 let variant_def = adt_def.variant_of_res(res);
382 let subpatterns = self.lower_tuple_subpats(pats, variant_def.fields.len(), ddpos);
383 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
384 }
385
386 hir::PatKind::Struct(ref qpath, fields, _) => {
387 let res = self.typeck_results.qpath_res(qpath, pat.hir_id);
388 let subpatterns = fields
389 .iter()
390 .map(|field| {
391 let mut pattern = *self.lower_pattern(field.pat);
392 if let PatKind::Binding { ref mut is_shorthand, .. } = pattern.kind {
393 *is_shorthand = field.is_shorthand;
394 }
395 let field = self.typeck_results.field_index(field.hir_id);
396 FieldPat { field, pattern }
397 })
398 .collect();
399
400 self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
401 }
402
403 hir::PatKind::Or(pats) => PatKind::Or { pats: self.lower_patterns(pats) },
404
405 hir::PatKind::Guard(pat, _) => self.lower_pattern(pat).kind,
407
408 hir::PatKind::Err(guar) => PatKind::Error(guar),
409 };
410
411 Box::new(Pat { span, ty, kind })
412 }
413
414 fn lower_tuple_subpats(
415 &mut self,
416 pats: &'tcx [hir::Pat<'tcx>],
417 expected_len: usize,
418 gap_pos: hir::DotDotPos,
419 ) -> Vec<FieldPat<'tcx>> {
420 pats.iter()
421 .enumerate_and_adjust(expected_len, gap_pos)
422 .map(|(i, subpattern)| FieldPat {
423 field: FieldIdx::new(i),
424 pattern: *self.lower_pattern(subpattern),
425 })
426 .collect()
427 }
428
429 fn lower_patterns(&mut self, pats: &'tcx [hir::Pat<'tcx>]) -> Box<[Pat<'tcx>]> {
430 pats.iter().map(|p| *self.lower_pattern(p)).collect()
431 }
432
433 fn lower_opt_pattern(&mut self, pat: Option<&'tcx hir::Pat<'tcx>>) -> Option<Box<Pat<'tcx>>> {
434 pat.map(|p| self.lower_pattern(p))
435 }
436
437 fn slice_or_array_pattern(
438 &mut self,
439 span: Span,
440 ty: Ty<'tcx>,
441 prefix: &'tcx [hir::Pat<'tcx>],
442 slice: Option<&'tcx hir::Pat<'tcx>>,
443 suffix: &'tcx [hir::Pat<'tcx>],
444 ) -> PatKind<'tcx> {
445 let prefix = self.lower_patterns(prefix);
446 let slice = self.lower_opt_pattern(slice);
447 let suffix = self.lower_patterns(suffix);
448 match ty.kind() {
449 ty::Slice(..) => PatKind::Slice { prefix, slice, suffix },
451 ty::Array(_, len) => {
453 let len = len
454 .try_to_target_usize(self.tcx)
455 .expect("expected len of array pat to be definite");
456 assert!(len >= prefix.len() as u64 + suffix.len() as u64);
457 PatKind::Array { prefix, slice, suffix }
458 }
459 _ => span_bug!(span, "bad slice pattern type {:?}", ty),
460 }
461 }
462
463 fn lower_variant_or_leaf(
464 &mut self,
465 res: Res,
466 hir_id: hir::HirId,
467 span: Span,
468 ty: Ty<'tcx>,
469 subpatterns: Vec<FieldPat<'tcx>>,
470 ) -> PatKind<'tcx> {
471 let res = match res {
472 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => {
473 let variant_id = self.tcx.parent(variant_ctor_id);
474 Res::Def(DefKind::Variant, variant_id)
475 }
476 res => res,
477 };
478
479 let mut kind = match res {
480 Res::Def(DefKind::Variant, variant_id) => {
481 let enum_id = self.tcx.parent(variant_id);
482 let adt_def = self.tcx.adt_def(enum_id);
483 if adt_def.is_enum() {
484 let args = match ty.kind() {
485 ty::Adt(_, args) | ty::FnDef(_, args) => args,
486 ty::Error(e) => {
487 return PatKind::Error(*e);
489 }
490 _ => bug!("inappropriate type for def: {:?}", ty),
491 };
492 PatKind::Variant {
493 adt_def,
494 args,
495 variant_index: adt_def.variant_index_with_id(variant_id),
496 subpatterns,
497 }
498 } else {
499 PatKind::Leaf { subpatterns }
500 }
501 }
502
503 Res::Def(
504 DefKind::Struct
505 | DefKind::Ctor(CtorOf::Struct, ..)
506 | DefKind::Union
507 | DefKind::TyAlias
508 | DefKind::AssocTy,
509 _,
510 )
511 | Res::SelfTyParam { .. }
512 | Res::SelfTyAlias { .. }
513 | Res::SelfCtor(..) => PatKind::Leaf { subpatterns },
514 _ => {
515 let e = match res {
516 Res::Def(DefKind::ConstParam, def_id) => {
517 let const_span = self.tcx.def_span(def_id);
518 self.tcx.dcx().emit_err(ConstParamInPattern { span, const_span })
519 }
520 Res::Def(DefKind::Static { .. }, def_id) => {
521 let static_span = self.tcx.def_span(def_id);
522 self.tcx.dcx().emit_err(StaticInPattern { span, static_span })
523 }
524 _ => self.tcx.dcx().emit_err(NonConstPath { span }),
525 };
526 PatKind::Error(e)
527 }
528 };
529
530 if let Some(user_ty) = self.user_args_applied_to_ty_of_hir_id(hir_id) {
531 debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span);
532 let annotation = CanonicalUserTypeAnnotation {
533 user_ty: Box::new(user_ty),
534 span,
535 inferred_ty: self.typeck_results.node_type(hir_id),
536 };
537 kind = PatKind::AscribeUserType {
538 subpattern: Box::new(Pat { span, ty, kind }),
539 ascription: Ascription { annotation, variance: ty::Covariant },
540 };
541 }
542
543 kind
544 }
545
546 fn user_args_applied_to_ty_of_hir_id(
547 &self,
548 hir_id: hir::HirId,
549 ) -> Option<ty::CanonicalUserType<'tcx>> {
550 crate::thir::util::user_args_applied_to_ty_of_hir_id(self.tcx, self.typeck_results, hir_id)
551 }
552
553 #[instrument(skip(self), level = "debug")]
557 fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Box<Pat<'tcx>> {
558 let ty = self.typeck_results.node_type(id);
559 let res = self.typeck_results.qpath_res(qpath, id);
560
561 let (def_id, user_ty) = match res {
562 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
563 (def_id, self.typeck_results.user_provided_types().get(id))
564 }
565
566 _ => {
567 let kind = self.lower_variant_or_leaf(res, id, span, ty, vec![]);
570 return Box::new(Pat { span, ty, kind });
571 }
572 };
573
574 let args = self.typeck_results.node_args(id);
576 let c = ty::Const::new_unevaluated(self.tcx, ty::UnevaluatedConst { def: def_id, args });
579 let mut pattern = self.const_to_pat(c, ty, id, span);
580
581 if let Some(&user_ty) = user_ty {
584 let annotation = CanonicalUserTypeAnnotation {
585 user_ty: Box::new(user_ty),
586 span,
587 inferred_ty: self.typeck_results.node_type(id),
588 };
589 let kind = PatKind::AscribeUserType {
590 subpattern: pattern,
591 ascription: Ascription {
592 annotation,
593 variance: ty::Contravariant,
596 },
597 };
598 pattern = Box::new(Pat { span, kind, ty });
599 }
600
601 pattern
602 }
603
604 fn lower_inline_const(
606 &mut self,
607 block: &'tcx hir::ConstBlock,
608 id: hir::HirId,
609 span: Span,
610 ) -> PatKind<'tcx> {
611 let tcx = self.tcx;
612 let def_id = block.def_id;
613 let ty = tcx.typeck(def_id).node_type(block.hir_id);
614
615 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
616 let parent_args = ty::GenericArgs::identity_for_item(tcx, typeck_root_def_id);
617 let args = ty::InlineConstArgs::new(tcx, ty::InlineConstArgsParts { parent_args, ty }).args;
618
619 let ct = ty::UnevaluatedConst { def: def_id.to_def_id(), args };
620 let c = ty::Const::new_unevaluated(self.tcx, ct);
621 let pattern = self.const_to_pat(c, ty, id, span);
622
623 let annotation = {
625 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
626 let args = ty::InlineConstArgs::new(
627 tcx,
628 ty::InlineConstArgsParts { parent_args, ty: infcx.next_ty_var(span) },
629 )
630 .args;
631 infcx.canonicalize_user_type_annotation(ty::UserType::new(ty::UserTypeKind::TypeOf(
632 def_id.to_def_id(),
633 ty::UserArgs { args, user_self_ty: None },
634 )))
635 };
636 let annotation =
637 CanonicalUserTypeAnnotation { user_ty: Box::new(annotation), span, inferred_ty: ty };
638 PatKind::AscribeUserType {
639 subpattern: pattern,
640 ascription: Ascription {
641 annotation,
642 variance: ty::Contravariant,
645 },
646 }
647 }
648
649 fn lower_pat_expr(
654 &mut self,
655 expr: &'tcx hir::PatExpr<'tcx>,
656 pat_ty: Option<Ty<'tcx>>,
657 ) -> PatKind<'tcx> {
658 match &expr.kind {
659 hir::PatExprKind::Path(qpath) => self.lower_path(qpath, expr.hir_id, expr.span).kind,
660 hir::PatExprKind::ConstBlock(anon_const) => {
661 self.lower_inline_const(anon_const, expr.hir_id, expr.span)
662 }
663 hir::PatExprKind::Lit { lit, negated } => {
664 let ct_ty = match pat_ty {
674 Some(pat_ty)
675 if let ty::Adt(def, _) = *pat_ty.kind()
676 && self.tcx.is_lang_item(def.did(), LangItem::String) =>
677 {
678 if !self.tcx.features().string_deref_patterns() {
679 span_bug!(
680 expr.span,
681 "matching on `String` went through without enabling string_deref_patterns"
682 );
683 }
684 self.typeck_results.node_type(expr.hir_id)
685 }
686 Some(pat_ty) => pat_ty,
687 None => self.typeck_results.node_type(expr.hir_id),
688 };
689 let lit_input = LitToConstInput { lit: lit.node, ty: ct_ty, neg: *negated };
690 let constant = self.tcx.at(expr.span).lit_to_const(lit_input);
691 self.const_to_pat(constant, ct_ty, expr.hir_id, lit.span).kind
692 }
693 }
694 }
695}