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