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