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