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, 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: BinOp,
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 wildcard pattern: `_`.
751 Wild,
752
753 AscribeUserType {
754 ascription: Ascription<'tcx>,
755 subpattern: Box<Pat<'tcx>>,
756 },
757
758 /// `x`, `ref x`, `x @ P`, etc.
759 Binding {
760 name: Symbol,
761 #[type_visitable(ignore)]
762 mode: BindingMode,
763 #[type_visitable(ignore)]
764 var: LocalVarId,
765 ty: Ty<'tcx>,
766 subpattern: Option<Box<Pat<'tcx>>>,
767
768 /// Is this the leftmost occurrence of the binding, i.e., is `var` the
769 /// `HirId` of this pattern?
770 ///
771 /// (The same binding can occur multiple times in different branches of
772 /// an or-pattern, but only one of them will be primary.)
773 is_primary: bool,
774 },
775
776 /// `Foo(...)` or `Foo{...}` or `Foo`, where `Foo` is a variant name from an ADT with
777 /// multiple variants.
778 Variant {
779 adt_def: AdtDef<'tcx>,
780 args: GenericArgsRef<'tcx>,
781 variant_index: VariantIdx,
782 subpatterns: Vec<FieldPat<'tcx>>,
783 },
784
785 /// `(...)`, `Foo(...)`, `Foo{...}`, or `Foo`, where `Foo` is a variant name from an ADT with
786 /// a single variant.
787 Leaf {
788 subpatterns: Vec<FieldPat<'tcx>>,
789 },
790
791 /// `box P`, `&P`, `&mut P`, etc.
792 Deref {
793 subpattern: Box<Pat<'tcx>>,
794 },
795
796 /// Deref pattern, written `box P` for now.
797 DerefPattern {
798 subpattern: Box<Pat<'tcx>>,
799 mutability: hir::Mutability,
800 },
801
802 /// One of the following:
803 /// * `&str` (represented as a valtree), which will be handled as a string pattern and thus
804 /// exhaustiveness checking will detect if you use the same string twice in different
805 /// patterns.
806 /// * integer, bool, char or float (represented as a valtree), which will be handled by
807 /// exhaustiveness to cover exactly its own value, similar to `&str`, but these values are
808 /// much simpler.
809 /// * `String`, if `string_deref_patterns` is enabled.
810 Constant {
811 value: mir::Const<'tcx>,
812 },
813
814 /// Pattern obtained by converting a constant (inline or named) to its pattern
815 /// representation using `const_to_pat`.
816 ExpandedConstant {
817 /// [DefId] of the constant, we need this so that we have a
818 /// reference that can be used by unsafety checking to visit nested
819 /// unevaluated constants and for diagnostics. If the `DefId` doesn't
820 /// correspond to a local crate, it points at the `const` item.
821 def_id: DefId,
822 /// If `false`, then `def_id` points at a `const` item, otherwise it
823 /// corresponds to a local inline const.
824 is_inline: bool,
825 /// If the inline constant is used in a range pattern, this subpattern
826 /// represents the range (if both ends are inline constants, there will
827 /// be multiple InlineConstant wrappers).
828 ///
829 /// Otherwise, the actual pattern that the constant lowered to. As with
830 /// other constants, inline constants are matched structurally where
831 /// possible.
832 subpattern: Box<Pat<'tcx>>,
833 },
834
835 Range(Arc<PatRange<'tcx>>),
836
837 /// Matches against a slice, checking the length and extracting elements.
838 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
839 /// e.g., `&[ref xs @ ..]`.
840 Slice {
841 prefix: Box<[Pat<'tcx>]>,
842 slice: Option<Box<Pat<'tcx>>>,
843 suffix: Box<[Pat<'tcx>]>,
844 },
845
846 /// Fixed match against an array; irrefutable.
847 Array {
848 prefix: Box<[Pat<'tcx>]>,
849 slice: Option<Box<Pat<'tcx>>>,
850 suffix: Box<[Pat<'tcx>]>,
851 },
852
853 /// An or-pattern, e.g. `p | q`.
854 /// Invariant: `pats.len() >= 2`.
855 Or {
856 pats: Box<[Pat<'tcx>]>,
857 },
858
859 /// A never pattern `!`.
860 Never,
861
862 /// An error has been encountered during lowering. We probably shouldn't report more lints
863 /// related to this pattern.
864 Error(ErrorGuaranteed),
865}
866
867/// A range pattern.
868/// The boundaries must be of the same type and that type must be numeric.
869#[derive(Clone, Debug, PartialEq, HashStable, TypeVisitable)]
870pub struct PatRange<'tcx> {
871 /// Must not be `PosInfinity`.
872 pub lo: PatRangeBoundary<'tcx>,
873 /// Must not be `NegInfinity`.
874 pub hi: PatRangeBoundary<'tcx>,
875 #[type_visitable(ignore)]
876 pub end: RangeEnd,
877 pub ty: Ty<'tcx>,
878}
879
880impl<'tcx> PatRange<'tcx> {
881 /// Whether this range covers the full extent of possible values (best-effort, we ignore floats).
882 #[inline]
883 pub fn is_full_range(&self, tcx: TyCtxt<'tcx>) -> Option<bool> {
884 let (min, max, size, bias) = match *self.ty.kind() {
885 ty::Char => (0, std::char::MAX as u128, Size::from_bits(32), 0),
886 ty::Int(ity) => {
887 let size = Integer::from_int_ty(&tcx, ity).size();
888 let max = size.truncate(u128::MAX);
889 let bias = 1u128 << (size.bits() - 1);
890 (0, max, size, bias)
891 }
892 ty::Uint(uty) => {
893 let size = Integer::from_uint_ty(&tcx, uty).size();
894 let max = size.unsigned_int_max();
895 (0, max, size, 0)
896 }
897 _ => return None,
898 };
899
900 // We want to compare ranges numerically, but the order of the bitwise representation of
901 // signed integers does not match their numeric order. Thus, to correct the ordering, we
902 // need to shift the range of signed integers to correct the comparison. This is achieved by
903 // XORing with a bias (see pattern/deconstruct_pat.rs for another pertinent example of this
904 // pattern).
905 //
906 // Also, for performance, it's important to only do the second `try_to_bits` if necessary.
907 let lo_is_min = match self.lo {
908 PatRangeBoundary::NegInfinity => true,
909 PatRangeBoundary::Finite(value) => {
910 let lo = value.try_to_bits(size).unwrap() ^ bias;
911 lo <= min
912 }
913 PatRangeBoundary::PosInfinity => false,
914 };
915 if lo_is_min {
916 let hi_is_max = match self.hi {
917 PatRangeBoundary::NegInfinity => false,
918 PatRangeBoundary::Finite(value) => {
919 let hi = value.try_to_bits(size).unwrap() ^ bias;
920 hi > max || hi == max && self.end == RangeEnd::Included
921 }
922 PatRangeBoundary::PosInfinity => true,
923 };
924 if hi_is_max {
925 return Some(true);
926 }
927 }
928 Some(false)
929 }
930
931 #[inline]
932 pub fn contains(
933 &self,
934 value: mir::Const<'tcx>,
935 tcx: TyCtxt<'tcx>,
936 typing_env: ty::TypingEnv<'tcx>,
937 ) -> Option<bool> {
938 use Ordering::*;
939 debug_assert_eq!(self.ty, value.ty());
940 let ty = self.ty;
941 let value = PatRangeBoundary::Finite(value);
942 // For performance, it's important to only do the second comparison if necessary.
943 Some(
944 match self.lo.compare_with(value, ty, tcx, typing_env)? {
945 Less | Equal => true,
946 Greater => false,
947 } && match value.compare_with(self.hi, ty, tcx, typing_env)? {
948 Less => true,
949 Equal => self.end == RangeEnd::Included,
950 Greater => false,
951 },
952 )
953 }
954
955 #[inline]
956 pub fn overlaps(
957 &self,
958 other: &Self,
959 tcx: TyCtxt<'tcx>,
960 typing_env: ty::TypingEnv<'tcx>,
961 ) -> Option<bool> {
962 use Ordering::*;
963 debug_assert_eq!(self.ty, other.ty);
964 // For performance, it's important to only do the second comparison if necessary.
965 Some(
966 match other.lo.compare_with(self.hi, self.ty, tcx, typing_env)? {
967 Less => true,
968 Equal => self.end == RangeEnd::Included,
969 Greater => false,
970 } && match self.lo.compare_with(other.hi, self.ty, tcx, typing_env)? {
971 Less => true,
972 Equal => other.end == RangeEnd::Included,
973 Greater => false,
974 },
975 )
976 }
977}
978
979impl<'tcx> fmt::Display for PatRange<'tcx> {
980 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
981 if let PatRangeBoundary::Finite(value) = &self.lo {
982 write!(f, "{value}")?;
983 }
984 if let PatRangeBoundary::Finite(value) = &self.hi {
985 write!(f, "{}", self.end)?;
986 write!(f, "{value}")?;
987 } else {
988 // `0..` is parsed as an inclusive range, we must display it correctly.
989 write!(f, "..")?;
990 }
991 Ok(())
992 }
993}
994
995/// A (possibly open) boundary of a range pattern.
996/// If present, the const must be of a numeric type.
997#[derive(Copy, Clone, Debug, PartialEq, HashStable, TypeVisitable)]
998pub enum PatRangeBoundary<'tcx> {
999 Finite(mir::Const<'tcx>),
1000 NegInfinity,
1001 PosInfinity,
1002}
1003
1004impl<'tcx> PatRangeBoundary<'tcx> {
1005 #[inline]
1006 pub fn is_finite(self) -> bool {
1007 matches!(self, Self::Finite(..))
1008 }
1009 #[inline]
1010 pub fn as_finite(self) -> Option<mir::Const<'tcx>> {
1011 match self {
1012 Self::Finite(value) => Some(value),
1013 Self::NegInfinity | Self::PosInfinity => None,
1014 }
1015 }
1016 pub fn eval_bits(
1017 self,
1018 ty: Ty<'tcx>,
1019 tcx: TyCtxt<'tcx>,
1020 typing_env: ty::TypingEnv<'tcx>,
1021 ) -> u128 {
1022 match self {
1023 Self::Finite(value) => value.eval_bits(tcx, typing_env),
1024 Self::NegInfinity => {
1025 // Unwrap is ok because the type is known to be numeric.
1026 ty.numeric_min_and_max_as_bits(tcx).unwrap().0
1027 }
1028 Self::PosInfinity => {
1029 // Unwrap is ok because the type is known to be numeric.
1030 ty.numeric_min_and_max_as_bits(tcx).unwrap().1
1031 }
1032 }
1033 }
1034
1035 #[instrument(skip(tcx, typing_env), level = "debug", ret)]
1036 pub fn compare_with(
1037 self,
1038 other: Self,
1039 ty: Ty<'tcx>,
1040 tcx: TyCtxt<'tcx>,
1041 typing_env: ty::TypingEnv<'tcx>,
1042 ) -> Option<Ordering> {
1043 use PatRangeBoundary::*;
1044 match (self, other) {
1045 // When comparing with infinities, we must remember that `0u8..` and `0u8..=255`
1046 // describe the same range. These two shortcuts are ok, but for the rest we must check
1047 // bit values.
1048 (PosInfinity, PosInfinity) => return Some(Ordering::Equal),
1049 (NegInfinity, NegInfinity) => return Some(Ordering::Equal),
1050
1051 // This code is hot when compiling matches with many ranges. So we
1052 // special-case extraction of evaluated scalars for speed, for types where
1053 // we can do scalar comparisons. E.g. `unicode-normalization` has
1054 // many ranges such as '\u{037A}'..='\u{037F}', and chars can be compared
1055 // in this way.
1056 (Finite(a), Finite(b)) if matches!(ty.kind(), ty::Int(_) | ty::Uint(_) | ty::Char) => {
1057 if let (Some(a), Some(b)) = (a.try_to_scalar_int(), b.try_to_scalar_int()) {
1058 let sz = ty.primitive_size(tcx);
1059 let cmp = match ty.kind() {
1060 ty::Uint(_) | ty::Char => a.to_uint(sz).cmp(&b.to_uint(sz)),
1061 ty::Int(_) => a.to_int(sz).cmp(&b.to_int(sz)),
1062 _ => unreachable!(),
1063 };
1064 return Some(cmp);
1065 }
1066 }
1067 _ => {}
1068 }
1069
1070 let a = self.eval_bits(ty, tcx, typing_env);
1071 let b = other.eval_bits(ty, tcx, typing_env);
1072
1073 match ty.kind() {
1074 ty::Float(ty::FloatTy::F16) => {
1075 use rustc_apfloat::Float;
1076 let a = rustc_apfloat::ieee::Half::from_bits(a);
1077 let b = rustc_apfloat::ieee::Half::from_bits(b);
1078 a.partial_cmp(&b)
1079 }
1080 ty::Float(ty::FloatTy::F32) => {
1081 use rustc_apfloat::Float;
1082 let a = rustc_apfloat::ieee::Single::from_bits(a);
1083 let b = rustc_apfloat::ieee::Single::from_bits(b);
1084 a.partial_cmp(&b)
1085 }
1086 ty::Float(ty::FloatTy::F64) => {
1087 use rustc_apfloat::Float;
1088 let a = rustc_apfloat::ieee::Double::from_bits(a);
1089 let b = rustc_apfloat::ieee::Double::from_bits(b);
1090 a.partial_cmp(&b)
1091 }
1092 ty::Float(ty::FloatTy::F128) => {
1093 use rustc_apfloat::Float;
1094 let a = rustc_apfloat::ieee::Quad::from_bits(a);
1095 let b = rustc_apfloat::ieee::Quad::from_bits(b);
1096 a.partial_cmp(&b)
1097 }
1098 ty::Int(ity) => {
1099 let size = rustc_abi::Integer::from_int_ty(&tcx, *ity).size();
1100 let a = size.sign_extend(a) as i128;
1101 let b = size.sign_extend(b) as i128;
1102 Some(a.cmp(&b))
1103 }
1104 ty::Uint(_) | ty::Char => Some(a.cmp(&b)),
1105 _ => bug!(),
1106 }
1107 }
1108}
1109
1110// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
1111#[cfg(target_pointer_width = "64")]
1112mod size_asserts {
1113 use rustc_data_structures::static_assert_size;
1114
1115 use super::*;
1116 // tidy-alphabetical-start
1117 static_assert_size!(Block, 48);
1118 static_assert_size!(Expr<'_>, 72);
1119 static_assert_size!(ExprKind<'_>, 40);
1120 static_assert_size!(Pat<'_>, 64);
1121 static_assert_size!(PatKind<'_>, 48);
1122 static_assert_size!(Stmt<'_>, 48);
1123 static_assert_size!(StmtKind<'_>, 48);
1124 // tidy-alphabetical-end
1125}