]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/mod.rs
3ca79cb850128fe3b3dd9bd67f5187195ce6d696
[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, LitKind, 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 implemented by a `Vec` instead of a
135         /// tree or hash map.
136         pub struct ItemLocalId {
137             derive [HashStable]
138         }
139     }
140 }
141
142 pub use self::item_local_id_inner::ItemLocalId;
143
144 /// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_INDEX`.
145 pub const CRATE_HIR_ID: HirId = HirId {
146     owner: CRATE_DEF_INDEX,
147     local_id: ItemLocalId::from_u32_const(0)
148 };
149
150 pub const DUMMY_HIR_ID: HirId = HirId {
151     owner: CRATE_DEF_INDEX,
152     local_id: DUMMY_ITEM_LOCAL_ID,
153 };
154
155 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId::MAX;
156
157 #[derive(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 literal.
1335 pub type Lit = Spanned<LitKind>;
1336
1337 /// A constant (expression) that's not an item or associated item,
1338 /// but needs its own `DefId` for type-checking, const-eval, etc.
1339 /// These are usually found nested inside types (e.g., array lengths)
1340 /// or expressions (e.g., repeat counts), and also used to define
1341 /// explicit discriminant values for enum variants.
1342 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1343 pub struct AnonConst {
1344     pub hir_id: HirId,
1345     pub body: BodyId,
1346 }
1347
1348 /// An expression
1349 #[derive(Clone, RustcEncodable, RustcDecodable)]
1350 pub struct Expr {
1351     pub span: Span,
1352     pub node: ExprKind,
1353     pub attrs: ThinVec<Attribute>,
1354     pub hir_id: HirId,
1355 }
1356
1357 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1358 #[cfg(target_arch = "x86_64")]
1359 static_assert_size!(Expr, 72);
1360
1361 impl Expr {
1362     pub fn precedence(&self) -> ExprPrecedence {
1363         match self.node {
1364             ExprKind::Box(_) => ExprPrecedence::Box,
1365             ExprKind::Array(_) => ExprPrecedence::Array,
1366             ExprKind::Call(..) => ExprPrecedence::Call,
1367             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1368             ExprKind::Tup(_) => ExprPrecedence::Tup,
1369             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1370             ExprKind::Unary(..) => ExprPrecedence::Unary,
1371             ExprKind::Lit(_) => ExprPrecedence::Lit,
1372             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1373             ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1374             ExprKind::While(..) => ExprPrecedence::While,
1375             ExprKind::Loop(..) => ExprPrecedence::Loop,
1376             ExprKind::Match(..) => ExprPrecedence::Match,
1377             ExprKind::Closure(..) => ExprPrecedence::Closure,
1378             ExprKind::Block(..) => ExprPrecedence::Block,
1379             ExprKind::Assign(..) => ExprPrecedence::Assign,
1380             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1381             ExprKind::Field(..) => ExprPrecedence::Field,
1382             ExprKind::Index(..) => ExprPrecedence::Index,
1383             ExprKind::Path(..) => ExprPrecedence::Path,
1384             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1385             ExprKind::Break(..) => ExprPrecedence::Break,
1386             ExprKind::Continue(..) => ExprPrecedence::Continue,
1387             ExprKind::Ret(..) => ExprPrecedence::Ret,
1388             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1389             ExprKind::Struct(..) => ExprPrecedence::Struct,
1390             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1391             ExprKind::Yield(..) => ExprPrecedence::Yield,
1392             ExprKind::Err => ExprPrecedence::Err,
1393         }
1394     }
1395
1396     pub fn is_place_expr(&self) -> bool {
1397          match self.node {
1398             ExprKind::Path(QPath::Resolved(_, ref path)) => {
1399                 match path.res {
1400                     Res::Local(..)
1401                     | Res::Upvar(..)
1402                     | Res::Def(DefKind::Static, _)
1403                     | Res::Err => true,
1404                     _ => false,
1405                 }
1406             }
1407
1408             ExprKind::Type(ref e, _) => {
1409                 e.is_place_expr()
1410             }
1411
1412             ExprKind::Unary(UnDeref, _) |
1413             ExprKind::Field(..) |
1414             ExprKind::Index(..) => {
1415                 true
1416             }
1417
1418             // Partially qualified paths in expressions can only legally
1419             // refer to associated items which are always rvalues.
1420             ExprKind::Path(QPath::TypeRelative(..)) |
1421
1422             ExprKind::Call(..) |
1423             ExprKind::MethodCall(..) |
1424             ExprKind::Struct(..) |
1425             ExprKind::Tup(..) |
1426             ExprKind::Match(..) |
1427             ExprKind::Closure(..) |
1428             ExprKind::Block(..) |
1429             ExprKind::Repeat(..) |
1430             ExprKind::Array(..) |
1431             ExprKind::Break(..) |
1432             ExprKind::Continue(..) |
1433             ExprKind::Ret(..) |
1434             ExprKind::While(..) |
1435             ExprKind::Loop(..) |
1436             ExprKind::Assign(..) |
1437             ExprKind::InlineAsm(..) |
1438             ExprKind::AssignOp(..) |
1439             ExprKind::Lit(_) |
1440             ExprKind::Unary(..) |
1441             ExprKind::Box(..) |
1442             ExprKind::AddrOf(..) |
1443             ExprKind::Binary(..) |
1444             ExprKind::Yield(..) |
1445             ExprKind::Cast(..) |
1446             ExprKind::DropTemps(..) |
1447             ExprKind::Err => {
1448                 false
1449             }
1450         }
1451     }
1452 }
1453
1454 impl fmt::Debug for Expr {
1455     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1456         write!(f, "expr({}: {})", self.hir_id,
1457                print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1458     }
1459 }
1460
1461 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1462 pub enum ExprKind {
1463     /// A `box x` expression.
1464     Box(P<Expr>),
1465     /// An array (e.g., `[a, b, c, d]`).
1466     Array(HirVec<Expr>),
1467     /// A function call.
1468     ///
1469     /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1470     /// and the second field is the list of arguments.
1471     /// This also represents calling the constructor of
1472     /// tuple-like ADTs such as tuple structs and enum variants.
1473     Call(P<Expr>, HirVec<Expr>),
1474     /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1475     ///
1476     /// The `PathSegment`/`Span` represent the method name and its generic arguments
1477     /// (within the angle brackets).
1478     /// The first element of the vector of `Expr`s is the expression that evaluates
1479     /// to the object on which the method is being called on (the receiver),
1480     /// and the remaining elements are the rest of the arguments.
1481     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1482     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1483     MethodCall(P<PathSegment>, Span, HirVec<Expr>),
1484     /// A tuple (e.g., `(a, b, c ,d)`).
1485     Tup(HirVec<Expr>),
1486     /// A binary operation (e.g., `a + b`, `a * b`).
1487     Binary(BinOp, P<Expr>, P<Expr>),
1488     /// A unary operation (e.g., `!x`, `*x`).
1489     Unary(UnOp, P<Expr>),
1490     /// A literal (e.g., `1`, `"foo"`).
1491     Lit(Lit),
1492     /// A cast (e.g., `foo as f64`).
1493     Cast(P<Expr>, P<Ty>),
1494     /// A type reference (e.g., `Foo`).
1495     Type(P<Expr>, P<Ty>),
1496     /// Wraps the expression in a terminating scope.
1497     /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1498     ///
1499     /// This construct only exists to tweak the drop order in HIR lowering.
1500     /// An example of that is the desugaring of `for` loops.
1501     DropTemps(P<Expr>),
1502     /// A while loop, with an optional label
1503     ///
1504     /// I.e., `'label: while expr { <block> }`.
1505     While(P<Expr>, P<Block>, Option<Label>),
1506     /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1507     ///
1508     /// I.e., `'label: loop { <block> }`.
1509     Loop(P<Block>, Option<Label>, LoopSource),
1510     /// A `match` block, with a source that indicates whether or not it is
1511     /// the result of a desugaring, and if so, which kind.
1512     Match(P<Expr>, HirVec<Arm>, MatchSource),
1513     /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1514     ///
1515     /// The final span is the span of the argument block `|...|`.
1516     ///
1517     /// This may also be a generator literal, indicated by the final boolean,
1518     /// in that case there is an `GeneratorClause`.
1519     Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1520     /// A block (e.g., `'label: { ... }`).
1521     Block(P<Block>, Option<Label>),
1522
1523     /// An assignment (e.g., `a = foo()`).
1524     Assign(P<Expr>, P<Expr>),
1525     /// An assignment with an operator.
1526     ///
1527     /// E.g., `a += 1`.
1528     AssignOp(BinOp, P<Expr>, P<Expr>),
1529     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1530     Field(P<Expr>, Ident),
1531     /// An indexing operation (`foo[2]`).
1532     Index(P<Expr>, P<Expr>),
1533
1534     /// Path to a definition, possibly containing lifetime or type parameters.
1535     Path(QPath),
1536
1537     /// A referencing operation (i.e., `&a` or `&mut a`).
1538     AddrOf(Mutability, P<Expr>),
1539     /// A `break`, with an optional label to break.
1540     Break(Destination, Option<P<Expr>>),
1541     /// A `continue`, with an optional label.
1542     Continue(Destination),
1543     /// A `return`, with an optional value to be returned.
1544     Ret(Option<P<Expr>>),
1545
1546     /// Inline assembly (from `asm!`), with its outputs and inputs.
1547     InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1548
1549     /// A struct or struct-like variant literal expression.
1550     ///
1551     /// For example, `Foo {x: 1, y: 2}`, or
1552     /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1553     Struct(P<QPath>, HirVec<Field>, Option<P<Expr>>),
1554
1555     /// An array literal constructed from one repeated element.
1556     ///
1557     /// For example, `[1; 5]`. The first expression is the element
1558     /// to be repeated; the second is the number of times to repeat it.
1559     Repeat(P<Expr>, AnonConst),
1560
1561     /// A suspension point for generators (i.e., `yield <expr>`).
1562     Yield(P<Expr>),
1563
1564     /// A placeholder for an expression that wasn't syntactically well formed in some way.
1565     Err,
1566 }
1567
1568 /// Optionally `Self`-qualified value/type path or associated extension.
1569 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1570 pub enum QPath {
1571     /// Path to a definition, optionally "fully-qualified" with a `Self`
1572     /// type, if the path points to an associated item in a trait.
1573     ///
1574     /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1575     /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1576     /// even though they both have the same two-segment `Clone::clone` `Path`.
1577     Resolved(Option<P<Ty>>, P<Path>),
1578
1579     /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1580     /// Will be resolved by type-checking to an associated item.
1581     ///
1582     /// UFCS source paths can desugar into this, with `Vec::new` turning into
1583     /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1584     /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1585     TypeRelative(P<Ty>, P<PathSegment>)
1586 }
1587
1588 /// Hints at the original code for a let statement.
1589 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1590 pub enum LocalSource {
1591     /// A `match _ { .. }`.
1592     Normal,
1593     /// A desugared `for _ in _ { .. }` loop.
1594     ForLoopDesugar,
1595     /// When lowering async functions, we create locals within the `async move` so that
1596     /// all arguments are dropped after the future is polled.
1597     ///
1598     /// ```ignore (pseudo-Rust)
1599     /// async fn foo(<pattern> @ x: Type) {
1600     ///     async move {
1601     ///         let <pattern> = x;
1602     ///     }
1603     /// }
1604     /// ```
1605     AsyncFn,
1606     /// A desugared `<expr>.await`.
1607     AwaitDesugar,
1608 }
1609
1610 /// Hints at the original code for a `match _ { .. }`.
1611 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy, HashStable)]
1612 pub enum MatchSource {
1613     /// A `match _ { .. }`.
1614     Normal,
1615     /// An `if _ { .. }` (optionally with `else { .. }`).
1616     IfDesugar {
1617         contains_else_clause: bool,
1618     },
1619     /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1620     IfLetDesugar {
1621         contains_else_clause: bool,
1622     },
1623     /// A `while let _ = _ { .. }` (which was desugared to a
1624     /// `loop { match _ { .. } }`).
1625     WhileLetDesugar,
1626     /// A desugared `for _ in _ { .. }` loop.
1627     ForLoopDesugar,
1628     /// A desugared `?` operator.
1629     TryDesugar,
1630     /// A desugared `<expr>.await`.
1631     AwaitDesugar,
1632 }
1633
1634 /// The loop type that yielded an `ExprKind::Loop`.
1635 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1636 pub enum LoopSource {
1637     /// A `loop { .. }` loop.
1638     Loop,
1639     /// A `while let _ = _ { .. }` loop.
1640     WhileLet,
1641     /// A `for _ in _ { .. }` loop.
1642     ForLoop,
1643 }
1644
1645 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1646 pub enum LoopIdError {
1647     OutsideLoopScope,
1648     UnlabeledCfInWhileCondition,
1649     UnresolvedLabel,
1650 }
1651
1652 impl fmt::Display for LoopIdError {
1653     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1654         fmt::Display::fmt(match *self {
1655             LoopIdError::OutsideLoopScope => "not inside loop scope",
1656             LoopIdError::UnlabeledCfInWhileCondition =>
1657                 "unlabeled control flow (break or continue) in while condition",
1658             LoopIdError::UnresolvedLabel => "label not found",
1659         }, f)
1660     }
1661 }
1662
1663 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1664 pub struct Destination {
1665     // This is `Some(_)` iff there is an explicit user-specified `label
1666     pub label: Option<Label>,
1667
1668     // These errors are caught and then reported during the diagnostics pass in
1669     // librustc_passes/loops.rs
1670     pub target_id: Result<HirId, LoopIdError>,
1671 }
1672
1673 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1674          RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1675 pub enum GeneratorMovability {
1676     Static,
1677     Movable,
1678 }
1679
1680 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable)]
1681 pub enum CaptureClause {
1682     CaptureByValue,
1683     CaptureByRef,
1684 }
1685
1686 // N.B., if you change this, you'll probably want to change the corresponding
1687 // type structure in middle/ty.rs as well.
1688 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1689 pub struct MutTy {
1690     pub ty: P<Ty>,
1691     pub mutbl: Mutability,
1692 }
1693
1694 /// Represents a method's signature in a trait declaration or implementation.
1695 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1696 pub struct MethodSig {
1697     pub header: FnHeader,
1698     pub decl: P<FnDecl>,
1699 }
1700
1701 // The bodies for items are stored "out of line", in a separate
1702 // hashmap in the `Crate`. Here we just record the node-id of the item
1703 // so it can fetched later.
1704 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1705 pub struct TraitItemId {
1706     pub hir_id: HirId,
1707 }
1708
1709 /// Represents an item declaration within a trait declaration,
1710 /// possibly including a default implementation. A trait item is
1711 /// either required (meaning it doesn't have an implementation, just a
1712 /// signature) or provided (meaning it has a default implementation).
1713 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1714 pub struct TraitItem {
1715     pub ident: Ident,
1716     pub hir_id: HirId,
1717     pub attrs: HirVec<Attribute>,
1718     pub generics: Generics,
1719     pub node: TraitItemKind,
1720     pub span: Span,
1721 }
1722
1723 /// A trait method's body (or just argument names).
1724 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1725 pub enum TraitMethod {
1726     /// No default body in the trait, just a signature.
1727     Required(HirVec<Ident>),
1728
1729     /// Both signature and body are provided in the trait.
1730     Provided(BodyId),
1731 }
1732
1733 /// Represents a trait method or associated constant or type
1734 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1735 pub enum TraitItemKind {
1736     /// An associated constant with an optional value (otherwise `impl`s
1737     /// must contain a value)
1738     Const(P<Ty>, Option<BodyId>),
1739     /// A method with an optional body
1740     Method(MethodSig, TraitMethod),
1741     /// An associated type with (possibly empty) bounds and optional concrete
1742     /// type
1743     Type(GenericBounds, Option<P<Ty>>),
1744 }
1745
1746 // The bodies for items are stored "out of line", in a separate
1747 // hashmap in the `Crate`. Here we just record the node-id of the item
1748 // so it can fetched later.
1749 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1750 pub struct ImplItemId {
1751     pub hir_id: HirId,
1752 }
1753
1754 /// Represents anything within an `impl` block
1755 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1756 pub struct ImplItem {
1757     pub ident: Ident,
1758     pub hir_id: HirId,
1759     pub vis: Visibility,
1760     pub defaultness: Defaultness,
1761     pub attrs: HirVec<Attribute>,
1762     pub generics: Generics,
1763     pub node: ImplItemKind,
1764     pub span: Span,
1765 }
1766
1767 /// Represents different contents within `impl`s
1768 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1769 pub enum ImplItemKind {
1770     /// An associated constant of the given type, set to the constant result
1771     /// of the expression
1772     Const(P<Ty>, BodyId),
1773     /// A method implementation with the given signature and body
1774     Method(MethodSig, BodyId),
1775     /// An associated type
1776     Type(P<Ty>),
1777     /// An associated existential type
1778     Existential(GenericBounds),
1779 }
1780
1781 // Bind a type to an associated type: `A=Foo`.
1782 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1783 pub struct TypeBinding {
1784     pub hir_id: HirId,
1785     #[stable_hasher(project(name))]
1786     pub ident: Ident,
1787     pub ty: P<Ty>,
1788     pub span: Span,
1789 }
1790
1791 #[derive(Clone, RustcEncodable, RustcDecodable)]
1792 pub struct Ty {
1793     pub node: TyKind,
1794     pub span: Span,
1795     pub hir_id: HirId,
1796 }
1797
1798 impl fmt::Debug for Ty {
1799     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1800         write!(f, "type({})",
1801                print::to_string(print::NO_ANN, |s| s.print_type(self)))
1802     }
1803 }
1804
1805 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1806 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy, HashStable)]
1807 pub enum PrimTy {
1808     Int(IntTy),
1809     Uint(UintTy),
1810     Float(FloatTy),
1811     Str,
1812     Bool,
1813     Char,
1814 }
1815
1816 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1817 pub struct BareFnTy {
1818     pub unsafety: Unsafety,
1819     pub abi: Abi,
1820     pub generic_params: HirVec<GenericParam>,
1821     pub decl: P<FnDecl>,
1822     pub arg_names: HirVec<Ident>,
1823 }
1824
1825 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1826 pub struct ExistTy {
1827     pub generics: Generics,
1828     pub bounds: GenericBounds,
1829     pub impl_trait_fn: Option<DefId>,
1830     pub origin: ExistTyOrigin,
1831 }
1832
1833 /// Where the existential type came from
1834 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1835 pub enum ExistTyOrigin {
1836     /// `existential type Foo: Trait;`
1837     ExistentialType,
1838     /// `-> impl Trait`
1839     ReturnImplTrait,
1840     /// `async fn`
1841     AsyncFn,
1842 }
1843
1844 /// The various kinds of types recognized by the compiler.
1845 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1846 pub enum TyKind {
1847     /// A variable length slice (i.e., `[T]`).
1848     Slice(P<Ty>),
1849     /// A fixed length array (i.e., `[T; n]`).
1850     Array(P<Ty>, AnonConst),
1851     /// A raw pointer (i.e., `*const T` or `*mut T`).
1852     Ptr(MutTy),
1853     /// A reference (i.e., `&'a T` or `&'a mut T`).
1854     Rptr(Lifetime, MutTy),
1855     /// A bare function (e.g., `fn(usize) -> bool`).
1856     BareFn(P<BareFnTy>),
1857     /// The never type (`!`).
1858     Never,
1859     /// A tuple (`(A, B, C, D,...)`).
1860     Tup(HirVec<Ty>),
1861     /// A path to a type definition (`module::module::...::Type`), or an
1862     /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
1863     ///
1864     /// Type parameters may be stored in each `PathSegment`.
1865     Path(QPath),
1866     /// A type definition itself. This is currently only used for the `existential type`
1867     /// item that `impl Trait` in return position desugars to.
1868     ///
1869     /// The generic argument list contains the lifetimes (and in the future possibly parameters)
1870     /// that are actually bound on the `impl Trait`.
1871     Def(ItemId, HirVec<GenericArg>),
1872     /// A trait object type `Bound1 + Bound2 + Bound3`
1873     /// where `Bound` is a trait or a lifetime.
1874     TraitObject(HirVec<PolyTraitRef>, Lifetime),
1875     /// Unused for now.
1876     Typeof(AnonConst),
1877     /// `TyKind::Infer` means the type should be inferred instead of it having been
1878     /// specified. This can appear anywhere in a type.
1879     Infer,
1880     /// Placeholder for a type that has failed to be defined.
1881     Err,
1882     /// Placeholder for C-variadic arguments. We "spoof" the `VaList` created
1883     /// from the variadic arguments. This type is only valid up to typeck.
1884     CVarArgs(Lifetime),
1885 }
1886
1887 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1888 pub struct InlineAsmOutput {
1889     pub constraint: Symbol,
1890     pub is_rw: bool,
1891     pub is_indirect: bool,
1892     pub span: Span,
1893 }
1894
1895 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1896 pub struct InlineAsm {
1897     pub asm: Symbol,
1898     pub asm_str_style: StrStyle,
1899     pub outputs: HirVec<InlineAsmOutput>,
1900     pub inputs: HirVec<Symbol>,
1901     pub clobbers: HirVec<Symbol>,
1902     pub volatile: bool,
1903     pub alignstack: bool,
1904     pub dialect: AsmDialect,
1905     #[stable_hasher(ignore)] // This is used for error reporting
1906     pub ctxt: SyntaxContext,
1907 }
1908
1909 /// Represents an argument in a function header.
1910 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1911 pub struct Arg {
1912     pub pat: P<Pat>,
1913     pub hir_id: HirId,
1914     pub source: ArgSource,
1915 }
1916
1917 impl Arg {
1918     /// Returns the pattern representing the original binding for this argument.
1919     pub fn original_pat(&self) -> &P<Pat> {
1920         match &self.source {
1921             ArgSource::Normal => &self.pat,
1922             ArgSource::AsyncFn(pat) => &pat,
1923         }
1924     }
1925 }
1926
1927 /// Represents the source of an argument in a function header.
1928 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1929 pub enum ArgSource {
1930     /// Argument as specified by the user.
1931     Normal,
1932     /// Generated argument from `async fn` lowering, contains the original binding pattern.
1933     AsyncFn(P<Pat>),
1934 }
1935
1936 /// Represents the header (not the body) of a function declaration.
1937 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1938 pub struct FnDecl {
1939     /// The types of the function's arguments.
1940     ///
1941     /// Additional argument data is stored in the function's [body](Body::arguments).
1942     pub inputs: HirVec<Ty>,
1943     pub output: FunctionRetTy,
1944     pub c_variadic: bool,
1945     /// Does the function have an implicit self?
1946     pub implicit_self: ImplicitSelfKind,
1947 }
1948
1949 /// Represents what type of implicit self a function has, if any.
1950 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, HashStable)]
1951 pub enum ImplicitSelfKind {
1952     /// Represents a `fn x(self);`.
1953     Imm,
1954     /// Represents a `fn x(mut self);`.
1955     Mut,
1956     /// Represents a `fn x(&self);`.
1957     ImmRef,
1958     /// Represents a `fn x(&mut self);`.
1959     MutRef,
1960     /// Represents when a function does not have a self argument or
1961     /// when a function has a `self: X` argument.
1962     None
1963 }
1964
1965 impl ImplicitSelfKind {
1966     /// Does this represent an implicit self?
1967     pub fn has_implicit_self(&self) -> bool {
1968         match *self {
1969             ImplicitSelfKind::None => false,
1970             _ => true,
1971         }
1972     }
1973 }
1974
1975 /// Is the trait definition an auto trait?
1976 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1977 pub enum IsAuto {
1978     Yes,
1979     No
1980 }
1981
1982 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, HashStable,
1983          Ord, RustcEncodable, RustcDecodable, Debug)]
1984 pub enum IsAsync {
1985     Async,
1986     NotAsync,
1987 }
1988
1989 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, HashStable,
1990          RustcEncodable, RustcDecodable, Hash, Debug)]
1991 pub enum Unsafety {
1992     Unsafe,
1993     Normal,
1994 }
1995
1996 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
1997 pub enum Constness {
1998     Const,
1999     NotConst,
2000 }
2001
2002 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2003 pub enum Defaultness {
2004     Default { has_value: bool },
2005     Final,
2006 }
2007
2008 impl Defaultness {
2009     pub fn has_value(&self) -> bool {
2010         match *self {
2011             Defaultness::Default { has_value, .. } => has_value,
2012             Defaultness::Final => true,
2013         }
2014     }
2015
2016     pub fn is_final(&self) -> bool {
2017         *self == Defaultness::Final
2018     }
2019
2020     pub fn is_default(&self) -> bool {
2021         match *self {
2022             Defaultness::Default { .. } => true,
2023             _ => false,
2024         }
2025     }
2026 }
2027
2028 impl fmt::Display for Unsafety {
2029     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2030         fmt::Display::fmt(match *self {
2031                               Unsafety::Normal => "normal",
2032                               Unsafety::Unsafe => "unsafe",
2033                           },
2034                           f)
2035     }
2036 }
2037
2038 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2039 pub enum ImplPolarity {
2040     /// `impl Trait for Type`
2041     Positive,
2042     /// `impl !Trait for Type`
2043     Negative,
2044 }
2045
2046 impl fmt::Debug for ImplPolarity {
2047     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2048         match *self {
2049             ImplPolarity::Positive => "positive".fmt(f),
2050             ImplPolarity::Negative => "negative".fmt(f),
2051         }
2052     }
2053 }
2054
2055
2056 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2057 pub enum FunctionRetTy {
2058     /// Return type is not specified.
2059     ///
2060     /// Functions default to `()` and
2061     /// closures default to inference. Span points to where return
2062     /// type would be inserted.
2063     DefaultReturn(Span),
2064     /// Everything else.
2065     Return(P<Ty>),
2066 }
2067
2068 impl fmt::Display for FunctionRetTy {
2069     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2070         match self {
2071             Return(ref ty) => print::to_string(print::NO_ANN, |s| s.print_type(ty)).fmt(f),
2072             DefaultReturn(_) => "()".fmt(f),
2073         }
2074     }
2075 }
2076
2077 impl FunctionRetTy {
2078     pub fn span(&self) -> Span {
2079         match *self {
2080             DefaultReturn(span) => span,
2081             Return(ref ty) => ty.span,
2082         }
2083     }
2084 }
2085
2086 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2087 pub struct Mod {
2088     /// A span from the first token past `{` to the last token until `}`.
2089     /// For `mod foo;`, the inner span ranges from the first token
2090     /// to the last token in the external file.
2091     pub inner: Span,
2092     pub item_ids: HirVec<ItemId>,
2093 }
2094
2095 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2096 pub struct ForeignMod {
2097     pub abi: Abi,
2098     pub items: HirVec<ForeignItem>,
2099 }
2100
2101 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2102 pub struct GlobalAsm {
2103     pub asm: Symbol,
2104     #[stable_hasher(ignore)] // This is used for error reporting
2105     pub ctxt: SyntaxContext,
2106 }
2107
2108 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2109 pub struct EnumDef {
2110     pub variants: HirVec<Variant>,
2111 }
2112
2113 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2114 pub struct VariantKind {
2115     /// Name of the variant.
2116     #[stable_hasher(project(name))]
2117     pub ident: Ident,
2118     /// Attributes of the variant.
2119     pub attrs: HirVec<Attribute>,
2120     /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2121     pub id: HirId,
2122     /// Fields and constructor id of the variant.
2123     pub data: VariantData,
2124     /// Explicit discriminant (e.g., `Foo = 1`).
2125     pub disr_expr: Option<AnonConst>,
2126 }
2127
2128 pub type Variant = Spanned<VariantKind>;
2129
2130 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2131 pub enum UseKind {
2132     /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2133     /// Also produced for each element of a list `use`, e.g.
2134     /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2135     Single,
2136
2137     /// Glob import, e.g., `use foo::*`.
2138     Glob,
2139
2140     /// Degenerate list import, e.g., `use foo::{a, b}` produces
2141     /// an additional `use foo::{}` for performing checks such as
2142     /// unstable feature gating. May be removed in the future.
2143     ListStem,
2144 }
2145
2146 /// TraitRef's appear in impls.
2147 ///
2148 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
2149 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
2150 /// trait being referred to but just a unique NodeId that serves as a key
2151 /// within the resolution map.
2152 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2153 pub struct TraitRef {
2154     pub path: Path,
2155     // Don't hash the ref_id. It is tracked via the thing it is used to access
2156     #[stable_hasher(ignore)]
2157     pub hir_ref_id: HirId,
2158 }
2159
2160 impl TraitRef {
2161     /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2162     pub fn trait_def_id(&self) -> DefId {
2163         match self.path.res {
2164             Res::Def(DefKind::Trait, did) => did,
2165             Res::Def(DefKind::TraitAlias, did) => did,
2166             Res::Err => {
2167                 FatalError.raise();
2168             }
2169             _ => unreachable!(),
2170         }
2171     }
2172 }
2173
2174 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2175 pub struct PolyTraitRef {
2176     /// The `'a` in `<'a> Foo<&'a T>`.
2177     pub bound_generic_params: HirVec<GenericParam>,
2178
2179     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2180     pub trait_ref: TraitRef,
2181
2182     pub span: Span,
2183 }
2184
2185 pub type Visibility = Spanned<VisibilityKind>;
2186
2187 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2188 pub enum VisibilityKind {
2189     Public,
2190     Crate(CrateSugar),
2191     Restricted { path: P<Path>, hir_id: HirId },
2192     Inherited,
2193 }
2194
2195 impl VisibilityKind {
2196     pub fn is_pub(&self) -> bool {
2197         match *self {
2198             VisibilityKind::Public => true,
2199             _ => false
2200         }
2201     }
2202
2203     pub fn is_pub_restricted(&self) -> bool {
2204         match *self {
2205             VisibilityKind::Public |
2206             VisibilityKind::Inherited => false,
2207             VisibilityKind::Crate(..) |
2208             VisibilityKind::Restricted { .. } => true,
2209         }
2210     }
2211
2212     pub fn descr(&self) -> &'static str {
2213         match *self {
2214             VisibilityKind::Public => "public",
2215             VisibilityKind::Inherited => "private",
2216             VisibilityKind::Crate(..) => "crate-visible",
2217             VisibilityKind::Restricted { .. } => "restricted",
2218         }
2219     }
2220 }
2221
2222 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2223 pub struct StructField {
2224     pub span: Span,
2225     #[stable_hasher(project(name))]
2226     pub ident: Ident,
2227     pub vis: Visibility,
2228     pub hir_id: HirId,
2229     pub ty: P<Ty>,
2230     pub attrs: HirVec<Attribute>,
2231 }
2232
2233 impl StructField {
2234     // Still necessary in couple of places
2235     pub fn is_positional(&self) -> bool {
2236         let first = self.ident.as_str().as_bytes()[0];
2237         first >= b'0' && first <= b'9'
2238     }
2239 }
2240
2241 /// Fields and constructor ids of enum variants and structs
2242 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2243 pub enum VariantData {
2244     /// Struct variant.
2245     ///
2246     /// e.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2247     Struct(HirVec<StructField>, /* recovered */ bool),
2248     /// Tuple variant.
2249     ///
2250     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2251     Tuple(HirVec<StructField>, HirId),
2252     /// Unit variant.
2253     ///
2254     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2255     Unit(HirId),
2256 }
2257
2258 impl VariantData {
2259     /// Return the fields of this variant.
2260     pub fn fields(&self) -> &[StructField] {
2261         match *self {
2262             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2263             _ => &[],
2264         }
2265     }
2266
2267     /// Return the `HirId` of this variant's constructor, if it has one.
2268     pub fn ctor_hir_id(&self) -> Option<HirId> {
2269         match *self {
2270             VariantData::Struct(_, _) => None,
2271             VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2272         }
2273     }
2274 }
2275
2276 // The bodies for items are stored "out of line", in a separate
2277 // hashmap in the `Crate`. Here we just record the node-id of the item
2278 // so it can fetched later.
2279 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2280 pub struct ItemId {
2281     pub id: HirId,
2282 }
2283
2284 /// An item
2285 ///
2286 /// The name might be a dummy name in case of anonymous items
2287 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2288 pub struct Item {
2289     pub ident: Ident,
2290     pub hir_id: HirId,
2291     pub attrs: HirVec<Attribute>,
2292     pub node: ItemKind,
2293     pub vis: Visibility,
2294     pub span: Span,
2295 }
2296
2297 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, HashStable)]
2298 pub struct FnHeader {
2299     pub unsafety: Unsafety,
2300     pub constness: Constness,
2301     pub asyncness: IsAsync,
2302     pub abi: Abi,
2303 }
2304
2305 impl FnHeader {
2306     pub fn is_const(&self) -> bool {
2307         match &self.constness {
2308             Constness::Const => true,
2309             _ => false,
2310         }
2311     }
2312 }
2313
2314 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2315 pub enum ItemKind {
2316     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2317     ///
2318     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2319     ExternCrate(Option<Name>),
2320
2321     /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2322     ///
2323     /// or just
2324     ///
2325     /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2326     Use(P<Path>, UseKind),
2327
2328     /// A `static` item
2329     Static(P<Ty>, Mutability, BodyId),
2330     /// A `const` item
2331     Const(P<Ty>, BodyId),
2332     /// A function declaration
2333     Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2334     /// A module
2335     Mod(Mod),
2336     /// An external module
2337     ForeignMod(ForeignMod),
2338     /// Module-level inline assembly (from global_asm!)
2339     GlobalAsm(P<GlobalAsm>),
2340     /// A type alias, e.g., `type Foo = Bar<u8>`
2341     Ty(P<Ty>, Generics),
2342     /// An existential type definition, e.g., `existential type Foo: Bar;`
2343     Existential(ExistTy),
2344     /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
2345     Enum(EnumDef, Generics),
2346     /// A struct definition, e.g., `struct Foo<A> {x: A}`
2347     Struct(VariantData, Generics),
2348     /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
2349     Union(VariantData, Generics),
2350     /// Represents a Trait Declaration
2351     Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2352     /// Represents a Trait Alias Declaration
2353     TraitAlias(Generics, GenericBounds),
2354
2355     /// An implementation, eg `impl<A> Trait for Foo { .. }`
2356     Impl(Unsafety,
2357          ImplPolarity,
2358          Defaultness,
2359          Generics,
2360          Option<TraitRef>, // (optional) trait this impl implements
2361          P<Ty>, // self
2362          HirVec<ImplItemRef>),
2363 }
2364
2365 impl ItemKind {
2366     pub fn descriptive_variant(&self) -> &str {
2367         match *self {
2368             ItemKind::ExternCrate(..) => "extern crate",
2369             ItemKind::Use(..) => "use",
2370             ItemKind::Static(..) => "static item",
2371             ItemKind::Const(..) => "constant item",
2372             ItemKind::Fn(..) => "function",
2373             ItemKind::Mod(..) => "module",
2374             ItemKind::ForeignMod(..) => "foreign module",
2375             ItemKind::GlobalAsm(..) => "global asm",
2376             ItemKind::Ty(..) => "type alias",
2377             ItemKind::Existential(..) => "existential type",
2378             ItemKind::Enum(..) => "enum",
2379             ItemKind::Struct(..) => "struct",
2380             ItemKind::Union(..) => "union",
2381             ItemKind::Trait(..) => "trait",
2382             ItemKind::TraitAlias(..) => "trait alias",
2383             ItemKind::Impl(..) => "impl",
2384         }
2385     }
2386
2387     pub fn adt_kind(&self) -> Option<AdtKind> {
2388         match *self {
2389             ItemKind::Struct(..) => Some(AdtKind::Struct),
2390             ItemKind::Union(..) => Some(AdtKind::Union),
2391             ItemKind::Enum(..) => Some(AdtKind::Enum),
2392             _ => None,
2393         }
2394     }
2395
2396     pub fn generics(&self) -> Option<&Generics> {
2397         Some(match *self {
2398             ItemKind::Fn(_, _, ref generics, _) |
2399             ItemKind::Ty(_, ref generics) |
2400             ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2401             ItemKind::Enum(_, ref generics) |
2402             ItemKind::Struct(_, ref generics) |
2403             ItemKind::Union(_, ref generics) |
2404             ItemKind::Trait(_, _, ref generics, _, _) |
2405             ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2406             _ => return None
2407         })
2408     }
2409 }
2410
2411 /// A reference from an trait to one of its associated items. This
2412 /// contains the item's id, naturally, but also the item's name and
2413 /// some other high-level details (like whether it is an associated
2414 /// type or method, and whether it is public). This allows other
2415 /// passes to find the impl they want without loading the ID (which
2416 /// means fewer edges in the incremental compilation graph).
2417 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2418 pub struct TraitItemRef {
2419     pub id: TraitItemId,
2420     #[stable_hasher(project(name))]
2421     pub ident: Ident,
2422     pub kind: AssociatedItemKind,
2423     pub span: Span,
2424     pub defaultness: Defaultness,
2425 }
2426
2427 /// A reference from an impl to one of its associated items. This
2428 /// contains the item's ID, naturally, but also the item's name and
2429 /// some other high-level details (like whether it is an associated
2430 /// type or method, and whether it is public). This allows other
2431 /// passes to find the impl they want without loading the ID (which
2432 /// means fewer edges in the incremental compilation graph).
2433 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2434 pub struct ImplItemRef {
2435     pub id: ImplItemId,
2436     #[stable_hasher(project(name))]
2437     pub ident: Ident,
2438     pub kind: AssociatedItemKind,
2439     pub span: Span,
2440     pub vis: Visibility,
2441     pub defaultness: Defaultness,
2442 }
2443
2444 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)]
2445 pub enum AssociatedItemKind {
2446     Const,
2447     Method { has_self: bool },
2448     Type,
2449     Existential,
2450 }
2451
2452 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2453 pub struct ForeignItem {
2454     #[stable_hasher(project(name))]
2455     pub ident: Ident,
2456     pub attrs: HirVec<Attribute>,
2457     pub node: ForeignItemKind,
2458     pub hir_id: HirId,
2459     pub span: Span,
2460     pub vis: Visibility,
2461 }
2462
2463 /// An item within an `extern` block.
2464 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
2465 pub enum ForeignItemKind {
2466     /// A foreign function.
2467     Fn(P<FnDecl>, HirVec<Ident>, Generics),
2468     /// A foreign static item (`static ext: u8`).
2469     Static(P<Ty>, Mutability),
2470     /// A foreign type.
2471     Type,
2472 }
2473
2474 impl ForeignItemKind {
2475     pub fn descriptive_variant(&self) -> &str {
2476         match *self {
2477             ForeignItemKind::Fn(..) => "foreign function",
2478             ForeignItemKind::Static(..) => "foreign static item",
2479             ForeignItemKind::Type => "foreign type",
2480         }
2481     }
2482 }
2483
2484 /// A variable captured by a closure.
2485 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable, HashStable)]
2486 pub struct Upvar<Id = HirId> {
2487     /// The variable being captured.
2488     pub res: Res<Id>,
2489
2490     // First span where it is accessed (there can be multiple).
2491     pub span: Span
2492 }
2493
2494 impl<Id: fmt::Debug + Copy> Upvar<Id> {
2495     pub fn map_id<R>(self, map: impl FnMut(Id) -> R) -> Upvar<R> {
2496         Upvar {
2497             res: self.res.map_id(map),
2498             span: self.span,
2499         }
2500     }
2501
2502     pub fn var_id(&self) -> Id {
2503         match self.res {
2504             Res::Local(id) | Res::Upvar(id, ..) => id,
2505             _ => bug!("Upvar::var_id: bad res ({:?})", self.res)
2506         }
2507     }
2508 }
2509
2510 pub type UpvarMap = NodeMap<Vec<Upvar<ast::NodeId>>>;
2511
2512 pub type CaptureModeMap = NodeMap<CaptureClause>;
2513
2514  // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2515  // has length > 0 if the trait is found through an chain of imports, starting with the
2516  // import/use statement in the scope where the trait is used.
2517 #[derive(Clone, Debug)]
2518 pub struct TraitCandidate {
2519     pub def_id: DefId,
2520     pub import_ids: SmallVec<[NodeId; 1]>,
2521 }
2522
2523 // Trait method resolution
2524 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2525
2526 // Map from the NodeId of a glob import to a list of items which are actually
2527 // imported.
2528 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2529
2530
2531 pub fn provide(providers: &mut Providers<'_>) {
2532     check_attr::provide(providers);
2533     providers.def_kind = map::def_kind;
2534 }
2535
2536 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2537 pub struct CodegenFnAttrs {
2538     pub flags: CodegenFnAttrFlags,
2539     /// Parsed representation of the `#[inline]` attribute
2540     pub inline: InlineAttr,
2541     /// Parsed representation of the `#[optimize]` attribute
2542     pub optimize: OptimizeAttr,
2543     /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
2544     /// function should be exported under
2545     pub export_name: Option<Symbol>,
2546     /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
2547     /// imported function should be imported as. Note that `export_name`
2548     /// probably isn't set when this is set, this is for foreign items while
2549     /// `#[export_name]` is for Rust-defined functions.
2550     pub link_name: Option<Symbol>,
2551     /// The `#[target_feature(enable = "...")]` attribute and the enabled
2552     /// features (only enabled features are supported right now).
2553     pub target_features: Vec<Symbol>,
2554     /// The `#[linkage = "..."]` attribute and the value we found.
2555     pub linkage: Option<Linkage>,
2556     /// The `#[link_section = "..."]` attribute, or what executable section this
2557     /// should be placed in.
2558     pub link_section: Option<Symbol>,
2559 }
2560
2561 bitflags! {
2562     #[derive(RustcEncodable, RustcDecodable, HashStable)]
2563     pub struct CodegenFnAttrFlags: u32 {
2564         /// `#[cold]`: a hint to LLVM that this function, when called, is never on
2565         /// the hot path.
2566         const COLD                      = 1 << 0;
2567         /// `#[allocator]`: a hint to LLVM that the pointer returned from this
2568         /// function is never null.
2569         const ALLOCATOR                 = 1 << 1;
2570         /// `#[unwind]`: an indicator that this function may unwind despite what
2571         /// its ABI signature may otherwise imply.
2572         const UNWIND                    = 1 << 2;
2573         /// `#[rust_allocator_nounwind]`, an indicator that an imported FFI
2574         /// function will never unwind. Probably obsolete by recent changes with
2575         /// #[unwind], but hasn't been removed/migrated yet
2576         const RUSTC_ALLOCATOR_NOUNWIND  = 1 << 3;
2577         /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
2578         /// should be generated.
2579         const NAKED                     = 1 << 4;
2580         /// `#[no_mangle]`: an indicator that the function's name should be the same
2581         /// as its symbol.
2582         const NO_MANGLE                 = 1 << 5;
2583         /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
2584         /// "weird symbol" for the standard library in that it has slightly
2585         /// different linkage, visibility, and reachability rules.
2586         const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2587         /// `#[no_debug]`: an indicator that no debugging information should be
2588         /// generated for this function by LLVM.
2589         const NO_DEBUG                  = 1 << 7;
2590         /// `#[thread_local]`: indicates a static is actually a thread local
2591         /// piece of memory
2592         const THREAD_LOCAL              = 1 << 8;
2593         /// `#[used]`: indicates that LLVM can't eliminate this function (but the
2594         /// linker can!).
2595         const USED                      = 1 << 9;
2596         /// #[ffi_returns_twice], indicates that an extern function can return
2597         /// multiple times
2598         const FFI_RETURNS_TWICE = 1 << 10;
2599     }
2600 }
2601
2602 impl CodegenFnAttrs {
2603     pub fn new() -> CodegenFnAttrs {
2604         CodegenFnAttrs {
2605             flags: CodegenFnAttrFlags::empty(),
2606             inline: InlineAttr::None,
2607             optimize: OptimizeAttr::None,
2608             export_name: None,
2609             link_name: None,
2610             target_features: vec![],
2611             linkage: None,
2612             link_section: None,
2613         }
2614     }
2615
2616     /// Returns `true` if `#[inline]` or `#[inline(always)]` is present.
2617     pub fn requests_inline(&self) -> bool {
2618         match self.inline {
2619             InlineAttr::Hint | InlineAttr::Always => true,
2620             InlineAttr::None | InlineAttr::Never => false,
2621         }
2622     }
2623
2624     /// True if it looks like this symbol needs to be exported, for example:
2625     ///
2626     /// * `#[no_mangle]` is present
2627     /// * `#[export_name(...)]` is present
2628     /// * `#[linkage]` is present
2629     pub fn contains_extern_indicator(&self) -> bool {
2630         self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
2631             self.export_name.is_some() ||
2632             match self.linkage {
2633                 // these are private, make sure we don't try to consider
2634                 // them external
2635                 None |
2636                 Some(Linkage::Internal) |
2637                 Some(Linkage::Private) => false,
2638                 Some(_) => true,
2639             }
2640     }
2641 }
2642
2643 #[derive(Copy, Clone, Debug)]
2644 pub enum Node<'hir> {
2645     Item(&'hir Item),
2646     ForeignItem(&'hir ForeignItem),
2647     TraitItem(&'hir TraitItem),
2648     ImplItem(&'hir ImplItem),
2649     Variant(&'hir Variant),
2650     Field(&'hir StructField),
2651     AnonConst(&'hir AnonConst),
2652     Expr(&'hir Expr),
2653     Stmt(&'hir Stmt),
2654     PathSegment(&'hir PathSegment),
2655     Ty(&'hir Ty),
2656     TraitRef(&'hir TraitRef),
2657     Binding(&'hir Pat),
2658     Pat(&'hir Pat),
2659     Block(&'hir Block),
2660     Local(&'hir Local),
2661     MacroDef(&'hir MacroDef),
2662
2663     /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2664     /// with synthesized constructors.
2665     Ctor(&'hir VariantData),
2666
2667     Lifetime(&'hir Lifetime),
2668     GenericParam(&'hir GenericParam),
2669     Visibility(&'hir Visibility),
2670
2671     Crate,
2672 }