]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/thir.rs
Merge commit 'c4416f20dcaec5d93077f72470e83e150fb923b1' into sync-rustfmt
[rust.git] / compiler / rustc_middle / src / 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
11 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
12 use rustc_hir as hir;
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;
29
30 use std::fmt;
31 use std::ops::Index;
32
33 pub mod abstract_const;
34 pub mod visit;
35
36 newtype_index! {
37     /// An index to an [`Arm`] stored in [`Thir::arms`]
38     #[derive(HashStable)]
39     pub struct ArmId {
40         DEBUG_FORMAT = "a{}"
41     }
42 }
43
44 newtype_index! {
45     /// An index to an [`Expr`] stored in [`Thir::exprs`]
46     #[derive(HashStable)]
47     pub struct ExprId {
48         DEBUG_FORMAT = "e{}"
49     }
50 }
51
52 newtype_index! {
53     #[derive(HashStable)]
54     /// An index to a [`Stmt`] stored in [`Thir::stmts`]
55     pub struct StmtId {
56         DEBUG_FORMAT = "s{}"
57     }
58 }
59
60 macro_rules! thir_with_elements {
61     ($($name:ident: $id:ty => $value:ty,)*) => {
62         /// A container for a THIR body.
63         ///
64         /// This can be indexed directly by any THIR index (e.g. [`ExprId`]).
65         #[derive(Debug, HashStable, Clone)]
66         pub struct Thir<'tcx> {
67             $(
68                 pub $name: IndexVec<$id, $value>,
69             )*
70         }
71
72         impl<'tcx> Thir<'tcx> {
73             pub fn new() -> Thir<'tcx> {
74                 Thir {
75                     $(
76                         $name: IndexVec::new(),
77                     )*
78                 }
79             }
80         }
81
82         $(
83             impl<'tcx> Index<$id> for Thir<'tcx> {
84                 type Output = $value;
85                 fn index(&self, index: $id) -> &Self::Output {
86                     &self.$name[index]
87                 }
88             }
89         )*
90     }
91 }
92
93 thir_with_elements! {
94     arms: ArmId => Arm<'tcx>,
95     exprs: ExprId => Expr<'tcx>,
96     stmts: StmtId => Stmt<'tcx>,
97 }
98
99 #[derive(Copy, Clone, Debug, HashStable)]
100 pub enum LintLevel {
101     Inherited,
102     Explicit(hir::HirId),
103 }
104
105 #[derive(Clone, Debug, HashStable)]
106 pub struct Block {
107     /// Whether the block itself has a label. Used by `label: {}`
108     /// and `try` blocks.
109     ///
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.
116     pub span: Span,
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,
122 }
123
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>,
131
132     /// Optional user-given substs: for something like `let x =
133     /// Bar::<T> { ... }`.
134     pub user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
135
136     pub fields: Box<[FieldExpr]>,
137     /// The base, e.g. `Foo {x: 1, .. base}`.
138     pub base: Option<FruInfo<'tcx>>,
139 }
140
141 #[derive(Copy, Clone, Debug, HashStable)]
142 pub enum BlockSafety {
143     Safe,
144     /// A compiler-generated unsafe block
145     BuiltinUnsafe,
146     /// An `unsafe` block. The `HirId` is the ID of the block.
147     ExplicitUnsafe(hir::HirId),
148 }
149
150 #[derive(Clone, Debug, HashStable)]
151 pub struct Stmt<'tcx> {
152     pub kind: StmtKind<'tcx>,
153     pub opt_destruction_scope: Option<region::Scope>,
154 }
155
156 #[derive(Clone, Debug, HashStable)]
157 pub enum StmtKind<'tcx> {
158     /// An expression with a trailing semicolon.
159     Expr {
160         /// The scope for this statement; may be used as lifetime of temporaries.
161         scope: region::Scope,
162
163         /// The expression being evaluated in this statement.
164         expr: ExprId,
165     },
166
167     /// A `let` binding.
168     Let {
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,
172
173         /// The scope for the initialization itself; might be used as
174         /// lifetime of temporaries.
175         init_scope: region::Scope,
176
177         /// `let <PAT> = ...`
178         ///
179         /// If a type annotation is included, it is added as an ascription pattern.
180         pattern: Pat<'tcx>,
181
182         /// `let pat: ty = <INIT>`
183         initializer: Option<ExprId>,
184
185         /// The lint level for this `let` statement.
186         lint_level: LintLevel,
187     },
188 }
189
190 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
191 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
192 rustc_data_structures::static_assert_size!(Expr<'_>, 104);
193
194 #[derive(
195     Clone,
196     Debug,
197     Copy,
198     PartialEq,
199     Eq,
200     Hash,
201     HashStable,
202     TyEncodable,
203     TyDecodable,
204     TypeFoldable
205 )]
206 pub struct LocalVarId(pub hir::HirId);
207
208 /// A THIR expression.
209 #[derive(Clone, Debug, HashStable)]
210 pub struct Expr<'tcx> {
211     /// The type of this expression
212     pub ty: Ty<'tcx>,
213
214     /// The lifetime of this expression if it should be spilled into a
215     /// temporary; should be `None` only if in a constant context
216     pub temp_lifetime: Option<region::Scope>,
217
218     /// span of the expression in the source
219     pub span: Span,
220
221     /// kind of expression
222     pub kind: ExprKind<'tcx>,
223 }
224
225 #[derive(Clone, Debug, HashStable)]
226 pub enum ExprKind<'tcx> {
227     /// `Scope`s are used to explicitly mark destruction scopes,
228     /// and to track the `HirId` of the expressions within the scope.
229     Scope {
230         region_scope: region::Scope,
231         lint_level: LintLevel,
232         value: ExprId,
233     },
234     /// A `box <value>` expression.
235     Box {
236         value: ExprId,
237     },
238     /// An `if` expression.
239     If {
240         if_then_scope: region::Scope,
241         cond: ExprId,
242         then: ExprId,
243         else_opt: Option<ExprId>,
244     },
245     /// A function call. Method calls and overloaded operators are converted to plain function calls.
246     Call {
247         /// The type of the function. This is often a [`FnDef`] or a [`FnPtr`].
248         ///
249         /// [`FnDef`]: ty::TyKind::FnDef
250         /// [`FnPtr`]: ty::TyKind::FnPtr
251         ty: Ty<'tcx>,
252         /// The function itself.
253         fun: ExprId,
254         /// The arguments passed to the function.
255         ///
256         /// Note: in some cases (like calling a closure), the function call `f(...args)` gets
257         /// rewritten as a call to a function trait method (e.g. `FnOnce::call_once(f, (...args))`).
258         args: Box<[ExprId]>,
259         /// Whether this is from an overloaded operator rather than a
260         /// function call from HIR. `true` for overloaded function call.
261         from_hir_call: bool,
262         /// The span of the function, without the dot and receiver
263         /// (e.g. `foo(a, b)` in `x.foo(a, b)`).
264         fn_span: Span,
265     },
266     /// A *non-overloaded* dereference.
267     Deref {
268         arg: ExprId,
269     },
270     /// A *non-overloaded* binary operation.
271     Binary {
272         op: BinOp,
273         lhs: ExprId,
274         rhs: ExprId,
275     },
276     /// A logical operation. This is distinct from `BinaryOp` because
277     /// the operands need to be lazily evaluated.
278     LogicalOp {
279         op: LogicalOp,
280         lhs: ExprId,
281         rhs: ExprId,
282     },
283     /// A *non-overloaded* unary operation. Note that here the deref (`*`)
284     /// operator is represented by `ExprKind::Deref`.
285     Unary {
286         op: UnOp,
287         arg: ExprId,
288     },
289     /// A cast: `<source> as <type>`. The type we cast to is the type of
290     /// the parent expression.
291     Cast {
292         source: ExprId,
293     },
294     Use {
295         source: ExprId,
296     }, // Use a lexpr to get a vexpr.
297     /// A coercion from `!` to any type.
298     NeverToAny {
299         source: ExprId,
300     },
301     /// A pointer cast. More information can be found in [`PointerCast`].
302     Pointer {
303         cast: PointerCast,
304         source: ExprId,
305     },
306     /// A `loop` expression.
307     Loop {
308         body: ExprId,
309     },
310     Let {
311         expr: ExprId,
312         pat: Pat<'tcx>,
313     },
314     /// A `match` expression.
315     Match {
316         scrutinee: ExprId,
317         arms: Box<[ArmId]>,
318     },
319     /// A block.
320     Block {
321         body: Block,
322     },
323     /// An assignment: `lhs = rhs`.
324     Assign {
325         lhs: ExprId,
326         rhs: ExprId,
327     },
328     /// A *non-overloaded* operation assignment, e.g. `lhs += rhs`.
329     AssignOp {
330         op: BinOp,
331         lhs: ExprId,
332         rhs: ExprId,
333     },
334     /// Access to a field of a struct, a tuple, an union, or an enum.
335     Field {
336         lhs: ExprId,
337         /// Variant containing the field.
338         variant_index: VariantIdx,
339         /// This can be a named (`.foo`) or unnamed (`.0`) field.
340         name: Field,
341     },
342     /// A *non-overloaded* indexing operation.
343     Index {
344         lhs: ExprId,
345         index: ExprId,
346     },
347     /// A local variable.
348     VarRef {
349         id: LocalVarId,
350     },
351     /// Used to represent upvars mentioned in a closure/generator
352     UpvarRef {
353         /// DefId of the closure/generator
354         closure_def_id: DefId,
355
356         /// HirId of the root variable
357         var_hir_id: LocalVarId,
358     },
359     /// A borrow, e.g. `&arg`.
360     Borrow {
361         borrow_kind: BorrowKind,
362         arg: ExprId,
363     },
364     /// A `&raw [const|mut] $place_expr` raw borrow resulting in type `*[const|mut] T`.
365     AddressOf {
366         mutability: hir::Mutability,
367         arg: ExprId,
368     },
369     /// A `break` expression.
370     Break {
371         label: region::Scope,
372         value: Option<ExprId>,
373     },
374     /// A `continue` expression.
375     Continue {
376         label: region::Scope,
377     },
378     /// A `return` expression.
379     Return {
380         value: Option<ExprId>,
381     },
382     /// An inline `const` block, e.g. `const {}`.
383     ConstBlock {
384         did: DefId,
385         substs: SubstsRef<'tcx>,
386     },
387     /// An array literal constructed from one repeated element, e.g. `[1; 5]`.
388     Repeat {
389         value: ExprId,
390         count: ty::Const<'tcx>,
391     },
392     /// An array, e.g. `[a, b, c, d]`.
393     Array {
394         fields: Box<[ExprId]>,
395     },
396     /// A tuple, e.g. `(a, b, c, d)`.
397     Tuple {
398         fields: Box<[ExprId]>,
399     },
400     /// An ADT constructor, e.g. `Foo {x: 1, y: 2}`.
401     Adt(Box<Adt<'tcx>>),
402     /// A type ascription on a place.
403     PlaceTypeAscription {
404         source: ExprId,
405         /// Type that the user gave to this expression
406         user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
407     },
408     /// A type ascription on a value, e.g. `42: i32`.
409     ValueTypeAscription {
410         source: ExprId,
411         /// Type that the user gave to this expression
412         user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
413     },
414     /// A closure definition.
415     Closure {
416         closure_id: DefId,
417         substs: UpvarSubsts<'tcx>,
418         upvars: Box<[ExprId]>,
419         movability: Option<hir::Movability>,
420         fake_reads: Vec<(ExprId, FakeReadCause, hir::HirId)>,
421     },
422     /// A literal.
423     Literal {
424         lit: &'tcx hir::Lit,
425         neg: bool,
426     },
427     /// For literals that don't correspond to anything in the HIR
428     NonHirLiteral {
429         lit: ty::ScalarInt,
430         user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
431     },
432     /// Associated constants and named constants
433     NamedConst {
434         def_id: DefId,
435         substs: SubstsRef<'tcx>,
436         user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
437     },
438     ConstParam {
439         param: ty::ParamConst,
440         def_id: DefId,
441     },
442     // FIXME improve docs for `StaticRef` by distinguishing it from `NamedConst`
443     /// A literal containing the address of a `static`.
444     ///
445     /// This is only distinguished from `Literal` so that we can register some
446     /// info for diagnostics.
447     StaticRef {
448         alloc_id: AllocId,
449         ty: Ty<'tcx>,
450         def_id: DefId,
451     },
452     /// Inline assembly, i.e. `asm!()`.
453     InlineAsm {
454         template: &'tcx [InlineAsmTemplatePiece],
455         operands: Box<[InlineAsmOperand<'tcx>]>,
456         options: InlineAsmOptions,
457         line_spans: &'tcx [Span],
458     },
459     /// An expression taking a reference to a thread local.
460     ThreadLocalRef(DefId),
461     /// A `yield` expression.
462     Yield {
463         value: ExprId,
464     },
465 }
466
467 impl<'tcx> ExprKind<'tcx> {
468     pub fn zero_sized_literal(user_ty: Option<Canonical<'tcx, UserType<'tcx>>>) -> Self {
469         ExprKind::NonHirLiteral { lit: ty::ScalarInt::ZST, user_ty }
470     }
471 }
472
473 /// Represents the association of a field identifier and an expression.
474 ///
475 /// This is used in struct constructors.
476 #[derive(Clone, Debug, HashStable)]
477 pub struct FieldExpr {
478     pub name: Field,
479     pub expr: ExprId,
480 }
481
482 #[derive(Clone, Debug, HashStable)]
483 pub struct FruInfo<'tcx> {
484     pub base: ExprId,
485     pub field_types: Box<[Ty<'tcx>]>,
486 }
487
488 /// A `match` arm.
489 #[derive(Clone, Debug, HashStable)]
490 pub struct Arm<'tcx> {
491     pub pattern: Pat<'tcx>,
492     pub guard: Option<Guard<'tcx>>,
493     pub body: ExprId,
494     pub lint_level: LintLevel,
495     pub scope: region::Scope,
496     pub span: Span,
497 }
498
499 /// A `match` guard.
500 #[derive(Clone, Debug, HashStable)]
501 pub enum Guard<'tcx> {
502     If(ExprId),
503     IfLet(Pat<'tcx>, ExprId),
504 }
505
506 #[derive(Copy, Clone, Debug, HashStable)]
507 pub enum LogicalOp {
508     /// The `&&` operator.
509     And,
510     /// The `||` operator.
511     Or,
512 }
513
514 #[derive(Clone, Debug, HashStable)]
515 pub enum InlineAsmOperand<'tcx> {
516     In {
517         reg: InlineAsmRegOrRegClass,
518         expr: ExprId,
519     },
520     Out {
521         reg: InlineAsmRegOrRegClass,
522         late: bool,
523         expr: Option<ExprId>,
524     },
525     InOut {
526         reg: InlineAsmRegOrRegClass,
527         late: bool,
528         expr: ExprId,
529     },
530     SplitInOut {
531         reg: InlineAsmRegOrRegClass,
532         late: bool,
533         in_expr: ExprId,
534         out_expr: Option<ExprId>,
535     },
536     Const {
537         value: mir::ConstantKind<'tcx>,
538         span: Span,
539     },
540     SymFn {
541         value: mir::ConstantKind<'tcx>,
542         span: Span,
543     },
544     SymStatic {
545         def_id: DefId,
546     },
547 }
548
549 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
550 pub enum BindingMode {
551     ByValue,
552     ByRef(BorrowKind),
553 }
554
555 #[derive(Clone, Debug, HashStable)]
556 pub struct FieldPat<'tcx> {
557     pub field: Field,
558     pub pattern: Pat<'tcx>,
559 }
560
561 #[derive(Clone, Debug, HashStable)]
562 pub struct Pat<'tcx> {
563     pub ty: Ty<'tcx>,
564     pub span: Span,
565     pub kind: Box<PatKind<'tcx>>,
566 }
567
568 impl<'tcx> Pat<'tcx> {
569     pub fn wildcard_from_ty(ty: Ty<'tcx>) -> Self {
570         Pat { ty, span: DUMMY_SP, kind: Box::new(PatKind::Wild) }
571     }
572 }
573
574 #[derive(Clone, Debug, HashStable)]
575 pub struct Ascription<'tcx> {
576     pub annotation: CanonicalUserTypeAnnotation<'tcx>,
577     /// Variance to use when relating the `user_ty` to the **type of the value being
578     /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
579     /// have a type that is some subtype of the ascribed type.
580     ///
581     /// Note that this variance does not apply for any bindings within subpatterns. The type
582     /// assigned to those bindings must be exactly equal to the `user_ty` given here.
583     ///
584     /// The only place where this field is not `Covariant` is when matching constants, where
585     /// we currently use `Contravariant` -- this is because the constant type just needs to
586     /// be "comparable" to the type of the input value. So, for example:
587     ///
588     /// ```text
589     /// match x { "foo" => .. }
590     /// ```
591     ///
592     /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
593     /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
594     /// of the old type-check for now. See #57280 for details.
595     pub variance: ty::Variance,
596 }
597
598 #[derive(Clone, Debug, HashStable)]
599 pub enum PatKind<'tcx> {
600     /// A wildcard pattern: `_`.
601     Wild,
602
603     AscribeUserType {
604         ascription: Ascription<'tcx>,
605         subpattern: Pat<'tcx>,
606     },
607
608     /// `x`, `ref x`, `x @ P`, etc.
609     Binding {
610         mutability: Mutability,
611         name: Symbol,
612         mode: BindingMode,
613         var: LocalVarId,
614         ty: Ty<'tcx>,
615         subpattern: Option<Pat<'tcx>>,
616         /// Is this the leftmost occurrence of the binding, i.e., is `var` the
617         /// `HirId` of this pattern?
618         is_primary: bool,
619     },
620
621     /// `Foo(...)` or `Foo{...}` or `Foo`, where `Foo` is a variant name from an ADT with
622     /// multiple variants.
623     Variant {
624         adt_def: AdtDef<'tcx>,
625         substs: SubstsRef<'tcx>,
626         variant_index: VariantIdx,
627         subpatterns: Vec<FieldPat<'tcx>>,
628     },
629
630     /// `(...)`, `Foo(...)`, `Foo{...}`, or `Foo`, where `Foo` is a variant name from an ADT with
631     /// a single variant.
632     Leaf {
633         subpatterns: Vec<FieldPat<'tcx>>,
634     },
635
636     /// `box P`, `&P`, `&mut P`, etc.
637     Deref {
638         subpattern: Pat<'tcx>,
639     },
640
641     /// One of the following:
642     /// * `&str`, which will be handled as a string pattern and thus exhaustiveness
643     ///   checking will detect if you use the same string twice in different patterns.
644     /// * integer, bool, char or float, which will be handled by exhaustiveness to cover exactly
645     ///   its own value, similar to `&str`, but these values are much simpler.
646     /// * Opaque constants, that must not be matched structurally. So anything that does not derive
647     ///   `PartialEq` and `Eq`.
648     Constant {
649         value: mir::ConstantKind<'tcx>,
650     },
651
652     Range(PatRange<'tcx>),
653
654     /// Matches against a slice, checking the length and extracting elements.
655     /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
656     /// e.g., `&[ref xs @ ..]`.
657     Slice {
658         prefix: Vec<Pat<'tcx>>,
659         slice: Option<Pat<'tcx>>,
660         suffix: Vec<Pat<'tcx>>,
661     },
662
663     /// Fixed match against an array; irrefutable.
664     Array {
665         prefix: Vec<Pat<'tcx>>,
666         slice: Option<Pat<'tcx>>,
667         suffix: Vec<Pat<'tcx>>,
668     },
669
670     /// An or-pattern, e.g. `p | q`.
671     /// Invariant: `pats.len() >= 2`.
672     Or {
673         pats: Vec<Pat<'tcx>>,
674     },
675 }
676
677 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
678 pub struct PatRange<'tcx> {
679     pub lo: mir::ConstantKind<'tcx>,
680     pub hi: mir::ConstantKind<'tcx>,
681     pub end: RangeEnd,
682 }
683
684 impl<'tcx> fmt::Display for Pat<'tcx> {
685     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
686         // Printing lists is a chore.
687         let mut first = true;
688         let mut start_or_continue = |s| {
689             if first {
690                 first = false;
691                 ""
692             } else {
693                 s
694             }
695         };
696         let mut start_or_comma = || start_or_continue(", ");
697
698         match *self.kind {
699             PatKind::Wild => write!(f, "_"),
700             PatKind::AscribeUserType { ref subpattern, .. } => write!(f, "{}: _", subpattern),
701             PatKind::Binding { mutability, name, mode, ref subpattern, .. } => {
702                 let is_mut = match mode {
703                     BindingMode::ByValue => mutability == Mutability::Mut,
704                     BindingMode::ByRef(bk) => {
705                         write!(f, "ref ")?;
706                         matches!(bk, BorrowKind::Mut { .. })
707                     }
708                 };
709                 if is_mut {
710                     write!(f, "mut ")?;
711                 }
712                 write!(f, "{}", name)?;
713                 if let Some(ref subpattern) = *subpattern {
714                     write!(f, " @ {}", subpattern)?;
715                 }
716                 Ok(())
717             }
718             PatKind::Variant { ref subpatterns, .. } | PatKind::Leaf { ref subpatterns } => {
719                 let variant = match *self.kind {
720                     PatKind::Variant { adt_def, variant_index, .. } => {
721                         Some(adt_def.variant(variant_index))
722                     }
723                     _ => self.ty.ty_adt_def().and_then(|adt| {
724                         if !adt.is_enum() { Some(adt.non_enum_variant()) } else { None }
725                     }),
726                 };
727
728                 if let Some(variant) = variant {
729                     write!(f, "{}", variant.name)?;
730
731                     // Only for Adt we can have `S {...}`,
732                     // which we handle separately here.
733                     if variant.ctor_kind == CtorKind::Fictive {
734                         write!(f, " {{ ")?;
735
736                         let mut printed = 0;
737                         for p in subpatterns {
738                             if let PatKind::Wild = *p.pattern.kind {
739                                 continue;
740                             }
741                             let name = variant.fields[p.field.index()].name;
742                             write!(f, "{}{}: {}", start_or_comma(), name, p.pattern)?;
743                             printed += 1;
744                         }
745
746                         if printed < variant.fields.len() {
747                             write!(f, "{}..", start_or_comma())?;
748                         }
749
750                         return write!(f, " }}");
751                     }
752                 }
753
754                 let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
755                 if num_fields != 0 || variant.is_none() {
756                     write!(f, "(")?;
757                     for i in 0..num_fields {
758                         write!(f, "{}", start_or_comma())?;
759
760                         // Common case: the field is where we expect it.
761                         if let Some(p) = subpatterns.get(i) {
762                             if p.field.index() == i {
763                                 write!(f, "{}", p.pattern)?;
764                                 continue;
765                             }
766                         }
767
768                         // Otherwise, we have to go looking for it.
769                         if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
770                             write!(f, "{}", p.pattern)?;
771                         } else {
772                             write!(f, "_")?;
773                         }
774                     }
775                     write!(f, ")")?;
776                 }
777
778                 Ok(())
779             }
780             PatKind::Deref { ref subpattern } => {
781                 match self.ty.kind() {
782                     ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
783                     ty::Ref(_, _, mutbl) => {
784                         write!(f, "&{}", mutbl.prefix_str())?;
785                     }
786                     _ => bug!("{} is a bad Deref pattern type", self.ty),
787                 }
788                 write!(f, "{}", subpattern)
789             }
790             PatKind::Constant { value } => write!(f, "{}", value),
791             PatKind::Range(PatRange { lo, hi, end }) => {
792                 write!(f, "{}", lo)?;
793                 write!(f, "{}", end)?;
794                 write!(f, "{}", hi)
795             }
796             PatKind::Slice { ref prefix, ref slice, ref suffix }
797             | PatKind::Array { ref prefix, ref slice, ref suffix } => {
798                 write!(f, "[")?;
799                 for p in prefix {
800                     write!(f, "{}{}", start_or_comma(), p)?;
801                 }
802                 if let Some(ref slice) = *slice {
803                     write!(f, "{}", start_or_comma())?;
804                     match *slice.kind {
805                         PatKind::Wild => {}
806                         _ => write!(f, "{}", slice)?,
807                     }
808                     write!(f, "..")?;
809                 }
810                 for p in suffix {
811                     write!(f, "{}{}", start_or_comma(), p)?;
812                 }
813                 write!(f, "]")
814             }
815             PatKind::Or { ref pats } => {
816                 for pat in pats {
817                     write!(f, "{}{}", start_or_continue(" | "), pat)?;
818                 }
819                 Ok(())
820             }
821         }
822     }
823 }