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