1 //! THIR datatypes and definitions. See the [rustc dev guide] for more info.
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.
9 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/thir.html
11 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
13 use rustc_hir::def::CtorKind;
14 use rustc_hir::def_id::DefId;
15 use rustc_hir::RangeEnd;
16 use rustc_index::newtype_index;
17 use rustc_index::vec::IndexVec;
18 use rustc_middle::infer::canonical::Canonical;
19 use rustc_middle::middle::region;
20 use rustc_middle::mir::interpret::AllocId;
21 use rustc_middle::mir::{self, BinOp, BorrowKind, FakeReadCause, Field, Mutability, UnOp};
22 use rustc_middle::ty::adjustment::PointerCast;
23 use rustc_middle::ty::subst::SubstsRef;
24 use rustc_middle::ty::CanonicalUserTypeAnnotation;
25 use rustc_middle::ty::{self, AdtDef, Ty, UpvarSubsts, UserType};
26 use rustc_span::{Span, Symbol, DUMMY_SP};
27 use rustc_target::abi::VariantIdx;
28 use rustc_target::asm::InlineAsmRegOrRegClass;
36 /// An index to an [`Arm`] stored in [`Thir::arms`]
44 /// An index to an [`Expr`] stored in [`Thir::exprs`]
53 /// An index to a [`Stmt`] stored in [`Thir::stmts`]
59 macro_rules! thir_with_elements {
60 ($($name:ident: $id:ty => $value:ty,)*) => {
61 /// A container for a THIR body.
63 /// This can be indexed directly by any THIR index (e.g. [`ExprId`]).
64 #[derive(Debug, HashStable, Clone)]
65 pub struct Thir<'tcx> {
67 pub $name: IndexVec<$id, $value>,
71 impl<'tcx> Thir<'tcx> {
72 pub fn new() -> Thir<'tcx> {
75 $name: IndexVec::new(),
82 impl<'tcx> Index<$id> for Thir<'tcx> {
84 fn index(&self, index: $id) -> &Self::Output {
93 arms: ArmId => Arm<'tcx>,
94 exprs: ExprId => Expr<'tcx>,
95 stmts: StmtId => Stmt<'tcx>,
98 #[derive(Copy, Clone, Debug, HashStable)]
101 Explicit(hir::HirId),
104 #[derive(Clone, Debug, HashStable)]
106 /// Whether the block itself has a label. Used by `label: {}`
107 /// and `try` blocks.
109 /// This does *not* include labels on loops, e.g. `'label: loop {}`.
110 pub targeted_by_break: bool,
111 pub region_scope: region::Scope,
112 pub opt_destruction_scope: Option<region::Scope>,
113 /// The span of the block, including the opening braces,
114 /// the label, and the `unsafe` keyword, if present.
116 /// The statements in the blocK.
117 pub stmts: Box<[StmtId]>,
118 /// The trailing expression of the block, if any.
119 pub expr: Option<ExprId>,
120 pub safety_mode: BlockSafety,
123 #[derive(Clone, Debug, HashStable)]
124 pub struct Adt<'tcx> {
125 /// The ADT we're constructing.
126 pub adt_def: AdtDef<'tcx>,
127 /// The variant of the ADT.
128 pub variant_index: VariantIdx,
129 pub substs: SubstsRef<'tcx>,
131 /// Optional user-given substs: for something like `let x =
132 /// Bar::<T> { ... }`.
133 pub user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
135 pub fields: Box<[FieldExpr]>,
136 /// The base, e.g. `Foo {x: 1, .. base}`.
137 pub base: Option<FruInfo<'tcx>>,
140 #[derive(Copy, Clone, Debug, HashStable)]
141 pub enum BlockSafety {
143 /// A compiler-generated unsafe block
145 /// An `unsafe` block. The `HirId` is the ID of the block.
146 ExplicitUnsafe(hir::HirId),
149 #[derive(Clone, Debug, HashStable)]
150 pub struct Stmt<'tcx> {
151 pub kind: StmtKind<'tcx>,
152 pub opt_destruction_scope: Option<region::Scope>,
155 #[derive(Clone, Debug, HashStable)]
156 pub enum StmtKind<'tcx> {
157 /// An expression with a trailing semicolon.
159 /// The scope for this statement; may be used as lifetime of temporaries.
160 scope: region::Scope,
162 /// The expression being evaluated in this statement.
168 /// The scope for variables bound in this `let`; it covers this and
169 /// all the remaining statements in the block.
170 remainder_scope: region::Scope,
172 /// The scope for the initialization itself; might be used as
173 /// lifetime of temporaries.
174 init_scope: region::Scope,
176 /// `let <PAT> = ...`
178 /// If a type annotation is included, it is added as an ascription pattern.
181 /// `let pat: ty = <INIT>`
182 initializer: Option<ExprId>,
184 /// `let pat: ty = <INIT> else { <ELSE> }
185 else_block: Option<Block>,
187 /// The lint level for this `let` statement.
188 lint_level: LintLevel,
192 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
193 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
194 rustc_data_structures::static_assert_size!(Expr<'_>, 104);
196 #[derive(Clone, Debug, Copy, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
197 #[derive(TypeFoldable, TypeVisitable)]
198 pub struct LocalVarId(pub hir::HirId);
200 /// A THIR expression.
201 #[derive(Clone, Debug, HashStable)]
202 pub struct Expr<'tcx> {
203 /// The type of this expression
206 /// The lifetime of this expression if it should be spilled into a
207 /// temporary; should be `None` only if in a constant context
208 pub temp_lifetime: Option<region::Scope>,
210 /// span of the expression in the source
213 /// kind of expression
214 pub kind: ExprKind<'tcx>,
217 #[derive(Clone, Debug, HashStable)]
218 pub enum ExprKind<'tcx> {
219 /// `Scope`s are used to explicitly mark destruction scopes,
220 /// and to track the `HirId` of the expressions within the scope.
222 region_scope: region::Scope,
223 lint_level: LintLevel,
226 /// A `box <value>` expression.
230 /// An `if` expression.
232 if_then_scope: region::Scope,
235 else_opt: Option<ExprId>,
237 /// A function call. Method calls and overloaded operators are converted to plain function calls.
239 /// The type of the function. This is often a [`FnDef`] or a [`FnPtr`].
241 /// [`FnDef`]: ty::TyKind::FnDef
242 /// [`FnPtr`]: ty::TyKind::FnPtr
244 /// The function itself.
246 /// The arguments passed to the function.
248 /// Note: in some cases (like calling a closure), the function call `f(...args)` gets
249 /// rewritten as a call to a function trait method (e.g. `FnOnce::call_once(f, (...args))`).
251 /// Whether this is from an overloaded operator rather than a
252 /// function call from HIR. `true` for overloaded function call.
254 /// The span of the function, without the dot and receiver
255 /// (e.g. `foo(a, b)` in `x.foo(a, b)`).
258 /// A *non-overloaded* dereference.
262 /// A *non-overloaded* binary operation.
268 /// A logical operation. This is distinct from `BinaryOp` because
269 /// the operands need to be lazily evaluated.
275 /// A *non-overloaded* unary operation. Note that here the deref (`*`)
276 /// operator is represented by `ExprKind::Deref`.
281 /// A cast: `<source> as <type>`. The type we cast to is the type of
282 /// the parent expression.
288 }, // Use a lexpr to get a vexpr.
289 /// A coercion from `!` to any type.
293 /// A pointer cast. More information can be found in [`PointerCast`].
298 /// A `loop` expression.
306 /// A `match` expression.
315 /// An assignment: `lhs = rhs`.
320 /// A *non-overloaded* operation assignment, e.g. `lhs += rhs`.
326 /// Access to a field of a struct, a tuple, an union, or an enum.
329 /// Variant containing the field.
330 variant_index: VariantIdx,
331 /// This can be a named (`.foo`) or unnamed (`.0`) field.
334 /// A *non-overloaded* indexing operation.
339 /// A local variable.
343 /// Used to represent upvars mentioned in a closure/generator
345 /// DefId of the closure/generator
346 closure_def_id: DefId,
348 /// HirId of the root variable
349 var_hir_id: LocalVarId,
351 /// A borrow, e.g. `&arg`.
353 borrow_kind: BorrowKind,
356 /// A `&raw [const|mut] $place_expr` raw borrow resulting in type `*[const|mut] T`.
358 mutability: hir::Mutability,
361 /// A `break` expression.
363 label: region::Scope,
364 value: Option<ExprId>,
366 /// A `continue` expression.
368 label: region::Scope,
370 /// A `return` expression.
372 value: Option<ExprId>,
374 /// An inline `const` block, e.g. `const {}`.
377 substs: SubstsRef<'tcx>,
379 /// An array literal constructed from one repeated element, e.g. `[1; 5]`.
382 count: ty::Const<'tcx>,
384 /// An array, e.g. `[a, b, c, d]`.
386 fields: Box<[ExprId]>,
388 /// A tuple, e.g. `(a, b, c, d)`.
390 fields: Box<[ExprId]>,
392 /// An ADT constructor, e.g. `Foo {x: 1, y: 2}`.
394 /// A type ascription on a place.
395 PlaceTypeAscription {
397 /// Type that the user gave to this expression
398 user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
400 /// A type ascription on a value, e.g. `42: i32`.
401 ValueTypeAscription {
403 /// Type that the user gave to this expression
404 user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
406 /// A closure definition.
409 substs: UpvarSubsts<'tcx>,
410 upvars: Box<[ExprId]>,
411 movability: Option<hir::Movability>,
412 fake_reads: Vec<(ExprId, FakeReadCause, hir::HirId)>,
419 /// For literals that don't correspond to anything in the HIR
422 user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
424 /// A literal of a ZST type.
426 user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
428 /// Associated constants and named constants
431 substs: SubstsRef<'tcx>,
432 user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
435 param: ty::ParamConst,
438 // FIXME improve docs for `StaticRef` by distinguishing it from `NamedConst`
439 /// A literal containing the address of a `static`.
441 /// This is only distinguished from `Literal` so that we can register some
442 /// info for diagnostics.
448 /// Inline assembly, i.e. `asm!()`.
450 template: &'tcx [InlineAsmTemplatePiece],
451 operands: Box<[InlineAsmOperand<'tcx>]>,
452 options: InlineAsmOptions,
453 line_spans: &'tcx [Span],
455 /// An expression taking a reference to a thread local.
456 ThreadLocalRef(DefId),
457 /// A `yield` expression.
463 /// Represents the association of a field identifier and an expression.
465 /// This is used in struct constructors.
466 #[derive(Clone, Debug, HashStable)]
467 pub struct FieldExpr {
472 #[derive(Clone, Debug, HashStable)]
473 pub struct FruInfo<'tcx> {
475 pub field_types: Box<[Ty<'tcx>]>,
479 #[derive(Clone, Debug, HashStable)]
480 pub struct Arm<'tcx> {
481 pub pattern: Pat<'tcx>,
482 pub guard: Option<Guard<'tcx>>,
484 pub lint_level: LintLevel,
485 pub scope: region::Scope,
490 #[derive(Clone, Debug, HashStable)]
491 pub enum Guard<'tcx> {
493 IfLet(Pat<'tcx>, ExprId),
496 #[derive(Copy, Clone, Debug, HashStable)]
498 /// The `&&` operator.
500 /// The `||` operator.
504 #[derive(Clone, Debug, HashStable)]
505 pub enum InlineAsmOperand<'tcx> {
507 reg: InlineAsmRegOrRegClass,
511 reg: InlineAsmRegOrRegClass,
513 expr: Option<ExprId>,
516 reg: InlineAsmRegOrRegClass,
521 reg: InlineAsmRegOrRegClass,
524 out_expr: Option<ExprId>,
527 value: mir::ConstantKind<'tcx>,
531 value: mir::ConstantKind<'tcx>,
539 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
540 pub enum BindingMode {
545 #[derive(Clone, Debug, HashStable)]
546 pub struct FieldPat<'tcx> {
548 pub pattern: Pat<'tcx>,
551 #[derive(Clone, Debug, HashStable)]
552 pub struct Pat<'tcx> {
555 pub kind: Box<PatKind<'tcx>>,
558 impl<'tcx> Pat<'tcx> {
559 pub fn wildcard_from_ty(ty: Ty<'tcx>) -> Self {
560 Pat { ty, span: DUMMY_SP, kind: Box::new(PatKind::Wild) }
564 #[derive(Clone, Debug, HashStable)]
565 pub struct Ascription<'tcx> {
566 pub annotation: CanonicalUserTypeAnnotation<'tcx>,
567 /// Variance to use when relating the `user_ty` to the **type of the value being
568 /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
569 /// have a type that is some subtype of the ascribed type.
571 /// Note that this variance does not apply for any bindings within subpatterns. The type
572 /// assigned to those bindings must be exactly equal to the `user_ty` given here.
574 /// The only place where this field is not `Covariant` is when matching constants, where
575 /// we currently use `Contravariant` -- this is because the constant type just needs to
576 /// be "comparable" to the type of the input value. So, for example:
579 /// match x { "foo" => .. }
582 /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
583 /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
584 /// of the old type-check for now. See #57280 for details.
585 pub variance: ty::Variance,
588 #[derive(Clone, Debug, HashStable)]
589 pub enum PatKind<'tcx> {
590 /// A wildcard pattern: `_`.
594 ascription: Ascription<'tcx>,
595 subpattern: Pat<'tcx>,
598 /// `x`, `ref x`, `x @ P`, etc.
600 mutability: Mutability,
605 subpattern: Option<Pat<'tcx>>,
606 /// Is this the leftmost occurrence of the binding, i.e., is `var` the
607 /// `HirId` of this pattern?
611 /// `Foo(...)` or `Foo{...}` or `Foo`, where `Foo` is a variant name from an ADT with
612 /// multiple variants.
614 adt_def: AdtDef<'tcx>,
615 substs: SubstsRef<'tcx>,
616 variant_index: VariantIdx,
617 subpatterns: Vec<FieldPat<'tcx>>,
620 /// `(...)`, `Foo(...)`, `Foo{...}`, or `Foo`, where `Foo` is a variant name from an ADT with
621 /// a single variant.
623 subpatterns: Vec<FieldPat<'tcx>>,
626 /// `box P`, `&P`, `&mut P`, etc.
628 subpattern: Pat<'tcx>,
631 /// One of the following:
632 /// * `&str`, which will be handled as a string pattern and thus exhaustiveness
633 /// checking will detect if you use the same string twice in different patterns.
634 /// * integer, bool, char or float, which will be handled by exhaustiveness to cover exactly
635 /// its own value, similar to `&str`, but these values are much simpler.
636 /// * Opaque constants, that must not be matched structurally. So anything that does not derive
637 /// `PartialEq` and `Eq`.
639 value: mir::ConstantKind<'tcx>,
642 Range(PatRange<'tcx>),
644 /// Matches against a slice, checking the length and extracting elements.
645 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
646 /// e.g., `&[ref xs @ ..]`.
648 prefix: Vec<Pat<'tcx>>,
649 slice: Option<Pat<'tcx>>,
650 suffix: Vec<Pat<'tcx>>,
653 /// Fixed match against an array; irrefutable.
655 prefix: Vec<Pat<'tcx>>,
656 slice: Option<Pat<'tcx>>,
657 suffix: Vec<Pat<'tcx>>,
660 /// An or-pattern, e.g. `p | q`.
661 /// Invariant: `pats.len() >= 2`.
663 pats: Vec<Pat<'tcx>>,
667 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
668 pub struct PatRange<'tcx> {
669 pub lo: mir::ConstantKind<'tcx>,
670 pub hi: mir::ConstantKind<'tcx>,
674 impl<'tcx> fmt::Display for Pat<'tcx> {
675 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
676 // Printing lists is a chore.
677 let mut first = true;
678 let mut start_or_continue = |s| {
686 let mut start_or_comma = || start_or_continue(", ");
689 PatKind::Wild => write!(f, "_"),
690 PatKind::AscribeUserType { ref subpattern, .. } => write!(f, "{}: _", subpattern),
691 PatKind::Binding { mutability, name, mode, ref subpattern, .. } => {
692 let is_mut = match mode {
693 BindingMode::ByValue => mutability == Mutability::Mut,
694 BindingMode::ByRef(bk) => {
696 matches!(bk, BorrowKind::Mut { .. })
702 write!(f, "{}", name)?;
703 if let Some(ref subpattern) = *subpattern {
704 write!(f, " @ {}", subpattern)?;
708 PatKind::Variant { ref subpatterns, .. } | PatKind::Leaf { ref subpatterns } => {
709 let variant = match *self.kind {
710 PatKind::Variant { adt_def, variant_index, .. } => {
711 Some(adt_def.variant(variant_index))
713 _ => self.ty.ty_adt_def().and_then(|adt| {
714 if !adt.is_enum() { Some(adt.non_enum_variant()) } else { None }
718 if let Some(variant) = variant {
719 write!(f, "{}", variant.name)?;
721 // Only for Adt we can have `S {...}`,
722 // which we handle separately here.
723 if variant.ctor_kind == CtorKind::Fictive {
727 for p in subpatterns {
728 if let PatKind::Wild = *p.pattern.kind {
731 let name = variant.fields[p.field.index()].name;
732 write!(f, "{}{}: {}", start_or_comma(), name, p.pattern)?;
736 if printed < variant.fields.len() {
737 write!(f, "{}..", start_or_comma())?;
740 return write!(f, " }}");
744 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
745 if num_fields != 0 || variant.is_none() {
747 for i in 0..num_fields {
748 write!(f, "{}", start_or_comma())?;
750 // Common case: the field is where we expect it.
751 if let Some(p) = subpatterns.get(i) {
752 if p.field.index() == i {
753 write!(f, "{}", p.pattern)?;
758 // Otherwise, we have to go looking for it.
759 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
760 write!(f, "{}", p.pattern)?;
770 PatKind::Deref { ref subpattern } => {
771 match self.ty.kind() {
772 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
773 ty::Ref(_, _, mutbl) => {
774 write!(f, "&{}", mutbl.prefix_str())?;
776 _ => bug!("{} is a bad Deref pattern type", self.ty),
778 write!(f, "{}", subpattern)
780 PatKind::Constant { value } => write!(f, "{}", value),
781 PatKind::Range(PatRange { lo, hi, end }) => {
782 write!(f, "{}", lo)?;
783 write!(f, "{}", end)?;
786 PatKind::Slice { ref prefix, ref slice, ref suffix }
787 | PatKind::Array { ref prefix, ref slice, ref suffix } => {
790 write!(f, "{}{}", start_or_comma(), p)?;
792 if let Some(ref slice) = *slice {
793 write!(f, "{}", start_or_comma())?;
796 _ => write!(f, "{}", slice)?,
801 write!(f, "{}{}", start_or_comma(), p)?;
805 PatKind::Or { ref pats } => {
807 write!(f, "{}{}", start_or_continue(" | "), pat)?;