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::middle::region;
19 use rustc_middle::mir::interpret::AllocId;
20 use rustc_middle::mir::{self, BinOp, BorrowKind, FakeReadCause, Field, Mutability, UnOp};
21 use rustc_middle::ty::adjustment::PointerCast;
22 use rustc_middle::ty::subst::SubstsRef;
23 use rustc_middle::ty::{self, AdtDef, Ty, UpvarSubsts};
24 use rustc_middle::ty::{CanonicalUserType, CanonicalUserTypeAnnotation};
25 use rustc_span::def_id::LocalDefId;
26 use rustc_span::{sym, Span, Symbol, DUMMY_SP};
27 use rustc_target::abi::VariantIdx;
28 use rustc_target::asm::InlineAsmRegOrRegClass;
34 macro_rules! thir_with_elements {
35 ($($name:ident: $id:ty => $value:ty => $format:literal,)*) => {
40 DEBUG_FORMAT = $format
45 /// A container for a THIR body.
47 /// This can be indexed directly by any THIR index (e.g. [`ExprId`]).
48 #[derive(Debug, HashStable, Clone)]
49 pub struct Thir<'tcx> {
51 pub $name: IndexVec<$id, $value>,
55 impl<'tcx> Thir<'tcx> {
56 pub fn new() -> Thir<'tcx> {
59 $name: IndexVec::new(),
66 impl<'tcx> Index<$id> for Thir<'tcx> {
68 fn index(&self, index: $id) -> &Self::Output {
76 pub const UPVAR_ENV_PARAM: ParamId = ParamId::from_u32(0);
79 arms: ArmId => Arm<'tcx> => "a{}",
80 blocks: BlockId => Block => "b{}",
81 exprs: ExprId => Expr<'tcx> => "e{}",
82 stmts: StmtId => Stmt<'tcx> => "s{}",
83 params: ParamId => Param<'tcx> => "p{}",
86 /// Description of a type-checked function parameter.
87 #[derive(Clone, Debug, HashStable)]
88 pub struct Param<'tcx> {
89 /// The pattern that appears in the parameter list, or None for implicit parameters.
90 pub pat: Option<Box<Pat<'tcx>>>,
91 /// The possibly inferred type.
93 /// Span of the explicitly provided type, or None if inferred for closures.
94 pub ty_span: Option<Span>,
95 /// Whether this param is `self`, and how it is bound.
96 pub self_kind: Option<hir::ImplicitSelfKind>,
98 pub hir_id: Option<hir::HirId>,
101 #[derive(Copy, Clone, Debug, HashStable)]
104 Explicit(hir::HirId),
107 #[derive(Clone, Debug, HashStable)]
109 /// Whether the block itself has a label. Used by `label: {}`
110 /// and `try` blocks.
112 /// This does *not* include labels on loops, e.g. `'label: loop {}`.
113 pub targeted_by_break: bool,
114 pub region_scope: region::Scope,
115 pub opt_destruction_scope: Option<region::Scope>,
116 /// The span of the block, including the opening braces,
117 /// the label, and the `unsafe` keyword, if present.
119 /// The statements in the blocK.
120 pub stmts: Box<[StmtId]>,
121 /// The trailing expression of the block, if any.
122 pub expr: Option<ExprId>,
123 pub safety_mode: BlockSafety,
126 type UserTy<'tcx> = Option<Box<CanonicalUserType<'tcx>>>;
128 #[derive(Clone, Debug, HashStable)]
129 pub struct AdtExpr<'tcx> {
130 /// The ADT we're constructing.
131 pub adt_def: AdtDef<'tcx>,
132 /// The variant of the ADT.
133 pub variant_index: VariantIdx,
134 pub substs: SubstsRef<'tcx>,
136 /// Optional user-given substs: for something like `let x =
137 /// Bar::<T> { ... }`.
138 pub user_ty: UserTy<'tcx>,
140 pub fields: Box<[FieldExpr]>,
141 /// The base, e.g. `Foo {x: 1, .. base}`.
142 pub base: Option<FruInfo<'tcx>>,
145 #[derive(Clone, Debug, HashStable)]
146 pub struct ClosureExpr<'tcx> {
147 pub closure_id: LocalDefId,
148 pub substs: UpvarSubsts<'tcx>,
149 pub upvars: Box<[ExprId]>,
150 pub movability: Option<hir::Movability>,
151 pub fake_reads: Vec<(ExprId, FakeReadCause, hir::HirId)>,
154 #[derive(Clone, Debug, HashStable)]
155 pub struct InlineAsmExpr<'tcx> {
156 pub template: &'tcx [InlineAsmTemplatePiece],
157 pub operands: Box<[InlineAsmOperand<'tcx>]>,
158 pub options: InlineAsmOptions,
159 pub line_spans: &'tcx [Span],
162 #[derive(Copy, Clone, Debug, HashStable)]
163 pub enum BlockSafety {
165 /// A compiler-generated unsafe block
167 /// An `unsafe` block. The `HirId` is the ID of the block.
168 ExplicitUnsafe(hir::HirId),
171 #[derive(Clone, Debug, HashStable)]
172 pub struct Stmt<'tcx> {
173 pub kind: StmtKind<'tcx>,
174 pub opt_destruction_scope: Option<region::Scope>,
177 #[derive(Clone, Debug, HashStable)]
178 pub enum StmtKind<'tcx> {
179 /// An expression with a trailing semicolon.
181 /// The scope for this statement; may be used as lifetime of temporaries.
182 scope: region::Scope,
184 /// The expression being evaluated in this statement.
190 /// The scope for variables bound in this `let`; it covers this and
191 /// all the remaining statements in the block.
192 remainder_scope: region::Scope,
194 /// The scope for the initialization itself; might be used as
195 /// lifetime of temporaries.
196 init_scope: region::Scope,
198 /// `let <PAT> = ...`
200 /// If a type annotation is included, it is added as an ascription pattern.
201 pattern: Box<Pat<'tcx>>,
203 /// `let pat: ty = <INIT>`
204 initializer: Option<ExprId>,
206 /// `let pat: ty = <INIT> else { <ELSE> }`
207 else_block: Option<BlockId>,
209 /// The lint level for this `let` statement.
210 lint_level: LintLevel,
214 #[derive(Clone, Debug, Copy, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
215 #[derive(TypeFoldable, TypeVisitable)]
216 pub struct LocalVarId(pub hir::HirId);
218 /// A THIR expression.
219 #[derive(Clone, Debug, HashStable)]
220 pub struct Expr<'tcx> {
221 /// The type of this expression
224 /// The lifetime of this expression if it should be spilled into a
225 /// temporary; should be `None` only if in a constant context
226 pub temp_lifetime: Option<region::Scope>,
228 /// span of the expression in the source
231 /// kind of expression
232 pub kind: ExprKind<'tcx>,
235 #[derive(Clone, Debug, HashStable)]
236 pub enum ExprKind<'tcx> {
237 /// `Scope`s are used to explicitly mark destruction scopes,
238 /// and to track the `HirId` of the expressions within the scope.
240 region_scope: region::Scope,
241 lint_level: LintLevel,
244 /// A `box <value>` expression.
248 /// An `if` expression.
250 if_then_scope: region::Scope,
253 else_opt: Option<ExprId>,
255 /// A function call. Method calls and overloaded operators are converted to plain function calls.
257 /// The type of the function. This is often a [`FnDef`] or a [`FnPtr`].
259 /// [`FnDef`]: ty::TyKind::FnDef
260 /// [`FnPtr`]: ty::TyKind::FnPtr
262 /// The function itself.
264 /// The arguments passed to the function.
266 /// Note: in some cases (like calling a closure), the function call `f(...args)` gets
267 /// rewritten as a call to a function trait method (e.g. `FnOnce::call_once(f, (...args))`).
269 /// Whether this is from an overloaded operator rather than a
270 /// function call from HIR. `true` for overloaded function call.
272 /// The span of the function, without the dot and receiver
273 /// (e.g. `foo(a, b)` in `x.foo(a, b)`).
276 /// A *non-overloaded* dereference.
280 /// A *non-overloaded* binary operation.
286 /// A logical operation. This is distinct from `BinaryOp` because
287 /// the operands need to be lazily evaluated.
293 /// A *non-overloaded* unary operation. Note that here the deref (`*`)
294 /// operator is represented by `ExprKind::Deref`.
299 /// A cast: `<source> as <type>`. The type we cast to is the type of
300 /// the parent expression.
306 }, // Use a lexpr to get a vexpr.
307 /// A coercion from `!` to any type.
311 /// A pointer cast. More information can be found in [`PointerCast`].
316 /// A `loop` expression.
324 /// A `match` expression.
333 /// An assignment: `lhs = rhs`.
338 /// A *non-overloaded* operation assignment, e.g. `lhs += rhs`.
344 /// Access to a field of a struct, a tuple, an union, or an enum.
347 /// Variant containing the field.
348 variant_index: VariantIdx,
349 /// This can be a named (`.foo`) or unnamed (`.0`) field.
352 /// A *non-overloaded* indexing operation.
357 /// A local variable.
361 /// Used to represent upvars mentioned in a closure/generator
363 /// DefId of the closure/generator
364 closure_def_id: DefId,
366 /// HirId of the root variable
367 var_hir_id: LocalVarId,
369 /// A borrow, e.g. `&arg`.
371 borrow_kind: BorrowKind,
374 /// A `&raw [const|mut] $place_expr` raw borrow resulting in type `*[const|mut] T`.
376 mutability: hir::Mutability,
379 /// A `break` expression.
381 label: region::Scope,
382 value: Option<ExprId>,
384 /// A `continue` expression.
386 label: region::Scope,
388 /// A `return` expression.
390 value: Option<ExprId>,
392 /// An inline `const` block, e.g. `const {}`.
395 substs: SubstsRef<'tcx>,
397 /// An array literal constructed from one repeated element, e.g. `[1; 5]`.
400 count: ty::Const<'tcx>,
402 /// An array, e.g. `[a, b, c, d]`.
404 fields: Box<[ExprId]>,
406 /// A tuple, e.g. `(a, b, c, d)`.
408 fields: Box<[ExprId]>,
410 /// An ADT constructor, e.g. `Foo {x: 1, y: 2}`.
411 Adt(Box<AdtExpr<'tcx>>),
412 /// A type ascription on a place.
413 PlaceTypeAscription {
415 /// Type that the user gave to this expression
416 user_ty: UserTy<'tcx>,
418 /// A type ascription on a value, e.g. `42: i32`.
419 ValueTypeAscription {
421 /// Type that the user gave to this expression
422 user_ty: UserTy<'tcx>,
424 /// A closure definition.
425 Closure(Box<ClosureExpr<'tcx>>),
431 /// For literals that don't correspond to anything in the HIR
434 user_ty: UserTy<'tcx>,
436 /// A literal of a ZST type.
438 user_ty: UserTy<'tcx>,
440 /// Associated constants and named constants
443 substs: SubstsRef<'tcx>,
444 user_ty: UserTy<'tcx>,
447 param: ty::ParamConst,
450 // FIXME improve docs for `StaticRef` by distinguishing it from `NamedConst`
451 /// A literal containing the address of a `static`.
453 /// This is only distinguished from `Literal` so that we can register some
454 /// info for diagnostics.
460 /// Inline assembly, i.e. `asm!()`.
461 InlineAsm(Box<InlineAsmExpr<'tcx>>),
462 /// An expression taking a reference to a thread local.
463 ThreadLocalRef(DefId),
464 /// A `yield` expression.
470 /// Represents the association of a field identifier and an expression.
472 /// This is used in struct constructors.
473 #[derive(Clone, Debug, HashStable)]
474 pub struct FieldExpr {
479 #[derive(Clone, Debug, HashStable)]
480 pub struct FruInfo<'tcx> {
482 pub field_types: Box<[Ty<'tcx>]>,
486 #[derive(Clone, Debug, HashStable)]
487 pub struct Arm<'tcx> {
488 pub pattern: Box<Pat<'tcx>>,
489 pub guard: Option<Guard<'tcx>>,
491 pub lint_level: LintLevel,
492 pub scope: region::Scope,
497 #[derive(Clone, Debug, HashStable)]
498 pub enum Guard<'tcx> {
500 IfLet(Box<Pat<'tcx>>, ExprId),
503 #[derive(Copy, Clone, Debug, HashStable)]
505 /// The `&&` operator.
507 /// The `||` operator.
511 #[derive(Clone, Debug, HashStable)]
512 pub enum InlineAsmOperand<'tcx> {
514 reg: InlineAsmRegOrRegClass,
518 reg: InlineAsmRegOrRegClass,
520 expr: Option<ExprId>,
523 reg: InlineAsmRegOrRegClass,
528 reg: InlineAsmRegOrRegClass,
531 out_expr: Option<ExprId>,
534 value: mir::ConstantKind<'tcx>,
538 value: mir::ConstantKind<'tcx>,
546 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
547 pub enum BindingMode {
552 #[derive(Clone, Debug, HashStable)]
553 pub struct FieldPat<'tcx> {
555 pub pattern: Box<Pat<'tcx>>,
558 #[derive(Clone, Debug, HashStable)]
559 pub struct Pat<'tcx> {
562 pub kind: PatKind<'tcx>,
565 impl<'tcx> Pat<'tcx> {
566 pub fn wildcard_from_ty(ty: Ty<'tcx>) -> Self {
567 Pat { ty, span: DUMMY_SP, kind: PatKind::Wild }
570 pub fn simple_ident(&self) -> Option<Symbol> {
572 PatKind::Binding { name, mode: BindingMode::ByValue, subpattern: None, .. } => {
580 #[derive(Clone, Debug, HashStable)]
581 pub struct Ascription<'tcx> {
582 pub annotation: CanonicalUserTypeAnnotation<'tcx>,
583 /// Variance to use when relating the `user_ty` to the **type of the value being
584 /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
585 /// have a type that is some subtype of the ascribed type.
587 /// Note that this variance does not apply for any bindings within subpatterns. The type
588 /// assigned to those bindings must be exactly equal to the `user_ty` given here.
590 /// The only place where this field is not `Covariant` is when matching constants, where
591 /// we currently use `Contravariant` -- this is because the constant type just needs to
592 /// be "comparable" to the type of the input value. So, for example:
595 /// match x { "foo" => .. }
598 /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
599 /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
600 /// of the old type-check for now. See #57280 for details.
601 pub variance: ty::Variance,
604 #[derive(Clone, Debug, HashStable)]
605 pub enum PatKind<'tcx> {
606 /// A wildcard pattern: `_`.
610 ascription: Ascription<'tcx>,
611 subpattern: Box<Pat<'tcx>>,
614 /// `x`, `ref x`, `x @ P`, etc.
616 mutability: Mutability,
621 subpattern: Option<Box<Pat<'tcx>>>,
622 /// Is this the leftmost occurrence of the binding, i.e., is `var` the
623 /// `HirId` of this pattern?
627 /// `Foo(...)` or `Foo{...}` or `Foo`, where `Foo` is a variant name from an ADT with
628 /// multiple variants.
630 adt_def: AdtDef<'tcx>,
631 substs: SubstsRef<'tcx>,
632 variant_index: VariantIdx,
633 subpatterns: Vec<FieldPat<'tcx>>,
636 /// `(...)`, `Foo(...)`, `Foo{...}`, or `Foo`, where `Foo` is a variant name from an ADT with
637 /// a single variant.
639 subpatterns: Vec<FieldPat<'tcx>>,
642 /// `box P`, `&P`, `&mut P`, etc.
644 subpattern: Box<Pat<'tcx>>,
647 /// One of the following:
648 /// * `&str`, which will be handled as a string pattern and thus exhaustiveness
649 /// checking will detect if you use the same string twice in different patterns.
650 /// * integer, bool, char or float, which will be handled by exhaustiveness to cover exactly
651 /// its own value, similar to `&str`, but these values are much simpler.
652 /// * Opaque constants, that must not be matched structurally. So anything that does not derive
653 /// `PartialEq` and `Eq`.
655 value: mir::ConstantKind<'tcx>,
658 Range(Box<PatRange<'tcx>>),
660 /// Matches against a slice, checking the length and extracting elements.
661 /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
662 /// e.g., `&[ref xs @ ..]`.
664 prefix: Box<[Box<Pat<'tcx>>]>,
665 slice: Option<Box<Pat<'tcx>>>,
666 suffix: Box<[Box<Pat<'tcx>>]>,
669 /// Fixed match against an array; irrefutable.
671 prefix: Box<[Box<Pat<'tcx>>]>,
672 slice: Option<Box<Pat<'tcx>>>,
673 suffix: Box<[Box<Pat<'tcx>>]>,
676 /// An or-pattern, e.g. `p | q`.
677 /// Invariant: `pats.len() >= 2`.
679 pats: Box<[Box<Pat<'tcx>>]>,
683 #[derive(Clone, Debug, PartialEq, HashStable)]
684 pub struct PatRange<'tcx> {
685 pub lo: mir::ConstantKind<'tcx>,
686 pub hi: mir::ConstantKind<'tcx>,
690 impl<'tcx> fmt::Display for Pat<'tcx> {
691 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
692 // Printing lists is a chore.
693 let mut first = true;
694 let mut start_or_continue = |s| {
702 let mut start_or_comma = || start_or_continue(", ");
705 PatKind::Wild => write!(f, "_"),
706 PatKind::AscribeUserType { ref subpattern, .. } => write!(f, "{}: _", subpattern),
707 PatKind::Binding { mutability, name, mode, ref subpattern, .. } => {
708 let is_mut = match mode {
709 BindingMode::ByValue => mutability == Mutability::Mut,
710 BindingMode::ByRef(bk) => {
712 matches!(bk, BorrowKind::Mut { .. })
718 write!(f, "{}", name)?;
719 if let Some(ref subpattern) = *subpattern {
720 write!(f, " @ {}", subpattern)?;
724 PatKind::Variant { ref subpatterns, .. } | PatKind::Leaf { ref subpatterns } => {
725 let variant_and_name = match self.kind {
726 PatKind::Variant { adt_def, variant_index, .. } => ty::tls::with(|tcx| {
727 let variant = adt_def.variant(variant_index);
728 let adt_did = adt_def.did();
729 let name = if tcx.get_diagnostic_item(sym::Option) == Some(adt_did)
730 || tcx.get_diagnostic_item(sym::Result) == Some(adt_did)
732 variant.name.to_string()
734 format!("{}::{}", tcx.def_path_str(adt_def.did()), variant.name)
736 Some((variant, name))
738 _ => self.ty.ty_adt_def().and_then(|adt_def| {
739 if !adt_def.is_enum() {
740 ty::tls::with(|tcx| {
741 Some((adt_def.non_enum_variant(), tcx.def_path_str(adt_def.did())))
749 if let Some((variant, name)) = &variant_and_name {
750 write!(f, "{}", name)?;
752 // Only for Adt we can have `S {...}`,
753 // which we handle separately here.
754 if variant.ctor_kind == CtorKind::Fictive {
758 for p in subpatterns {
759 if let PatKind::Wild = p.pattern.kind {
762 let name = variant.fields[p.field.index()].name;
763 write!(f, "{}{}: {}", start_or_comma(), name, p.pattern)?;
767 if printed < variant.fields.len() {
768 write!(f, "{}..", start_or_comma())?;
771 return write!(f, " }}");
776 variant_and_name.as_ref().map_or(subpatterns.len(), |(v, _)| v.fields.len());
777 if num_fields != 0 || variant_and_name.is_none() {
779 for i in 0..num_fields {
780 write!(f, "{}", start_or_comma())?;
782 // Common case: the field is where we expect it.
783 if let Some(p) = subpatterns.get(i) {
784 if p.field.index() == i {
785 write!(f, "{}", p.pattern)?;
790 // Otherwise, we have to go looking for it.
791 if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
792 write!(f, "{}", p.pattern)?;
802 PatKind::Deref { ref subpattern } => {
803 match self.ty.kind() {
804 ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
805 ty::Ref(_, _, mutbl) => {
806 write!(f, "&{}", mutbl.prefix_str())?;
808 _ => bug!("{} is a bad Deref pattern type", self.ty),
810 write!(f, "{}", subpattern)
812 PatKind::Constant { value } => write!(f, "{}", value),
813 PatKind::Range(box PatRange { lo, hi, end }) => {
814 write!(f, "{}", lo)?;
815 write!(f, "{}", end)?;
818 PatKind::Slice { ref prefix, ref slice, ref suffix }
819 | PatKind::Array { ref prefix, ref slice, ref suffix } => {
821 for p in prefix.iter() {
822 write!(f, "{}{}", start_or_comma(), p)?;
824 if let Some(ref slice) = *slice {
825 write!(f, "{}", start_or_comma())?;
828 _ => write!(f, "{}", slice)?,
832 for p in suffix.iter() {
833 write!(f, "{}{}", start_or_comma(), p)?;
837 PatKind::Or { ref pats } => {
838 for pat in pats.iter() {
839 write!(f, "{}{}", start_or_continue(" | "), pat)?;
847 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
848 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
851 // tidy-alphabetical-start
852 static_assert_size!(Block, 56);
853 static_assert_size!(Expr<'_>, 64);
854 static_assert_size!(ExprKind<'_>, 40);
855 static_assert_size!(Pat<'_>, 72);
856 static_assert_size!(PatKind<'_>, 56);
857 static_assert_size!(Stmt<'_>, 48);
858 static_assert_size!(StmtKind<'_>, 40);
859 // tidy-alphabetical-end