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