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