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