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