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;
33 pub mod abstract_const;
37 /// An index to an [`Arm`] stored in [`Thir::arms`]
45 /// An index to an [`Expr`] stored in [`Thir::exprs`]
54 /// An index to a [`Stmt`] stored in [`Thir::stmts`]
60 macro_rules! thir_with_elements {
61 ($($name:ident: $id:ty => $value:ty,)*) => {
62 /// A container for a THIR body.
64 /// This can be indexed directly by any THIR index (e.g. [`ExprId`]).
65 #[derive(Debug, HashStable, Clone)]
66 pub struct Thir<'tcx> {
68 pub $name: IndexVec<$id, $value>,
72 impl<'tcx> Thir<'tcx> {
73 pub fn new() -> Thir<'tcx> {
76 $name: IndexVec::new(),
83 impl<'tcx> Index<$id> for Thir<'tcx> {
85 fn index(&self, index: $id) -> &Self::Output {
94 arms: ArmId => Arm<'tcx>,
95 exprs: ExprId => Expr<'tcx>,
96 stmts: StmtId => Stmt<'tcx>,
99 #[derive(Copy, Clone, Debug, HashStable)]
102 Explicit(hir::HirId),
105 #[derive(Clone, Debug, HashStable)]
107 /// Whether the block itself has a label. Used by `label: {}`
108 /// and `try` blocks.
110 /// This does *not* include labels on loops, e.g. `'label: loop {}`.
111 pub targeted_by_break: bool,
112 pub region_scope: region::Scope,
113 pub opt_destruction_scope: Option<region::Scope>,
114 /// The span of the block, including the opening braces,
115 /// the label, and the `unsafe` keyword, if present.
117 /// The statements in the blocK.
118 pub stmts: Box<[StmtId]>,
119 /// The trailing expression of the block, if any.
120 pub expr: Option<ExprId>,
121 pub safety_mode: BlockSafety,
124 #[derive(Clone, Debug, HashStable)]
125 pub struct Adt<'tcx> {
126 /// The ADT we're constructing.
127 pub adt_def: AdtDef<'tcx>,
128 /// The variant of the ADT.
129 pub variant_index: VariantIdx,
130 pub substs: SubstsRef<'tcx>,
132 /// Optional user-given substs: for something like `let x =
133 /// Bar::<T> { ... }`.
134 pub user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
136 pub fields: Box<[FieldExpr]>,
137 /// The base, e.g. `Foo {x: 1, .. base}`.
138 pub base: Option<FruInfo<'tcx>>,
141 #[derive(Copy, Clone, Debug, HashStable)]
142 pub enum BlockSafety {
144 /// A compiler-generated unsafe block
146 /// An `unsafe` block. The `HirId` is the ID of the block.
147 ExplicitUnsafe(hir::HirId),
150 #[derive(Clone, Debug, HashStable)]
151 pub struct Stmt<'tcx> {
152 pub kind: StmtKind<'tcx>,
153 pub opt_destruction_scope: Option<region::Scope>,
156 #[derive(Clone, Debug, HashStable)]
157 pub enum StmtKind<'tcx> {
158 /// An expression with a trailing semicolon.
160 /// The scope for this statement; may be used as lifetime of temporaries.
161 scope: region::Scope,
163 /// The expression being evaluated in this statement.
169 /// The scope for variables bound in this `let`; it covers this and
170 /// all the remaining statements in the block.
171 remainder_scope: region::Scope,
173 /// The scope for the initialization itself; might be used as
174 /// lifetime of temporaries.
175 init_scope: region::Scope,
177 /// `let <PAT> = ...`
179 /// If a type annotation is included, it is added as an ascription pattern.
182 /// `let pat: ty = <INIT>`
183 initializer: Option<ExprId>,
185 /// `let pat: ty = <INIT> else { <ELSE> }
186 else_block: Option<Block>,
188 /// The lint level for this `let` statement.
189 lint_level: LintLevel,
193 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
194 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
195 rustc_data_structures::static_assert_size!(Expr<'_>, 104);
197 #[derive(Clone, Debug, Copy, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
198 #[derive(TypeFoldable, TypeVisitable)]
199 pub struct LocalVarId(pub hir::HirId);
201 /// A THIR expression.
202 #[derive(Clone, Debug, HashStable)]
203 pub struct Expr<'tcx> {
204 /// The type of this expression
207 /// The lifetime of this expression if it should be spilled into a
208 /// temporary; should be `None` only if in a constant context
209 pub temp_lifetime: Option<region::Scope>,
211 /// span of the expression in the source
214 /// kind of expression
215 pub kind: ExprKind<'tcx>,
218 #[derive(Clone, Debug, HashStable)]
219 pub enum ExprKind<'tcx> {
220 /// `Scope`s are used to explicitly mark destruction scopes,
221 /// and to track the `HirId` of the expressions within the scope.
223 region_scope: region::Scope,
224 lint_level: LintLevel,
227 /// A `box <value>` expression.
231 /// An `if` expression.
233 if_then_scope: region::Scope,
236 else_opt: Option<ExprId>,
238 /// A function call. Method calls and overloaded operators are converted to plain function calls.
240 /// The type of the function. This is often a [`FnDef`] or a [`FnPtr`].
242 /// [`FnDef`]: ty::TyKind::FnDef
243 /// [`FnPtr`]: ty::TyKind::FnPtr
245 /// The function itself.
247 /// The arguments passed to the function.
249 /// Note: in some cases (like calling a closure), the function call `f(...args)` gets
250 /// rewritten as a call to a function trait method (e.g. `FnOnce::call_once(f, (...args))`).
252 /// Whether this is from an overloaded operator rather than a
253 /// function call from HIR. `true` for overloaded function call.
255 /// The span of the function, without the dot and receiver
256 /// (e.g. `foo(a, b)` in `x.foo(a, b)`).
259 /// A *non-overloaded* dereference.
263 /// A *non-overloaded* binary operation.
269 /// A logical operation. This is distinct from `BinaryOp` because
270 /// the operands need to be lazily evaluated.
276 /// A *non-overloaded* unary operation. Note that here the deref (`*`)
277 /// operator is represented by `ExprKind::Deref`.
282 /// A cast: `<source> as <type>`. The type we cast to is the type of
283 /// the parent expression.
289 }, // Use a lexpr to get a vexpr.
290 /// A coercion from `!` to any type.
294 /// A pointer cast. More information can be found in [`PointerCast`].
299 /// A `loop` expression.
307 /// A `match` expression.
316 /// An assignment: `lhs = rhs`.
321 /// A *non-overloaded* operation assignment, e.g. `lhs += rhs`.
327 /// Access to a field of a struct, a tuple, an union, or an enum.
330 /// Variant containing the field.
331 variant_index: VariantIdx,
332 /// This can be a named (`.foo`) or unnamed (`.0`) field.
335 /// A *non-overloaded* indexing operation.
340 /// A local variable.
344 /// Used to represent upvars mentioned in a closure/generator
346 /// DefId of the closure/generator
347 closure_def_id: DefId,
349 /// HirId of the root variable
350 var_hir_id: LocalVarId,
352 /// A borrow, e.g. `&arg`.
354 borrow_kind: BorrowKind,
357 /// A `&raw [const|mut] $place_expr` raw borrow resulting in type `*[const|mut] T`.
359 mutability: hir::Mutability,
362 /// A `break` expression.
364 label: region::Scope,
365 value: Option<ExprId>,
367 /// A `continue` expression.
369 label: region::Scope,
371 /// A `return` expression.
373 value: Option<ExprId>,
375 /// An inline `const` block, e.g. `const {}`.
378 substs: SubstsRef<'tcx>,
380 /// An array literal constructed from one repeated element, e.g. `[1; 5]`.
383 count: ty::Const<'tcx>,
385 /// An array, e.g. `[a, b, c, d]`.
387 fields: Box<[ExprId]>,
389 /// A tuple, e.g. `(a, b, c, d)`.
391 fields: Box<[ExprId]>,
393 /// An ADT constructor, e.g. `Foo {x: 1, y: 2}`.
395 /// A type ascription on a place.
396 PlaceTypeAscription {
398 /// Type that the user gave to this expression
399 user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
401 /// A type ascription on a value, e.g. `42: i32`.
402 ValueTypeAscription {
404 /// Type that the user gave to this expression
405 user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
407 /// A closure definition.
410 substs: UpvarSubsts<'tcx>,
411 upvars: Box<[ExprId]>,
412 movability: Option<hir::Movability>,
413 fake_reads: Vec<(ExprId, FakeReadCause, hir::HirId)>,
420 /// For literals that don't correspond to anything in the HIR
423 user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
425 /// A literal of a ZST type.
427 user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
429 /// Associated constants and named constants
432 substs: SubstsRef<'tcx>,
433 user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
436 param: ty::ParamConst,
439 // FIXME improve docs for `StaticRef` by distinguishing it from `NamedConst`
440 /// A literal containing the address of a `static`.
442 /// This is only distinguished from `Literal` so that we can register some
443 /// info for diagnostics.
449 /// Inline assembly, i.e. `asm!()`.
451 template: &'tcx [InlineAsmTemplatePiece],
452 operands: Box<[InlineAsmOperand<'tcx>]>,
453 options: InlineAsmOptions,
454 line_spans: &'tcx [Span],
456 /// An expression taking a reference to a thread local.
457 ThreadLocalRef(DefId),
458 /// A `yield` expression.
464 /// Represents the association of a field identifier and an expression.
466 /// This is used in struct constructors.
467 #[derive(Clone, Debug, HashStable)]
468 pub struct FieldExpr {
473 #[derive(Clone, Debug, HashStable)]
474 pub struct FruInfo<'tcx> {
476 pub field_types: Box<[Ty<'tcx>]>,
480 #[derive(Clone, Debug, HashStable)]
481 pub struct Arm<'tcx> {
482 pub pattern: Pat<'tcx>,
483 pub guard: Option<Guard<'tcx>>,
485 pub lint_level: LintLevel,
486 pub scope: region::Scope,
491 #[derive(Clone, Debug, HashStable)]
492 pub enum Guard<'tcx> {
494 IfLet(Pat<'tcx>, ExprId),
497 #[derive(Copy, Clone, Debug, HashStable)]
499 /// The `&&` operator.
501 /// The `||` operator.
505 #[derive(Clone, Debug, HashStable)]
506 pub enum InlineAsmOperand<'tcx> {
508 reg: InlineAsmRegOrRegClass,
512 reg: InlineAsmRegOrRegClass,
514 expr: Option<ExprId>,
517 reg: InlineAsmRegOrRegClass,
522 reg: InlineAsmRegOrRegClass,
525 out_expr: Option<ExprId>,
528 value: mir::ConstantKind<'tcx>,
532 value: mir::ConstantKind<'tcx>,
540 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
541 pub enum BindingMode {
546 #[derive(Clone, Debug, HashStable)]
547 pub struct FieldPat<'tcx> {
549 pub pattern: Pat<'tcx>,
552 #[derive(Clone, Debug, HashStable)]
553 pub struct Pat<'tcx> {
556 pub kind: Box<PatKind<'tcx>>,
559 impl<'tcx> Pat<'tcx> {
560 pub fn wildcard_from_ty(ty: Ty<'tcx>) -> Self {
561 Pat { ty, span: DUMMY_SP, kind: Box::new(PatKind::Wild) }
565 #[derive(Clone, Debug, HashStable)]
566 pub struct Ascription<'tcx> {
567 pub annotation: CanonicalUserTypeAnnotation<'tcx>,
568 /// Variance to use when relating the `user_ty` to the **type of the value being
569 /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
570 /// have a type that is some subtype of the ascribed type.
572 /// Note that this variance does not apply for any bindings within subpatterns. The type
573 /// assigned to those bindings must be exactly equal to the `user_ty` given here.
575 /// The only place where this field is not `Covariant` is when matching constants, where
576 /// we currently use `Contravariant` -- this is because the constant type just needs to
577 /// be "comparable" to the type of the input value. So, for example:
580 /// match x { "foo" => .. }
583 /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
584 /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
585 /// of the old type-check for now. See #57280 for details.
586 pub variance: ty::Variance,
589 #[derive(Clone, Debug, HashStable)]
590 pub enum PatKind<'tcx> {
591 /// A wildcard pattern: `_`.
595 ascription: Ascription<'tcx>,
596 subpattern: Pat<'tcx>,
599 /// `x`, `ref x`, `x @ P`, etc.
601 mutability: Mutability,
606 subpattern: Option<Pat<'tcx>>,
607 /// Is this the leftmost occurrence of the binding, i.e., is `var` the
608 /// `HirId` of this pattern?
612 /// `Foo(...)` or `Foo{...}` or `Foo`, where `Foo` is a variant name from an ADT with
613 /// multiple variants.
615 adt_def: AdtDef<'tcx>,
616 substs: SubstsRef<'tcx>,
617 variant_index: VariantIdx,
618 subpatterns: Vec<FieldPat<'tcx>>,
621 /// `(...)`, `Foo(...)`, `Foo{...}`, or `Foo`, where `Foo` is a variant name from an ADT with
622 /// a single variant.
624 subpatterns: Vec<FieldPat<'tcx>>,
627 /// `box P`, `&P`, `&mut P`, etc.
629 subpattern: Pat<'tcx>,
632 /// One of the following:
633 /// * `&str`, which will be handled as a string pattern and thus exhaustiveness
634 /// checking will detect if you use the same string twice in different patterns.
635 /// * integer, bool, char or float, which will be handled by exhaustiveness to cover exactly
636 /// its own value, similar to `&str`, but these values are much simpler.
637 /// * Opaque constants, that must not be matched structurally. So anything that does not derive
638 /// `PartialEq` and `Eq`.
640 value: mir::ConstantKind<'tcx>,
643 Range(PatRange<'tcx>),
645 /// Matches against a slice, checking the length and extracting elements.
646 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
647 /// e.g., `&[ref xs @ ..]`.
649 prefix: Vec<Pat<'tcx>>,
650 slice: Option<Pat<'tcx>>,
651 suffix: Vec<Pat<'tcx>>,
654 /// Fixed match against an array; irrefutable.
656 prefix: Vec<Pat<'tcx>>,
657 slice: Option<Pat<'tcx>>,
658 suffix: Vec<Pat<'tcx>>,
661 /// An or-pattern, e.g. `p | q`.
662 /// Invariant: `pats.len() >= 2`.
664 pats: Vec<Pat<'tcx>>,
668 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
669 pub struct PatRange<'tcx> {
670 pub lo: mir::ConstantKind<'tcx>,
671 pub hi: mir::ConstantKind<'tcx>,
675 impl<'tcx> fmt::Display for Pat<'tcx> {
676 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
677 // Printing lists is a chore.
678 let mut first = true;
679 let mut start_or_continue = |s| {
687 let mut start_or_comma = || start_or_continue(", ");
690 PatKind::Wild => write!(f, "_"),
691 PatKind::AscribeUserType { ref subpattern, .. } => write!(f, "{}: _", subpattern),
692 PatKind::Binding { mutability, name, mode, ref subpattern, .. } => {
693 let is_mut = match mode {
694 BindingMode::ByValue => mutability == Mutability::Mut,
695 BindingMode::ByRef(bk) => {
697 matches!(bk, BorrowKind::Mut { .. })
703 write!(f, "{}", name)?;
704 if let Some(ref subpattern) = *subpattern {
705 write!(f, " @ {}", subpattern)?;
709 PatKind::Variant { ref subpatterns, .. } | PatKind::Leaf { ref subpatterns } => {
710 let variant = match *self.kind {
711 PatKind::Variant { adt_def, variant_index, .. } => {
712 Some(adt_def.variant(variant_index))
714 _ => self.ty.ty_adt_def().and_then(|adt| {
715 if !adt.is_enum() { Some(adt.non_enum_variant()) } else { None }
719 if let Some(variant) = variant {
720 write!(f, "{}", variant.name)?;
722 // Only for Adt we can have `S {...}`,
723 // which we handle separately here.
724 if variant.ctor_kind == CtorKind::Fictive {
728 for p in subpatterns {
729 if let PatKind::Wild = *p.pattern.kind {
732 let name = variant.fields[p.field.index()].name;
733 write!(f, "{}{}: {}", start_or_comma(), name, p.pattern)?;
737 if printed < variant.fields.len() {
738 write!(f, "{}..", start_or_comma())?;
741 return write!(f, " }}");
745 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
746 if num_fields != 0 || variant.is_none() {
748 for i in 0..num_fields {
749 write!(f, "{}", start_or_comma())?;
751 // Common case: the field is where we expect it.
752 if let Some(p) = subpatterns.get(i) {
753 if p.field.index() == i {
754 write!(f, "{}", p.pattern)?;
759 // Otherwise, we have to go looking for it.
760 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
761 write!(f, "{}", p.pattern)?;
771 PatKind::Deref { ref subpattern } => {
772 match self.ty.kind() {
773 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
774 ty::Ref(_, _, mutbl) => {
775 write!(f, "&{}", mutbl.prefix_str())?;
777 _ => bug!("{} is a bad Deref pattern type", self.ty),
779 write!(f, "{}", subpattern)
781 PatKind::Constant { value } => write!(f, "{}", value),
782 PatKind::Range(PatRange { lo, hi, end }) => {
783 write!(f, "{}", lo)?;
784 write!(f, "{}", end)?;
787 PatKind::Slice { ref prefix, ref slice, ref suffix }
788 | PatKind::Array { ref prefix, ref slice, ref suffix } => {
791 write!(f, "{}{}", start_or_comma(), p)?;
793 if let Some(ref slice) = *slice {
794 write!(f, "{}", start_or_comma())?;
797 _ => write!(f, "{}", slice)?,
802 write!(f, "{}{}", start_or_comma(), p)?;
806 PatKind::Or { ref pats } => {
808 write!(f, "{}{}", start_or_continue(" | "), pat)?;