]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/hir.rs
Rollup merge of #85409 - CDirkx:cfg_redox, r=nagisa
[rust.git] / compiler / rustc_hir / src / hir.rs
1 // ignore-tidy-filelength
2 use crate::def::{CtorKind, DefKind, Res};
3 use crate::def_id::DefId;
4 crate use crate::hir_id::HirId;
5 use crate::{itemlikevisit, LangItem};
6
7 use rustc_ast::util::parser::ExprPrecedence;
8 use rustc_ast::{self as ast, CrateSugar, LlvmAsmDialect};
9 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, TraitObjectSyntax, UintTy};
10 pub use rustc_ast::{BorrowKind, ImplPolarity, IsAuto};
11 pub use rustc_ast::{CaptureBy, Movability, Mutability};
12 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
13 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
14 use rustc_macros::HashStable_Generic;
15 use rustc_span::source_map::Spanned;
16 use rustc_span::symbol::{kw, sym, Ident, Symbol};
17 use rustc_span::{def_id::LocalDefId, BytePos};
18 use rustc_span::{MultiSpan, Span, DUMMY_SP};
19 use rustc_target::asm::InlineAsmRegOrRegClass;
20 use rustc_target::spec::abi::Abi;
21
22 use smallvec::SmallVec;
23 use std::collections::{BTreeMap, BTreeSet};
24 use std::fmt;
25
26 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
27 pub struct Lifetime {
28     pub hir_id: HirId,
29     pub span: Span,
30
31     /// Either "`'a`", referring to a named lifetime definition,
32     /// or "``" (i.e., `kw::Empty`), for elision placeholders.
33     ///
34     /// HIR lowering inserts these placeholders in type paths that
35     /// refer to type definitions needing lifetime parameters,
36     /// `&T` and `&mut T`, and trait objects without `... + 'a`.
37     pub name: LifetimeName,
38 }
39
40 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
41 #[derive(HashStable_Generic)]
42 pub enum ParamName {
43     /// Some user-given name like `T` or `'x`.
44     Plain(Ident),
45
46     /// Synthetic name generated when user elided a lifetime in an impl header.
47     ///
48     /// E.g., the lifetimes in cases like these:
49     ///
50     ///     impl Foo for &u32
51     ///     impl Foo<'_> for u32
52     ///
53     /// in that case, we rewrite to
54     ///
55     ///     impl<'f> Foo for &'f u32
56     ///     impl<'f> Foo<'f> for u32
57     ///
58     /// where `'f` is something like `Fresh(0)`. The indices are
59     /// unique per impl, but not necessarily continuous.
60     Fresh(usize),
61
62     /// Indicates an illegal name was given and an error has been
63     /// reported (so we should squelch other derived errors). Occurs
64     /// when, e.g., `'_` is used in the wrong place.
65     Error,
66 }
67
68 impl ParamName {
69     pub fn ident(&self) -> Ident {
70         match *self {
71             ParamName::Plain(ident) => ident,
72             ParamName::Fresh(_) | ParamName::Error => {
73                 Ident::with_dummy_span(kw::UnderscoreLifetime)
74             }
75         }
76     }
77
78     pub fn normalize_to_macros_2_0(&self) -> ParamName {
79         match *self {
80             ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
81             param_name => param_name,
82         }
83     }
84 }
85
86 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
87 #[derive(HashStable_Generic)]
88 pub enum LifetimeName {
89     /// User-given names or fresh (synthetic) names.
90     Param(ParamName),
91
92     /// User wrote nothing (e.g., the lifetime in `&u32`).
93     Implicit,
94
95     /// Implicit lifetime in a context like `dyn Foo`. This is
96     /// distinguished from implicit lifetimes elsewhere because the
97     /// lifetime that they default to must appear elsewhere within the
98     /// enclosing type.  This means that, in an `impl Trait` context, we
99     /// don't have to create a parameter for them. That is, `impl
100     /// Trait<Item = &u32>` expands to an opaque type like `type
101     /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
102     /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
103     /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
104     /// that surrounding code knows not to create a lifetime
105     /// parameter.
106     ImplicitObjectLifetimeDefault,
107
108     /// Indicates an error during lowering (usually `'_` in wrong place)
109     /// that was already reported.
110     Error,
111
112     /// User wrote specifies `'_`.
113     Underscore,
114
115     /// User wrote `'static`.
116     Static,
117 }
118
119 impl LifetimeName {
120     pub fn ident(&self) -> Ident {
121         match *self {
122             LifetimeName::ImplicitObjectLifetimeDefault
123             | LifetimeName::Implicit
124             | LifetimeName::Error => Ident::invalid(),
125             LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
126             LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
127             LifetimeName::Param(param_name) => param_name.ident(),
128         }
129     }
130
131     pub fn is_elided(&self) -> bool {
132         match self {
133             LifetimeName::ImplicitObjectLifetimeDefault
134             | LifetimeName::Implicit
135             | LifetimeName::Underscore => true,
136
137             // It might seem surprising that `Fresh(_)` counts as
138             // *not* elided -- but this is because, as far as the code
139             // in the compiler is concerned -- `Fresh(_)` variants act
140             // equivalently to "some fresh name". They correspond to
141             // early-bound regions on an impl, in other words.
142             LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
143         }
144     }
145
146     fn is_static(&self) -> bool {
147         self == &LifetimeName::Static
148     }
149
150     pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
151         match *self {
152             LifetimeName::Param(param_name) => {
153                 LifetimeName::Param(param_name.normalize_to_macros_2_0())
154             }
155             lifetime_name => lifetime_name,
156         }
157     }
158 }
159
160 impl fmt::Display for Lifetime {
161     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162         self.name.ident().fmt(f)
163     }
164 }
165
166 impl fmt::Debug for Lifetime {
167     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168         write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
169     }
170 }
171
172 impl Lifetime {
173     pub fn is_elided(&self) -> bool {
174         self.name.is_elided()
175     }
176
177     pub fn is_static(&self) -> bool {
178         self.name.is_static()
179     }
180 }
181
182 /// A `Path` is essentially Rust's notion of a name; for instance,
183 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
184 /// along with a bunch of supporting information.
185 #[derive(Debug, HashStable_Generic)]
186 pub struct Path<'hir> {
187     pub span: Span,
188     /// The resolution for the path.
189     pub res: Res,
190     /// The segments in the path: the things separated by `::`.
191     pub segments: &'hir [PathSegment<'hir>],
192 }
193
194 impl Path<'_> {
195     pub fn is_global(&self) -> bool {
196         !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
197     }
198 }
199
200 /// A segment of a path: an identifier, an optional lifetime, and a set of
201 /// types.
202 #[derive(Debug, HashStable_Generic)]
203 pub struct PathSegment<'hir> {
204     /// The identifier portion of this path segment.
205     #[stable_hasher(project(name))]
206     pub ident: Ident,
207     // `id` and `res` are optional. We currently only use these in save-analysis,
208     // any path segments without these will not have save-analysis info and
209     // therefore will not have 'jump to def' in IDEs, but otherwise will not be
210     // affected. (In general, we don't bother to get the defs for synthesized
211     // segments, only for segments which have come from the AST).
212     pub hir_id: Option<HirId>,
213     pub res: Option<Res>,
214
215     /// Type/lifetime parameters attached to this path. They come in
216     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
217     /// this is more than just simple syntactic sugar; the use of
218     /// parens affects the region binding rules, so we preserve the
219     /// distinction.
220     pub args: Option<&'hir GenericArgs<'hir>>,
221
222     /// Whether to infer remaining type parameters, if any.
223     /// This only applies to expression and pattern paths, and
224     /// out of those only the segments with no type parameters
225     /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
226     pub infer_args: bool,
227 }
228
229 impl<'hir> PathSegment<'hir> {
230     /// Converts an identifier to the corresponding segment.
231     pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
232         PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
233     }
234
235     pub fn invalid() -> Self {
236         Self::from_ident(Ident::invalid())
237     }
238
239     pub fn args(&self) -> &GenericArgs<'hir> {
240         if let Some(ref args) = self.args {
241             args
242         } else {
243             const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
244             DUMMY
245         }
246     }
247 }
248
249 #[derive(Encodable, Debug, HashStable_Generic)]
250 pub struct ConstArg {
251     pub value: AnonConst,
252     pub span: Span,
253 }
254
255 #[derive(Debug, HashStable_Generic)]
256 pub enum GenericArg<'hir> {
257     Lifetime(Lifetime),
258     Type(Ty<'hir>),
259     Const(ConstArg),
260 }
261
262 impl GenericArg<'_> {
263     pub fn span(&self) -> Span {
264         match self {
265             GenericArg::Lifetime(l) => l.span,
266             GenericArg::Type(t) => t.span,
267             GenericArg::Const(c) => c.span,
268         }
269     }
270
271     pub fn id(&self) -> HirId {
272         match self {
273             GenericArg::Lifetime(l) => l.hir_id,
274             GenericArg::Type(t) => t.hir_id,
275             GenericArg::Const(c) => c.value.hir_id,
276         }
277     }
278
279     pub fn is_const(&self) -> bool {
280         matches!(self, GenericArg::Const(_))
281     }
282
283     pub fn is_synthetic(&self) -> bool {
284         matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::invalid())
285     }
286
287     pub fn descr(&self) -> &'static str {
288         match self {
289             GenericArg::Lifetime(_) => "lifetime",
290             GenericArg::Type(_) => "type",
291             GenericArg::Const(_) => "constant",
292         }
293     }
294
295     pub fn to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd {
296         match self {
297             GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
298             GenericArg::Type(_) => ast::ParamKindOrd::Type,
299             GenericArg::Const(_) => {
300                 ast::ParamKindOrd::Const { unordered: feats.unordered_const_ty_params() }
301             }
302         }
303     }
304 }
305
306 #[derive(Debug, HashStable_Generic)]
307 pub struct GenericArgs<'hir> {
308     /// The generic arguments for this path segment.
309     pub args: &'hir [GenericArg<'hir>],
310     /// Bindings (equality constraints) on associated types, if present.
311     /// E.g., `Foo<A = Bar>`.
312     pub bindings: &'hir [TypeBinding<'hir>],
313     /// Were arguments written in parenthesized form `Fn(T) -> U`?
314     /// This is required mostly for pretty-printing and diagnostics,
315     /// but also for changing lifetime elision rules to be "function-like".
316     pub parenthesized: bool,
317     /// The span encompassing arguments and the surrounding brackets `<>` or `()`
318     ///       Foo<A, B, AssocTy = D>           Fn(T, U, V) -> W
319     ///          ^^^^^^^^^^^^^^^^^^^             ^^^^^^^^^
320     /// Note that this may be:
321     /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
322     /// - dummy, if this was generated while desugaring
323     pub span_ext: Span,
324 }
325
326 impl GenericArgs<'_> {
327     pub const fn none() -> Self {
328         Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
329     }
330
331     pub fn inputs(&self) -> &[Ty<'_>] {
332         if self.parenthesized {
333             for arg in self.args {
334                 match arg {
335                     GenericArg::Lifetime(_) => {}
336                     GenericArg::Type(ref ty) => {
337                         if let TyKind::Tup(ref tys) = ty.kind {
338                             return tys;
339                         }
340                         break;
341                     }
342                     GenericArg::Const(_) => {}
343                 }
344             }
345         }
346         panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
347     }
348
349     pub fn own_counts(&self) -> GenericParamCount {
350         // We could cache this as a property of `GenericParamCount`, but
351         // the aim is to refactor this away entirely eventually and the
352         // presence of this method will be a constant reminder.
353         let mut own_counts: GenericParamCount = Default::default();
354
355         for arg in self.args {
356             match arg {
357                 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
358                 GenericArg::Type(_) => own_counts.types += 1,
359                 GenericArg::Const(_) => own_counts.consts += 1,
360             };
361         }
362
363         own_counts
364     }
365
366     /// The span encompassing the text inside the surrounding brackets.
367     /// It will also include bindings if they aren't in the form `-> Ret`
368     /// Returns `None` if the span is empty (e.g. no brackets) or dummy
369     pub fn span(&self) -> Option<Span> {
370         let span_ext = self.span_ext()?;
371         Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
372     }
373
374     /// Returns span encompassing arguments and their surrounding `<>` or `()`
375     pub fn span_ext(&self) -> Option<Span> {
376         Some(self.span_ext).filter(|span| !span.is_empty())
377     }
378
379     pub fn is_empty(&self) -> bool {
380         self.args.is_empty()
381     }
382 }
383
384 /// A modifier on a bound, currently this is only used for `?Sized`, where the
385 /// modifier is `Maybe`. Negative bounds should also be handled here.
386 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
387 #[derive(HashStable_Generic)]
388 pub enum TraitBoundModifier {
389     None,
390     Maybe,
391     MaybeConst,
392 }
393
394 /// The AST represents all type param bounds as types.
395 /// `typeck::collect::compute_bounds` matches these against
396 /// the "special" built-in traits (see `middle::lang_items`) and
397 /// detects `Copy`, `Send` and `Sync`.
398 #[derive(Clone, Debug, HashStable_Generic)]
399 pub enum GenericBound<'hir> {
400     Trait(PolyTraitRef<'hir>, TraitBoundModifier),
401     // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
402     LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
403     Outlives(Lifetime),
404 }
405
406 impl GenericBound<'_> {
407     pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
408         match self {
409             GenericBound::Trait(data, _) => Some(&data.trait_ref),
410             _ => None,
411         }
412     }
413
414     pub fn span(&self) -> Span {
415         match self {
416             GenericBound::Trait(t, ..) => t.span,
417             GenericBound::LangItemTrait(_, span, ..) => *span,
418             GenericBound::Outlives(l) => l.span,
419         }
420     }
421 }
422
423 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
424
425 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
426 pub enum LifetimeParamKind {
427     // Indicates that the lifetime definition was explicitly declared (e.g., in
428     // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
429     Explicit,
430
431     // Indicates that the lifetime definition was synthetically added
432     // as a result of an in-band lifetime usage (e.g., in
433     // `fn foo(x: &'a u8) -> &'a u8 { x }`).
434     InBand,
435
436     // Indication that the lifetime was elided (e.g., in both cases in
437     // `fn foo(x: &u8) -> &'_ u8 { x }`).
438     Elided,
439
440     // Indication that the lifetime name was somehow in error.
441     Error,
442 }
443
444 #[derive(Debug, HashStable_Generic)]
445 pub enum GenericParamKind<'hir> {
446     /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
447     Lifetime {
448         kind: LifetimeParamKind,
449     },
450     Type {
451         default: Option<&'hir Ty<'hir>>,
452         synthetic: Option<SyntheticTyParamKind>,
453     },
454     Const {
455         ty: &'hir Ty<'hir>,
456         /// Optional default value for the const generic param
457         default: Option<AnonConst>,
458     },
459 }
460
461 #[derive(Debug, HashStable_Generic)]
462 pub struct GenericParam<'hir> {
463     pub hir_id: HirId,
464     pub name: ParamName,
465     pub bounds: GenericBounds<'hir>,
466     pub span: Span,
467     pub pure_wrt_drop: bool,
468     pub kind: GenericParamKind<'hir>,
469 }
470
471 impl GenericParam<'hir> {
472     pub fn bounds_span(&self) -> Option<Span> {
473         self.bounds.iter().fold(None, |span, bound| {
474             let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
475
476             Some(span)
477         })
478     }
479 }
480
481 #[derive(Default)]
482 pub struct GenericParamCount {
483     pub lifetimes: usize,
484     pub types: usize,
485     pub consts: usize,
486 }
487
488 /// Represents lifetimes and type parameters attached to a declaration
489 /// of a function, enum, trait, etc.
490 #[derive(Debug, HashStable_Generic)]
491 pub struct Generics<'hir> {
492     pub params: &'hir [GenericParam<'hir>],
493     pub where_clause: WhereClause<'hir>,
494     pub span: Span,
495 }
496
497 impl Generics<'hir> {
498     pub const fn empty() -> Generics<'hir> {
499         Generics {
500             params: &[],
501             where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
502             span: DUMMY_SP,
503         }
504     }
505
506     pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
507         for param in self.params {
508             if name == param.name.ident().name {
509                 return Some(param);
510             }
511         }
512         None
513     }
514
515     pub fn spans(&self) -> MultiSpan {
516         if self.params.is_empty() {
517             self.span.into()
518         } else {
519             self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
520         }
521     }
522 }
523
524 /// Synthetic type parameters are converted to another form during lowering; this allows
525 /// us to track the original form they had, and is useful for error messages.
526 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
527 #[derive(HashStable_Generic)]
528 pub enum SyntheticTyParamKind {
529     ImplTrait,
530     // Created by the `#[rustc_synthetic]` attribute.
531     FromAttr,
532 }
533
534 /// A where-clause in a definition.
535 #[derive(Debug, HashStable_Generic)]
536 pub struct WhereClause<'hir> {
537     pub predicates: &'hir [WherePredicate<'hir>],
538     // Only valid if predicates aren't empty.
539     pub span: Span,
540 }
541
542 impl WhereClause<'_> {
543     pub fn span(&self) -> Option<Span> {
544         if self.predicates.is_empty() { None } else { Some(self.span) }
545     }
546
547     /// The `WhereClause` under normal circumstances points at either the predicates or the empty
548     /// space where the `where` clause should be. Only of use for diagnostic suggestions.
549     pub fn span_for_predicates_or_empty_place(&self) -> Span {
550         self.span
551     }
552
553     /// `Span` where further predicates would be suggested, accounting for trailing commas, like
554     ///  in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
555     pub fn tail_span_for_suggestion(&self) -> Span {
556         let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
557         self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
558     }
559 }
560
561 /// A single predicate in a where-clause.
562 #[derive(Debug, HashStable_Generic)]
563 pub enum WherePredicate<'hir> {
564     /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
565     BoundPredicate(WhereBoundPredicate<'hir>),
566     /// A lifetime predicate (e.g., `'a: 'b + 'c`).
567     RegionPredicate(WhereRegionPredicate<'hir>),
568     /// An equality predicate (unsupported).
569     EqPredicate(WhereEqPredicate<'hir>),
570 }
571
572 impl WherePredicate<'_> {
573     pub fn span(&self) -> Span {
574         match self {
575             WherePredicate::BoundPredicate(p) => p.span,
576             WherePredicate::RegionPredicate(p) => p.span,
577             WherePredicate::EqPredicate(p) => p.span,
578         }
579     }
580 }
581
582 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
583 #[derive(Debug, HashStable_Generic)]
584 pub struct WhereBoundPredicate<'hir> {
585     pub span: Span,
586     /// Any generics from a `for` binding.
587     pub bound_generic_params: &'hir [GenericParam<'hir>],
588     /// The type being bounded.
589     pub bounded_ty: &'hir Ty<'hir>,
590     /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
591     pub bounds: GenericBounds<'hir>,
592 }
593
594 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
595 #[derive(Debug, HashStable_Generic)]
596 pub struct WhereRegionPredicate<'hir> {
597     pub span: Span,
598     pub lifetime: Lifetime,
599     pub bounds: GenericBounds<'hir>,
600 }
601
602 /// An equality predicate (e.g., `T = int`); currently unsupported.
603 #[derive(Debug, HashStable_Generic)]
604 pub struct WhereEqPredicate<'hir> {
605     pub hir_id: HirId,
606     pub span: Span,
607     pub lhs_ty: &'hir Ty<'hir>,
608     pub rhs_ty: &'hir Ty<'hir>,
609 }
610
611 #[derive(Default, Encodable, Debug, HashStable_Generic)]
612 pub struct ModuleItems {
613     // Use BTreeSets here so items are in the same order as in the
614     // list of all items in Crate
615     pub items: BTreeSet<ItemId>,
616     pub trait_items: BTreeSet<TraitItemId>,
617     pub impl_items: BTreeSet<ImplItemId>,
618     pub foreign_items: BTreeSet<ForeignItemId>,
619 }
620
621 /// The top-level data structure that stores the entire contents of
622 /// the crate currently being compiled.
623 ///
624 /// For more details, see the [rustc dev guide].
625 ///
626 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
627 #[derive(Debug)]
628 pub struct Crate<'hir> {
629     pub item: Mod<'hir>,
630     pub exported_macros: &'hir [MacroDef<'hir>],
631     // Attributes from non-exported macros, kept only for collecting the library feature list.
632     pub non_exported_macro_attrs: &'hir [Attribute],
633
634     // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
635     // over the ids in increasing order. In principle it should not
636     // matter what order we visit things in, but in *practice* it
637     // does, because it can affect the order in which errors are
638     // detected, which in turn can make UI tests yield
639     // slightly different results.
640     pub items: BTreeMap<ItemId, Item<'hir>>,
641
642     pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
643     pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
644     pub foreign_items: BTreeMap<ForeignItemId, ForeignItem<'hir>>,
645     pub bodies: BTreeMap<BodyId, Body<'hir>>,
646     pub trait_impls: BTreeMap<DefId, Vec<LocalDefId>>,
647
648     /// A list of the body ids written out in the order in which they
649     /// appear in the crate. If you're going to process all the bodies
650     /// in the crate, you should iterate over this list rather than the keys
651     /// of bodies.
652     pub body_ids: Vec<BodyId>,
653
654     /// A list of modules written out in the order in which they
655     /// appear in the crate. This includes the main crate module.
656     pub modules: BTreeMap<LocalDefId, ModuleItems>,
657     /// A list of proc macro HirIds, written out in the order in which
658     /// they are declared in the static array generated by proc_macro_harness.
659     pub proc_macros: Vec<HirId>,
660
661     pub trait_map: BTreeMap<HirId, Vec<TraitCandidate>>,
662
663     /// Collected attributes from HIR nodes.
664     pub attrs: BTreeMap<HirId, &'hir [Attribute]>,
665 }
666
667 impl Crate<'hir> {
668     pub fn item(&self, id: ItemId) -> &Item<'hir> {
669         &self.items[&id]
670     }
671
672     pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
673         &self.trait_items[&id]
674     }
675
676     pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
677         &self.impl_items[&id]
678     }
679
680     pub fn foreign_item(&self, id: ForeignItemId) -> &ForeignItem<'hir> {
681         &self.foreign_items[&id]
682     }
683
684     pub fn body(&self, id: BodyId) -> &Body<'hir> {
685         &self.bodies[&id]
686     }
687 }
688
689 impl Crate<'_> {
690     /// Visits all items in the crate in some deterministic (but
691     /// unspecified) order. If you just need to process every item,
692     /// but don't care about nesting, this method is the best choice.
693     ///
694     /// If you do care about nesting -- usually because your algorithm
695     /// follows lexical scoping rules -- then you want a different
696     /// approach. You should override `visit_nested_item` in your
697     /// visitor and then call `intravisit::walk_crate` instead.
698     pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
699     where
700         V: itemlikevisit::ItemLikeVisitor<'hir>,
701     {
702         for item in self.items.values() {
703             visitor.visit_item(item);
704         }
705
706         for trait_item in self.trait_items.values() {
707             visitor.visit_trait_item(trait_item);
708         }
709
710         for impl_item in self.impl_items.values() {
711             visitor.visit_impl_item(impl_item);
712         }
713
714         for foreign_item in self.foreign_items.values() {
715             visitor.visit_foreign_item(foreign_item);
716         }
717     }
718
719     /// A parallel version of `visit_all_item_likes`.
720     pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
721     where
722         V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
723     {
724         parallel!(
725             {
726                 par_for_each_in(&self.items, |(_, item)| {
727                     visitor.visit_item(item);
728                 });
729             },
730             {
731                 par_for_each_in(&self.trait_items, |(_, trait_item)| {
732                     visitor.visit_trait_item(trait_item);
733                 });
734             },
735             {
736                 par_for_each_in(&self.impl_items, |(_, impl_item)| {
737                     visitor.visit_impl_item(impl_item);
738                 });
739             },
740             {
741                 par_for_each_in(&self.foreign_items, |(_, foreign_item)| {
742                     visitor.visit_foreign_item(foreign_item);
743                 });
744             }
745         );
746     }
747 }
748
749 /// A macro definition, in this crate or imported from another.
750 ///
751 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
752 #[derive(Debug)]
753 pub struct MacroDef<'hir> {
754     pub ident: Ident,
755     pub vis: Visibility<'hir>,
756     pub def_id: LocalDefId,
757     pub span: Span,
758     pub ast: ast::MacroDef,
759 }
760
761 impl MacroDef<'_> {
762     #[inline]
763     pub fn hir_id(&self) -> HirId {
764         HirId::make_owner(self.def_id)
765     }
766 }
767
768 /// A block of statements `{ .. }`, which may have a label (in this case the
769 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
770 /// the `rules` being anything but `DefaultBlock`.
771 #[derive(Debug, HashStable_Generic)]
772 pub struct Block<'hir> {
773     /// Statements in a block.
774     pub stmts: &'hir [Stmt<'hir>],
775     /// An expression at the end of the block
776     /// without a semicolon, if any.
777     pub expr: Option<&'hir Expr<'hir>>,
778     #[stable_hasher(ignore)]
779     pub hir_id: HirId,
780     /// Distinguishes between `unsafe { ... }` and `{ ... }`.
781     pub rules: BlockCheckMode,
782     pub span: Span,
783     /// If true, then there may exist `break 'a` values that aim to
784     /// break out of this block early.
785     /// Used by `'label: {}` blocks and by `try {}` blocks.
786     pub targeted_by_break: bool,
787 }
788
789 #[derive(Debug, HashStable_Generic)]
790 pub struct Pat<'hir> {
791     #[stable_hasher(ignore)]
792     pub hir_id: HirId,
793     pub kind: PatKind<'hir>,
794     pub span: Span,
795     // Whether to use default binding modes.
796     // At present, this is false only for destructuring assignment.
797     pub default_binding_modes: bool,
798 }
799
800 impl<'hir> Pat<'hir> {
801     // FIXME(#19596) this is a workaround, but there should be a better way
802     fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
803         if !it(self) {
804             return false;
805         }
806
807         use PatKind::*;
808         match &self.kind {
809             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
810             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
811             Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
812             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
813             Slice(before, slice, after) => {
814                 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
815             }
816         }
817     }
818
819     /// Walk the pattern in left-to-right order,
820     /// short circuiting (with `.all(..)`) if `false` is returned.
821     ///
822     /// Note that when visiting e.g. `Tuple(ps)`,
823     /// if visiting `ps[0]` returns `false`,
824     /// then `ps[1]` will not be visited.
825     pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
826         self.walk_short_(&mut it)
827     }
828
829     // FIXME(#19596) this is a workaround, but there should be a better way
830     fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
831         if !it(self) {
832             return;
833         }
834
835         use PatKind::*;
836         match &self.kind {
837             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
838             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
839             Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
840             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
841             Slice(before, slice, after) => {
842                 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
843             }
844         }
845     }
846
847     /// Walk the pattern in left-to-right order.
848     ///
849     /// If `it(pat)` returns `false`, the children are not visited.
850     pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
851         self.walk_(&mut it)
852     }
853
854     /// Walk the pattern in left-to-right order.
855     ///
856     /// If you always want to recurse, prefer this method over `walk`.
857     pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
858         self.walk(|p| {
859             it(p);
860             true
861         })
862     }
863 }
864
865 /// A single field in a struct pattern.
866 ///
867 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
868 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
869 /// except `is_shorthand` is true.
870 #[derive(Debug, HashStable_Generic)]
871 pub struct PatField<'hir> {
872     #[stable_hasher(ignore)]
873     pub hir_id: HirId,
874     /// The identifier for the field.
875     #[stable_hasher(project(name))]
876     pub ident: Ident,
877     /// The pattern the field is destructured to.
878     pub pat: &'hir Pat<'hir>,
879     pub is_shorthand: bool,
880     pub span: Span,
881 }
882
883 /// Explicit binding annotations given in the HIR for a binding. Note
884 /// that this is not the final binding *mode* that we infer after type
885 /// inference.
886 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
887 pub enum BindingAnnotation {
888     /// No binding annotation given: this means that the final binding mode
889     /// will depend on whether we have skipped through a `&` reference
890     /// when matching. For example, the `x` in `Some(x)` will have binding
891     /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
892     /// ultimately be inferred to be by-reference.
893     ///
894     /// Note that implicit reference skipping is not implemented yet (#42640).
895     Unannotated,
896
897     /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
898     Mutable,
899
900     /// Annotated as `ref`, like `ref x`
901     Ref,
902
903     /// Annotated as `ref mut x`.
904     RefMut,
905 }
906
907 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
908 pub enum RangeEnd {
909     Included,
910     Excluded,
911 }
912
913 impl fmt::Display for RangeEnd {
914     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
915         f.write_str(match self {
916             RangeEnd::Included => "..=",
917             RangeEnd::Excluded => "..",
918         })
919     }
920 }
921
922 #[derive(Debug, HashStable_Generic)]
923 pub enum PatKind<'hir> {
924     /// Represents a wildcard pattern (i.e., `_`).
925     Wild,
926
927     /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
928     /// The `HirId` is the canonical ID for the variable being bound,
929     /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
930     /// which is the pattern ID of the first `x`.
931     Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
932
933     /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
934     /// The `bool` is `true` in the presence of a `..`.
935     Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
936
937     /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
938     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
939     /// `0 <= position <= subpats.len()`
940     TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
941
942     /// An or-pattern `A | B | C`.
943     /// Invariant: `pats.len() >= 2`.
944     Or(&'hir [&'hir Pat<'hir>]),
945
946     /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
947     Path(QPath<'hir>),
948
949     /// A tuple pattern (e.g., `(a, b)`).
950     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
951     /// `0 <= position <= subpats.len()`
952     Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
953
954     /// A `box` pattern.
955     Box(&'hir Pat<'hir>),
956
957     /// A reference pattern (e.g., `&mut (a, b)`).
958     Ref(&'hir Pat<'hir>, Mutability),
959
960     /// A literal.
961     Lit(&'hir Expr<'hir>),
962
963     /// A range pattern (e.g., `1..=2` or `1..2`).
964     Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
965
966     /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
967     ///
968     /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
969     /// If `slice` exists, then `after` can be non-empty.
970     ///
971     /// The representation for e.g., `[a, b, .., c, d]` is:
972     /// ```
973     /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
974     /// ```
975     Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
976 }
977
978 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
979 pub enum BinOpKind {
980     /// The `+` operator (addition).
981     Add,
982     /// The `-` operator (subtraction).
983     Sub,
984     /// The `*` operator (multiplication).
985     Mul,
986     /// The `/` operator (division).
987     Div,
988     /// The `%` operator (modulus).
989     Rem,
990     /// The `&&` operator (logical and).
991     And,
992     /// The `||` operator (logical or).
993     Or,
994     /// The `^` operator (bitwise xor).
995     BitXor,
996     /// The `&` operator (bitwise and).
997     BitAnd,
998     /// The `|` operator (bitwise or).
999     BitOr,
1000     /// The `<<` operator (shift left).
1001     Shl,
1002     /// The `>>` operator (shift right).
1003     Shr,
1004     /// The `==` operator (equality).
1005     Eq,
1006     /// The `<` operator (less than).
1007     Lt,
1008     /// The `<=` operator (less than or equal to).
1009     Le,
1010     /// The `!=` operator (not equal to).
1011     Ne,
1012     /// The `>=` operator (greater than or equal to).
1013     Ge,
1014     /// The `>` operator (greater than).
1015     Gt,
1016 }
1017
1018 impl BinOpKind {
1019     pub fn as_str(self) -> &'static str {
1020         match self {
1021             BinOpKind::Add => "+",
1022             BinOpKind::Sub => "-",
1023             BinOpKind::Mul => "*",
1024             BinOpKind::Div => "/",
1025             BinOpKind::Rem => "%",
1026             BinOpKind::And => "&&",
1027             BinOpKind::Or => "||",
1028             BinOpKind::BitXor => "^",
1029             BinOpKind::BitAnd => "&",
1030             BinOpKind::BitOr => "|",
1031             BinOpKind::Shl => "<<",
1032             BinOpKind::Shr => ">>",
1033             BinOpKind::Eq => "==",
1034             BinOpKind::Lt => "<",
1035             BinOpKind::Le => "<=",
1036             BinOpKind::Ne => "!=",
1037             BinOpKind::Ge => ">=",
1038             BinOpKind::Gt => ">",
1039         }
1040     }
1041
1042     pub fn is_lazy(self) -> bool {
1043         matches!(self, BinOpKind::And | BinOpKind::Or)
1044     }
1045
1046     pub fn is_shift(self) -> bool {
1047         matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1048     }
1049
1050     pub fn is_comparison(self) -> bool {
1051         match self {
1052             BinOpKind::Eq
1053             | BinOpKind::Lt
1054             | BinOpKind::Le
1055             | BinOpKind::Ne
1056             | BinOpKind::Gt
1057             | BinOpKind::Ge => true,
1058             BinOpKind::And
1059             | BinOpKind::Or
1060             | BinOpKind::Add
1061             | BinOpKind::Sub
1062             | BinOpKind::Mul
1063             | BinOpKind::Div
1064             | BinOpKind::Rem
1065             | BinOpKind::BitXor
1066             | BinOpKind::BitAnd
1067             | BinOpKind::BitOr
1068             | BinOpKind::Shl
1069             | BinOpKind::Shr => false,
1070         }
1071     }
1072
1073     /// Returns `true` if the binary operator takes its arguments by value.
1074     pub fn is_by_value(self) -> bool {
1075         !self.is_comparison()
1076     }
1077 }
1078
1079 impl Into<ast::BinOpKind> for BinOpKind {
1080     fn into(self) -> ast::BinOpKind {
1081         match self {
1082             BinOpKind::Add => ast::BinOpKind::Add,
1083             BinOpKind::Sub => ast::BinOpKind::Sub,
1084             BinOpKind::Mul => ast::BinOpKind::Mul,
1085             BinOpKind::Div => ast::BinOpKind::Div,
1086             BinOpKind::Rem => ast::BinOpKind::Rem,
1087             BinOpKind::And => ast::BinOpKind::And,
1088             BinOpKind::Or => ast::BinOpKind::Or,
1089             BinOpKind::BitXor => ast::BinOpKind::BitXor,
1090             BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1091             BinOpKind::BitOr => ast::BinOpKind::BitOr,
1092             BinOpKind::Shl => ast::BinOpKind::Shl,
1093             BinOpKind::Shr => ast::BinOpKind::Shr,
1094             BinOpKind::Eq => ast::BinOpKind::Eq,
1095             BinOpKind::Lt => ast::BinOpKind::Lt,
1096             BinOpKind::Le => ast::BinOpKind::Le,
1097             BinOpKind::Ne => ast::BinOpKind::Ne,
1098             BinOpKind::Ge => ast::BinOpKind::Ge,
1099             BinOpKind::Gt => ast::BinOpKind::Gt,
1100         }
1101     }
1102 }
1103
1104 pub type BinOp = Spanned<BinOpKind>;
1105
1106 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1107 pub enum UnOp {
1108     /// The `*` operator (deferencing).
1109     Deref,
1110     /// The `!` operator (logical negation).
1111     Not,
1112     /// The `-` operator (negation).
1113     Neg,
1114 }
1115
1116 impl UnOp {
1117     pub fn as_str(self) -> &'static str {
1118         match self {
1119             Self::Deref => "*",
1120             Self::Not => "!",
1121             Self::Neg => "-",
1122         }
1123     }
1124
1125     /// Returns `true` if the unary operator takes its argument by value.
1126     pub fn is_by_value(self) -> bool {
1127         matches!(self, Self::Neg | Self::Not)
1128     }
1129 }
1130
1131 /// A statement.
1132 #[derive(Debug, HashStable_Generic)]
1133 pub struct Stmt<'hir> {
1134     pub hir_id: HirId,
1135     pub kind: StmtKind<'hir>,
1136     pub span: Span,
1137 }
1138
1139 /// The contents of a statement.
1140 #[derive(Debug, HashStable_Generic)]
1141 pub enum StmtKind<'hir> {
1142     /// A local (`let`) binding.
1143     Local(&'hir Local<'hir>),
1144
1145     /// An item binding.
1146     Item(ItemId),
1147
1148     /// An expression without a trailing semi-colon (must have unit type).
1149     Expr(&'hir Expr<'hir>),
1150
1151     /// An expression with a trailing semi-colon (may have any type).
1152     Semi(&'hir Expr<'hir>),
1153 }
1154
1155 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1156 #[derive(Debug, HashStable_Generic)]
1157 pub struct Local<'hir> {
1158     pub pat: &'hir Pat<'hir>,
1159     /// Type annotation, if any (otherwise the type will be inferred).
1160     pub ty: Option<&'hir Ty<'hir>>,
1161     /// Initializer expression to set the value, if any.
1162     pub init: Option<&'hir Expr<'hir>>,
1163     pub hir_id: HirId,
1164     pub span: Span,
1165     /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1166     /// desugaring. Otherwise will be `Normal`.
1167     pub source: LocalSource,
1168 }
1169
1170 /// Represents a single arm of a `match` expression, e.g.
1171 /// `<pat> (if <guard>) => <body>`.
1172 #[derive(Debug, HashStable_Generic)]
1173 pub struct Arm<'hir> {
1174     #[stable_hasher(ignore)]
1175     pub hir_id: HirId,
1176     pub span: Span,
1177     /// If this pattern and the optional guard matches, then `body` is evaluated.
1178     pub pat: &'hir Pat<'hir>,
1179     /// Optional guard clause.
1180     pub guard: Option<Guard<'hir>>,
1181     /// The expression the arm evaluates to if this arm matches.
1182     pub body: &'hir Expr<'hir>,
1183 }
1184
1185 #[derive(Debug, HashStable_Generic)]
1186 pub enum Guard<'hir> {
1187     If(&'hir Expr<'hir>),
1188     IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1189 }
1190
1191 #[derive(Debug, HashStable_Generic)]
1192 pub struct ExprField<'hir> {
1193     #[stable_hasher(ignore)]
1194     pub hir_id: HirId,
1195     pub ident: Ident,
1196     pub expr: &'hir Expr<'hir>,
1197     pub span: Span,
1198     pub is_shorthand: bool,
1199 }
1200
1201 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1202 pub enum BlockCheckMode {
1203     DefaultBlock,
1204     UnsafeBlock(UnsafeSource),
1205     PushUnsafeBlock(UnsafeSource),
1206     PopUnsafeBlock(UnsafeSource),
1207 }
1208
1209 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1210 pub enum UnsafeSource {
1211     CompilerGenerated,
1212     UserProvided,
1213 }
1214
1215 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1216 pub struct BodyId {
1217     pub hir_id: HirId,
1218 }
1219
1220 /// The body of a function, closure, or constant value. In the case of
1221 /// a function, the body contains not only the function body itself
1222 /// (which is an expression), but also the argument patterns, since
1223 /// those are something that the caller doesn't really care about.
1224 ///
1225 /// # Examples
1226 ///
1227 /// ```
1228 /// fn foo((x, y): (u32, u32)) -> u32 {
1229 ///     x + y
1230 /// }
1231 /// ```
1232 ///
1233 /// Here, the `Body` associated with `foo()` would contain:
1234 ///
1235 /// - an `params` array containing the `(x, y)` pattern
1236 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1237 /// - `generator_kind` would be `None`
1238 ///
1239 /// All bodies have an **owner**, which can be accessed via the HIR
1240 /// map using `body_owner_def_id()`.
1241 #[derive(Debug)]
1242 pub struct Body<'hir> {
1243     pub params: &'hir [Param<'hir>],
1244     pub value: Expr<'hir>,
1245     pub generator_kind: Option<GeneratorKind>,
1246 }
1247
1248 impl Body<'hir> {
1249     pub fn id(&self) -> BodyId {
1250         BodyId { hir_id: self.value.hir_id }
1251     }
1252
1253     pub fn generator_kind(&self) -> Option<GeneratorKind> {
1254         self.generator_kind
1255     }
1256 }
1257
1258 /// The type of source expression that caused this generator to be created.
1259 #[derive(
1260     Clone,
1261     PartialEq,
1262     PartialOrd,
1263     Eq,
1264     Hash,
1265     HashStable_Generic,
1266     Encodable,
1267     Decodable,
1268     Debug,
1269     Copy
1270 )]
1271 pub enum GeneratorKind {
1272     /// An explicit `async` block or the body of an async function.
1273     Async(AsyncGeneratorKind),
1274
1275     /// A generator literal created via a `yield` inside a closure.
1276     Gen,
1277 }
1278
1279 impl fmt::Display for GeneratorKind {
1280     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1281         match self {
1282             GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1283             GeneratorKind::Gen => f.write_str("generator"),
1284         }
1285     }
1286 }
1287
1288 impl GeneratorKind {
1289     pub fn descr(&self) -> &'static str {
1290         match self {
1291             GeneratorKind::Async(ask) => ask.descr(),
1292             GeneratorKind::Gen => "generator",
1293         }
1294     }
1295 }
1296
1297 /// In the case of a generator created as part of an async construct,
1298 /// which kind of async construct caused it to be created?
1299 ///
1300 /// This helps error messages but is also used to drive coercions in
1301 /// type-checking (see #60424).
1302 #[derive(
1303     Clone,
1304     PartialEq,
1305     PartialOrd,
1306     Eq,
1307     Hash,
1308     HashStable_Generic,
1309     Encodable,
1310     Decodable,
1311     Debug,
1312     Copy
1313 )]
1314 pub enum AsyncGeneratorKind {
1315     /// An explicit `async` block written by the user.
1316     Block,
1317
1318     /// An explicit `async` block written by the user.
1319     Closure,
1320
1321     /// The `async` block generated as the body of an async function.
1322     Fn,
1323 }
1324
1325 impl fmt::Display for AsyncGeneratorKind {
1326     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1327         f.write_str(match self {
1328             AsyncGeneratorKind::Block => "`async` block",
1329             AsyncGeneratorKind::Closure => "`async` closure body",
1330             AsyncGeneratorKind::Fn => "`async fn` body",
1331         })
1332     }
1333 }
1334
1335 impl AsyncGeneratorKind {
1336     pub fn descr(&self) -> &'static str {
1337         match self {
1338             AsyncGeneratorKind::Block => "`async` block",
1339             AsyncGeneratorKind::Closure => "`async` closure body",
1340             AsyncGeneratorKind::Fn => "`async fn` body",
1341         }
1342     }
1343 }
1344
1345 #[derive(Copy, Clone, Debug)]
1346 pub enum BodyOwnerKind {
1347     /// Functions and methods.
1348     Fn,
1349
1350     /// Closures
1351     Closure,
1352
1353     /// Constants and associated constants.
1354     Const,
1355
1356     /// Initializer of a `static` item.
1357     Static(Mutability),
1358 }
1359
1360 impl BodyOwnerKind {
1361     pub fn is_fn_or_closure(self) -> bool {
1362         match self {
1363             BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1364             BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1365         }
1366     }
1367 }
1368
1369 /// The kind of an item that requires const-checking.
1370 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1371 pub enum ConstContext {
1372     /// A `const fn`.
1373     ConstFn,
1374
1375     /// A `static` or `static mut`.
1376     Static(Mutability),
1377
1378     /// A `const`, associated `const`, or other const context.
1379     ///
1380     /// Other contexts include:
1381     /// - Array length expressions
1382     /// - Enum discriminants
1383     /// - Const generics
1384     ///
1385     /// For the most part, other contexts are treated just like a regular `const`, so they are
1386     /// lumped into the same category.
1387     Const,
1388 }
1389
1390 impl ConstContext {
1391     /// A description of this const context that can appear between backticks in an error message.
1392     ///
1393     /// E.g. `const` or `static mut`.
1394     pub fn keyword_name(self) -> &'static str {
1395         match self {
1396             Self::Const => "const",
1397             Self::Static(Mutability::Not) => "static",
1398             Self::Static(Mutability::Mut) => "static mut",
1399             Self::ConstFn => "const fn",
1400         }
1401     }
1402 }
1403
1404 /// A colloquial, trivially pluralizable description of this const context for use in error
1405 /// messages.
1406 impl fmt::Display for ConstContext {
1407     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1408         match *self {
1409             Self::Const => write!(f, "constant"),
1410             Self::Static(_) => write!(f, "static"),
1411             Self::ConstFn => write!(f, "constant function"),
1412         }
1413     }
1414 }
1415
1416 /// A literal.
1417 pub type Lit = Spanned<LitKind>;
1418
1419 /// A constant (expression) that's not an item or associated item,
1420 /// but needs its own `DefId` for type-checking, const-eval, etc.
1421 /// These are usually found nested inside types (e.g., array lengths)
1422 /// or expressions (e.g., repeat counts), and also used to define
1423 /// explicit discriminant values for enum variants.
1424 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1425 pub struct AnonConst {
1426     pub hir_id: HirId,
1427     pub body: BodyId,
1428 }
1429
1430 /// An expression.
1431 #[derive(Debug)]
1432 pub struct Expr<'hir> {
1433     pub hir_id: HirId,
1434     pub kind: ExprKind<'hir>,
1435     pub span: Span,
1436 }
1437
1438 impl Expr<'_> {
1439     pub fn precedence(&self) -> ExprPrecedence {
1440         match self.kind {
1441             ExprKind::Box(_) => ExprPrecedence::Box,
1442             ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1443             ExprKind::Array(_) => ExprPrecedence::Array,
1444             ExprKind::Call(..) => ExprPrecedence::Call,
1445             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1446             ExprKind::Tup(_) => ExprPrecedence::Tup,
1447             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1448             ExprKind::Unary(..) => ExprPrecedence::Unary,
1449             ExprKind::Lit(_) => ExprPrecedence::Lit,
1450             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1451             ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1452             ExprKind::If(..) => ExprPrecedence::If,
1453             ExprKind::Loop(..) => ExprPrecedence::Loop,
1454             ExprKind::Match(..) => ExprPrecedence::Match,
1455             ExprKind::Closure(..) => ExprPrecedence::Closure,
1456             ExprKind::Block(..) => ExprPrecedence::Block,
1457             ExprKind::Assign(..) => ExprPrecedence::Assign,
1458             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1459             ExprKind::Field(..) => ExprPrecedence::Field,
1460             ExprKind::Index(..) => ExprPrecedence::Index,
1461             ExprKind::Path(..) => ExprPrecedence::Path,
1462             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1463             ExprKind::Break(..) => ExprPrecedence::Break,
1464             ExprKind::Continue(..) => ExprPrecedence::Continue,
1465             ExprKind::Ret(..) => ExprPrecedence::Ret,
1466             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1467             ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1468             ExprKind::Struct(..) => ExprPrecedence::Struct,
1469             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1470             ExprKind::Yield(..) => ExprPrecedence::Yield,
1471             ExprKind::Err => ExprPrecedence::Err,
1472         }
1473     }
1474
1475     // Whether this looks like a place expr, without checking for deref
1476     // adjustments.
1477     // This will return `true` in some potentially surprising cases such as
1478     // `CONSTANT.field`.
1479     pub fn is_syntactic_place_expr(&self) -> bool {
1480         self.is_place_expr(|_| true)
1481     }
1482
1483     /// Whether this is a place expression.
1484     ///
1485     /// `allow_projections_from` should return `true` if indexing a field or index expression based
1486     /// on the given expression should be considered a place expression.
1487     pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1488         match self.kind {
1489             ExprKind::Path(QPath::Resolved(_, ref path)) => {
1490                 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1491             }
1492
1493             // Type ascription inherits its place expression kind from its
1494             // operand. See:
1495             // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1496             ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1497
1498             ExprKind::Unary(UnOp::Deref, _) => true,
1499
1500             ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1501                 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1502             }
1503
1504             // Lang item paths cannot currently be local variables or statics.
1505             ExprKind::Path(QPath::LangItem(..)) => false,
1506
1507             // Partially qualified paths in expressions can only legally
1508             // refer to associated items which are always rvalues.
1509             ExprKind::Path(QPath::TypeRelative(..))
1510             | ExprKind::Call(..)
1511             | ExprKind::MethodCall(..)
1512             | ExprKind::Struct(..)
1513             | ExprKind::Tup(..)
1514             | ExprKind::If(..)
1515             | ExprKind::Match(..)
1516             | ExprKind::Closure(..)
1517             | ExprKind::Block(..)
1518             | ExprKind::Repeat(..)
1519             | ExprKind::Array(..)
1520             | ExprKind::Break(..)
1521             | ExprKind::Continue(..)
1522             | ExprKind::Ret(..)
1523             | ExprKind::Loop(..)
1524             | ExprKind::Assign(..)
1525             | ExprKind::InlineAsm(..)
1526             | ExprKind::LlvmInlineAsm(..)
1527             | ExprKind::AssignOp(..)
1528             | ExprKind::Lit(_)
1529             | ExprKind::ConstBlock(..)
1530             | ExprKind::Unary(..)
1531             | ExprKind::Box(..)
1532             | ExprKind::AddrOf(..)
1533             | ExprKind::Binary(..)
1534             | ExprKind::Yield(..)
1535             | ExprKind::Cast(..)
1536             | ExprKind::DropTemps(..)
1537             | ExprKind::Err => false,
1538         }
1539     }
1540
1541     /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1542     /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1543     /// silent, only signaling the ownership system. By doing this, suggestions that check the
1544     /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1545     /// beyond remembering to call this function before doing analysis on it.
1546     pub fn peel_drop_temps(&self) -> &Self {
1547         let mut expr = self;
1548         while let ExprKind::DropTemps(inner) = &expr.kind {
1549             expr = inner;
1550         }
1551         expr
1552     }
1553
1554     pub fn peel_blocks(&self) -> &Self {
1555         let mut expr = self;
1556         while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1557             expr = inner;
1558         }
1559         expr
1560     }
1561
1562     pub fn can_have_side_effects(&self) -> bool {
1563         match self.peel_drop_temps().kind {
1564             ExprKind::Path(_) | ExprKind::Lit(_) => false,
1565             ExprKind::Type(base, _)
1566             | ExprKind::Unary(_, base)
1567             | ExprKind::Field(base, _)
1568             | ExprKind::Index(base, _)
1569             | ExprKind::AddrOf(.., base)
1570             | ExprKind::Cast(base, _) => {
1571                 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1572                 // method exclusively for diagnostics and there's a *cultural* pressure against
1573                 // them being used only for its side-effects.
1574                 base.can_have_side_effects()
1575             }
1576             ExprKind::Struct(_, fields, init) => fields
1577                 .iter()
1578                 .map(|field| field.expr)
1579                 .chain(init.into_iter())
1580                 .all(|e| e.can_have_side_effects()),
1581
1582             ExprKind::Array(args)
1583             | ExprKind::Tup(args)
1584             | ExprKind::Call(
1585                 Expr {
1586                     kind:
1587                         ExprKind::Path(QPath::Resolved(
1588                             None,
1589                             Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1590                         )),
1591                     ..
1592                 },
1593                 args,
1594             ) => args.iter().all(|arg| arg.can_have_side_effects()),
1595             ExprKind::If(..)
1596             | ExprKind::Match(..)
1597             | ExprKind::MethodCall(..)
1598             | ExprKind::Call(..)
1599             | ExprKind::Closure(..)
1600             | ExprKind::Block(..)
1601             | ExprKind::Repeat(..)
1602             | ExprKind::Break(..)
1603             | ExprKind::Continue(..)
1604             | ExprKind::Ret(..)
1605             | ExprKind::Loop(..)
1606             | ExprKind::Assign(..)
1607             | ExprKind::InlineAsm(..)
1608             | ExprKind::LlvmInlineAsm(..)
1609             | ExprKind::AssignOp(..)
1610             | ExprKind::ConstBlock(..)
1611             | ExprKind::Box(..)
1612             | ExprKind::Binary(..)
1613             | ExprKind::Yield(..)
1614             | ExprKind::DropTemps(..)
1615             | ExprKind::Err => true,
1616         }
1617     }
1618 }
1619
1620 /// Checks if the specified expression is a built-in range literal.
1621 /// (See: `LoweringContext::lower_expr()`).
1622 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1623     match expr.kind {
1624         // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1625         ExprKind::Struct(ref qpath, _, _) => matches!(
1626             **qpath,
1627             QPath::LangItem(
1628                 LangItem::Range
1629                     | LangItem::RangeTo
1630                     | LangItem::RangeFrom
1631                     | LangItem::RangeFull
1632                     | LangItem::RangeToInclusive,
1633                 _,
1634             )
1635         ),
1636
1637         // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1638         ExprKind::Call(ref func, _) => {
1639             matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1640         }
1641
1642         _ => false,
1643     }
1644 }
1645
1646 #[derive(Debug, HashStable_Generic)]
1647 pub enum ExprKind<'hir> {
1648     /// A `box x` expression.
1649     Box(&'hir Expr<'hir>),
1650     /// Allow anonymous constants from an inline `const` block
1651     ConstBlock(AnonConst),
1652     /// An array (e.g., `[a, b, c, d]`).
1653     Array(&'hir [Expr<'hir>]),
1654     /// A function call.
1655     ///
1656     /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1657     /// and the second field is the list of arguments.
1658     /// This also represents calling the constructor of
1659     /// tuple-like ADTs such as tuple structs and enum variants.
1660     Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1661     /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1662     ///
1663     /// The `PathSegment`/`Span` represent the method name and its generic arguments
1664     /// (within the angle brackets).
1665     /// The first element of the vector of `Expr`s is the expression that evaluates
1666     /// to the object on which the method is being called on (the receiver),
1667     /// and the remaining elements are the rest of the arguments.
1668     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1669     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1670     /// The final `Span` represents the span of the function and arguments
1671     /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1672     ///
1673     /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1674     /// the `hir_id` of the `MethodCall` node itself.
1675     ///
1676     /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1677     MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1678     /// A tuple (e.g., `(a, b, c, d)`).
1679     Tup(&'hir [Expr<'hir>]),
1680     /// A binary operation (e.g., `a + b`, `a * b`).
1681     Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1682     /// A unary operation (e.g., `!x`, `*x`).
1683     Unary(UnOp, &'hir Expr<'hir>),
1684     /// A literal (e.g., `1`, `"foo"`).
1685     Lit(Lit),
1686     /// A cast (e.g., `foo as f64`).
1687     Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1688     /// A type reference (e.g., `Foo`).
1689     Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1690     /// Wraps the expression in a terminating scope.
1691     /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1692     ///
1693     /// This construct only exists to tweak the drop order in HIR lowering.
1694     /// An example of that is the desugaring of `for` loops.
1695     DropTemps(&'hir Expr<'hir>),
1696     /// An `if` block, with an optional else block.
1697     ///
1698     /// I.e., `if <expr> { <expr> } else { <expr> }`.
1699     If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1700     /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1701     ///
1702     /// I.e., `'label: loop { <block> }`.
1703     ///
1704     /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1705     Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1706     /// A `match` block, with a source that indicates whether or not it is
1707     /// the result of a desugaring, and if so, which kind.
1708     Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1709     /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1710     ///
1711     /// The `Span` is the argument block `|...|`.
1712     ///
1713     /// This may also be a generator literal or an `async block` as indicated by the
1714     /// `Option<Movability>`.
1715     Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1716     /// A block (e.g., `'label: { ... }`).
1717     Block(&'hir Block<'hir>, Option<Label>),
1718
1719     /// An assignment (e.g., `a = foo()`).
1720     Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1721     /// An assignment with an operator.
1722     ///
1723     /// E.g., `a += 1`.
1724     AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1725     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1726     Field(&'hir Expr<'hir>, Ident),
1727     /// An indexing operation (`foo[2]`).
1728     Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1729
1730     /// Path to a definition, possibly containing lifetime or type parameters.
1731     Path(QPath<'hir>),
1732
1733     /// A referencing operation (i.e., `&a` or `&mut a`).
1734     AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1735     /// A `break`, with an optional label to break.
1736     Break(Destination, Option<&'hir Expr<'hir>>),
1737     /// A `continue`, with an optional label.
1738     Continue(Destination),
1739     /// A `return`, with an optional value to be returned.
1740     Ret(Option<&'hir Expr<'hir>>),
1741
1742     /// Inline assembly (from `asm!`), with its outputs and inputs.
1743     InlineAsm(&'hir InlineAsm<'hir>),
1744     /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1745     LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1746
1747     /// A struct or struct-like variant literal expression.
1748     ///
1749     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1750     /// where `base` is the `Option<Expr>`.
1751     Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1752
1753     /// An array literal constructed from one repeated element.
1754     ///
1755     /// E.g., `[1; 5]`. The first expression is the element
1756     /// to be repeated; the second is the number of times to repeat it.
1757     Repeat(&'hir Expr<'hir>, AnonConst),
1758
1759     /// A suspension point for generators (i.e., `yield <expr>`).
1760     Yield(&'hir Expr<'hir>, YieldSource),
1761
1762     /// A placeholder for an expression that wasn't syntactically well formed in some way.
1763     Err,
1764 }
1765
1766 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1767 ///
1768 /// To resolve the path to a `DefId`, call [`qpath_res`].
1769 ///
1770 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1771 #[derive(Debug, HashStable_Generic)]
1772 pub enum QPath<'hir> {
1773     /// Path to a definition, optionally "fully-qualified" with a `Self`
1774     /// type, if the path points to an associated item in a trait.
1775     ///
1776     /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1777     /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1778     /// even though they both have the same two-segment `Clone::clone` `Path`.
1779     Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1780
1781     /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1782     /// Will be resolved by type-checking to an associated item.
1783     ///
1784     /// UFCS source paths can desugar into this, with `Vec::new` turning into
1785     /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1786     /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1787     TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1788
1789     /// Reference to a `#[lang = "foo"]` item.
1790     LangItem(LangItem, Span),
1791 }
1792
1793 impl<'hir> QPath<'hir> {
1794     /// Returns the span of this `QPath`.
1795     pub fn span(&self) -> Span {
1796         match *self {
1797             QPath::Resolved(_, path) => path.span,
1798             QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1799             QPath::LangItem(_, span) => span,
1800         }
1801     }
1802
1803     /// Returns the span of the qself of this `QPath`. For example, `()` in
1804     /// `<() as Trait>::method`.
1805     pub fn qself_span(&self) -> Span {
1806         match *self {
1807             QPath::Resolved(_, path) => path.span,
1808             QPath::TypeRelative(qself, _) => qself.span,
1809             QPath::LangItem(_, span) => span,
1810         }
1811     }
1812
1813     /// Returns the span of the last segment of this `QPath`. For example, `method` in
1814     /// `<() as Trait>::method`.
1815     pub fn last_segment_span(&self) -> Span {
1816         match *self {
1817             QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1818             QPath::TypeRelative(_, segment) => segment.ident.span,
1819             QPath::LangItem(_, span) => span,
1820         }
1821     }
1822 }
1823
1824 /// Hints at the original code for a let statement.
1825 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1826 pub enum LocalSource {
1827     /// A `match _ { .. }`.
1828     Normal,
1829     /// A desugared `for _ in _ { .. }` loop.
1830     ForLoopDesugar,
1831     /// When lowering async functions, we create locals within the `async move` so that
1832     /// all parameters are dropped after the future is polled.
1833     ///
1834     /// ```ignore (pseudo-Rust)
1835     /// async fn foo(<pattern> @ x: Type) {
1836     ///     async move {
1837     ///         let <pattern> = x;
1838     ///     }
1839     /// }
1840     /// ```
1841     AsyncFn,
1842     /// A desugared `<expr>.await`.
1843     AwaitDesugar,
1844     /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1845     /// The span is that of the `=` sign.
1846     AssignDesugar(Span),
1847 }
1848
1849 /// Hints at the original code for a `match _ { .. }`.
1850 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1851 #[derive(HashStable_Generic)]
1852 pub enum MatchSource {
1853     /// A `match _ { .. }`.
1854     Normal,
1855     /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1856     IfLetDesugar { contains_else_clause: bool },
1857     /// An `if let _ = _ => { .. }` match guard.
1858     IfLetGuardDesugar,
1859     /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1860     WhileDesugar,
1861     /// A `while let _ = _ { .. }` (which was desugared to a
1862     /// `loop { match _ { .. } }`).
1863     WhileLetDesugar,
1864     /// A desugared `for _ in _ { .. }` loop.
1865     ForLoopDesugar,
1866     /// A desugared `?` operator.
1867     TryDesugar,
1868     /// A desugared `<expr>.await`.
1869     AwaitDesugar,
1870 }
1871
1872 impl MatchSource {
1873     pub fn name(self) -> &'static str {
1874         use MatchSource::*;
1875         match self {
1876             Normal => "match",
1877             IfLetDesugar { .. } | IfLetGuardDesugar => "if",
1878             WhileDesugar | WhileLetDesugar => "while",
1879             ForLoopDesugar => "for",
1880             TryDesugar => "?",
1881             AwaitDesugar => ".await",
1882         }
1883     }
1884 }
1885
1886 /// The loop type that yielded an `ExprKind::Loop`.
1887 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1888 pub enum LoopSource {
1889     /// A `loop { .. }` loop.
1890     Loop,
1891     /// A `while _ { .. }` loop.
1892     While,
1893     /// A `while let _ = _ { .. }` loop.
1894     WhileLet,
1895     /// A `for _ in _ { .. }` loop.
1896     ForLoop,
1897 }
1898
1899 impl LoopSource {
1900     pub fn name(self) -> &'static str {
1901         match self {
1902             LoopSource::Loop => "loop",
1903             LoopSource::While | LoopSource::WhileLet => "while",
1904             LoopSource::ForLoop => "for",
1905         }
1906     }
1907 }
1908
1909 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1910 pub enum LoopIdError {
1911     OutsideLoopScope,
1912     UnlabeledCfInWhileCondition,
1913     UnresolvedLabel,
1914 }
1915
1916 impl fmt::Display for LoopIdError {
1917     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1918         f.write_str(match self {
1919             LoopIdError::OutsideLoopScope => "not inside loop scope",
1920             LoopIdError::UnlabeledCfInWhileCondition => {
1921                 "unlabeled control flow (break or continue) in while condition"
1922             }
1923             LoopIdError::UnresolvedLabel => "label not found",
1924         })
1925     }
1926 }
1927
1928 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1929 pub struct Destination {
1930     // This is `Some(_)` iff there is an explicit user-specified `label
1931     pub label: Option<Label>,
1932
1933     // These errors are caught and then reported during the diagnostics pass in
1934     // librustc_passes/loops.rs
1935     pub target_id: Result<HirId, LoopIdError>,
1936 }
1937
1938 /// The yield kind that caused an `ExprKind::Yield`.
1939 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1940 pub enum YieldSource {
1941     /// An `<expr>.await`.
1942     Await { expr: Option<HirId> },
1943     /// A plain `yield`.
1944     Yield,
1945 }
1946
1947 impl YieldSource {
1948     pub fn is_await(&self) -> bool {
1949         match self {
1950             YieldSource::Await { .. } => true,
1951             YieldSource::Yield => false,
1952         }
1953     }
1954 }
1955
1956 impl fmt::Display for YieldSource {
1957     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1958         f.write_str(match self {
1959             YieldSource::Await { .. } => "`await`",
1960             YieldSource::Yield => "`yield`",
1961         })
1962     }
1963 }
1964
1965 impl From<GeneratorKind> for YieldSource {
1966     fn from(kind: GeneratorKind) -> Self {
1967         match kind {
1968             // Guess based on the kind of the current generator.
1969             GeneratorKind::Gen => Self::Yield,
1970             GeneratorKind::Async(_) => Self::Await { expr: None },
1971         }
1972     }
1973 }
1974
1975 // N.B., if you change this, you'll probably want to change the corresponding
1976 // type structure in middle/ty.rs as well.
1977 #[derive(Debug, HashStable_Generic)]
1978 pub struct MutTy<'hir> {
1979     pub ty: &'hir Ty<'hir>,
1980     pub mutbl: Mutability,
1981 }
1982
1983 /// Represents a function's signature in a trait declaration,
1984 /// trait implementation, or a free function.
1985 #[derive(Debug, HashStable_Generic)]
1986 pub struct FnSig<'hir> {
1987     pub header: FnHeader,
1988     pub decl: &'hir FnDecl<'hir>,
1989     pub span: Span,
1990 }
1991
1992 // The bodies for items are stored "out of line", in a separate
1993 // hashmap in the `Crate`. Here we just record the hir-id of the item
1994 // so it can fetched later.
1995 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1996 pub struct TraitItemId {
1997     pub def_id: LocalDefId,
1998 }
1999
2000 impl TraitItemId {
2001     #[inline]
2002     pub fn hir_id(&self) -> HirId {
2003         // Items are always HIR owners.
2004         HirId::make_owner(self.def_id)
2005     }
2006 }
2007
2008 /// Represents an item declaration within a trait declaration,
2009 /// possibly including a default implementation. A trait item is
2010 /// either required (meaning it doesn't have an implementation, just a
2011 /// signature) or provided (meaning it has a default implementation).
2012 #[derive(Debug)]
2013 pub struct TraitItem<'hir> {
2014     pub ident: Ident,
2015     pub def_id: LocalDefId,
2016     pub generics: Generics<'hir>,
2017     pub kind: TraitItemKind<'hir>,
2018     pub span: Span,
2019 }
2020
2021 impl TraitItem<'_> {
2022     #[inline]
2023     pub fn hir_id(&self) -> HirId {
2024         // Items are always HIR owners.
2025         HirId::make_owner(self.def_id)
2026     }
2027
2028     pub fn trait_item_id(&self) -> TraitItemId {
2029         TraitItemId { def_id: self.def_id }
2030     }
2031 }
2032
2033 /// Represents a trait method's body (or just argument names).
2034 #[derive(Encodable, Debug, HashStable_Generic)]
2035 pub enum TraitFn<'hir> {
2036     /// No default body in the trait, just a signature.
2037     Required(&'hir [Ident]),
2038
2039     /// Both signature and body are provided in the trait.
2040     Provided(BodyId),
2041 }
2042
2043 /// Represents a trait method or associated constant or type
2044 #[derive(Debug, HashStable_Generic)]
2045 pub enum TraitItemKind<'hir> {
2046     /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2047     Const(&'hir Ty<'hir>, Option<BodyId>),
2048     /// An associated function with an optional body.
2049     Fn(FnSig<'hir>, TraitFn<'hir>),
2050     /// An associated type with (possibly empty) bounds and optional concrete
2051     /// type.
2052     Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2053 }
2054
2055 // The bodies for items are stored "out of line", in a separate
2056 // hashmap in the `Crate`. Here we just record the hir-id of the item
2057 // so it can fetched later.
2058 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2059 pub struct ImplItemId {
2060     pub def_id: LocalDefId,
2061 }
2062
2063 impl ImplItemId {
2064     #[inline]
2065     pub fn hir_id(&self) -> HirId {
2066         // Items are always HIR owners.
2067         HirId::make_owner(self.def_id)
2068     }
2069 }
2070
2071 /// Represents anything within an `impl` block.
2072 #[derive(Debug)]
2073 pub struct ImplItem<'hir> {
2074     pub ident: Ident,
2075     pub def_id: LocalDefId,
2076     pub vis: Visibility<'hir>,
2077     pub defaultness: Defaultness,
2078     pub generics: Generics<'hir>,
2079     pub kind: ImplItemKind<'hir>,
2080     pub span: Span,
2081 }
2082
2083 impl ImplItem<'_> {
2084     #[inline]
2085     pub fn hir_id(&self) -> HirId {
2086         // Items are always HIR owners.
2087         HirId::make_owner(self.def_id)
2088     }
2089
2090     pub fn impl_item_id(&self) -> ImplItemId {
2091         ImplItemId { def_id: self.def_id }
2092     }
2093 }
2094
2095 /// Represents various kinds of content within an `impl`.
2096 #[derive(Debug, HashStable_Generic)]
2097 pub enum ImplItemKind<'hir> {
2098     /// An associated constant of the given type, set to the constant result
2099     /// of the expression.
2100     Const(&'hir Ty<'hir>, BodyId),
2101     /// An associated function implementation with the given signature and body.
2102     Fn(FnSig<'hir>, BodyId),
2103     /// An associated type.
2104     TyAlias(&'hir Ty<'hir>),
2105 }
2106
2107 // The name of the associated type for `Fn` return types.
2108 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2109
2110 /// Bind a type to an associated type (i.e., `A = Foo`).
2111 ///
2112 /// Bindings like `A: Debug` are represented as a special type `A =
2113 /// $::Debug` that is understood by the astconv code.
2114 ///
2115 /// FIXME(alexreg): why have a separate type for the binding case,
2116 /// wouldn't it be better to make the `ty` field an enum like the
2117 /// following?
2118 ///
2119 /// ```
2120 /// enum TypeBindingKind {
2121 ///    Equals(...),
2122 ///    Binding(...),
2123 /// }
2124 /// ```
2125 #[derive(Debug, HashStable_Generic)]
2126 pub struct TypeBinding<'hir> {
2127     pub hir_id: HirId,
2128     #[stable_hasher(project(name))]
2129     pub ident: Ident,
2130     pub gen_args: &'hir GenericArgs<'hir>,
2131     pub kind: TypeBindingKind<'hir>,
2132     pub span: Span,
2133 }
2134
2135 // Represents the two kinds of type bindings.
2136 #[derive(Debug, HashStable_Generic)]
2137 pub enum TypeBindingKind<'hir> {
2138     /// E.g., `Foo<Bar: Send>`.
2139     Constraint { bounds: &'hir [GenericBound<'hir>] },
2140     /// E.g., `Foo<Bar = ()>`.
2141     Equality { ty: &'hir Ty<'hir> },
2142 }
2143
2144 impl TypeBinding<'_> {
2145     pub fn ty(&self) -> &Ty<'_> {
2146         match self.kind {
2147             TypeBindingKind::Equality { ref ty } => ty,
2148             _ => panic!("expected equality type binding for parenthesized generic args"),
2149         }
2150     }
2151 }
2152
2153 #[derive(Debug)]
2154 pub struct Ty<'hir> {
2155     pub hir_id: HirId,
2156     pub kind: TyKind<'hir>,
2157     pub span: Span,
2158 }
2159
2160 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2161 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2162 #[derive(HashStable_Generic)]
2163 pub enum PrimTy {
2164     Int(IntTy),
2165     Uint(UintTy),
2166     Float(FloatTy),
2167     Str,
2168     Bool,
2169     Char,
2170 }
2171
2172 impl PrimTy {
2173     /// All of the primitive types
2174     pub const ALL: [Self; 17] = [
2175         // any changes here should also be reflected in `PrimTy::from_name`
2176         Self::Int(IntTy::I8),
2177         Self::Int(IntTy::I16),
2178         Self::Int(IntTy::I32),
2179         Self::Int(IntTy::I64),
2180         Self::Int(IntTy::I128),
2181         Self::Int(IntTy::Isize),
2182         Self::Uint(UintTy::U8),
2183         Self::Uint(UintTy::U16),
2184         Self::Uint(UintTy::U32),
2185         Self::Uint(UintTy::U64),
2186         Self::Uint(UintTy::U128),
2187         Self::Uint(UintTy::Usize),
2188         Self::Float(FloatTy::F32),
2189         Self::Float(FloatTy::F64),
2190         Self::Bool,
2191         Self::Char,
2192         Self::Str,
2193     ];
2194
2195     /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2196     ///
2197     /// Used by clippy.
2198     pub fn name_str(self) -> &'static str {
2199         match self {
2200             PrimTy::Int(i) => i.name_str(),
2201             PrimTy::Uint(u) => u.name_str(),
2202             PrimTy::Float(f) => f.name_str(),
2203             PrimTy::Str => "str",
2204             PrimTy::Bool => "bool",
2205             PrimTy::Char => "char",
2206         }
2207     }
2208
2209     pub fn name(self) -> Symbol {
2210         match self {
2211             PrimTy::Int(i) => i.name(),
2212             PrimTy::Uint(u) => u.name(),
2213             PrimTy::Float(f) => f.name(),
2214             PrimTy::Str => sym::str,
2215             PrimTy::Bool => sym::bool,
2216             PrimTy::Char => sym::char,
2217         }
2218     }
2219
2220     /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2221     /// Returns `None` if no matching type is found.
2222     pub fn from_name(name: Symbol) -> Option<Self> {
2223         let ty = match name {
2224             // any changes here should also be reflected in `PrimTy::ALL`
2225             sym::i8 => Self::Int(IntTy::I8),
2226             sym::i16 => Self::Int(IntTy::I16),
2227             sym::i32 => Self::Int(IntTy::I32),
2228             sym::i64 => Self::Int(IntTy::I64),
2229             sym::i128 => Self::Int(IntTy::I128),
2230             sym::isize => Self::Int(IntTy::Isize),
2231             sym::u8 => Self::Uint(UintTy::U8),
2232             sym::u16 => Self::Uint(UintTy::U16),
2233             sym::u32 => Self::Uint(UintTy::U32),
2234             sym::u64 => Self::Uint(UintTy::U64),
2235             sym::u128 => Self::Uint(UintTy::U128),
2236             sym::usize => Self::Uint(UintTy::Usize),
2237             sym::f32 => Self::Float(FloatTy::F32),
2238             sym::f64 => Self::Float(FloatTy::F64),
2239             sym::bool => Self::Bool,
2240             sym::char => Self::Char,
2241             sym::str => Self::Str,
2242             _ => return None,
2243         };
2244         Some(ty)
2245     }
2246 }
2247
2248 #[derive(Debug, HashStable_Generic)]
2249 pub struct BareFnTy<'hir> {
2250     pub unsafety: Unsafety,
2251     pub abi: Abi,
2252     pub generic_params: &'hir [GenericParam<'hir>],
2253     pub decl: &'hir FnDecl<'hir>,
2254     pub param_names: &'hir [Ident],
2255 }
2256
2257 #[derive(Debug, HashStable_Generic)]
2258 pub struct OpaqueTy<'hir> {
2259     pub generics: Generics<'hir>,
2260     pub bounds: GenericBounds<'hir>,
2261     pub impl_trait_fn: Option<DefId>,
2262     pub origin: OpaqueTyOrigin,
2263 }
2264
2265 /// From whence the opaque type came.
2266 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2267 pub enum OpaqueTyOrigin {
2268     /// `-> impl Trait`
2269     FnReturn,
2270     /// `async fn`
2271     AsyncFn,
2272     /// `let _: impl Trait = ...`
2273     Binding,
2274     /// type aliases: `type Foo = impl Trait;`
2275     TyAlias,
2276     /// Impl trait consts, statics, bounds.
2277     Misc,
2278 }
2279
2280 /// The various kinds of types recognized by the compiler.
2281 #[derive(Debug, HashStable_Generic)]
2282 pub enum TyKind<'hir> {
2283     /// A variable length slice (i.e., `[T]`).
2284     Slice(&'hir Ty<'hir>),
2285     /// A fixed length array (i.e., `[T; n]`).
2286     Array(&'hir Ty<'hir>, AnonConst),
2287     /// A raw pointer (i.e., `*const T` or `*mut T`).
2288     Ptr(MutTy<'hir>),
2289     /// A reference (i.e., `&'a T` or `&'a mut T`).
2290     Rptr(Lifetime, MutTy<'hir>),
2291     /// A bare function (e.g., `fn(usize) -> bool`).
2292     BareFn(&'hir BareFnTy<'hir>),
2293     /// The never type (`!`).
2294     Never,
2295     /// A tuple (`(A, B, C, D, ...)`).
2296     Tup(&'hir [Ty<'hir>]),
2297     /// A path to a type definition (`module::module::...::Type`), or an
2298     /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2299     ///
2300     /// Type parameters may be stored in each `PathSegment`.
2301     Path(QPath<'hir>),
2302     /// A opaque type definition itself. This is currently only used for the
2303     /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2304     ///
2305     /// The generic argument list contains the lifetimes (and in the future
2306     /// possibly parameters) that are actually bound on the `impl Trait`.
2307     OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2308     /// A trait object type `Bound1 + Bound2 + Bound3`
2309     /// where `Bound` is a trait or a lifetime.
2310     TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2311     /// Unused for now.
2312     Typeof(AnonConst),
2313     /// `TyKind::Infer` means the type should be inferred instead of it having been
2314     /// specified. This can appear anywhere in a type.
2315     Infer,
2316     /// Placeholder for a type that has failed to be defined.
2317     Err,
2318 }
2319
2320 #[derive(Debug, HashStable_Generic)]
2321 pub enum InlineAsmOperand<'hir> {
2322     In {
2323         reg: InlineAsmRegOrRegClass,
2324         expr: Expr<'hir>,
2325     },
2326     Out {
2327         reg: InlineAsmRegOrRegClass,
2328         late: bool,
2329         expr: Option<Expr<'hir>>,
2330     },
2331     InOut {
2332         reg: InlineAsmRegOrRegClass,
2333         late: bool,
2334         expr: Expr<'hir>,
2335     },
2336     SplitInOut {
2337         reg: InlineAsmRegOrRegClass,
2338         late: bool,
2339         in_expr: Expr<'hir>,
2340         out_expr: Option<Expr<'hir>>,
2341     },
2342     Const {
2343         anon_const: AnonConst,
2344     },
2345     Sym {
2346         expr: Expr<'hir>,
2347     },
2348 }
2349
2350 impl<'hir> InlineAsmOperand<'hir> {
2351     pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2352         match *self {
2353             Self::In { reg, .. }
2354             | Self::Out { reg, .. }
2355             | Self::InOut { reg, .. }
2356             | Self::SplitInOut { reg, .. } => Some(reg),
2357             Self::Const { .. } | Self::Sym { .. } => None,
2358         }
2359     }
2360 }
2361
2362 #[derive(Debug, HashStable_Generic)]
2363 pub struct InlineAsm<'hir> {
2364     pub template: &'hir [InlineAsmTemplatePiece],
2365     pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2366     pub options: InlineAsmOptions,
2367     pub line_spans: &'hir [Span],
2368 }
2369
2370 #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2371 pub struct LlvmInlineAsmOutput {
2372     pub constraint: Symbol,
2373     pub is_rw: bool,
2374     pub is_indirect: bool,
2375     pub span: Span,
2376 }
2377
2378 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2379 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2380 // arena-allocated slice.
2381 #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2382 pub struct LlvmInlineAsmInner {
2383     pub asm: Symbol,
2384     pub asm_str_style: StrStyle,
2385     pub outputs: Vec<LlvmInlineAsmOutput>,
2386     pub inputs: Vec<Symbol>,
2387     pub clobbers: Vec<Symbol>,
2388     pub volatile: bool,
2389     pub alignstack: bool,
2390     pub dialect: LlvmAsmDialect,
2391 }
2392
2393 #[derive(Debug, HashStable_Generic)]
2394 pub struct LlvmInlineAsm<'hir> {
2395     pub inner: LlvmInlineAsmInner,
2396     pub outputs_exprs: &'hir [Expr<'hir>],
2397     pub inputs_exprs: &'hir [Expr<'hir>],
2398 }
2399
2400 /// Represents a parameter in a function header.
2401 #[derive(Debug, HashStable_Generic)]
2402 pub struct Param<'hir> {
2403     pub hir_id: HirId,
2404     pub pat: &'hir Pat<'hir>,
2405     pub ty_span: Span,
2406     pub span: Span,
2407 }
2408
2409 /// Represents the header (not the body) of a function declaration.
2410 #[derive(Debug, HashStable_Generic)]
2411 pub struct FnDecl<'hir> {
2412     /// The types of the function's parameters.
2413     ///
2414     /// Additional argument data is stored in the function's [body](Body::params).
2415     pub inputs: &'hir [Ty<'hir>],
2416     pub output: FnRetTy<'hir>,
2417     pub c_variadic: bool,
2418     /// Does the function have an implicit self?
2419     pub implicit_self: ImplicitSelfKind,
2420 }
2421
2422 /// Represents what type of implicit self a function has, if any.
2423 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2424 pub enum ImplicitSelfKind {
2425     /// Represents a `fn x(self);`.
2426     Imm,
2427     /// Represents a `fn x(mut self);`.
2428     Mut,
2429     /// Represents a `fn x(&self);`.
2430     ImmRef,
2431     /// Represents a `fn x(&mut self);`.
2432     MutRef,
2433     /// Represents when a function does not have a self argument or
2434     /// when a function has a `self: X` argument.
2435     None,
2436 }
2437
2438 impl ImplicitSelfKind {
2439     /// Does this represent an implicit self?
2440     pub fn has_implicit_self(&self) -> bool {
2441         !matches!(*self, ImplicitSelfKind::None)
2442     }
2443 }
2444
2445 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2446 #[derive(HashStable_Generic)]
2447 pub enum IsAsync {
2448     Async,
2449     NotAsync,
2450 }
2451
2452 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2453 pub enum Defaultness {
2454     Default { has_value: bool },
2455     Final,
2456 }
2457
2458 impl Defaultness {
2459     pub fn has_value(&self) -> bool {
2460         match *self {
2461             Defaultness::Default { has_value } => has_value,
2462             Defaultness::Final => true,
2463         }
2464     }
2465
2466     pub fn is_final(&self) -> bool {
2467         *self == Defaultness::Final
2468     }
2469
2470     pub fn is_default(&self) -> bool {
2471         matches!(*self, Defaultness::Default { .. })
2472     }
2473 }
2474
2475 #[derive(Debug, HashStable_Generic)]
2476 pub enum FnRetTy<'hir> {
2477     /// Return type is not specified.
2478     ///
2479     /// Functions default to `()` and
2480     /// closures default to inference. Span points to where return
2481     /// type would be inserted.
2482     DefaultReturn(Span),
2483     /// Everything else.
2484     Return(&'hir Ty<'hir>),
2485 }
2486
2487 impl FnRetTy<'_> {
2488     pub fn span(&self) -> Span {
2489         match *self {
2490             Self::DefaultReturn(span) => span,
2491             Self::Return(ref ty) => ty.span,
2492         }
2493     }
2494 }
2495
2496 #[derive(Encodable, Debug)]
2497 pub struct Mod<'hir> {
2498     /// A span from the first token past `{` to the last token until `}`.
2499     /// For `mod foo;`, the inner span ranges from the first token
2500     /// to the last token in the external file.
2501     pub inner: Span,
2502     pub item_ids: &'hir [ItemId],
2503 }
2504
2505 #[derive(Debug, HashStable_Generic)]
2506 pub struct EnumDef<'hir> {
2507     pub variants: &'hir [Variant<'hir>],
2508 }
2509
2510 #[derive(Debug, HashStable_Generic)]
2511 pub struct Variant<'hir> {
2512     /// Name of the variant.
2513     #[stable_hasher(project(name))]
2514     pub ident: Ident,
2515     /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2516     pub id: HirId,
2517     /// Fields and constructor id of the variant.
2518     pub data: VariantData<'hir>,
2519     /// Explicit discriminant (e.g., `Foo = 1`).
2520     pub disr_expr: Option<AnonConst>,
2521     /// Span
2522     pub span: Span,
2523 }
2524
2525 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2526 pub enum UseKind {
2527     /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2528     /// Also produced for each element of a list `use`, e.g.
2529     /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2530     Single,
2531
2532     /// Glob import, e.g., `use foo::*`.
2533     Glob,
2534
2535     /// Degenerate list import, e.g., `use foo::{a, b}` produces
2536     /// an additional `use foo::{}` for performing checks such as
2537     /// unstable feature gating. May be removed in the future.
2538     ListStem,
2539 }
2540
2541 /// References to traits in impls.
2542 ///
2543 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2544 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2545 /// trait being referred to but just a unique `HirId` that serves as a key
2546 /// within the resolution map.
2547 #[derive(Clone, Debug, HashStable_Generic)]
2548 pub struct TraitRef<'hir> {
2549     pub path: &'hir Path<'hir>,
2550     // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2551     #[stable_hasher(ignore)]
2552     pub hir_ref_id: HirId,
2553 }
2554
2555 impl TraitRef<'_> {
2556     /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2557     pub fn trait_def_id(&self) -> Option<DefId> {
2558         match self.path.res {
2559             Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2560             Res::Err => None,
2561             _ => unreachable!(),
2562         }
2563     }
2564 }
2565
2566 #[derive(Clone, Debug, HashStable_Generic)]
2567 pub struct PolyTraitRef<'hir> {
2568     /// The `'a` in `for<'a> Foo<&'a T>`.
2569     pub bound_generic_params: &'hir [GenericParam<'hir>],
2570
2571     /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2572     pub trait_ref: TraitRef<'hir>,
2573
2574     pub span: Span,
2575 }
2576
2577 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2578
2579 #[derive(Debug)]
2580 pub enum VisibilityKind<'hir> {
2581     Public,
2582     Crate(CrateSugar),
2583     Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2584     Inherited,
2585 }
2586
2587 impl VisibilityKind<'_> {
2588     pub fn is_pub(&self) -> bool {
2589         matches!(*self, VisibilityKind::Public)
2590     }
2591
2592     pub fn is_pub_restricted(&self) -> bool {
2593         match *self {
2594             VisibilityKind::Public | VisibilityKind::Inherited => false,
2595             VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2596         }
2597     }
2598 }
2599
2600 #[derive(Debug, HashStable_Generic)]
2601 pub struct FieldDef<'hir> {
2602     pub span: Span,
2603     #[stable_hasher(project(name))]
2604     pub ident: Ident,
2605     pub vis: Visibility<'hir>,
2606     pub hir_id: HirId,
2607     pub ty: &'hir Ty<'hir>,
2608 }
2609
2610 impl FieldDef<'_> {
2611     // Still necessary in couple of places
2612     pub fn is_positional(&self) -> bool {
2613         let first = self.ident.as_str().as_bytes()[0];
2614         (b'0'..=b'9').contains(&first)
2615     }
2616 }
2617
2618 /// Fields and constructor IDs of enum variants and structs.
2619 #[derive(Debug, HashStable_Generic)]
2620 pub enum VariantData<'hir> {
2621     /// A struct variant.
2622     ///
2623     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2624     Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2625     /// A tuple variant.
2626     ///
2627     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2628     Tuple(&'hir [FieldDef<'hir>], HirId),
2629     /// A unit variant.
2630     ///
2631     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2632     Unit(HirId),
2633 }
2634
2635 impl VariantData<'hir> {
2636     /// Return the fields of this variant.
2637     pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2638         match *self {
2639             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2640             _ => &[],
2641         }
2642     }
2643
2644     /// Return the `HirId` of this variant's constructor, if it has one.
2645     pub fn ctor_hir_id(&self) -> Option<HirId> {
2646         match *self {
2647             VariantData::Struct(_, _) => None,
2648             VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2649         }
2650     }
2651 }
2652
2653 // The bodies for items are stored "out of line", in a separate
2654 // hashmap in the `Crate`. Here we just record the hir-id of the item
2655 // so it can fetched later.
2656 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)]
2657 pub struct ItemId {
2658     pub def_id: LocalDefId,
2659 }
2660
2661 impl ItemId {
2662     #[inline]
2663     pub fn hir_id(&self) -> HirId {
2664         // Items are always HIR owners.
2665         HirId::make_owner(self.def_id)
2666     }
2667 }
2668
2669 /// An item
2670 ///
2671 /// The name might be a dummy name in case of anonymous items
2672 #[derive(Debug)]
2673 pub struct Item<'hir> {
2674     pub ident: Ident,
2675     pub def_id: LocalDefId,
2676     pub kind: ItemKind<'hir>,
2677     pub vis: Visibility<'hir>,
2678     pub span: Span,
2679 }
2680
2681 impl Item<'_> {
2682     #[inline]
2683     pub fn hir_id(&self) -> HirId {
2684         // Items are always HIR owners.
2685         HirId::make_owner(self.def_id)
2686     }
2687
2688     pub fn item_id(&self) -> ItemId {
2689         ItemId { def_id: self.def_id }
2690     }
2691 }
2692
2693 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2694 #[derive(Encodable, Decodable, HashStable_Generic)]
2695 pub enum Unsafety {
2696     Unsafe,
2697     Normal,
2698 }
2699
2700 impl Unsafety {
2701     pub fn prefix_str(&self) -> &'static str {
2702         match self {
2703             Self::Unsafe => "unsafe ",
2704             Self::Normal => "",
2705         }
2706     }
2707 }
2708
2709 impl fmt::Display for Unsafety {
2710     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2711         f.write_str(match *self {
2712             Self::Unsafe => "unsafe",
2713             Self::Normal => "normal",
2714         })
2715     }
2716 }
2717
2718 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2719 #[derive(Encodable, Decodable, HashStable_Generic)]
2720 pub enum Constness {
2721     Const,
2722     NotConst,
2723 }
2724
2725 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2726 pub struct FnHeader {
2727     pub unsafety: Unsafety,
2728     pub constness: Constness,
2729     pub asyncness: IsAsync,
2730     pub abi: Abi,
2731 }
2732
2733 impl FnHeader {
2734     pub fn is_const(&self) -> bool {
2735         matches!(&self.constness, Constness::Const)
2736     }
2737 }
2738
2739 #[derive(Debug, HashStable_Generic)]
2740 pub enum ItemKind<'hir> {
2741     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2742     ///
2743     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2744     ExternCrate(Option<Symbol>),
2745
2746     /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2747     ///
2748     /// or just
2749     ///
2750     /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2751     Use(&'hir Path<'hir>, UseKind),
2752
2753     /// A `static` item.
2754     Static(&'hir Ty<'hir>, Mutability, BodyId),
2755     /// A `const` item.
2756     Const(&'hir Ty<'hir>, BodyId),
2757     /// A function declaration.
2758     Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2759     /// A module.
2760     Mod(Mod<'hir>),
2761     /// An external module, e.g. `extern { .. }`.
2762     ForeignMod { abi: Abi, items: &'hir [ForeignItemRef<'hir>] },
2763     /// Module-level inline assembly (from `global_asm!`).
2764     GlobalAsm(&'hir InlineAsm<'hir>),
2765     /// A type alias, e.g., `type Foo = Bar<u8>`.
2766     TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2767     /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2768     OpaqueTy(OpaqueTy<'hir>),
2769     /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2770     Enum(EnumDef<'hir>, Generics<'hir>),
2771     /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2772     Struct(VariantData<'hir>, Generics<'hir>),
2773     /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2774     Union(VariantData<'hir>, Generics<'hir>),
2775     /// A trait definition.
2776     Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2777     /// A trait alias.
2778     TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2779
2780     /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2781     Impl(Impl<'hir>),
2782 }
2783
2784 #[derive(Debug, HashStable_Generic)]
2785 pub struct Impl<'hir> {
2786     pub unsafety: Unsafety,
2787     pub polarity: ImplPolarity,
2788     pub defaultness: Defaultness,
2789     // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2790     // decoding as `Span`s cannot be decoded when a `Session` is not available.
2791     pub defaultness_span: Option<Span>,
2792     pub constness: Constness,
2793     pub generics: Generics<'hir>,
2794
2795     /// The trait being implemented, if any.
2796     pub of_trait: Option<TraitRef<'hir>>,
2797
2798     pub self_ty: &'hir Ty<'hir>,
2799     pub items: &'hir [ImplItemRef<'hir>],
2800 }
2801
2802 impl ItemKind<'_> {
2803     pub fn generics(&self) -> Option<&Generics<'_>> {
2804         Some(match *self {
2805             ItemKind::Fn(_, ref generics, _)
2806             | ItemKind::TyAlias(_, ref generics)
2807             | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2808             | ItemKind::Enum(_, ref generics)
2809             | ItemKind::Struct(_, ref generics)
2810             | ItemKind::Union(_, ref generics)
2811             | ItemKind::Trait(_, _, ref generics, _, _)
2812             | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2813             _ => return None,
2814         })
2815     }
2816 }
2817
2818 /// A reference from an trait to one of its associated items. This
2819 /// contains the item's id, naturally, but also the item's name and
2820 /// some other high-level details (like whether it is an associated
2821 /// type or method, and whether it is public). This allows other
2822 /// passes to find the impl they want without loading the ID (which
2823 /// means fewer edges in the incremental compilation graph).
2824 #[derive(Encodable, Debug, HashStable_Generic)]
2825 pub struct TraitItemRef {
2826     pub id: TraitItemId,
2827     #[stable_hasher(project(name))]
2828     pub ident: Ident,
2829     pub kind: AssocItemKind,
2830     pub span: Span,
2831     pub defaultness: Defaultness,
2832 }
2833
2834 /// A reference from an impl to one of its associated items. This
2835 /// contains the item's ID, naturally, but also the item's name and
2836 /// some other high-level details (like whether it is an associated
2837 /// type or method, and whether it is public). This allows other
2838 /// passes to find the impl they want without loading the ID (which
2839 /// means fewer edges in the incremental compilation graph).
2840 #[derive(Debug, HashStable_Generic)]
2841 pub struct ImplItemRef<'hir> {
2842     pub id: ImplItemId,
2843     #[stable_hasher(project(name))]
2844     pub ident: Ident,
2845     pub kind: AssocItemKind,
2846     pub span: Span,
2847     pub vis: Visibility<'hir>,
2848     pub defaultness: Defaultness,
2849 }
2850
2851 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2852 pub enum AssocItemKind {
2853     Const,
2854     Fn { has_self: bool },
2855     Type,
2856 }
2857
2858 // The bodies for items are stored "out of line", in a separate
2859 // hashmap in the `Crate`. Here we just record the hir-id of the item
2860 // so it can fetched later.
2861 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2862 pub struct ForeignItemId {
2863     pub def_id: LocalDefId,
2864 }
2865
2866 impl ForeignItemId {
2867     #[inline]
2868     pub fn hir_id(&self) -> HirId {
2869         // Items are always HIR owners.
2870         HirId::make_owner(self.def_id)
2871     }
2872 }
2873
2874 /// A reference from a foreign block to one of its items. This
2875 /// contains the item's ID, naturally, but also the item's name and
2876 /// some other high-level details (like whether it is an associated
2877 /// type or method, and whether it is public). This allows other
2878 /// passes to find the impl they want without loading the ID (which
2879 /// means fewer edges in the incremental compilation graph).
2880 #[derive(Debug, HashStable_Generic)]
2881 pub struct ForeignItemRef<'hir> {
2882     pub id: ForeignItemId,
2883     #[stable_hasher(project(name))]
2884     pub ident: Ident,
2885     pub span: Span,
2886     pub vis: Visibility<'hir>,
2887 }
2888
2889 #[derive(Debug)]
2890 pub struct ForeignItem<'hir> {
2891     pub ident: Ident,
2892     pub kind: ForeignItemKind<'hir>,
2893     pub def_id: LocalDefId,
2894     pub span: Span,
2895     pub vis: Visibility<'hir>,
2896 }
2897
2898 impl ForeignItem<'_> {
2899     #[inline]
2900     pub fn hir_id(&self) -> HirId {
2901         // Items are always HIR owners.
2902         HirId::make_owner(self.def_id)
2903     }
2904
2905     pub fn foreign_item_id(&self) -> ForeignItemId {
2906         ForeignItemId { def_id: self.def_id }
2907     }
2908 }
2909
2910 /// An item within an `extern` block.
2911 #[derive(Debug, HashStable_Generic)]
2912 pub enum ForeignItemKind<'hir> {
2913     /// A foreign function.
2914     Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2915     /// A foreign static item (`static ext: u8`).
2916     Static(&'hir Ty<'hir>, Mutability),
2917     /// A foreign type.
2918     Type,
2919 }
2920
2921 /// A variable captured by a closure.
2922 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2923 pub struct Upvar {
2924     // First span where it is accessed (there can be multiple).
2925     pub span: Span,
2926 }
2927
2928 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2929 // has length > 0 if the trait is found through an chain of imports, starting with the
2930 // import/use statement in the scope where the trait is used.
2931 #[derive(Encodable, Decodable, Clone, Debug)]
2932 pub struct TraitCandidate {
2933     pub def_id: DefId,
2934     pub import_ids: SmallVec<[LocalDefId; 1]>,
2935 }
2936
2937 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2938 pub enum Node<'hir> {
2939     Param(&'hir Param<'hir>),
2940     Item(&'hir Item<'hir>),
2941     ForeignItem(&'hir ForeignItem<'hir>),
2942     TraitItem(&'hir TraitItem<'hir>),
2943     ImplItem(&'hir ImplItem<'hir>),
2944     Variant(&'hir Variant<'hir>),
2945     Field(&'hir FieldDef<'hir>),
2946     AnonConst(&'hir AnonConst),
2947     Expr(&'hir Expr<'hir>),
2948     Stmt(&'hir Stmt<'hir>),
2949     PathSegment(&'hir PathSegment<'hir>),
2950     Ty(&'hir Ty<'hir>),
2951     TraitRef(&'hir TraitRef<'hir>),
2952     Binding(&'hir Pat<'hir>),
2953     Pat(&'hir Pat<'hir>),
2954     Arm(&'hir Arm<'hir>),
2955     Block(&'hir Block<'hir>),
2956     Local(&'hir Local<'hir>),
2957     MacroDef(&'hir MacroDef<'hir>),
2958
2959     /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2960     /// with synthesized constructors.
2961     Ctor(&'hir VariantData<'hir>),
2962
2963     Lifetime(&'hir Lifetime),
2964     GenericParam(&'hir GenericParam<'hir>),
2965     Visibility(&'hir Visibility<'hir>),
2966
2967     Crate(&'hir Mod<'hir>),
2968 }
2969
2970 impl<'hir> Node<'hir> {
2971     pub fn ident(&self) -> Option<Ident> {
2972         match self {
2973             Node::TraitItem(TraitItem { ident, .. })
2974             | Node::ImplItem(ImplItem { ident, .. })
2975             | Node::ForeignItem(ForeignItem { ident, .. })
2976             | Node::Field(FieldDef { ident, .. })
2977             | Node::Variant(Variant { ident, .. })
2978             | Node::MacroDef(MacroDef { ident, .. })
2979             | Node::Item(Item { ident, .. }) => Some(*ident),
2980             _ => None,
2981         }
2982     }
2983
2984     pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
2985         match self {
2986             Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2987             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2988             | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2989             Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
2990                 Some(fn_decl)
2991             }
2992             _ => None,
2993         }
2994     }
2995
2996     pub fn body_id(&self) -> Option<BodyId> {
2997         match self {
2998             Node::TraitItem(TraitItem {
2999                 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3000                 ..
3001             })
3002             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3003             | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3004             _ => None,
3005         }
3006     }
3007
3008     pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3009         match self {
3010             Node::TraitItem(TraitItem { generics, .. })
3011             | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3012             Node::Item(item) => item.kind.generics(),
3013             _ => None,
3014         }
3015     }
3016
3017     pub fn hir_id(&self) -> Option<HirId> {
3018         match self {
3019             Node::Item(Item { def_id, .. })
3020             | Node::TraitItem(TraitItem { def_id, .. })
3021             | Node::ImplItem(ImplItem { def_id, .. })
3022             | Node::ForeignItem(ForeignItem { def_id, .. })
3023             | Node::MacroDef(MacroDef { def_id, .. }) => Some(HirId::make_owner(*def_id)),
3024             Node::Field(FieldDef { hir_id, .. })
3025             | Node::AnonConst(AnonConst { hir_id, .. })
3026             | Node::Expr(Expr { hir_id, .. })
3027             | Node::Stmt(Stmt { hir_id, .. })
3028             | Node::Ty(Ty { hir_id, .. })
3029             | Node::Binding(Pat { hir_id, .. })
3030             | Node::Pat(Pat { hir_id, .. })
3031             | Node::Arm(Arm { hir_id, .. })
3032             | Node::Block(Block { hir_id, .. })
3033             | Node::Local(Local { hir_id, .. })
3034             | Node::Lifetime(Lifetime { hir_id, .. })
3035             | Node::Param(Param { hir_id, .. })
3036             | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
3037             Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
3038             Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
3039             Node::Variant(Variant { id, .. }) => Some(*id),
3040             Node::Ctor(variant) => variant.ctor_hir_id(),
3041             Node::Crate(_) | Node::Visibility(_) => None,
3042         }
3043     }
3044 }
3045
3046 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3047 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3048 mod size_asserts {
3049     rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3050     rustc_data_structures::static_assert_size!(super::Expr<'static>, 64);
3051     rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3052     rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3053     rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3054
3055     rustc_data_structures::static_assert_size!(super::Item<'static>, 184);
3056     rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3057     rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152);
3058     rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136);
3059 }