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