]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/thir.rs
Auto merge of #92130 - Kobzol:stable-hash-str, r=cjgillot
[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::{
21     BinOp, BorrowKind, FakeReadCause, Field, Mutability, UnOp, UserTypeProjection,
22 };
23 use rustc_middle::ty::adjustment::PointerCast;
24 use rustc_middle::ty::subst::SubstsRef;
25 use rustc_middle::ty::{self, AdtDef, Const, Ty, UpvarSubsts, UserType};
26 use rustc_middle::ty::{
27     CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
28 };
29 use rustc_span::{Span, Symbol, DUMMY_SP};
30 use rustc_target::abi::VariantIdx;
31 use rustc_target::asm::InlineAsmRegOrRegClass;
32
33 use std::fmt;
34 use std::ops::Index;
35
36 pub mod abstract_const;
37 pub mod visit;
38
39 newtype_index! {
40     /// An index to an [`Arm`] stored in [`Thir::arms`]
41     #[derive(HashStable)]
42     pub struct ArmId {
43         DEBUG_FORMAT = "a{}"
44     }
45 }
46
47 newtype_index! {
48     /// An index to an [`Expr`] stored in [`Thir::exprs`]
49     #[derive(HashStable)]
50     pub struct ExprId {
51         DEBUG_FORMAT = "e{}"
52     }
53 }
54
55 newtype_index! {
56     #[derive(HashStable)]
57     /// An index to a [`Stmt`] stored in [`Thir::stmts`]
58     pub struct StmtId {
59         DEBUG_FORMAT = "s{}"
60     }
61 }
62
63 macro_rules! thir_with_elements {
64     ($($name:ident: $id:ty => $value:ty,)*) => {
65         /// A container for a THIR body.
66         ///
67         /// This can be indexed directly by any THIR index (e.g. [`ExprId`]).
68         #[derive(Debug, HashStable)]
69         pub struct Thir<'tcx> {
70             $(
71                 pub $name: IndexVec<$id, $value>,
72             )*
73         }
74
75         impl<'tcx> Thir<'tcx> {
76             pub fn new() -> Thir<'tcx> {
77                 Thir {
78                     $(
79                         $name: IndexVec::new(),
80                     )*
81                 }
82             }
83         }
84
85         $(
86             impl<'tcx> Index<$id> for Thir<'tcx> {
87                 type Output = $value;
88                 fn index(&self, index: $id) -> &Self::Output {
89                     &self.$name[index]
90                 }
91             }
92         )*
93     }
94 }
95
96 thir_with_elements! {
97     arms: ArmId => Arm<'tcx>,
98     exprs: ExprId => Expr<'tcx>,
99     stmts: StmtId => Stmt<'tcx>,
100 }
101
102 #[derive(Copy, Clone, Debug, HashStable)]
103 pub enum LintLevel {
104     Inherited,
105     Explicit(hir::HirId),
106 }
107
108 #[derive(Debug, HashStable)]
109 pub struct Block {
110     /// Whether the block itself has a label. Used by `label: {}`
111     /// and `try` blocks.
112     ///
113     /// This does *not* include labels on loops, e.g. `'label: loop {}`.
114     pub targeted_by_break: bool,
115     pub region_scope: region::Scope,
116     pub opt_destruction_scope: Option<region::Scope>,
117     /// The span of the block, including the opening braces,
118     /// the label, and the `unsafe` keyword, if present.
119     pub span: Span,
120     /// The statements in the blocK.
121     pub stmts: Box<[StmtId]>,
122     /// The trailing expression of the block, if any.
123     pub expr: Option<ExprId>,
124     pub safety_mode: BlockSafety,
125 }
126
127 #[derive(Debug, HashStable)]
128 pub struct Adt<'tcx> {
129     /// The ADT we're constructing.
130     pub adt_def: &'tcx AdtDef,
131     /// The variant of the ADT.
132     pub variant_index: VariantIdx,
133     pub substs: SubstsRef<'tcx>,
134
135     /// Optional user-given substs: for something like `let x =
136     /// Bar::<T> { ... }`.
137     pub user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
138
139     pub fields: Box<[FieldExpr]>,
140     /// The base, e.g. `Foo {x: 1, .. base}`.
141     pub base: Option<FruInfo<'tcx>>,
142 }
143
144 #[derive(Copy, Clone, Debug, HashStable)]
145 pub enum BlockSafety {
146     Safe,
147     /// A compiler-generated unsafe block
148     BuiltinUnsafe,
149     /// An `unsafe` block. The `HirId` is the ID of the block.
150     ExplicitUnsafe(hir::HirId),
151 }
152
153 #[derive(Debug, HashStable)]
154 pub struct Stmt<'tcx> {
155     pub kind: StmtKind<'tcx>,
156     pub opt_destruction_scope: Option<region::Scope>,
157 }
158
159 #[derive(Debug, HashStable)]
160 pub enum StmtKind<'tcx> {
161     /// An expression with a trailing semicolon.
162     Expr {
163         /// The scope for this statement; may be used as lifetime of temporaries.
164         scope: region::Scope,
165
166         /// The expression being evaluated in this statement.
167         expr: ExprId,
168     },
169
170     /// A `let` binding.
171     Let {
172         /// The scope for variables bound in this `let`; it covers this and
173         /// all the remaining statements in the block.
174         remainder_scope: region::Scope,
175
176         /// The scope for the initialization itself; might be used as
177         /// lifetime of temporaries.
178         init_scope: region::Scope,
179
180         /// `let <PAT> = ...`
181         ///
182         /// If a type annotation is included, it is added as an ascription pattern.
183         pattern: Pat<'tcx>,
184
185         /// `let pat: ty = <INIT>`
186         initializer: Option<ExprId>,
187
188         /// The lint level for this `let` statement.
189         lint_level: LintLevel,
190     },
191 }
192
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);
196
197 /// A THIR expression.
198 #[derive(Debug, HashStable)]
199 pub struct Expr<'tcx> {
200     /// The type of this expression
201     pub ty: Ty<'tcx>,
202
203     /// The lifetime of this expression if it should be spilled into a
204     /// temporary; should be `None` only if in a constant context
205     pub temp_lifetime: Option<region::Scope>,
206
207     /// span of the expression in the source
208     pub span: Span,
209
210     /// kind of expression
211     pub kind: ExprKind<'tcx>,
212 }
213
214 #[derive(Debug, HashStable)]
215 pub enum ExprKind<'tcx> {
216     /// `Scope`s are used to explicitely mark destruction scopes,
217     /// and to track the `HirId` of the expressions within the scope.
218     Scope {
219         region_scope: region::Scope,
220         lint_level: LintLevel,
221         value: ExprId,
222     },
223     /// A `box <value>` expression.
224     Box {
225         value: ExprId,
226     },
227     /// An `if` expression.
228     If {
229         if_then_scope: region::Scope,
230         cond: ExprId,
231         then: ExprId,
232         else_opt: Option<ExprId>,
233     },
234     /// A function call. Method calls and overloaded operators are converted to plain function calls.
235     Call {
236         /// The type of the function. This is often a [`FnDef`] or a [`FnPtr`].
237         ///
238         /// [`FnDef`]: ty::TyKind::FnDef
239         /// [`FnPtr`]: ty::TyKind::FnPtr
240         ty: Ty<'tcx>,
241         /// The function itself.
242         fun: ExprId,
243         /// The arguments passed to the function.
244         ///
245         /// Note: in some cases (like calling a closure), the function call `f(...args)` gets
246         /// rewritten as a call to a function trait method (e.g. `FnOnce::call_once(f, (...args))`).
247         args: Box<[ExprId]>,
248         /// Whether this is from an overloaded operator rather than a
249         /// function call from HIR. `true` for overloaded function call.
250         from_hir_call: bool,
251         /// The span of the function, without the dot and receiver
252         /// (e.g. `foo(a, b)` in `x.foo(a, b)`).
253         fn_span: Span,
254     },
255     /// A *non-overloaded* dereference.
256     Deref {
257         arg: ExprId,
258     },
259     /// A *non-overloaded* binary operation.
260     Binary {
261         op: BinOp,
262         lhs: ExprId,
263         rhs: ExprId,
264     },
265     /// A logical operation. This is distinct from `BinaryOp` because
266     /// the operands need to be lazily evaluated.
267     LogicalOp {
268         op: LogicalOp,
269         lhs: ExprId,
270         rhs: ExprId,
271     },
272     /// A *non-overloaded* unary operation. Note that here the deref (`*`)
273     /// operator is represented by `ExprKind::Deref`.
274     Unary {
275         op: UnOp,
276         arg: ExprId,
277     },
278     /// A cast: `<source> as <type>`. The type we cast to is the type of
279     /// the parent expression.
280     Cast {
281         source: ExprId,
282     },
283     Use {
284         source: ExprId,
285     }, // Use a lexpr to get a vexpr.
286     /// A coercion from `!` to any type.
287     NeverToAny {
288         source: ExprId,
289     },
290     /// A pointer cast. More information can be found in [`PointerCast`].
291     Pointer {
292         cast: PointerCast,
293         source: ExprId,
294     },
295     /// A `loop` expression.
296     Loop {
297         body: ExprId,
298     },
299     Let {
300         expr: ExprId,
301         pat: Pat<'tcx>,
302     },
303     /// A `match` expression.
304     Match {
305         scrutinee: ExprId,
306         arms: Box<[ArmId]>,
307     },
308     /// A block.
309     Block {
310         body: Block,
311     },
312     /// An assignment: `lhs = rhs`.
313     Assign {
314         lhs: ExprId,
315         rhs: ExprId,
316     },
317     /// A *non-overloaded* operation assignment, e.g. `lhs += rhs`.
318     AssignOp {
319         op: BinOp,
320         lhs: ExprId,
321         rhs: ExprId,
322     },
323     /// Access to a struct or tuple field.
324     Field {
325         lhs: ExprId,
326         /// This can be a named (`.foo`) or unnamed (`.0`) field.
327         name: Field,
328     },
329     /// A *non-overloaded* indexing operation.
330     Index {
331         lhs: ExprId,
332         index: ExprId,
333     },
334     /// A local variable.
335     VarRef {
336         id: hir::HirId,
337     },
338     /// Used to represent upvars mentioned in a closure/generator
339     UpvarRef {
340         /// DefId of the closure/generator
341         closure_def_id: DefId,
342
343         /// HirId of the root variable
344         var_hir_id: hir::HirId,
345     },
346     /// A borrow, e.g. `&arg`.
347     Borrow {
348         borrow_kind: BorrowKind,
349         arg: ExprId,
350     },
351     /// A `&raw [const|mut] $place_expr` raw borrow resulting in type `*[const|mut] T`.
352     AddressOf {
353         mutability: hir::Mutability,
354         arg: ExprId,
355     },
356     /// A `break` expression.
357     Break {
358         label: region::Scope,
359         value: Option<ExprId>,
360     },
361     /// A `continue` expression.
362     Continue {
363         label: region::Scope,
364     },
365     /// A `return` expression.
366     Return {
367         value: Option<ExprId>,
368     },
369     /// An inline `const` block, e.g. `const {}`.
370     ConstBlock {
371         value: &'tcx Const<'tcx>,
372     },
373     /// An array literal constructed from one repeated element, e.g. `[1; 5]`.
374     Repeat {
375         value: ExprId,
376         count: &'tcx Const<'tcx>,
377     },
378     /// An array, e.g. `[a, b, c, d]`.
379     Array {
380         fields: Box<[ExprId]>,
381     },
382     /// A tuple, e.g. `(a, b, c, d)`.
383     Tuple {
384         fields: Box<[ExprId]>,
385     },
386     /// An ADT constructor, e.g. `Foo {x: 1, y: 2}`.
387     Adt(Box<Adt<'tcx>>),
388     /// A type ascription on a place.
389     PlaceTypeAscription {
390         source: ExprId,
391         /// Type that the user gave to this expression
392         user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
393     },
394     /// A type ascription on a value, e.g. `42: i32`.
395     ValueTypeAscription {
396         source: ExprId,
397         /// Type that the user gave to this expression
398         user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
399     },
400     /// A closure definition.
401     Closure {
402         closure_id: DefId,
403         substs: UpvarSubsts<'tcx>,
404         upvars: Box<[ExprId]>,
405         movability: Option<hir::Movability>,
406         fake_reads: Vec<(ExprId, FakeReadCause, hir::HirId)>,
407     },
408     /// A literal.
409     Literal {
410         literal: &'tcx Const<'tcx>,
411         user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
412         /// The `DefId` of the `const` item this literal
413         /// was produced from, if this is not a user-written
414         /// literal value.
415         const_id: Option<DefId>,
416     },
417     /// A literal containing the address of a `static`.
418     ///
419     /// This is only distinguished from `Literal` so that we can register some
420     /// info for diagnostics.
421     StaticRef {
422         literal: &'tcx Const<'tcx>,
423         def_id: DefId,
424     },
425     /// Inline assembly, i.e. `asm!()`.
426     InlineAsm {
427         template: &'tcx [InlineAsmTemplatePiece],
428         operands: Box<[InlineAsmOperand<'tcx>]>,
429         options: InlineAsmOptions,
430         line_spans: &'tcx [Span],
431     },
432     /// An expression taking a reference to a thread local.
433     ThreadLocalRef(DefId),
434     /// Inline LLVM assembly, i.e. `llvm_asm!()`.
435     LlvmInlineAsm {
436         asm: &'tcx hir::LlvmInlineAsmInner,
437         outputs: Box<[ExprId]>,
438         inputs: Box<[ExprId]>,
439     },
440     /// A `yield` expression.
441     Yield {
442         value: ExprId,
443     },
444 }
445
446 /// Represents the association of a field identifier and an expression.
447 ///
448 /// This is used in struct constructors.
449 #[derive(Debug, HashStable)]
450 pub struct FieldExpr {
451     pub name: Field,
452     pub expr: ExprId,
453 }
454
455 #[derive(Debug, HashStable)]
456 pub struct FruInfo<'tcx> {
457     pub base: ExprId,
458     pub field_types: Box<[Ty<'tcx>]>,
459 }
460
461 /// A `match` arm.
462 #[derive(Debug, HashStable)]
463 pub struct Arm<'tcx> {
464     pub pattern: Pat<'tcx>,
465     pub guard: Option<Guard<'tcx>>,
466     pub body: ExprId,
467     pub lint_level: LintLevel,
468     pub scope: region::Scope,
469     pub span: Span,
470 }
471
472 /// A `match` guard.
473 #[derive(Debug, HashStable)]
474 pub enum Guard<'tcx> {
475     If(ExprId),
476     IfLet(Pat<'tcx>, ExprId),
477 }
478
479 #[derive(Copy, Clone, Debug, HashStable)]
480 pub enum LogicalOp {
481     /// The `&&` operator.
482     And,
483     /// The `||` operator.
484     Or,
485 }
486
487 #[derive(Debug, HashStable)]
488 pub enum InlineAsmOperand<'tcx> {
489     In {
490         reg: InlineAsmRegOrRegClass,
491         expr: ExprId,
492     },
493     Out {
494         reg: InlineAsmRegOrRegClass,
495         late: bool,
496         expr: Option<ExprId>,
497     },
498     InOut {
499         reg: InlineAsmRegOrRegClass,
500         late: bool,
501         expr: ExprId,
502     },
503     SplitInOut {
504         reg: InlineAsmRegOrRegClass,
505         late: bool,
506         in_expr: ExprId,
507         out_expr: Option<ExprId>,
508     },
509     Const {
510         value: &'tcx Const<'tcx>,
511         span: Span,
512     },
513     SymFn {
514         expr: ExprId,
515     },
516     SymStatic {
517         def_id: DefId,
518     },
519 }
520
521 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
522 pub enum BindingMode {
523     ByValue,
524     ByRef(BorrowKind),
525 }
526
527 #[derive(Clone, Debug, PartialEq, HashStable)]
528 pub struct FieldPat<'tcx> {
529     pub field: Field,
530     pub pattern: Pat<'tcx>,
531 }
532
533 #[derive(Clone, Debug, PartialEq, HashStable)]
534 pub struct Pat<'tcx> {
535     pub ty: Ty<'tcx>,
536     pub span: Span,
537     pub kind: Box<PatKind<'tcx>>,
538 }
539
540 impl<'tcx> Pat<'tcx> {
541     pub fn wildcard_from_ty(ty: Ty<'tcx>) -> Self {
542         Pat { ty, span: DUMMY_SP, kind: Box::new(PatKind::Wild) }
543     }
544 }
545
546 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
547 pub struct PatTyProj<'tcx> {
548     pub user_ty: CanonicalUserType<'tcx>,
549 }
550
551 impl<'tcx> PatTyProj<'tcx> {
552     pub fn from_user_type(user_annotation: CanonicalUserType<'tcx>) -> Self {
553         Self { user_ty: user_annotation }
554     }
555
556     pub fn user_ty(
557         self,
558         annotations: &mut CanonicalUserTypeAnnotations<'tcx>,
559         inferred_ty: Ty<'tcx>,
560         span: Span,
561     ) -> UserTypeProjection {
562         UserTypeProjection {
563             base: annotations.push(CanonicalUserTypeAnnotation {
564                 span,
565                 user_ty: self.user_ty,
566                 inferred_ty,
567             }),
568             projs: Vec::new(),
569         }
570     }
571 }
572
573 #[derive(Copy, Clone, Debug, PartialEq, HashStable)]
574 pub struct Ascription<'tcx> {
575     pub user_ty: PatTyProj<'tcx>,
576     /// Variance to use when relating the type `user_ty` to the **type of the value being
577     /// matched**. Typically, this is `Variance::Covariant`, since the value being matched must
578     /// have a type that is some subtype of the ascribed type.
579     ///
580     /// Note that this variance does not apply for any bindings within subpatterns. The type
581     /// assigned to those bindings must be exactly equal to the `user_ty` given here.
582     ///
583     /// The only place where this field is not `Covariant` is when matching constants, where
584     /// we currently use `Contravariant` -- this is because the constant type just needs to
585     /// be "comparable" to the type of the input value. So, for example:
586     ///
587     /// ```text
588     /// match x { "foo" => .. }
589     /// ```
590     ///
591     /// requires that `&'static str <: T_x`, where `T_x` is the type of `x`. Really, we should
592     /// probably be checking for a `PartialEq` impl instead, but this preserves the behavior
593     /// of the old type-check for now. See #57280 for details.
594     pub variance: ty::Variance,
595     pub user_ty_span: Span,
596 }
597
598 #[derive(Clone, Debug, PartialEq, HashStable)]
599 pub enum PatKind<'tcx> {
600     /// A wildward 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: hir::HirId,
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: &'tcx AdtDef,
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 exhaustivenes 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: &'tcx ty::Const<'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: &'tcx ty::Const<'tcx>,
680     pub hi: &'tcx ty::Const<'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.variants[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.ident)?;
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()].ident;
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 }