]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/mod.rs
or-patterns: `hir::Arm::pats` -> `::pat` + `Arm::top_pats_hack`.
[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_data_structures::indexed_vec::Idx;
126     use rustc_macros::HashStable;
127     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.node {
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<NodeId, 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 `catch` statements.
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 node: 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_<G>(&self, it: &mut G) -> bool
886         where G: FnMut(&Pat) -> bool
887     {
888         if !it(self) {
889             return false;
890         }
891
892         match self.node {
893             PatKind::Binding(.., Some(ref p)) => p.walk_(it),
894             PatKind::Struct(_, ref fields, _) => {
895                 fields.iter().all(|field| field.pat.walk_(it))
896             }
897             PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
898                 s.iter().all(|p| p.walk_(it))
899             }
900             PatKind::Or(ref pats) => pats.iter().all(|p| p.walk_(it)),
901             PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
902                 s.walk_(it)
903             }
904             PatKind::Slice(ref before, ref slice, ref after) => {
905                 before.iter()
906                       .chain(slice.iter())
907                       .chain(after.iter())
908                       .all(|p| p.walk_(it))
909             }
910             PatKind::Wild |
911             PatKind::Lit(_) |
912             PatKind::Range(..) |
913             PatKind::Binding(..) |
914             PatKind::Path(_) => {
915                 true
916             }
917         }
918     }
919
920     pub fn walk<F>(&self, mut it: F) -> bool
921         where F: FnMut(&Pat) -> bool
922     {
923         self.walk_(&mut it)
924     }
925 }
926
927 /// A single field in a struct pattern.
928 ///
929 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
930 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
931 /// except `is_shorthand` is true.
932 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
933 pub struct FieldPat {
934     #[stable_hasher(ignore)]
935     pub hir_id: HirId,
936     /// The identifier for the field.
937     #[stable_hasher(project(name))]
938     pub ident: Ident,
939     /// The pattern the field is destructured to.
940     pub pat: P<Pat>,
941     pub is_shorthand: bool,
942     pub span: Span,
943 }
944
945 /// Explicit binding annotations given in the HIR for a binding. Note
946 /// that this is not the final binding *mode* that we infer after type
947 /// inference.
948 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
949 pub enum BindingAnnotation {
950     /// No binding annotation given: this means that the final binding mode
951     /// will depend on whether we have skipped through a `&` reference
952     /// when matching. For example, the `x` in `Some(x)` will have binding
953     /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
954     /// ultimately be inferred to be by-reference.
955     ///
956     /// Note that implicit reference skipping is not implemented yet (#42640).
957     Unannotated,
958
959     /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
960     Mutable,
961
962     /// Annotated as `ref`, like `ref x`
963     Ref,
964
965     /// Annotated as `ref mut x`.
966     RefMut,
967 }
968
969 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
970 pub enum RangeEnd {
971     Included,
972     Excluded,
973 }
974
975 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
976 pub enum PatKind {
977     /// Represents a wildcard pattern (i.e., `_`).
978     Wild,
979
980     /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
981     /// The `HirId` is the canonical ID for the variable being bound,
982     /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
983     /// which is the pattern ID of the first `x`.
984     Binding(BindingAnnotation, HirId, Ident, Option<P<Pat>>),
985
986     /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
987     /// The `bool` is `true` in the presence of a `..`.
988     Struct(QPath, HirVec<FieldPat>, bool),
989
990     /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
991     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
992     /// `0 <= position <= subpats.len()`
993     TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
994
995     /// An or-pattern `A | B | C`.
996     /// Invariant: `pats.len() >= 2`.
997     Or(HirVec<P<Pat>>),
998
999     /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
1000     Path(QPath),
1001
1002     /// A tuple pattern (e.g., `(a, b)`).
1003     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1004     /// `0 <= position <= subpats.len()`
1005     Tuple(HirVec<P<Pat>>, Option<usize>),
1006
1007     /// A `box` pattern.
1008     Box(P<Pat>),
1009
1010     /// A reference pattern (e.g., `&mut (a, b)`).
1011     Ref(P<Pat>, Mutability),
1012
1013     /// A literal.
1014     Lit(P<Expr>),
1015
1016     /// A range pattern (e.g., `1..=2` or `1..2`).
1017     Range(P<Expr>, P<Expr>, RangeEnd),
1018
1019     /// `[a, b, ..i, y, z]` is represented as:
1020     ///     `PatKind::Slice(box [a, b], Some(i), box [y, z])`.
1021     Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
1022 }
1023
1024 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1025          RustcEncodable, RustcDecodable, Hash, Debug)]
1026 pub enum Mutability {
1027     MutMutable,
1028     MutImmutable,
1029 }
1030
1031 impl Mutability {
1032     /// Returns `MutMutable` only if both `self` and `other` are mutable.
1033     pub fn and(self, other: Self) -> Self {
1034         match self {
1035             MutMutable => other,
1036             MutImmutable => MutImmutable,
1037         }
1038     }
1039 }
1040
1041 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Hash, HashStable)]
1042 pub enum BinOpKind {
1043     /// The `+` operator (addition).
1044     Add,
1045     /// The `-` operator (subtraction).
1046     Sub,
1047     /// The `*` operator (multiplication).
1048     Mul,
1049     /// The `/` operator (division).
1050     Div,
1051     /// The `%` operator (modulus).
1052     Rem,
1053     /// The `&&` operator (logical and).
1054     And,
1055     /// The `||` operator (logical or).
1056     Or,
1057     /// The `^` operator (bitwise xor).
1058     BitXor,
1059     /// The `&` operator (bitwise and).
1060     BitAnd,
1061     /// The `|` operator (bitwise or).
1062     BitOr,
1063     /// The `<<` operator (shift left).
1064     Shl,
1065     /// The `>>` operator (shift right).
1066     Shr,
1067     /// The `==` operator (equality).
1068     Eq,
1069     /// The `<` operator (less than).
1070     Lt,
1071     /// The `<=` operator (less than or equal to).
1072     Le,
1073     /// The `!=` operator (not equal to).
1074     Ne,
1075     /// The `>=` operator (greater than or equal to).
1076     Ge,
1077     /// The `>` operator (greater than).
1078     Gt,
1079 }
1080
1081 impl BinOpKind {
1082     pub fn as_str(self) -> &'static str {
1083         match self {
1084             BinOpKind::Add => "+",
1085             BinOpKind::Sub => "-",
1086             BinOpKind::Mul => "*",
1087             BinOpKind::Div => "/",
1088             BinOpKind::Rem => "%",
1089             BinOpKind::And => "&&",
1090             BinOpKind::Or => "||",
1091             BinOpKind::BitXor => "^",
1092             BinOpKind::BitAnd => "&",
1093             BinOpKind::BitOr => "|",
1094             BinOpKind::Shl => "<<",
1095             BinOpKind::Shr => ">>",
1096             BinOpKind::Eq => "==",
1097             BinOpKind::Lt => "<",
1098             BinOpKind::Le => "<=",
1099             BinOpKind::Ne => "!=",
1100             BinOpKind::Ge => ">=",
1101             BinOpKind::Gt => ">",
1102         }
1103     }
1104
1105     pub fn is_lazy(self) -> bool {
1106         match self {
1107             BinOpKind::And | BinOpKind::Or => true,
1108             _ => false,
1109         }
1110     }
1111
1112     pub fn is_shift(self) -> bool {
1113         match self {
1114             BinOpKind::Shl | BinOpKind::Shr => true,
1115             _ => false,
1116         }
1117     }
1118
1119     pub fn is_comparison(self) -> bool {
1120         match self {
1121             BinOpKind::Eq |
1122             BinOpKind::Lt |
1123             BinOpKind::Le |
1124             BinOpKind::Ne |
1125             BinOpKind::Gt |
1126             BinOpKind::Ge => true,
1127             BinOpKind::And |
1128             BinOpKind::Or |
1129             BinOpKind::Add |
1130             BinOpKind::Sub |
1131             BinOpKind::Mul |
1132             BinOpKind::Div |
1133             BinOpKind::Rem |
1134             BinOpKind::BitXor |
1135             BinOpKind::BitAnd |
1136             BinOpKind::BitOr |
1137             BinOpKind::Shl |
1138             BinOpKind::Shr => false,
1139         }
1140     }
1141
1142     /// Returns `true` if the binary operator takes its arguments by value.
1143     pub fn is_by_value(self) -> bool {
1144         !self.is_comparison()
1145     }
1146 }
1147
1148 impl Into<ast::BinOpKind> for BinOpKind {
1149     fn into(self) -> ast::BinOpKind {
1150         match self {
1151             BinOpKind::Add => ast::BinOpKind::Add,
1152             BinOpKind::Sub => ast::BinOpKind::Sub,
1153             BinOpKind::Mul => ast::BinOpKind::Mul,
1154             BinOpKind::Div => ast::BinOpKind::Div,
1155             BinOpKind::Rem => ast::BinOpKind::Rem,
1156             BinOpKind::And => ast::BinOpKind::And,
1157             BinOpKind::Or => ast::BinOpKind::Or,
1158             BinOpKind::BitXor => ast::BinOpKind::BitXor,
1159             BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1160             BinOpKind::BitOr => ast::BinOpKind::BitOr,
1161             BinOpKind::Shl => ast::BinOpKind::Shl,
1162             BinOpKind::Shr => ast::BinOpKind::Shr,
1163             BinOpKind::Eq => ast::BinOpKind::Eq,
1164             BinOpKind::Lt => ast::BinOpKind::Lt,
1165             BinOpKind::Le => ast::BinOpKind::Le,
1166             BinOpKind::Ne => ast::BinOpKind::Ne,
1167             BinOpKind::Ge => ast::BinOpKind::Ge,
1168             BinOpKind::Gt => ast::BinOpKind::Gt,
1169         }
1170     }
1171 }
1172
1173 pub type BinOp = Spanned<BinOpKind>;
1174
1175 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Hash, HashStable)]
1176 pub enum UnOp {
1177     /// The `*` operator (deferencing).
1178     UnDeref,
1179     /// The `!` operator (logical negation).
1180     UnNot,
1181     /// The `-` operator (negation).
1182     UnNeg,
1183 }
1184
1185 impl UnOp {
1186     pub fn as_str(self) -> &'static str {
1187         match self {
1188             UnDeref => "*",
1189             UnNot => "!",
1190             UnNeg => "-",
1191         }
1192     }
1193
1194     /// Returns `true` if the unary operator takes its argument by value.
1195     pub fn is_by_value(self) -> bool {
1196         match self {
1197             UnNeg | UnNot => true,
1198             _ => false,
1199         }
1200     }
1201 }
1202
1203 /// A statement.
1204 #[derive(RustcEncodable, RustcDecodable)]
1205 pub struct Stmt {
1206     pub hir_id: HirId,
1207     pub node: StmtKind,
1208     pub span: Span,
1209 }
1210
1211 impl fmt::Debug for Stmt {
1212     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1213         write!(f, "stmt({}: {})", self.hir_id,
1214                print::to_string(print::NO_ANN, |s| s.print_stmt(self)))
1215     }
1216 }
1217
1218 /// The contents of a statement.
1219 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1220 pub enum StmtKind {
1221     /// A local (`let`) binding.
1222     Local(P<Local>),
1223
1224     /// An item binding.
1225     Item(ItemId),
1226
1227     /// An expression without a trailing semi-colon (must have unit type).
1228     Expr(P<Expr>),
1229
1230     /// An expression with a trailing semi-colon (may have any type).
1231     Semi(P<Expr>),
1232 }
1233
1234 impl StmtKind {
1235     pub fn attrs(&self) -> &[Attribute] {
1236         match *self {
1237             StmtKind::Local(ref l) => &l.attrs,
1238             StmtKind::Item(_) => &[],
1239             StmtKind::Expr(ref e) |
1240             StmtKind::Semi(ref e) => &e.attrs,
1241         }
1242     }
1243 }
1244
1245 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1246 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1247 pub struct Local {
1248     pub pat: P<Pat>,
1249     /// Type annotation, if any (otherwise the type will be inferred).
1250     pub ty: Option<P<Ty>>,
1251     /// Initializer expression to set the value, if any.
1252     pub init: Option<P<Expr>>,
1253     pub hir_id: HirId,
1254     pub span: Span,
1255     pub attrs: ThinVec<Attribute>,
1256     /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1257     /// desugaring. Otherwise will be `Normal`.
1258     pub source: LocalSource,
1259 }
1260
1261 /// Represents a single arm of a `match` expression, e.g.
1262 /// `<pat> (if <guard>) => <body>`.
1263 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1264 pub struct Arm {
1265     #[stable_hasher(ignore)]
1266     pub hir_id: HirId,
1267     pub span: Span,
1268     pub attrs: HirVec<Attribute>,
1269     /// If this pattern and the optional guard matches, then `body` is evaluated.
1270     pub pat: P<Pat>,
1271     /// Optional guard clause.
1272     pub guard: Option<Guard>,
1273     /// The expression the arm evaluates to if this arm matches.
1274     pub body: P<Expr>,
1275 }
1276
1277 impl Arm {
1278     // HACK(or_patterns; Centril | dlrobertson): Remove this and
1279     // correctly handle each case in which this method is used.
1280     pub fn top_pats_hack(&self) -> &[P<Pat>] {
1281         match &self.pat.node {
1282             PatKind::Or(pats) => pats,
1283             _ => std::slice::from_ref(&self.pat),
1284         }
1285     }
1286 }
1287
1288 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1289 pub enum Guard {
1290     If(P<Expr>),
1291 }
1292
1293 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1294 pub struct Field {
1295     #[stable_hasher(ignore)]
1296     pub hir_id: HirId,
1297     pub ident: Ident,
1298     pub expr: P<Expr>,
1299     pub span: Span,
1300     pub is_shorthand: bool,
1301 }
1302
1303 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1304 pub enum BlockCheckMode {
1305     DefaultBlock,
1306     UnsafeBlock(UnsafeSource),
1307     PushUnsafeBlock(UnsafeSource),
1308     PopUnsafeBlock(UnsafeSource),
1309 }
1310
1311 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1312 pub enum UnsafeSource {
1313     CompilerGenerated,
1314     UserProvided,
1315 }
1316
1317 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1318 pub struct BodyId {
1319     pub hir_id: HirId,
1320 }
1321
1322 /// The body of a function, closure, or constant value. In the case of
1323 /// a function, the body contains not only the function body itself
1324 /// (which is an expression), but also the argument patterns, since
1325 /// those are something that the caller doesn't really care about.
1326 ///
1327 /// # Examples
1328 ///
1329 /// ```
1330 /// fn foo((x, y): (u32, u32)) -> u32 {
1331 ///     x + y
1332 /// }
1333 /// ```
1334 ///
1335 /// Here, the `Body` associated with `foo()` would contain:
1336 ///
1337 /// - an `params` array containing the `(x, y)` pattern
1338 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1339 /// - `generator_kind` would be `None`
1340 ///
1341 /// All bodies have an **owner**, which can be accessed via the HIR
1342 /// map using `body_owner_def_id()`.
1343 #[derive(RustcEncodable, RustcDecodable, Debug)]
1344 pub struct Body {
1345     pub params: HirVec<Param>,
1346     pub value: Expr,
1347     pub generator_kind: Option<GeneratorKind>,
1348 }
1349
1350 impl Body {
1351     pub fn id(&self) -> BodyId {
1352         BodyId {
1353             hir_id: self.value.hir_id,
1354         }
1355     }
1356 }
1357
1358 /// The type of source expression that caused this generator to be created.
1359 // Not `IsAsync` because we want to eventually add support for `AsyncGen`
1360 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1361          RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1362 pub enum GeneratorKind {
1363     /// An `async` block or function.
1364     Async,
1365     /// A generator literal created via a `yield` inside a closure.
1366     Gen,
1367 }
1368
1369 impl fmt::Display for GeneratorKind {
1370     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1371         f.write_str(match self {
1372             GeneratorKind::Async => "`async` object",
1373             GeneratorKind::Gen => "generator",
1374         })
1375     }
1376 }
1377
1378 #[derive(Copy, Clone, Debug)]
1379 pub enum BodyOwnerKind {
1380     /// Functions and methods.
1381     Fn,
1382
1383     /// Closures
1384     Closure,
1385
1386     /// Constants and associated constants.
1387     Const,
1388
1389     /// Initializer of a `static` item.
1390     Static(Mutability),
1391 }
1392
1393 impl BodyOwnerKind {
1394     pub fn is_fn_or_closure(self) -> bool {
1395         match self {
1396             BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1397             BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1398         }
1399     }
1400 }
1401
1402 /// A literal.
1403 pub type Lit = Spanned<LitKind>;
1404
1405 /// A constant (expression) that's not an item or associated item,
1406 /// but needs its own `DefId` for type-checking, const-eval, etc.
1407 /// These are usually found nested inside types (e.g., array lengths)
1408 /// or expressions (e.g., repeat counts), and also used to define
1409 /// explicit discriminant values for enum variants.
1410 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1411 pub struct AnonConst {
1412     pub hir_id: HirId,
1413     pub body: BodyId,
1414 }
1415
1416 /// An expression.
1417 #[derive(RustcEncodable, RustcDecodable)]
1418 pub struct Expr {
1419     pub hir_id: HirId,
1420     pub node: ExprKind,
1421     pub attrs: ThinVec<Attribute>,
1422     pub span: Span,
1423 }
1424
1425 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1426 #[cfg(target_arch = "x86_64")]
1427 static_assert_size!(Expr, 72);
1428
1429 impl Expr {
1430     pub fn precedence(&self) -> ExprPrecedence {
1431         match self.node {
1432             ExprKind::Box(_) => ExprPrecedence::Box,
1433             ExprKind::Array(_) => ExprPrecedence::Array,
1434             ExprKind::Call(..) => ExprPrecedence::Call,
1435             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1436             ExprKind::Tup(_) => ExprPrecedence::Tup,
1437             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1438             ExprKind::Unary(..) => ExprPrecedence::Unary,
1439             ExprKind::Lit(_) => ExprPrecedence::Lit,
1440             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1441             ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1442             ExprKind::Loop(..) => ExprPrecedence::Loop,
1443             ExprKind::Match(..) => ExprPrecedence::Match,
1444             ExprKind::Closure(..) => ExprPrecedence::Closure,
1445             ExprKind::Block(..) => ExprPrecedence::Block,
1446             ExprKind::Assign(..) => ExprPrecedence::Assign,
1447             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1448             ExprKind::Field(..) => ExprPrecedence::Field,
1449             ExprKind::Index(..) => ExprPrecedence::Index,
1450             ExprKind::Path(..) => ExprPrecedence::Path,
1451             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1452             ExprKind::Break(..) => ExprPrecedence::Break,
1453             ExprKind::Continue(..) => ExprPrecedence::Continue,
1454             ExprKind::Ret(..) => ExprPrecedence::Ret,
1455             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1456             ExprKind::Struct(..) => ExprPrecedence::Struct,
1457             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1458             ExprKind::Yield(..) => ExprPrecedence::Yield,
1459             ExprKind::Err => ExprPrecedence::Err,
1460         }
1461     }
1462
1463     pub fn is_place_expr(&self) -> bool {
1464          match self.node {
1465             ExprKind::Path(QPath::Resolved(_, ref path)) => {
1466                 match path.res {
1467                     Res::Local(..)
1468                     | Res::Def(DefKind::Static, _)
1469                     | Res::Err => true,
1470                     _ => false,
1471                 }
1472             }
1473
1474             ExprKind::Type(ref e, _) => {
1475                 e.is_place_expr()
1476             }
1477
1478             ExprKind::Unary(UnDeref, _) |
1479             ExprKind::Field(..) |
1480             ExprKind::Index(..) => {
1481                 true
1482             }
1483
1484             // Partially qualified paths in expressions can only legally
1485             // refer to associated items which are always rvalues.
1486             ExprKind::Path(QPath::TypeRelative(..)) |
1487
1488             ExprKind::Call(..) |
1489             ExprKind::MethodCall(..) |
1490             ExprKind::Struct(..) |
1491             ExprKind::Tup(..) |
1492             ExprKind::Match(..) |
1493             ExprKind::Closure(..) |
1494             ExprKind::Block(..) |
1495             ExprKind::Repeat(..) |
1496             ExprKind::Array(..) |
1497             ExprKind::Break(..) |
1498             ExprKind::Continue(..) |
1499             ExprKind::Ret(..) |
1500             ExprKind::Loop(..) |
1501             ExprKind::Assign(..) |
1502             ExprKind::InlineAsm(..) |
1503             ExprKind::AssignOp(..) |
1504             ExprKind::Lit(_) |
1505             ExprKind::Unary(..) |
1506             ExprKind::Box(..) |
1507             ExprKind::AddrOf(..) |
1508             ExprKind::Binary(..) |
1509             ExprKind::Yield(..) |
1510             ExprKind::Cast(..) |
1511             ExprKind::DropTemps(..) |
1512             ExprKind::Err => {
1513                 false
1514             }
1515         }
1516     }
1517 }
1518
1519 impl fmt::Debug for Expr {
1520     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1521         write!(f, "expr({}: {})", self.hir_id,
1522                print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1523     }
1524 }
1525
1526 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1527 pub enum ExprKind {
1528     /// A `box x` expression.
1529     Box(P<Expr>),
1530     /// An array (e.g., `[a, b, c, d]`).
1531     Array(HirVec<Expr>),
1532     /// A function call.
1533     ///
1534     /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1535     /// and the second field is the list of arguments.
1536     /// This also represents calling the constructor of
1537     /// tuple-like ADTs such as tuple structs and enum variants.
1538     Call(P<Expr>, HirVec<Expr>),
1539     /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1540     ///
1541     /// The `PathSegment`/`Span` represent the method name and its generic arguments
1542     /// (within the angle brackets).
1543     /// The first element of the vector of `Expr`s is the expression that evaluates
1544     /// to the object on which the method is being called on (the receiver),
1545     /// and the remaining elements are the rest of the arguments.
1546     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1547     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1548     MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1549     /// A tuple (e.g., `(a, b, c ,d)`).
1550     Tup(HirVec<Expr>),
1551     /// A binary operation (e.g., `a + b`, `a * b`).
1552     Binary(BinOp, P<Expr>, P<Expr>),
1553     /// A unary operation (e.g., `!x`, `*x`).
1554     Unary(UnOp, P<Expr>),
1555     /// A literal (e.g., `1`, `"foo"`).
1556     Lit(Lit),
1557     /// A cast (e.g., `foo as f64`).
1558     Cast(P<Expr>, P<Ty>),
1559     /// A type reference (e.g., `Foo`).
1560     Type(P<Expr>, P<Ty>),
1561     /// Wraps the expression in a terminating scope.
1562     /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1563     ///
1564     /// This construct only exists to tweak the drop order in HIR lowering.
1565     /// An example of that is the desugaring of `for` loops.
1566     DropTemps(P<Expr>),
1567     /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1568     ///
1569     /// I.e., `'label: loop { <block> }`.
1570     Loop(P<Block>, Option<Label>, LoopSource),
1571     /// A `match` block, with a source that indicates whether or not it is
1572     /// the result of a desugaring, and if so, which kind.
1573     Match(P<Expr>, HirVec<Arm>, MatchSource),
1574     /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1575     ///
1576     /// The `Span` is the argument block `|...|`.
1577     ///
1578     /// This may also be a generator literal or an `async block` as indicated by the
1579     /// `Option<GeneratorMovability>`.
1580     Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1581     /// A block (e.g., `'label: { ... }`).
1582     Block(P<Block>, Option<Label>),
1583
1584     /// An assignment (e.g., `a = foo()`).
1585     Assign(P<Expr>, P<Expr>),
1586     /// An assignment with an operator.
1587     ///
1588     /// E.g., `a += 1`.
1589     AssignOp(BinOp, P<Expr>, P<Expr>),
1590     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1591     Field(P<Expr>, Ident),
1592     /// An indexing operation (`foo[2]`).
1593     Index(P<Expr>, P<Expr>),
1594
1595     /// Path to a definition, possibly containing lifetime or type parameters.
1596     Path(QPath),
1597
1598     /// A referencing operation (i.e., `&a` or `&mut a`).
1599     AddrOf(Mutability, P<Expr>),
1600     /// A `break`, with an optional label to break.
1601     Break(Destination, Option<P<Expr>>),
1602     /// A `continue`, with an optional label.
1603     Continue(Destination),
1604     /// A `return`, with an optional value to be returned.
1605     Ret(Option<P<Expr>>),
1606
1607     /// Inline assembly (from `asm!`), with its outputs and inputs.
1608     InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1609
1610     /// A struct or struct-like variant literal expression.
1611     ///
1612     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1613     /// where `base` is the `Option<Expr>`.
1614     Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1615
1616     /// An array literal constructed from one repeated element.
1617     ///
1618     /// E.g., `[1; 5]`. The first expression is the element
1619     /// to be repeated; the second is the number of times to repeat it.
1620     Repeat(P<Expr>, AnonConst),
1621
1622     /// A suspension point for generators (i.e., `yield <expr>`).
1623     Yield(P<Expr>, YieldSource),
1624
1625     /// A placeholder for an expression that wasn't syntactically well formed in some way.
1626     Err,
1627 }
1628
1629 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1630 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1631 pub enum QPath {
1632     /// Path to a definition, optionally "fully-qualified" with a `Self`
1633     /// type, if the path points to an associated item in a trait.
1634     ///
1635     /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1636     /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1637     /// even though they both have the same two-segment `Clone::clone` `Path`.
1638     Resolved(Option<P<Ty>>, P<Path>),
1639
1640     /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1641     /// Will be resolved by type-checking to an associated item.
1642     ///
1643     /// UFCS source paths can desugar into this, with `Vec::new` turning into
1644     /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1645     /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1646     TypeRelative(P<Ty>, P<PathSegment>)
1647 }
1648
1649 /// Hints at the original code for a let statement.
1650 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1651 pub enum LocalSource {
1652     /// A `match _ { .. }`.
1653     Normal,
1654     /// A desugared `for _ in _ { .. }` loop.
1655     ForLoopDesugar,
1656     /// When lowering async functions, we create locals within the `async move` so that
1657     /// all parameters are dropped after the future is polled.
1658     ///
1659     /// ```ignore (pseudo-Rust)
1660     /// async fn foo(<pattern> @ x: Type) {
1661     ///     async move {
1662     ///         let <pattern> = x;
1663     ///     }
1664     /// }
1665     /// ```
1666     AsyncFn,
1667     /// A desugared `<expr>.await`.
1668     AwaitDesugar,
1669 }
1670
1671 /// Hints at the original code for a `match _ { .. }`.
1672 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1673 pub enum MatchSource {
1674     /// A `match _ { .. }`.
1675     Normal,
1676     /// An `if _ { .. }` (optionally with `else { .. }`).
1677     IfDesugar {
1678         contains_else_clause: bool,
1679     },
1680     /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1681     IfLetDesugar {
1682         contains_else_clause: bool,
1683     },
1684     /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1685     WhileDesugar,
1686     /// A `while let _ = _ { .. }` (which was desugared to a
1687     /// `loop { match _ { .. } }`).
1688     WhileLetDesugar,
1689     /// A desugared `for _ in _ { .. }` loop.
1690     ForLoopDesugar,
1691     /// A desugared `?` operator.
1692     TryDesugar,
1693     /// A desugared `<expr>.await`.
1694     AwaitDesugar,
1695 }
1696
1697 /// The loop type that yielded an `ExprKind::Loop`.
1698 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1699 pub enum LoopSource {
1700     /// A `loop { .. }` loop.
1701     Loop,
1702     /// A `while _ { .. }` loop.
1703     While,
1704     /// A `while let _ = _ { .. }` loop.
1705     WhileLet,
1706     /// A `for _ in _ { .. }` loop.
1707     ForLoop,
1708 }
1709
1710 impl LoopSource {
1711     pub fn name(self) -> &'static str {
1712         match self {
1713             LoopSource::Loop => "loop",
1714             LoopSource::While => "while",
1715             LoopSource::WhileLet => "while let",
1716             LoopSource::ForLoop => "for",
1717         }
1718     }
1719 }
1720
1721 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1722 pub enum LoopIdError {
1723     OutsideLoopScope,
1724     UnlabeledCfInWhileCondition,
1725     UnresolvedLabel,
1726 }
1727
1728 impl fmt::Display for LoopIdError {
1729     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1730         f.write_str(match self {
1731             LoopIdError::OutsideLoopScope => "not inside loop scope",
1732             LoopIdError::UnlabeledCfInWhileCondition =>
1733                 "unlabeled control flow (break or continue) in while condition",
1734             LoopIdError::UnresolvedLabel => "label not found",
1735         })
1736     }
1737 }
1738
1739 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1740 pub struct Destination {
1741     // This is `Some(_)` iff there is an explicit user-specified `label
1742     pub label: Option<Label>,
1743
1744     // These errors are caught and then reported during the diagnostics pass in
1745     // librustc_passes/loops.rs
1746     pub target_id: Result<HirId, LoopIdError>,
1747 }
1748
1749 /// Whether a generator contains self-references, causing it to be `!Unpin`.
1750 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1751          RustcEncodable, RustcDecodable, Hash, Debug)]
1752 pub enum GeneratorMovability {
1753     /// May contain self-references, `!Unpin`.
1754     Static,
1755     /// Must not contain self-references, `Unpin`.
1756     Movable,
1757 }
1758
1759 /// The yield kind that caused an `ExprKind::Yield`.
1760 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable, HashStable)]
1761 pub enum YieldSource {
1762     /// An `<expr>.await`.
1763     Await,
1764     /// A plain `yield`.
1765     Yield,
1766 }
1767
1768 impl fmt::Display for YieldSource {
1769     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1770         f.write_str(match self {
1771             YieldSource::Await => "`await`",
1772             YieldSource::Yield => "`yield`",
1773         })
1774     }
1775 }
1776
1777 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1778 pub enum CaptureClause {
1779     CaptureByValue,
1780     CaptureByRef,
1781 }
1782
1783 // N.B., if you change this, you'll probably want to change the corresponding
1784 // type structure in middle/ty.rs as well.
1785 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1786 pub struct MutTy {
1787     pub ty: P<Ty>,
1788     pub mutbl: Mutability,
1789 }
1790
1791 /// Represents a method's signature in a trait declaration or implementation.
1792 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1793 pub struct MethodSig {
1794     pub header: FnHeader,
1795     pub decl: P<FnDecl>,
1796 }
1797
1798 // The bodies for items are stored "out of line", in a separate
1799 // hashmap in the `Crate`. Here we just record the node-id of the item
1800 // so it can fetched later.
1801 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1802 pub struct TraitItemId {
1803     pub hir_id: HirId,
1804 }
1805
1806 /// Represents an item declaration within a trait declaration,
1807 /// possibly including a default implementation. A trait item is
1808 /// either required (meaning it doesn't have an implementation, just a
1809 /// signature) or provided (meaning it has a default implementation).
1810 #[derive(RustcEncodable, RustcDecodable, Debug)]
1811 pub struct TraitItem {
1812     pub ident: Ident,
1813     pub hir_id: HirId,
1814     pub attrs: HirVec<Attribute>,
1815     pub generics: Generics,
1816     pub node: TraitItemKind,
1817     pub span: Span,
1818 }
1819
1820 /// Represents a trait method's body (or just argument names).
1821 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1822 pub enum TraitMethod {
1823     /// No default body in the trait, just a signature.
1824     Required(HirVec<Ident>),
1825
1826     /// Both signature and body are provided in the trait.
1827     Provided(BodyId),
1828 }
1829
1830 /// Represents a trait method or associated constant or type
1831 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1832 pub enum TraitItemKind {
1833     /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1834     Const(P<Ty>, Option<BodyId>),
1835     /// A method with an optional body.
1836     Method(MethodSig, TraitMethod),
1837     /// An associated type with (possibly empty) bounds and optional concrete
1838     /// type.
1839     Type(GenericBounds, Option<P<Ty>>),
1840 }
1841
1842 // The bodies for items are stored "out of line", in a separate
1843 // hashmap in the `Crate`. Here we just record the node-id of the item
1844 // so it can fetched later.
1845 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1846 pub struct ImplItemId {
1847     pub hir_id: HirId,
1848 }
1849
1850 /// Represents anything within an `impl` block.
1851 #[derive(RustcEncodable, RustcDecodable, Debug)]
1852 pub struct ImplItem {
1853     pub ident: Ident,
1854     pub hir_id: HirId,
1855     pub vis: Visibility,
1856     pub defaultness: Defaultness,
1857     pub attrs: HirVec<Attribute>,
1858     pub generics: Generics,
1859     pub node: ImplItemKind,
1860     pub span: Span,
1861 }
1862
1863 /// Represents various kinds of content within an `impl`.
1864 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1865 pub enum ImplItemKind {
1866     /// An associated constant of the given type, set to the constant result
1867     /// of the expression.
1868     Const(P<Ty>, BodyId),
1869     /// A method implementation with the given signature and body.
1870     Method(MethodSig, BodyId),
1871     /// An associated type.
1872     TyAlias(P<Ty>),
1873     /// An associated `type = impl Trait`.
1874     OpaqueTy(GenericBounds),
1875 }
1876
1877 /// Bind a type to an associated type (i.e., `A = Foo`).
1878 ///
1879 /// Bindings like `A: Debug` are represented as a special type `A =
1880 /// $::Debug` that is understood by the astconv code.
1881 ///
1882 /// FIXME(alexreg) -- why have a separate type for the binding case,
1883 /// wouldn't it be better to make the `ty` field an enum like:
1884 ///
1885 /// ```
1886 /// enum TypeBindingKind {
1887 ///    Equals(...),
1888 ///    Binding(...),
1889 /// }
1890 /// ```
1891 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1892 pub struct TypeBinding {
1893     pub hir_id: HirId,
1894     #[stable_hasher(project(name))]
1895     pub ident: Ident,
1896     pub kind: TypeBindingKind,
1897     pub span: Span,
1898 }
1899
1900 // Represents the two kinds of type bindings.
1901 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1902 pub enum TypeBindingKind {
1903     /// E.g., `Foo<Bar: Send>`.
1904     Constraint {
1905         bounds: HirVec<GenericBound>,
1906     },
1907     /// E.g., `Foo<Bar = ()>`.
1908     Equality {
1909         ty: P<Ty>,
1910     },
1911 }
1912
1913 impl TypeBinding {
1914     pub fn ty(&self) -> &Ty {
1915         match self.kind {
1916             TypeBindingKind::Equality { ref ty } => ty,
1917             _ => bug!("expected equality type binding for parenthesized generic args"),
1918         }
1919     }
1920 }
1921
1922 #[derive(RustcEncodable, RustcDecodable)]
1923 pub struct Ty {
1924     pub hir_id: HirId,
1925     pub node: TyKind,
1926     pub span: Span,
1927 }
1928
1929 impl fmt::Debug for Ty {
1930     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1931         write!(f, "type({})",
1932                print::to_string(print::NO_ANN, |s| s.print_type(self)))
1933     }
1934 }
1935
1936 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1937 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
1938 pub enum PrimTy {
1939     Int(IntTy),
1940     Uint(UintTy),
1941     Float(FloatTy),
1942     Str,
1943     Bool,
1944     Char,
1945 }
1946
1947 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1948 pub struct BareFnTy {
1949     pub unsafety: Unsafety,
1950     pub abi: Abi,
1951     pub generic_params: HirVec<GenericParam>,
1952     pub decl: P<FnDecl>,
1953     pub param_names: HirVec<Ident>,
1954 }
1955
1956 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1957 pub struct OpaqueTy {
1958     pub generics: Generics,
1959     pub bounds: GenericBounds,
1960     pub impl_trait_fn: Option<DefId>,
1961     pub origin: OpaqueTyOrigin,
1962 }
1963
1964 /// From whence the opaque type came.
1965 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1966 pub enum OpaqueTyOrigin {
1967     /// `type Foo = impl Trait;`
1968     TypeAlias,
1969     /// `-> impl Trait`
1970     FnReturn,
1971     /// `async fn`
1972     AsyncFn,
1973 }
1974
1975 /// The various kinds of types recognized by the compiler.
1976 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
1977 pub enum TyKind {
1978     /// A variable length slice (i.e., `[T]`).
1979     Slice(P<Ty>),
1980     /// A fixed length array (i.e., `[T; n]`).
1981     Array(P<Ty>, AnonConst),
1982     /// A raw pointer (i.e., `*const T` or `*mut T`).
1983     Ptr(MutTy),
1984     /// A reference (i.e., `&'a T` or `&'a mut T`).
1985     Rptr(Lifetime, MutTy),
1986     /// A bare function (e.g., `fn(usize) -> bool`).
1987     BareFn(P<BareFnTy>),
1988     /// The never type (`!`).
1989     Never,
1990     /// A tuple (`(A, B, C, D, ...)`).
1991     Tup(HirVec<Ty>),
1992     /// A path to a type definition (`module::module::...::Type`), or an
1993     /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
1994     ///
1995     /// Type parameters may be stored in each `PathSegment`.
1996     Path(QPath),
1997     /// A type definition itself. This is currently only used for the `type Foo = impl Trait`
1998     /// item that `impl Trait` in return position desugars to.
1999     ///
2000     /// The generic argument list contains the lifetimes (and in the future possibly parameters)
2001     /// that are actually bound on the `impl Trait`.
2002     Def(ItemId, HirVec<GenericArg>),
2003     /// A trait object type `Bound1 + Bound2 + Bound3`
2004     /// where `Bound` is a trait or a lifetime.
2005     TraitObject(HirVec<PolyTraitRef>, Lifetime),
2006     /// Unused for now.
2007     Typeof(AnonConst),
2008     /// `TyKind::Infer` means the type should be inferred instead of it having been
2009     /// specified. This can appear anywhere in a type.
2010     Infer,
2011     /// Placeholder for a type that has failed to be defined.
2012     Err,
2013     /// Placeholder for C-variadic arguments. We "spoof" the `VaListImpl` created
2014     /// from the variadic arguments. This type is only valid up to typeck.
2015     CVarArgs(Lifetime),
2016 }
2017
2018 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2019 pub struct InlineAsmOutput {
2020     pub constraint: Symbol,
2021     pub is_rw: bool,
2022     pub is_indirect: bool,
2023     pub span: Span,
2024 }
2025
2026 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2027 // it needs to be `Clone` and use plain `Vec<T>` instead of `HirVec<T>`.
2028 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2029 pub struct InlineAsm {
2030     pub asm: Symbol,
2031     pub asm_str_style: StrStyle,
2032     pub outputs: Vec<InlineAsmOutput>,
2033     pub inputs: Vec<Symbol>,
2034     pub clobbers: Vec<Symbol>,
2035     pub volatile: bool,
2036     pub alignstack: bool,
2037     pub dialect: AsmDialect,
2038 }
2039
2040 /// Represents a parameter in a function header.
2041 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2042 pub struct Param {
2043     pub attrs: HirVec<Attribute>,
2044     pub hir_id: HirId,
2045     pub pat: P<Pat>,
2046     pub span: Span,
2047 }
2048
2049 /// Represents the header (not the body) of a function declaration.
2050 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2051 pub struct FnDecl {
2052     /// The types of the function's parameters.
2053     ///
2054     /// Additional argument data is stored in the function's [body](Body::parameters).
2055     pub inputs: HirVec<Ty>,
2056     pub output: FunctionRetTy,
2057     pub c_variadic: bool,
2058     /// Does the function have an implicit self?
2059     pub implicit_self: ImplicitSelfKind,
2060 }
2061
2062 /// Represents what type of implicit self a function has, if any.
2063 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2064 pub enum ImplicitSelfKind {
2065     /// Represents a `fn x(self);`.
2066     Imm,
2067     /// Represents a `fn x(mut self);`.
2068     Mut,
2069     /// Represents a `fn x(&self);`.
2070     ImmRef,
2071     /// Represents a `fn x(&mut self);`.
2072     MutRef,
2073     /// Represents when a function does not have a self argument or
2074     /// when a function has a `self: X` argument.
2075     None
2076 }
2077
2078 impl ImplicitSelfKind {
2079     /// Does this represent an implicit self?
2080     pub fn has_implicit_self(&self) -> bool {
2081         match *self {
2082             ImplicitSelfKind::None => false,
2083             _ => true,
2084         }
2085     }
2086 }
2087
2088 /// Is the trait definition an auto trait?
2089 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2090 pub enum IsAuto {
2091     Yes,
2092     No
2093 }
2094
2095 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
2096          Ord, RustcEncodable, RustcDecodable, Debug)]
2097 pub enum IsAsync {
2098     Async,
2099     NotAsync,
2100 }
2101
2102 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
2103          RustcEncodable, RustcDecodable, Hash, Debug)]
2104 pub enum Unsafety {
2105     Unsafe,
2106     Normal,
2107 }
2108
2109 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2110 pub enum Constness {
2111     Const,
2112     NotConst,
2113 }
2114
2115 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2116 pub enum Defaultness {
2117     Default { has_value: bool },
2118     Final,
2119 }
2120
2121 impl Defaultness {
2122     pub fn has_value(&self) -> bool {
2123         match *self {
2124             Defaultness::Default { has_value, .. } => has_value,
2125             Defaultness::Final => true,
2126         }
2127     }
2128
2129     pub fn is_final(&self) -> bool {
2130         *self == Defaultness::Final
2131     }
2132
2133     pub fn is_default(&self) -> bool {
2134         match *self {
2135             Defaultness::Default { .. } => true,
2136             _ => false,
2137         }
2138     }
2139 }
2140
2141 impl fmt::Display for Unsafety {
2142     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2143         f.write_str(match self {
2144             Unsafety::Normal => "normal",
2145             Unsafety::Unsafe => "unsafe",
2146         })
2147     }
2148 }
2149
2150 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2151 pub enum ImplPolarity {
2152     /// `impl Trait for Type`
2153     Positive,
2154     /// `impl !Trait for Type`
2155     Negative,
2156 }
2157
2158 impl fmt::Debug for ImplPolarity {
2159     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2160         f.write_str(match self {
2161             ImplPolarity::Positive => "positive",
2162             ImplPolarity::Negative => "negative",
2163         })
2164     }
2165 }
2166
2167
2168 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2169 pub enum FunctionRetTy {
2170     /// Return type is not specified.
2171     ///
2172     /// Functions default to `()` and
2173     /// closures default to inference. Span points to where return
2174     /// type would be inserted.
2175     DefaultReturn(Span),
2176     /// Everything else.
2177     Return(P<Ty>),
2178 }
2179
2180 impl fmt::Display for FunctionRetTy {
2181     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2182         match self {
2183             Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2184             DefaultReturn(_) => "()".fmt(f),
2185         }
2186     }
2187 }
2188
2189 impl FunctionRetTy {
2190     pub fn span(&self) -> Span {
2191         match *self {
2192             DefaultReturn(span) => span,
2193             Return(ref ty) => ty.span,
2194         }
2195     }
2196 }
2197
2198 #[derive(RustcEncodable, RustcDecodable, Debug)]
2199 pub struct Mod {
2200     /// A span from the first token past `{` to the last token until `}`.
2201     /// For `mod foo;`, the inner span ranges from the first token
2202     /// to the last token in the external file.
2203     pub inner: Span,
2204     pub item_ids: HirVec<ItemId>,
2205 }
2206
2207 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2208 pub struct ForeignMod {
2209     pub abi: Abi,
2210     pub items: HirVec<ForeignItem>,
2211 }
2212
2213 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2214 pub struct GlobalAsm {
2215     pub asm: Symbol,
2216 }
2217
2218 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2219 pub struct EnumDef {
2220     pub variants: HirVec<Variant>,
2221 }
2222
2223 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2224 pub struct Variant {
2225     /// Name of the variant.
2226     #[stable_hasher(project(name))]
2227     pub ident: Ident,
2228     /// Attributes of the variant.
2229     pub attrs: HirVec<Attribute>,
2230     /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2231     pub id: HirId,
2232     /// Fields and constructor id of the variant.
2233     pub data: VariantData,
2234     /// Explicit discriminant (e.g., `Foo = 1`).
2235     pub disr_expr: Option<AnonConst>,
2236     /// Span
2237     pub span: Span
2238 }
2239
2240 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2241 pub enum UseKind {
2242     /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2243     /// Also produced for each element of a list `use`, e.g.
2244     /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2245     Single,
2246
2247     /// Glob import, e.g., `use foo::*`.
2248     Glob,
2249
2250     /// Degenerate list import, e.g., `use foo::{a, b}` produces
2251     /// an additional `use foo::{}` for performing checks such as
2252     /// unstable feature gating. May be removed in the future.
2253     ListStem,
2254 }
2255
2256 /// References to traits in impls.
2257 ///
2258 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2259 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2260 /// trait being referred to but just a unique `HirId` that serves as a key
2261 /// within the resolution map.
2262 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2263 pub struct TraitRef {
2264     pub path: P<Path>,
2265     // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2266     #[stable_hasher(ignore)]
2267     pub hir_ref_id: HirId,
2268 }
2269
2270 impl TraitRef {
2271     /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2272     pub fn trait_def_id(&self) -> DefId {
2273         match self.path.res {
2274             Res::Def(DefKind::Trait, did) => did,
2275             Res::Def(DefKind::TraitAlias, did) => did,
2276             Res::Err => {
2277                 FatalError.raise();
2278             }
2279             _ => unreachable!(),
2280         }
2281     }
2282 }
2283
2284 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2285 pub struct PolyTraitRef {
2286     /// The `'a` in `<'a> Foo<&'a T>`.
2287     pub bound_generic_params: HirVec<GenericParam>,
2288
2289     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2290     pub trait_ref: TraitRef,
2291
2292     pub span: Span,
2293 }
2294
2295 pub type Visibility = Spanned<VisibilityKind>;
2296
2297 #[derive(RustcEncodable, RustcDecodable, Debug)]
2298 pub enum VisibilityKind {
2299     Public,
2300     Crate(CrateSugar),
2301     Restricted { path: P<Path>, hir_id: HirId },
2302     Inherited,
2303 }
2304
2305 impl VisibilityKind {
2306     pub fn is_pub(&self) -> bool {
2307         match *self {
2308             VisibilityKind::Public => true,
2309             _ => false
2310         }
2311     }
2312
2313     pub fn is_pub_restricted(&self) -> bool {
2314         match *self {
2315             VisibilityKind::Public |
2316             VisibilityKind::Inherited => false,
2317             VisibilityKind::Crate(..) |
2318             VisibilityKind::Restricted { .. } => true,
2319         }
2320     }
2321
2322     pub fn descr(&self) -> &'static str {
2323         match *self {
2324             VisibilityKind::Public => "public",
2325             VisibilityKind::Inherited => "private",
2326             VisibilityKind::Crate(..) => "crate-visible",
2327             VisibilityKind::Restricted { .. } => "restricted",
2328         }
2329     }
2330 }
2331
2332 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2333 pub struct StructField {
2334     pub span: Span,
2335     #[stable_hasher(project(name))]
2336     pub ident: Ident,
2337     pub vis: Visibility,
2338     pub hir_id: HirId,
2339     pub ty: P<Ty>,
2340     pub attrs: HirVec<Attribute>,
2341 }
2342
2343 impl StructField {
2344     // Still necessary in couple of places
2345     pub fn is_positional(&self) -> bool {
2346         let first = self.ident.as_str().as_bytes()[0];
2347         first >= b'0' && first <= b'9'
2348     }
2349 }
2350
2351 /// Fields and constructor IDs of enum variants and structs.
2352 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2353 pub enum VariantData {
2354     /// A struct variant.
2355     ///
2356     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2357     Struct(HirVec<StructField>, /* recovered */ bool),
2358     /// A tuple variant.
2359     ///
2360     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2361     Tuple(HirVec<StructField>, HirId),
2362     /// A unit variant.
2363     ///
2364     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2365     Unit(HirId),
2366 }
2367
2368 impl VariantData {
2369     /// Return the fields of this variant.
2370     pub fn fields(&self) -> &[StructField] {
2371         match *self {
2372             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2373             _ => &[],
2374         }
2375     }
2376
2377     /// Return the `HirId` of this variant's constructor, if it has one.
2378     pub fn ctor_hir_id(&self) -> Option<HirId> {
2379         match *self {
2380             VariantData::Struct(_, _) => None,
2381             VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2382         }
2383     }
2384 }
2385
2386 // The bodies for items are stored "out of line", in a separate
2387 // hashmap in the `Crate`. Here we just record the node-id of the item
2388 // so it can fetched later.
2389 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2390 pub struct ItemId {
2391     pub id: HirId,
2392 }
2393
2394 /// An item
2395 ///
2396 /// The name might be a dummy name in case of anonymous items
2397 #[derive(RustcEncodable, RustcDecodable, Debug)]
2398 pub struct Item {
2399     pub ident: Ident,
2400     pub hir_id: HirId,
2401     pub attrs: HirVec<Attribute>,
2402     pub node: ItemKind,
2403     pub vis: Visibility,
2404     pub span: Span,
2405 }
2406
2407 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2408 pub struct FnHeader {
2409     pub unsafety: Unsafety,
2410     pub constness: Constness,
2411     pub asyncness: IsAsync,
2412     pub abi: Abi,
2413 }
2414
2415 impl FnHeader {
2416     pub fn is_const(&self) -> bool {
2417         match &self.constness {
2418             Constness::Const => true,
2419             _ => false,
2420         }
2421     }
2422 }
2423
2424 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2425 pub enum ItemKind {
2426     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2427     ///
2428     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2429     ExternCrate(Option<Name>),
2430
2431     /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2432     ///
2433     /// or just
2434     ///
2435     /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2436     Use(P<Path>, UseKind),
2437
2438     /// A `static` item.
2439     Static(P<Ty>, Mutability, BodyId),
2440     /// A `const` item.
2441     Const(P<Ty>, BodyId),
2442     /// A function declaration.
2443     Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2444     /// A module.
2445     Mod(Mod),
2446     /// An external module.
2447     ForeignMod(ForeignMod),
2448     /// Module-level inline assembly (from `global_asm!`).
2449     GlobalAsm(P<GlobalAsm>),
2450     /// A type alias, e.g., `type Foo = Bar<u8>`.
2451     TyAlias(P<Ty>, Generics),
2452     /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2453     OpaqueTy(OpaqueTy),
2454     /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2455     Enum(EnumDef, Generics),
2456     /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2457     Struct(VariantData, Generics),
2458     /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2459     Union(VariantData, Generics),
2460     /// A trait definition.
2461     Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2462     /// A trait alias.
2463     TraitAlias(Generics, GenericBounds),
2464
2465     /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2466     Impl(Unsafety,
2467          ImplPolarity,
2468          Defaultness,
2469          Generics,
2470          Option<TraitRef>, // (optional) trait this impl implements
2471          P<Ty>, // self
2472          HirVec<ImplItemRef>),
2473 }
2474
2475 impl ItemKind {
2476     pub fn descriptive_variant(&self) -> &str {
2477         match *self {
2478             ItemKind::ExternCrate(..) => "extern crate",
2479             ItemKind::Use(..) => "use",
2480             ItemKind::Static(..) => "static item",
2481             ItemKind::Const(..) => "constant item",
2482             ItemKind::Fn(..) => "function",
2483             ItemKind::Mod(..) => "module",
2484             ItemKind::ForeignMod(..) => "foreign module",
2485             ItemKind::GlobalAsm(..) => "global asm",
2486             ItemKind::TyAlias(..) => "type alias",
2487             ItemKind::OpaqueTy(..) => "opaque type",
2488             ItemKind::Enum(..) => "enum",
2489             ItemKind::Struct(..) => "struct",
2490             ItemKind::Union(..) => "union",
2491             ItemKind::Trait(..) => "trait",
2492             ItemKind::TraitAlias(..) => "trait alias",
2493             ItemKind::Impl(..) => "impl",
2494         }
2495     }
2496
2497     pub fn adt_kind(&self) -> Option<AdtKind> {
2498         match *self {
2499             ItemKind::Struct(..) => Some(AdtKind::Struct),
2500             ItemKind::Union(..) => Some(AdtKind::Union),
2501             ItemKind::Enum(..) => Some(AdtKind::Enum),
2502             _ => None,
2503         }
2504     }
2505
2506     pub fn generics(&self) -> Option<&Generics> {
2507         Some(match *self {
2508             ItemKind::Fn(_, _, ref generics, _) |
2509             ItemKind::TyAlias(_, ref generics) |
2510             ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. }) |
2511             ItemKind::Enum(_, ref generics) |
2512             ItemKind::Struct(_, ref generics) |
2513             ItemKind::Union(_, ref generics) |
2514             ItemKind::Trait(_, _, ref generics, _, _) |
2515             ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2516             _ => return None
2517         })
2518     }
2519 }
2520
2521 /// A reference from an trait to one of its associated items. This
2522 /// contains the item's id, naturally, but also the item's name and
2523 /// some other high-level details (like whether it is an associated
2524 /// type or method, and whether it is public). This allows other
2525 /// passes to find the impl they want without loading the ID (which
2526 /// means fewer edges in the incremental compilation graph).
2527 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2528 pub struct TraitItemRef {
2529     pub id: TraitItemId,
2530     #[stable_hasher(project(name))]
2531     pub ident: Ident,
2532     pub kind: AssocItemKind,
2533     pub span: Span,
2534     pub defaultness: Defaultness,
2535 }
2536
2537 /// A reference from an impl to one of its associated items. This
2538 /// contains the item's ID, naturally, but also the item's name and
2539 /// some other high-level details (like whether it is an associated
2540 /// type or method, and whether it is public). This allows other
2541 /// passes to find the impl they want without loading the ID (which
2542 /// means fewer edges in the incremental compilation graph).
2543 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2544 pub struct ImplItemRef {
2545     pub id: ImplItemId,
2546     #[stable_hasher(project(name))]
2547     pub ident: Ident,
2548     pub kind: AssocItemKind,
2549     pub span: Span,
2550     pub vis: Visibility,
2551     pub defaultness: Defaultness,
2552 }
2553
2554 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2555 pub enum AssocItemKind {
2556     Const,
2557     Method { has_self: bool },
2558     Type,
2559     OpaqueTy,
2560 }
2561
2562 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2563 pub struct ForeignItem {
2564     #[stable_hasher(project(name))]
2565     pub ident: Ident,
2566     pub attrs: HirVec<Attribute>,
2567     pub node: ForeignItemKind,
2568     pub hir_id: HirId,
2569     pub span: Span,
2570     pub vis: Visibility,
2571 }
2572
2573 /// An item within an `extern` block.
2574 #[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
2575 pub enum ForeignItemKind {
2576     /// A foreign function.
2577     Fn(P<FnDecl>, HirVec<Ident>, Generics),
2578     /// A foreign static item (`static ext: u8`).
2579     Static(P<Ty>, Mutability),
2580     /// A foreign type.
2581     Type,
2582 }
2583
2584 impl ForeignItemKind {
2585     pub fn descriptive_variant(&self) -> &str {
2586         match *self {
2587             ForeignItemKind::Fn(..) => "foreign function",
2588             ForeignItemKind::Static(..) => "foreign static item",
2589             ForeignItemKind::Type => "foreign type",
2590         }
2591     }
2592 }
2593
2594 /// A variable captured by a closure.
2595 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2596 pub struct Upvar {
2597     // First span where it is accessed (there can be multiple).
2598     pub span: Span
2599 }
2600
2601 pub type CaptureModeMap = NodeMap<CaptureClause>;
2602
2603  // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2604  // has length > 0 if the trait is found through an chain of imports, starting with the
2605  // import/use statement in the scope where the trait is used.
2606 #[derive(Clone, Debug)]
2607 pub struct TraitCandidate {
2608     pub def_id: DefId,
2609     pub import_ids: SmallVec<[NodeId; 1]>,
2610 }
2611
2612 // Trait method resolution
2613 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2614
2615 // Map from the NodeId of a glob import to a list of items which are actually
2616 // imported.
2617 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2618
2619 pub fn provide(providers: &mut Providers<'_>) {
2620     check_attr::provide(providers);
2621     map::provide(providers);
2622     upvars::provide(providers);
2623 }
2624
2625 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2626 pub struct CodegenFnAttrs {
2627     pub flags: CodegenFnAttrFlags,
2628     /// Parsed representation of the `#[inline]` attribute
2629     pub inline: InlineAttr,
2630     /// Parsed representation of the `#[optimize]` attribute
2631     pub optimize: OptimizeAttr,
2632     /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2633     /// function should be exported under
2634     pub export_name: Option<Symbol>,
2635     /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2636     /// imported function should be imported as. Note that `export_name`
2637     /// probably isn't set when this is set, this is for foreign items while
2638     /// `#[export_name]` is for Rust-defined functions.
2639     pub link_name: Option<Symbol>,
2640     /// The `#[target_feature(enable = "...")]` attribute and the enabled
2641     /// features (only enabled features are supported right now).
2642     pub target_features: Vec<Symbol>,
2643     /// The `#[linkage = "..."]` attribute and the value we found.
2644     pub linkage: Option<Linkage>,
2645     /// The `#[link_section = "..."]` attribute, or what executable section this
2646     /// should be placed in.
2647     pub link_section: Option<Symbol>,
2648 }
2649
2650 bitflags! {
2651     #[derive(RustcEncodable, RustcDecodable, HashStable)]
2652     pub struct CodegenFnAttrFlags: u32 {
2653         /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2654         /// the hot path.
2655         const COLD                      = 1 << 0;
2656         /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
2657         /// function is never null.
2658         const ALLOCATOR                 = 1 << 1;
2659         /// `#[unwind]`: an indicator that this function may unwind despite what
2660         /// its ABI signature may otherwise imply.
2661         const UNWIND                    = 1 << 2;
2662         /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2663         /// function will never unwind. Probably obsolete by recent changes with
2664         /// #[unwind], but hasn't been removed/migrated yet
2665         const RUSTC_ALLOCATOR_NOUNWIND  = 1 << 3;
2666         /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2667         /// should be generated.
2668         const NAKED                     = 1 << 4;
2669         /// `#[no_mangle]`: an indicator that the function's name should be the same
2670         /// as its symbol.
2671         const NO_MANGLE                 = 1 << 5;
2672         /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2673         /// "weird symbol" for the standard library in that it has slightly
2674         /// different linkage, visibility, and reachability rules.
2675         const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2676         /// `#[no_debug]`: an indicator that no debugging information should be
2677         /// generated for this function by LLVM.
2678         const NO_DEBUG                  = 1 << 7;
2679         /// `#[thread_local]`: indicates a static is actually a thread local
2680         /// piece of memory
2681         const THREAD_LOCAL              = 1 << 8;
2682         /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2683         /// linker can!).
2684         const USED                      = 1 << 9;
2685         /// #[ffi_returns_twice], indicates that an extern function can return
2686         /// multiple times
2687         const FFI_RETURNS_TWICE = 1 << 10;
2688     }
2689 }
2690
2691 impl CodegenFnAttrs {
2692     pub fn new() -> CodegenFnAttrs {
2693         CodegenFnAttrs {
2694             flags: CodegenFnAttrFlags::empty(),
2695             inline: InlineAttr::None,
2696             optimize: OptimizeAttr::None,
2697             export_name: None,
2698             link_name: None,
2699             target_features: vec![],
2700             linkage: None,
2701             link_section: None,
2702         }
2703     }
2704
2705     /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2706     pub fn requests_inline(&self) -> bool {
2707         match self.inline {
2708             InlineAttr::Hint | InlineAttr::Always => true,
2709             InlineAttr::None | InlineAttr::Never => false,
2710         }
2711     }
2712
2713     /// Returns `true` if it looks like this symbol needs to be exported, for example:
2714     ///
2715     /// * `#[no_mangle]` is present
2716     /// * `#[export_name(...)]` is present
2717     /// * `#[linkage]` is present
2718     pub fn contains_extern_indicator(&self) -> bool {
2719         self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2720             self.export_name.is_some() ||
2721             match self.linkage {
2722                 // These are private, so make sure we don't try to consider
2723                 // them external.
2724                 None |
2725                 Some(Linkage::Internal) |
2726                 Some(Linkage::Private) => false,
2727                 Some(_) => true,
2728             }
2729     }
2730 }
2731
2732 #[derive(Copy, Clone, Debug)]
2733 pub enum Node<'hir> {
2734     Param(&'hir Param),
2735     Item(&'hir Item),
2736     ForeignItem(&'hir ForeignItem),
2737     TraitItem(&'hir TraitItem),
2738     ImplItem(&'hir ImplItem),
2739     Variant(&'hir Variant),
2740     Field(&'hir StructField),
2741     AnonConst(&'hir AnonConst),
2742     Expr(&'hir Expr),
2743     Stmt(&'hir Stmt),
2744     PathSegment(&'hir PathSegment),
2745     Ty(&'hir Ty),
2746     TraitRef(&'hir TraitRef),
2747     Binding(&'hir Pat),
2748     Pat(&'hir Pat),
2749     Arm(&'hir Arm),
2750     Block(&'hir Block),
2751     Local(&'hir Local),
2752     MacroDef(&'hir MacroDef),
2753
2754     /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2755     /// with synthesized constructors.
2756     Ctor(&'hir VariantData),
2757
2758     Lifetime(&'hir Lifetime),
2759     GenericParam(&'hir GenericParam),
2760     Visibility(&'hir Visibility),
2761
2762     Crate,
2763 }