rustc_middle/thir.rs
1//! THIR datatypes and definitions. See the [rustc dev guide] for more info.
2//!
3//! If you compare the THIR [`ExprKind`] to [`hir::ExprKind`], you will see it is
4//! a good bit simpler. In fact, a number of the more straight-forward
5//! MIR simplifications are already done in the lowering to THIR. For
6//! example, method calls and overloaded operators are absent: they are
7//! expected to be converted into [`ExprKind::Call`] instances.
8//!
9//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/thir.html
10
11use std::cmp::Ordering;
12use std::fmt;
13use std::ops::Index;
14use std::sync::Arc;
15
16use rustc_abi::{FieldIdx, Integer, Size, VariantIdx};
17use rustc_ast::{AsmMacro, InlineAsmOptions, InlineAsmTemplatePiece};
18use rustc_hir as hir;
19use rustc_hir::def_id::DefId;
20use rustc_hir::{BindingMode, ByRef, HirId, MatchSource, RangeEnd};
21use rustc_index::{IndexVec, newtype_index};
22use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeVisitable};
23use rustc_span::def_id::LocalDefId;
24use rustc_span::{ErrorGuaranteed, Span, Symbol};
25use rustc_target::asm::InlineAsmRegOrRegClass;
26use tracing::instrument;
27
28use crate::middle::region;
29use crate::mir::interpret::AllocId;
30use crate::mir::{self, AssignOp, BinOp, BorrowKind, FakeReadCause, UnOp};
31use crate::thir::visit::for_each_immediate_subpat;
32use crate::ty::adjustment::PointerCoercion;
33use crate::ty::layout::IntegerExt;
34use crate::ty::{
35 self, AdtDef, CanonicalUserType, CanonicalUserTypeAnnotation, FnSig, GenericArgsRef, List, Ty,
36 TyCtxt, UpvarArgs,
37};
38
39pub mod visit;
40
41macro_rules! thir_with_elements {
42 (
43 $($name:ident: $id:ty => $value:ty => $format:literal,)*
44 ) => {
45 $(
46 newtype_index! {
47 #[derive(HashStable)]
48 #[debug_format = $format]
49 pub struct $id {}
50 }
51 )*
52
53 // Note: Making `Thir` implement `Clone` is useful for external tools that need access to
54 // THIR bodies even after the `Steal` query result has been stolen.
55 // One such tool is https://github.com/rust-corpus/qrates/.
56 /// A container for a THIR body.
57 ///
58 /// This can be indexed directly by any THIR index (e.g. [`ExprId`]).
59 #[derive(Debug, HashStable, Clone)]
60 pub struct Thir<'tcx> {
61 pub body_type: BodyTy<'tcx>,
62 $(
63 pub $name: IndexVec<$id, $value>,
64 )*
65 }
66
67 impl<'tcx> Thir<'tcx> {
68 pub fn new(body_type: BodyTy<'tcx>) -> Thir<'tcx> {
69 Thir {
70 body_type,
71 $(
72 $name: IndexVec::new(),
73 )*
74 }
75 }
76 }
77
78 $(
79 impl<'tcx> Index<$id> for Thir<'tcx> {
80 type Output = $value;
81 fn index(&self, index: $id) -> &Self::Output {
82 &self.$name[index]
83 }
84 }
85 )*
86 }
87}
88
89thir_with_elements! {
90 arms: ArmId => Arm<'tcx> => "a{}",
91 blocks: BlockId => Block => "b{}",
92 exprs: ExprId => Expr<'tcx> => "e{}",
93 stmts: StmtId => Stmt<'tcx> => "s{}",
94 params: ParamId => Param<'tcx> => "p{}",
95}
96
97#[derive(Debug, HashStable, Clone)]
98pub enum BodyTy<'tcx> {
99 Const(Ty<'tcx>),
100 Fn(FnSig<'tcx>),
101 GlobalAsm(Ty<'tcx>),
102}
103
104/// Description of a type-checked function parameter.
105#[derive(Clone, Debug, HashStable)]
106pub struct Param<'tcx> {
107 /// The pattern that appears in the parameter list, or None for implicit parameters.
108 pub pat: Option<Box<Pat<'tcx>>>,
109 /// The possibly inferred type.
110 pub ty: Ty<'tcx>,
111 /// Span of the explicitly provided type, or None if inferred for closures.
112 pub ty_span: Option<Span>,
113 /// Whether this param is `self`, and how it is bound.
114 pub self_kind: Option<hir::ImplicitSelfKind>,
115 /// HirId for lints.
116 pub hir_id: Option<HirId>,
117}
118
119#[derive(Copy, Clone, Debug, HashStable)]
120pub enum LintLevel {
121 Inherited,
122 Explicit(HirId),
123}
124
125#[derive(Clone, Debug, HashStable)]
126pub struct Block {
127 /// Whether the block itself has a label. Used by `label: {}`
128 /// and `try` blocks.
129 ///
130 /// This does *not* include labels on loops, e.g. `'label: loop {}`.
131 pub targeted_by_break: bool,
132 pub region_scope: region::Scope,
133 /// The span of the block, including the opening braces,
134 /// the label, and the `unsafe` keyword, if present.
135 pub span: Span,
136 /// The statements in the blocK.
137 pub stmts: Box<[StmtId]>,
138 /// The trailing expression of the block, if any.
139 pub expr: Option<ExprId>,
140 pub safety_mode: BlockSafety,
141}
142
143type UserTy<'tcx> = Option<Box<CanonicalUserType<'tcx>>>;
144
145#[derive(Clone, Debug, HashStable)]
146pub struct AdtExpr<'tcx> {
147 /// The ADT we're constructing.
148 pub adt_def: AdtDef<'tcx>,
149 /// The variant of the ADT.
150 pub variant_index: VariantIdx,
151 pub args: GenericArgsRef<'tcx>,
152
153 /// Optional user-given args: for something like `let x =
154 /// Bar::<T> { ... }`.
155 pub user_ty: UserTy<'tcx>,
156
157 pub fields: Box<[FieldExpr]>,
158 /// The base, e.g. `Foo {x: 1, ..base}`.
159 pub base: AdtExprBase<'tcx>,
160}
161
162#[derive(Clone, Debug, HashStable)]
163pub enum AdtExprBase<'tcx> {
164 /// A struct expression where all the fields are explicitly enumerated: `Foo { a, b }`.
165 None,
166 /// A struct expression with a "base", an expression of the same type as the outer struct that
167 /// will be used to populate any fields not explicitly mentioned: `Foo { ..base }`
168 Base(FruInfo<'tcx>),
169 /// A struct expression with a `..` tail but no "base" expression. The values from the struct
170 /// fields' default values will be used to populate any fields not explicitly mentioned:
171 /// `Foo { .. }`.
172 DefaultFields(Box<[Ty<'tcx>]>),
173}
174
175#[derive(Clone, Debug, HashStable)]
176pub struct ClosureExpr<'tcx> {
177 pub closure_id: LocalDefId,
178 pub args: UpvarArgs<'tcx>,
179 pub upvars: Box<[ExprId]>,
180 pub movability: Option<hir::Movability>,
181 pub fake_reads: Vec<(ExprId, FakeReadCause, HirId)>,
182}
183
184#[derive(Clone, Debug, HashStable)]
185pub struct InlineAsmExpr<'tcx> {
186 pub asm_macro: AsmMacro,
187 pub template: &'tcx [InlineAsmTemplatePiece],
188 pub operands: Box<[InlineAsmOperand<'tcx>]>,
189 pub options: InlineAsmOptions,
190 pub line_spans: &'tcx [Span],
191}
192
193#[derive(Copy, Clone, Debug, HashStable)]
194pub enum BlockSafety {
195 Safe,
196 /// A compiler-generated unsafe block
197 BuiltinUnsafe,
198 /// An `unsafe` block. The `HirId` is the ID of the block.
199 ExplicitUnsafe(HirId),
200}
201
202#[derive(Clone, Debug, HashStable)]
203pub struct Stmt<'tcx> {
204 pub kind: StmtKind<'tcx>,
205}
206
207#[derive(Clone, Debug, HashStable)]
208pub enum StmtKind<'tcx> {
209 /// An expression with a trailing semicolon.
210 Expr {
211 /// The scope for this statement; may be used as lifetime of temporaries.
212 scope: region::Scope,
213
214 /// The expression being evaluated in this statement.
215 expr: ExprId,
216 },
217
218 /// A `let` binding.
219 Let {
220 /// The scope for variables bound in this `let`; it covers this and
221 /// all the remaining statements in the block.
222 remainder_scope: region::Scope,
223
224 /// The scope for the initialization itself; might be used as
225 /// lifetime of temporaries.
226 init_scope: region::Scope,
227
228 /// `let <PAT> = ...`
229 ///
230 /// If a type annotation is included, it is added as an ascription pattern.
231 pattern: Box<Pat<'tcx>>,
232
233 /// `let pat: ty = <INIT>`
234 initializer: Option<ExprId>,
235
236 /// `let pat: ty = <INIT> else { <ELSE> }`
237 else_block: Option<BlockId>,
238
239 /// The lint level for this `let` statement.
240 lint_level: LintLevel,
241
242 /// Span of the `let <PAT> = <INIT>` part.
243 span: Span,
244 },
245}
246
247#[derive(Clone, Debug, Copy, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
248pub struct LocalVarId(pub HirId);
249
250/// A THIR expression.
251#[derive(Clone, Debug, HashStable)]
252pub struct Expr<'tcx> {
253 /// kind of expression
254 pub kind: ExprKind<'tcx>,
255
256 /// The type of this expression
257 pub ty: Ty<'tcx>,
258
259 /// The lifetime of this expression if it should be spilled into a
260 /// temporary
261 pub temp_lifetime: TempLifetime,
262
263 /// span of the expression in the source
264 pub span: Span,
265}
266
267/// Temporary lifetime information for THIR expressions
268#[derive(Clone, Copy, Debug, HashStable)]
269pub struct TempLifetime {
270 /// Lifetime for temporaries as expected.
271 /// This should be `None` in a constant context.
272 pub temp_lifetime: Option<region::Scope>,
273 /// If `Some(lt)`, indicates that the lifetime of this temporary will change to `lt` in a future edition.
274 /// If `None`, then no changes are expected, or lints are disabled.
275 pub backwards_incompatible: Option<region::Scope>,
276}
277
278#[derive(Clone, Debug, HashStable)]
279pub enum ExprKind<'tcx> {
280 /// `Scope`s are used to explicitly mark destruction scopes,
281 /// and to track the `HirId` of the expressions within the scope.
282 Scope {
283 region_scope: region::Scope,
284 lint_level: LintLevel,
285 value: ExprId,
286 },
287 /// A `box <value>` expression.
288 Box {
289 value: ExprId,
290 },
291 /// An `if` expression.
292 If {
293 if_then_scope: region::Scope,
294 cond: ExprId,
295 then: ExprId,
296 else_opt: Option<ExprId>,
297 },
298 /// A function call. Method calls and overloaded operators are converted to plain function calls.
299 Call {
300 /// The type of the function. This is often a [`FnDef`] or a [`FnPtr`].
301 ///
302 /// [`FnDef`]: ty::TyKind::FnDef
303 /// [`FnPtr`]: ty::TyKind::FnPtr
304 ty: Ty<'tcx>,
305 /// The function itself.
306 fun: ExprId,
307 /// The arguments passed to the function.
308 ///
309 /// Note: in some cases (like calling a closure), the function call `f(...args)` gets
310 /// rewritten as a call to a function trait method (e.g. `FnOnce::call_once(f, (...args))`).
311 args: Box<[ExprId]>,
312 /// Whether this is from an overloaded operator rather than a
313 /// function call from HIR. `true` for overloaded function call.
314 from_hir_call: bool,
315 /// The span of the function, without the dot and receiver
316 /// (e.g. `foo(a, b)` in `x.foo(a, b)`).
317 fn_span: Span,
318 },
319 /// A use expression `x.use`.
320 ByUse {
321 /// The expression on which use is applied.
322 expr: ExprId,
323 /// The span of use, without the dot and receiver
324 /// (e.g. `use` in `x.use`).
325 span: Span,
326 },
327 /// A *non-overloaded* dereference.
328 Deref {
329 arg: ExprId,
330 },
331 /// A *non-overloaded* binary operation.
332 Binary {
333 op: BinOp,
334 lhs: ExprId,
335 rhs: ExprId,
336 },
337 /// A logical operation. This is distinct from `BinaryOp` because
338 /// the operands need to be lazily evaluated.
339 LogicalOp {
340 op: LogicalOp,
341 lhs: ExprId,
342 rhs: ExprId,
343 },
344 /// A *non-overloaded* unary operation. Note that here the deref (`*`)
345 /// operator is represented by `ExprKind::Deref`.
346 Unary {
347 op: UnOp,
348 arg: ExprId,
349 },
350 /// A cast: `<source> as <type>`. The type we cast to is the type of
351 /// the parent expression.
352 Cast {
353 source: ExprId,
354 },
355 /// Forces its contents to be treated as a value expression, not a place
356 /// expression. This is inserted in some places where an operation would
357 /// otherwise be erased completely (e.g. some no-op casts), but we still
358 /// need to ensure that its operand is treated as a value and not a place.
359 Use {
360 source: ExprId,
361 },
362 /// A coercion from `!` to any type.
363 NeverToAny {
364 source: ExprId,
365 },
366 /// A pointer coercion. More information can be found in [`PointerCoercion`].
367 /// Pointer casts that cannot be done by coercions are represented by [`ExprKind::Cast`].
368 PointerCoercion {
369 cast: PointerCoercion,
370 source: ExprId,
371 /// Whether this coercion is written with an `as` cast in the source code.
372 is_from_as_cast: bool,
373 },
374 /// A `loop` expression.
375 Loop {
376 body: ExprId,
377 },
378 /// Special expression representing the `let` part of an `if let` or similar construct
379 /// (including `if let` guards in match arms, and let-chains formed by `&&`).
380 ///
381 /// This isn't considered a real expression in surface Rust syntax, so it can
382 /// only appear in specific situations, such as within the condition of an `if`.
383 ///
384 /// (Not to be confused with [`StmtKind::Let`], which is a normal `let` statement.)
385 Let {
386 expr: ExprId,
387 pat: Box<Pat<'tcx>>,
388 },
389 /// A `match` expression.
390 Match {
391 scrutinee: ExprId,
392 arms: Box<[ArmId]>,
393 match_source: MatchSource,
394 },
395 /// A block.
396 Block {
397 block: BlockId,
398 },
399 /// An assignment: `lhs = rhs`.
400 Assign {
401 lhs: ExprId,
402 rhs: ExprId,
403 },
404 /// A *non-overloaded* operation assignment, e.g. `lhs += rhs`.
405 AssignOp {
406 op: AssignOp,
407 lhs: ExprId,
408 rhs: ExprId,
409 },
410 /// Access to a field of a struct, a tuple, an union, or an enum.
411 Field {
412 lhs: ExprId,
413 /// Variant containing the field.
414 variant_index: VariantIdx,
415 /// This can be a named (`.foo`) or unnamed (`.0`) field.
416 name: FieldIdx,
417 },
418 /// A *non-overloaded* indexing operation.
419 Index {
420 lhs: ExprId,
421 index: ExprId,
422 },
423 /// A local variable.
424 VarRef {
425 id: LocalVarId,
426 },
427 /// Used to represent upvars mentioned in a closure/coroutine
428 UpvarRef {
429 /// DefId of the closure/coroutine
430 closure_def_id: DefId,
431
432 /// HirId of the root variable
433 var_hir_id: LocalVarId,
434 },
435 /// A borrow, e.g. `&arg`.
436 Borrow {
437 borrow_kind: BorrowKind,
438 arg: ExprId,
439 },
440 /// A `&raw [const|mut] $place_expr` raw borrow resulting in type `*[const|mut] T`.
441 RawBorrow {
442 mutability: hir::Mutability,
443 arg: ExprId,
444 },
445 /// A `break` expression.
446 Break {
447 label: region::Scope,
448 value: Option<ExprId>,
449 },
450 /// A `continue` expression.
451 Continue {
452 label: region::Scope,
453 },
454 /// A `return` expression.
455 Return {
456 value: Option<ExprId>,
457 },
458 /// A `become` expression.
459 Become {
460 value: ExprId,
461 },
462 /// An inline `const` block, e.g. `const {}`.
463 ConstBlock {
464 did: DefId,
465 args: GenericArgsRef<'tcx>,
466 },
467 /// An array literal constructed from one repeated element, e.g. `[1; 5]`.
468 Repeat {
469 value: ExprId,
470 count: ty::Const<'tcx>,
471 },
472 /// An array, e.g. `[a, b, c, d]`.
473 Array {
474 fields: Box<[ExprId]>,
475 },
476 /// A tuple, e.g. `(a, b, c, d)`.
477 Tuple {
478 fields: Box<[ExprId]>,
479 },
480 /// An ADT constructor, e.g. `Foo {x: 1, y: 2}`.
481 Adt(Box<AdtExpr<'tcx>>),
482 /// A type ascription on a place.
483 PlaceTypeAscription {
484 source: ExprId,
485 /// Type that the user gave to this expression
486 user_ty: UserTy<'tcx>,
487 user_ty_span: Span,
488 },
489 /// A type ascription on a value, e.g. `type_ascribe!(42, i32)` or `42 as i32`.
490 ValueTypeAscription {
491 source: ExprId,
492 /// Type that the user gave to this expression
493 user_ty: UserTy<'tcx>,
494 user_ty_span: Span,
495 },
496 /// An unsafe binder cast on a place, e.g. `unwrap_binder!(*ptr)`.
497 PlaceUnwrapUnsafeBinder {
498 source: ExprId,
499 },
500 /// An unsafe binder cast on a value, e.g. `unwrap_binder!(rvalue())`,
501 /// which makes a temporary.
502 ValueUnwrapUnsafeBinder {
503 source: ExprId,
504 },
505 /// Construct an unsafe binder, e.g. `wrap_binder(&ref)`.
506 WrapUnsafeBinder {
507 source: ExprId,
508 },
509 /// A closure definition.
510 Closure(Box<ClosureExpr<'tcx>>),
511 /// A literal.
512 Literal {
513 lit: &'tcx hir::Lit,
514 neg: bool,
515 },
516 /// For literals that don't correspond to anything in the HIR
517 NonHirLiteral {
518 lit: ty::ScalarInt,
519 user_ty: UserTy<'tcx>,
520 },
521 /// A literal of a ZST type.
522 ZstLiteral {
523 user_ty: UserTy<'tcx>,
524 },
525 /// Associated constants and named constants
526 NamedConst {
527 def_id: DefId,
528 args: GenericArgsRef<'tcx>,
529 user_ty: UserTy<'tcx>,
530 },
531 ConstParam {
532 param: ty::ParamConst,
533 def_id: DefId,
534 },
535 // FIXME improve docs for `StaticRef` by distinguishing it from `NamedConst`
536 /// A literal containing the address of a `static`.
537 ///
538 /// This is only distinguished from `Literal` so that we can register some
539 /// info for diagnostics.
540 StaticRef {
541 alloc_id: AllocId,
542 ty: Ty<'tcx>,
543 def_id: DefId,
544 },
545 /// Inline assembly, i.e. `asm!()`.
546 InlineAsm(Box<InlineAsmExpr<'tcx>>),
547 /// Field offset (`offset_of!`)
548 OffsetOf {
549 container: Ty<'tcx>,
550 fields: &'tcx List<(VariantIdx, FieldIdx)>,
551 },
552 /// An expression taking a reference to a thread local.
553 ThreadLocalRef(DefId),
554 /// A `yield` expression.
555 Yield {
556 value: ExprId,
557 },
558}
559
560/// Represents the association of a field identifier and an expression.
561///
562/// This is used in struct constructors.
563#[derive(Clone, Debug, HashStable)]
564pub struct FieldExpr {
565 pub name: FieldIdx,
566 pub expr: ExprId,
567}
568
569#[derive(Clone, Debug, HashStable)]
570pub struct FruInfo<'tcx> {
571 pub base: ExprId,
572 pub field_types: Box<[Ty<'tcx>]>,
573}
574
575/// A `match` arm.
576#[derive(Clone, Debug, HashStable)]
577pub struct Arm<'tcx> {
578 pub pattern: Box<Pat<'tcx>>,
579 pub guard: Option<ExprId>,
580 pub body: ExprId,
581 pub lint_level: LintLevel,
582 pub scope: region::Scope,
583 pub span: Span,
584}
585
586#[derive(Copy, Clone, Debug, HashStable)]
587pub enum LogicalOp {
588 /// The `&&` operator.
589 And,
590 /// The `||` operator.
591 Or,
592}
593
594#[derive(Clone, Debug, HashStable)]
595pub enum InlineAsmOperand<'tcx> {
596 In {
597 reg: InlineAsmRegOrRegClass,
598 expr: ExprId,
599 },
600 Out {
601 reg: InlineAsmRegOrRegClass,
602 late: bool,
603 expr: Option<ExprId>,
604 },
605 InOut {
606 reg: InlineAsmRegOrRegClass,
607 late: bool,
608 expr: ExprId,
609 },
610 SplitInOut {
611 reg: InlineAsmRegOrRegClass,
612 late: bool,
613 in_expr: ExprId,
614 out_expr: Option<ExprId>,
615 },
616 Const {
617 value: mir::Const<'tcx>,
618 span: Span,
619 },
620 SymFn {
621 value: ExprId,
622 },
623 SymStatic {
624 def_id: DefId,
625 },
626 Label {
627 block: BlockId,
628 },
629}
630
631#[derive(Clone, Debug, HashStable, TypeVisitable)]
632pub struct FieldPat<'tcx> {
633 pub field: FieldIdx,
634 pub pattern: Pat<'tcx>,
635}
636
637#[derive(Clone, Debug, HashStable, TypeVisitable)]
638pub struct Pat<'tcx> {
639 pub ty: Ty<'tcx>,
640 pub span: Span,
641 pub kind: PatKind<'tcx>,
642}
643
644impl<'tcx> Pat<'tcx> {
645 pub fn simple_ident(&self) -> Option<Symbol> {
646 match self.kind {
647 PatKind::Binding {
648 name, mode: BindingMode(ByRef::No, _), subpattern: None, ..
649 } => Some(name),
650 _ => None,
651 }
652 }
653
654 /// Call `f` on every "binding" in a pattern, e.g., on `a` in
655 /// `match foo() { Some(a) => (), None => () }`
656 pub fn each_binding(&self, mut f: impl FnMut(Symbol, ByRef, Ty<'tcx>, Span)) {
657 self.walk_always(|p| {
658 if let PatKind::Binding { name, mode, ty, .. } = p.kind {
659 f(name, mode.0, ty, p.span);
660 }
661 });
662 }
663
664 /// Walk the pattern in left-to-right order.
665 ///
666 /// If `it(pat)` returns `false`, the children are not visited.
667 pub fn walk(&self, mut it: impl FnMut(&Pat<'tcx>) -> bool) {
668 self.walk_(&mut it)
669 }
670
671 fn walk_(&self, it: &mut impl FnMut(&Pat<'tcx>) -> bool) {
672 if !it(self) {
673 return;
674 }
675
676 for_each_immediate_subpat(self, |p| p.walk_(it));
677 }
678
679 /// Whether the pattern has a `PatKind::Error` nested within.
680 pub fn pat_error_reported(&self) -> Result<(), ErrorGuaranteed> {
681 let mut error = None;
682 self.walk(|pat| {
683 if let PatKind::Error(e) = pat.kind
684 && error.is_none()
685 {
686 error = Some(e);
687 }
688 error.is_none()
689 });
690 match error {
691 None => Ok(()),
692 Some(e) => Err(e),
693 }
694 }
695
696 /// Walk the pattern in left-to-right order.
697 ///
698 /// If you always want to recurse, prefer this method over `walk`.
699 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'tcx>)) {
700 self.walk(|p| {
701 it(p);
702 true
703 })
704 }
705
706 /// Whether this a never pattern.
707 pub fn is_never_pattern(&self) -> bool {
708 let mut is_never_pattern = false;
709 self.walk(|pat| match &pat.kind {
710 PatKind::Never => {
711 is_never_pattern = true;
712 false
713 }
714 PatKind::Or { pats } => {
715 is_never_pattern = pats.iter().all(|p| p.is_never_pattern());
716 false
717 }
718 _ => true,
719 });
720 is_never_pattern
721 }
722}
723
724#[derive(Clone, Debug, HashStable, TypeVisitable)]
725pub struct Ascription<'tcx> {
726 pub annotation: CanonicalUserTypeAnnotation<'tcx>,
727 /// Variance to use when relating the `user_ty` to the **type of the value being
728 /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
729 /// have a type that is some subtype of the ascribed type.
730 ///
731 /// Note that this variance does not apply for any bindings within subpatterns. The type
732 /// assigned to those bindings must be exactly equal to the `user_ty` given here.
733 ///
734 /// The only place where this field is not `Covariant` is when matching constants, where
735 /// we currently use `Contravariant` -- this is because the constant type just needs to
736 /// be "comparable" to the type of the input value. So, for example:
737 ///
738 /// ```text
739 /// match x { "foo" => .. }
740 /// ```
741 ///
742 /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
743 /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
744 /// of the old type-check for now. See #57280 for details.
745 pub variance: ty::Variance,
746}
747
748#[derive(Clone, Debug, HashStable, TypeVisitable)]
749pub enum PatKind<'tcx> {
750 /// A missing pattern, e.g. for an anonymous param in a bare fn like `fn f(u32)`.
751 Missing,
752
753 /// A wildcard pattern: `_`.
754 Wild,
755
756 AscribeUserType {
757 ascription: Ascription<'tcx>,
758 subpattern: Box<Pat<'tcx>>,
759 },
760
761 /// `x`, `ref x`, `x @ P`, etc.
762 Binding {
763 name: Symbol,
764 #[type_visitable(ignore)]
765 mode: BindingMode,
766 #[type_visitable(ignore)]
767 var: LocalVarId,
768 ty: Ty<'tcx>,
769 subpattern: Option<Box<Pat<'tcx>>>,
770
771 /// Is this the leftmost occurrence of the binding, i.e., is `var` the
772 /// `HirId` of this pattern?
773 ///
774 /// (The same binding can occur multiple times in different branches of
775 /// an or-pattern, but only one of them will be primary.)
776 is_primary: bool,
777 },
778
779 /// `Foo(...)` or `Foo{...}` or `Foo`, where `Foo` is a variant name from an ADT with
780 /// multiple variants.
781 Variant {
782 adt_def: AdtDef<'tcx>,
783 args: GenericArgsRef<'tcx>,
784 variant_index: VariantIdx,
785 subpatterns: Vec<FieldPat<'tcx>>,
786 },
787
788 /// `(...)`, `Foo(...)`, `Foo{...}`, or `Foo`, where `Foo` is a variant name from an ADT with
789 /// a single variant.
790 Leaf {
791 subpatterns: Vec<FieldPat<'tcx>>,
792 },
793
794 /// `box P`, `&P`, `&mut P`, etc.
795 Deref {
796 subpattern: Box<Pat<'tcx>>,
797 },
798
799 /// Deref pattern, written `box P` for now.
800 DerefPattern {
801 subpattern: Box<Pat<'tcx>>,
802 mutability: hir::Mutability,
803 },
804
805 /// One of the following:
806 /// * `&str` (represented as a valtree), which will be handled as a string pattern and thus
807 /// exhaustiveness checking will detect if you use the same string twice in different
808 /// patterns.
809 /// * integer, bool, char or float (represented as a valtree), which will be handled by
810 /// exhaustiveness to cover exactly its own value, similar to `&str`, but these values are
811 /// much simpler.
812 /// * `String`, if `string_deref_patterns` is enabled.
813 Constant {
814 value: mir::Const<'tcx>,
815 },
816
817 /// Pattern obtained by converting a constant (inline or named) to its pattern
818 /// representation using `const_to_pat`. This is used for unsafety checking.
819 ExpandedConstant {
820 /// [DefId] of the constant item.
821 def_id: DefId,
822 /// The pattern that the constant lowered to.
823 ///
824 /// HACK: we need to keep the `DefId` of inline constants around for unsafety checking;
825 /// therefore when a range pattern contains inline constants, we re-wrap the range pattern
826 /// with the `ExpandedConstant` nodes that correspond to the range endpoints. Hence
827 /// `subpattern` may actually be a range pattern, and `def_id` be the constant for one of
828 /// its endpoints.
829 subpattern: Box<Pat<'tcx>>,
830 },
831
832 Range(Arc<PatRange<'tcx>>),
833
834 /// Matches against a slice, checking the length and extracting elements.
835 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
836 /// e.g., `&[ref xs @ ..]`.
837 Slice {
838 prefix: Box<[Pat<'tcx>]>,
839 slice: Option<Box<Pat<'tcx>>>,
840 suffix: Box<[Pat<'tcx>]>,
841 },
842
843 /// Fixed match against an array; irrefutable.
844 Array {
845 prefix: Box<[Pat<'tcx>]>,
846 slice: Option<Box<Pat<'tcx>>>,
847 suffix: Box<[Pat<'tcx>]>,
848 },
849
850 /// An or-pattern, e.g. `p | q`.
851 /// Invariant: `pats.len() >= 2`.
852 Or {
853 pats: Box<[Pat<'tcx>]>,
854 },
855
856 /// A never pattern `!`.
857 Never,
858
859 /// An error has been encountered during lowering. We probably shouldn't report more lints
860 /// related to this pattern.
861 Error(ErrorGuaranteed),
862}
863
864/// A range pattern.
865/// The boundaries must be of the same type and that type must be numeric.
866#[derive(Clone, Debug, PartialEq, HashStable, TypeVisitable)]
867pub struct PatRange<'tcx> {
868 /// Must not be `PosInfinity`.
869 pub lo: PatRangeBoundary<'tcx>,
870 /// Must not be `NegInfinity`.
871 pub hi: PatRangeBoundary<'tcx>,
872 #[type_visitable(ignore)]
873 pub end: RangeEnd,
874 pub ty: Ty<'tcx>,
875}
876
877impl<'tcx> PatRange<'tcx> {
878 /// Whether this range covers the full extent of possible values (best-effort, we ignore floats).
879 #[inline]
880 pub fn is_full_range(&self, tcx: TyCtxt<'tcx>) -> Option<bool> {
881 let (min, max, size, bias) = match *self.ty.kind() {
882 ty::Char => (0, std::char::MAX as u128, Size::from_bits(32), 0),
883 ty::Int(ity) => {
884 let size = Integer::from_int_ty(&tcx, ity).size();
885 let max = size.truncate(u128::MAX);
886 let bias = 1u128 << (size.bits() - 1);
887 (0, max, size, bias)
888 }
889 ty::Uint(uty) => {
890 let size = Integer::from_uint_ty(&tcx, uty).size();
891 let max = size.unsigned_int_max();
892 (0, max, size, 0)
893 }
894 _ => return None,
895 };
896
897 // We want to compare ranges numerically, but the order of the bitwise representation of
898 // signed integers does not match their numeric order. Thus, to correct the ordering, we
899 // need to shift the range of signed integers to correct the comparison. This is achieved by
900 // XORing with a bias (see pattern/deconstruct_pat.rs for another pertinent example of this
901 // pattern).
902 //
903 // Also, for performance, it's important to only do the second `try_to_bits` if necessary.
904 let lo_is_min = match self.lo {
905 PatRangeBoundary::NegInfinity => true,
906 PatRangeBoundary::Finite(value) => {
907 let lo = value.try_to_bits(size).unwrap() ^ bias;
908 lo <= min
909 }
910 PatRangeBoundary::PosInfinity => false,
911 };
912 if lo_is_min {
913 let hi_is_max = match self.hi {
914 PatRangeBoundary::NegInfinity => false,
915 PatRangeBoundary::Finite(value) => {
916 let hi = value.try_to_bits(size).unwrap() ^ bias;
917 hi > max || hi == max && self.end == RangeEnd::Included
918 }
919 PatRangeBoundary::PosInfinity => true,
920 };
921 if hi_is_max {
922 return Some(true);
923 }
924 }
925 Some(false)
926 }
927
928 #[inline]
929 pub fn contains(
930 &self,
931 value: mir::Const<'tcx>,
932 tcx: TyCtxt<'tcx>,
933 typing_env: ty::TypingEnv<'tcx>,
934 ) -> Option<bool> {
935 use Ordering::*;
936 debug_assert_eq!(self.ty, value.ty());
937 let ty = self.ty;
938 let value = PatRangeBoundary::Finite(value);
939 // For performance, it's important to only do the second comparison if necessary.
940 Some(
941 match self.lo.compare_with(value, ty, tcx, typing_env)? {
942 Less | Equal => true,
943 Greater => false,
944 } && match value.compare_with(self.hi, ty, tcx, typing_env)? {
945 Less => true,
946 Equal => self.end == RangeEnd::Included,
947 Greater => false,
948 },
949 )
950 }
951
952 #[inline]
953 pub fn overlaps(
954 &self,
955 other: &Self,
956 tcx: TyCtxt<'tcx>,
957 typing_env: ty::TypingEnv<'tcx>,
958 ) -> Option<bool> {
959 use Ordering::*;
960 debug_assert_eq!(self.ty, other.ty);
961 // For performance, it's important to only do the second comparison if necessary.
962 Some(
963 match other.lo.compare_with(self.hi, self.ty, tcx, typing_env)? {
964 Less => true,
965 Equal => self.end == RangeEnd::Included,
966 Greater => false,
967 } && match self.lo.compare_with(other.hi, self.ty, tcx, typing_env)? {
968 Less => true,
969 Equal => other.end == RangeEnd::Included,
970 Greater => false,
971 },
972 )
973 }
974}
975
976impl<'tcx> fmt::Display for PatRange<'tcx> {
977 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
978 if let PatRangeBoundary::Finite(value) = &self.lo {
979 write!(f, "{value}")?;
980 }
981 if let PatRangeBoundary::Finite(value) = &self.hi {
982 write!(f, "{}", self.end)?;
983 write!(f, "{value}")?;
984 } else {
985 // `0..` is parsed as an inclusive range, we must display it correctly.
986 write!(f, "..")?;
987 }
988 Ok(())
989 }
990}
991
992/// A (possibly open) boundary of a range pattern.
993/// If present, the const must be of a numeric type.
994#[derive(Copy, Clone, Debug, PartialEq, HashStable, TypeVisitable)]
995pub enum PatRangeBoundary<'tcx> {
996 Finite(mir::Const<'tcx>),
997 NegInfinity,
998 PosInfinity,
999}
1000
1001impl<'tcx> PatRangeBoundary<'tcx> {
1002 #[inline]
1003 pub fn is_finite(self) -> bool {
1004 matches!(self, Self::Finite(..))
1005 }
1006 #[inline]
1007 pub fn as_finite(self) -> Option<mir::Const<'tcx>> {
1008 match self {
1009 Self::Finite(value) => Some(value),
1010 Self::NegInfinity | Self::PosInfinity => None,
1011 }
1012 }
1013 pub fn eval_bits(
1014 self,
1015 ty: Ty<'tcx>,
1016 tcx: TyCtxt<'tcx>,
1017 typing_env: ty::TypingEnv<'tcx>,
1018 ) -> u128 {
1019 match self {
1020 Self::Finite(value) => value.eval_bits(tcx, typing_env),
1021 Self::NegInfinity => {
1022 // Unwrap is ok because the type is known to be numeric.
1023 ty.numeric_min_and_max_as_bits(tcx).unwrap().0
1024 }
1025 Self::PosInfinity => {
1026 // Unwrap is ok because the type is known to be numeric.
1027 ty.numeric_min_and_max_as_bits(tcx).unwrap().1
1028 }
1029 }
1030 }
1031
1032 #[instrument(skip(tcx, typing_env), level = "debug", ret)]
1033 pub fn compare_with(
1034 self,
1035 other: Self,
1036 ty: Ty<'tcx>,
1037 tcx: TyCtxt<'tcx>,
1038 typing_env: ty::TypingEnv<'tcx>,
1039 ) -> Option<Ordering> {
1040 use PatRangeBoundary::*;
1041 match (self, other) {
1042 // When comparing with infinities, we must remember that `0u8..` and `0u8..=255`
1043 // describe the same range. These two shortcuts are ok, but for the rest we must check
1044 // bit values.
1045 (PosInfinity, PosInfinity) => return Some(Ordering::Equal),
1046 (NegInfinity, NegInfinity) => return Some(Ordering::Equal),
1047
1048 // This code is hot when compiling matches with many ranges. So we
1049 // special-case extraction of evaluated scalars for speed, for types where
1050 // we can do scalar comparisons. E.g. `unicode-normalization` has
1051 // many ranges such as '\u{037A}'..='\u{037F}', and chars can be compared
1052 // in this way.
1053 (Finite(a), Finite(b)) if matches!(ty.kind(), ty::Int(_) | ty::Uint(_) | ty::Char) => {
1054 if let (Some(a), Some(b)) = (a.try_to_scalar_int(), b.try_to_scalar_int()) {
1055 let sz = ty.primitive_size(tcx);
1056 let cmp = match ty.kind() {
1057 ty::Uint(_) | ty::Char => a.to_uint(sz).cmp(&b.to_uint(sz)),
1058 ty::Int(_) => a.to_int(sz).cmp(&b.to_int(sz)),
1059 _ => unreachable!(),
1060 };
1061 return Some(cmp);
1062 }
1063 }
1064 _ => {}
1065 }
1066
1067 let a = self.eval_bits(ty, tcx, typing_env);
1068 let b = other.eval_bits(ty, tcx, typing_env);
1069
1070 match ty.kind() {
1071 ty::Float(ty::FloatTy::F16) => {
1072 use rustc_apfloat::Float;
1073 let a = rustc_apfloat::ieee::Half::from_bits(a);
1074 let b = rustc_apfloat::ieee::Half::from_bits(b);
1075 a.partial_cmp(&b)
1076 }
1077 ty::Float(ty::FloatTy::F32) => {
1078 use rustc_apfloat::Float;
1079 let a = rustc_apfloat::ieee::Single::from_bits(a);
1080 let b = rustc_apfloat::ieee::Single::from_bits(b);
1081 a.partial_cmp(&b)
1082 }
1083 ty::Float(ty::FloatTy::F64) => {
1084 use rustc_apfloat::Float;
1085 let a = rustc_apfloat::ieee::Double::from_bits(a);
1086 let b = rustc_apfloat::ieee::Double::from_bits(b);
1087 a.partial_cmp(&b)
1088 }
1089 ty::Float(ty::FloatTy::F128) => {
1090 use rustc_apfloat::Float;
1091 let a = rustc_apfloat::ieee::Quad::from_bits(a);
1092 let b = rustc_apfloat::ieee::Quad::from_bits(b);
1093 a.partial_cmp(&b)
1094 }
1095 ty::Int(ity) => {
1096 let size = rustc_abi::Integer::from_int_ty(&tcx, *ity).size();
1097 let a = size.sign_extend(a) as i128;
1098 let b = size.sign_extend(b) as i128;
1099 Some(a.cmp(&b))
1100 }
1101 ty::Uint(_) | ty::Char => Some(a.cmp(&b)),
1102 _ => bug!(),
1103 }
1104 }
1105}
1106
1107// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
1108#[cfg(target_pointer_width = "64")]
1109mod size_asserts {
1110 use rustc_data_structures::static_assert_size;
1111
1112 use super::*;
1113 // tidy-alphabetical-start
1114 static_assert_size!(Block, 48);
1115 static_assert_size!(Expr<'_>, 72);
1116 static_assert_size!(ExprKind<'_>, 40);
1117 static_assert_size!(Pat<'_>, 64);
1118 static_assert_size!(PatKind<'_>, 48);
1119 static_assert_size!(Stmt<'_>, 48);
1120 static_assert_size!(StmtKind<'_>, 48);
1121 // tidy-alphabetical-end
1122}