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