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