]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/mod.rs
Make the compiler support the label-break-value feature
[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.
782     /// Used by `'label {}` blocks and by `catch` statements.
783     pub targeted_by_break: bool,
784     /// If true, don't emit return value type errors as the parser had
785     /// to recover from a parse error so this block will not have an
786     /// appropriate type. A parse error will have been emitted so the
787     /// compilation will never succeed if this is true.
788     pub recovered: bool,
789 }
790
791 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
792 pub struct Pat {
793     pub id: NodeId,
794     pub hir_id: HirId,
795     pub node: PatKind,
796     pub span: Span,
797 }
798
799 impl fmt::Debug for Pat {
800     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
801         write!(f, "pat({}: {})", self.id,
802                print::to_string(print::NO_ANN, |s| s.print_pat(self)))
803     }
804 }
805
806 impl Pat {
807     // FIXME(#19596) this is a workaround, but there should be a better way
808     fn walk_<G>(&self, it: &mut G) -> bool
809         where G: FnMut(&Pat) -> bool
810     {
811         if !it(self) {
812             return false;
813         }
814
815         match self.node {
816             PatKind::Binding(.., Some(ref p)) => p.walk_(it),
817             PatKind::Struct(_, ref fields, _) => {
818                 fields.iter().all(|field| field.node.pat.walk_(it))
819             }
820             PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
821                 s.iter().all(|p| p.walk_(it))
822             }
823             PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
824                 s.walk_(it)
825             }
826             PatKind::Slice(ref before, ref slice, ref after) => {
827                 before.iter().all(|p| p.walk_(it)) &&
828                 slice.iter().all(|p| p.walk_(it)) &&
829                 after.iter().all(|p| p.walk_(it))
830             }
831             PatKind::Wild |
832             PatKind::Lit(_) |
833             PatKind::Range(..) |
834             PatKind::Binding(..) |
835             PatKind::Path(_) => {
836                 true
837             }
838         }
839     }
840
841     pub fn walk<F>(&self, mut it: F) -> bool
842         where F: FnMut(&Pat) -> bool
843     {
844         self.walk_(&mut it)
845     }
846 }
847
848 /// A single field in a struct pattern
849 ///
850 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
851 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
852 /// except is_shorthand is true
853 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
854 pub struct FieldPat {
855     pub id: NodeId,
856     /// The identifier for the field
857     pub name: Name,
858     /// The pattern the field is destructured to
859     pub pat: P<Pat>,
860     pub is_shorthand: bool,
861 }
862
863 /// Explicit binding annotations given in the HIR for a binding. Note
864 /// that this is not the final binding *mode* that we infer after type
865 /// inference.
866 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
867 pub enum BindingAnnotation {
868   /// No binding annotation given: this means that the final binding mode
869   /// will depend on whether we have skipped through a `&` reference
870   /// when matching. For example, the `x` in `Some(x)` will have binding
871   /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
872   /// ultimately be inferred to be by-reference.
873   ///
874   /// Note that implicit reference skipping is not implemented yet (#42640).
875   Unannotated,
876
877   /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
878   Mutable,
879
880   /// Annotated as `ref`, like `ref x`
881   Ref,
882
883   /// Annotated as `ref mut x`.
884   RefMut,
885 }
886
887 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
888 pub enum RangeEnd {
889     Included,
890     Excluded,
891 }
892
893 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
894 pub enum PatKind {
895     /// Represents a wildcard pattern (`_`)
896     Wild,
897
898     /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
899     /// The `NodeId` is the canonical ID for the variable being bound,
900     /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
901     /// which is the pattern ID of the first `x`.
902     Binding(BindingAnnotation, NodeId, Spanned<Name>, Option<P<Pat>>),
903
904     /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
905     /// The `bool` is `true` in the presence of a `..`.
906     Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
907
908     /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
909     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
910     /// 0 <= position <= subpats.len()
911     TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
912
913     /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
914     Path(QPath),
915
916     /// A tuple pattern `(a, b)`.
917     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
918     /// 0 <= position <= subpats.len()
919     Tuple(HirVec<P<Pat>>, Option<usize>),
920     /// A `box` pattern
921     Box(P<Pat>),
922     /// A reference pattern, e.g. `&mut (a, b)`
923     Ref(P<Pat>, Mutability),
924     /// A literal
925     Lit(P<Expr>),
926     /// A range pattern, e.g. `1...2` or `1..2`
927     Range(P<Expr>, P<Expr>, RangeEnd),
928     /// `[a, b, ..i, y, z]` is represented as:
929     ///     `PatKind::Slice(box [a, b], Some(i), box [y, z])`
930     Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
931 }
932
933 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
934 pub enum Mutability {
935     MutMutable,
936     MutImmutable,
937 }
938
939 impl Mutability {
940     /// Return MutMutable only if both arguments are mutable.
941     pub fn and(self, other: Self) -> Self {
942         match self {
943             MutMutable => other,
944             MutImmutable => MutImmutable,
945         }
946     }
947 }
948
949 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
950 pub enum BinOp_ {
951     /// The `+` operator (addition)
952     BiAdd,
953     /// The `-` operator (subtraction)
954     BiSub,
955     /// The `*` operator (multiplication)
956     BiMul,
957     /// The `/` operator (division)
958     BiDiv,
959     /// The `%` operator (modulus)
960     BiRem,
961     /// The `&&` operator (logical and)
962     BiAnd,
963     /// The `||` operator (logical or)
964     BiOr,
965     /// The `^` operator (bitwise xor)
966     BiBitXor,
967     /// The `&` operator (bitwise and)
968     BiBitAnd,
969     /// The `|` operator (bitwise or)
970     BiBitOr,
971     /// The `<<` operator (shift left)
972     BiShl,
973     /// The `>>` operator (shift right)
974     BiShr,
975     /// The `==` operator (equality)
976     BiEq,
977     /// The `<` operator (less than)
978     BiLt,
979     /// The `<=` operator (less than or equal to)
980     BiLe,
981     /// The `!=` operator (not equal to)
982     BiNe,
983     /// The `>=` operator (greater than or equal to)
984     BiGe,
985     /// The `>` operator (greater than)
986     BiGt,
987 }
988
989 impl BinOp_ {
990     pub fn as_str(self) -> &'static str {
991         match self {
992             BiAdd => "+",
993             BiSub => "-",
994             BiMul => "*",
995             BiDiv => "/",
996             BiRem => "%",
997             BiAnd => "&&",
998             BiOr => "||",
999             BiBitXor => "^",
1000             BiBitAnd => "&",
1001             BiBitOr => "|",
1002             BiShl => "<<",
1003             BiShr => ">>",
1004             BiEq => "==",
1005             BiLt => "<",
1006             BiLe => "<=",
1007             BiNe => "!=",
1008             BiGe => ">=",
1009             BiGt => ">",
1010         }
1011     }
1012
1013     pub fn is_lazy(self) -> bool {
1014         match self {
1015             BiAnd | BiOr => true,
1016             _ => false,
1017         }
1018     }
1019
1020     pub fn is_shift(self) -> bool {
1021         match self {
1022             BiShl | BiShr => true,
1023             _ => false,
1024         }
1025     }
1026
1027     pub fn is_comparison(self) -> bool {
1028         match self {
1029             BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
1030             BiAnd |
1031             BiOr |
1032             BiAdd |
1033             BiSub |
1034             BiMul |
1035             BiDiv |
1036             BiRem |
1037             BiBitXor |
1038             BiBitAnd |
1039             BiBitOr |
1040             BiShl |
1041             BiShr => false,
1042         }
1043     }
1044
1045     /// Returns `true` if the binary operator takes its arguments by value
1046     pub fn is_by_value(self) -> bool {
1047         !self.is_comparison()
1048     }
1049 }
1050
1051 impl Into<ast::BinOpKind> for BinOp_ {
1052     fn into(self) -> ast::BinOpKind {
1053         match self {
1054             BiAdd => ast::BinOpKind::Add,
1055             BiSub => ast::BinOpKind::Sub,
1056             BiMul => ast::BinOpKind::Mul,
1057             BiDiv => ast::BinOpKind::Div,
1058             BiRem => ast::BinOpKind::Rem,
1059             BiAnd => ast::BinOpKind::And,
1060             BiOr => ast::BinOpKind::Or,
1061             BiBitXor => ast::BinOpKind::BitXor,
1062             BiBitAnd => ast::BinOpKind::BitAnd,
1063             BiBitOr => ast::BinOpKind::BitOr,
1064             BiShl => ast::BinOpKind::Shl,
1065             BiShr => ast::BinOpKind::Shr,
1066             BiEq => ast::BinOpKind::Eq,
1067             BiLt => ast::BinOpKind::Lt,
1068             BiLe => ast::BinOpKind::Le,
1069             BiNe => ast::BinOpKind::Ne,
1070             BiGe => ast::BinOpKind::Ge,
1071             BiGt => ast::BinOpKind::Gt,
1072         }
1073     }
1074 }
1075
1076 pub type BinOp = Spanned<BinOp_>;
1077
1078 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1079 pub enum UnOp {
1080     /// The `*` operator for dereferencing
1081     UnDeref,
1082     /// The `!` operator for logical inversion
1083     UnNot,
1084     /// The `-` operator for negation
1085     UnNeg,
1086 }
1087
1088 impl UnOp {
1089     pub fn as_str(self) -> &'static str {
1090         match self {
1091             UnDeref => "*",
1092             UnNot => "!",
1093             UnNeg => "-",
1094         }
1095     }
1096
1097     /// Returns `true` if the unary operator takes its argument by value
1098     pub fn is_by_value(self) -> bool {
1099         match self {
1100             UnNeg | UnNot => true,
1101             _ => false,
1102         }
1103     }
1104 }
1105
1106 /// A statement
1107 pub type Stmt = Spanned<Stmt_>;
1108
1109 impl fmt::Debug for Stmt_ {
1110     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1111         // Sadness.
1112         let spanned = codemap::dummy_spanned(self.clone());
1113         write!(f,
1114                "stmt({}: {})",
1115                spanned.node.id(),
1116                print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
1117     }
1118 }
1119
1120 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1121 pub enum Stmt_ {
1122     /// Could be an item or a local (let) binding:
1123     StmtDecl(P<Decl>, NodeId),
1124
1125     /// Expr without trailing semi-colon (must have unit type):
1126     StmtExpr(P<Expr>, NodeId),
1127
1128     /// Expr with trailing semi-colon (may have any type):
1129     StmtSemi(P<Expr>, NodeId),
1130 }
1131
1132 impl Stmt_ {
1133     pub fn attrs(&self) -> &[Attribute] {
1134         match *self {
1135             StmtDecl(ref d, _) => d.node.attrs(),
1136             StmtExpr(ref e, _) |
1137             StmtSemi(ref e, _) => &e.attrs,
1138         }
1139     }
1140
1141     pub fn id(&self) -> NodeId {
1142         match *self {
1143             StmtDecl(_, id) => id,
1144             StmtExpr(_, id) => id,
1145             StmtSemi(_, id) => id,
1146         }
1147     }
1148 }
1149
1150 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
1151 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1152 pub struct Local {
1153     pub pat: P<Pat>,
1154     pub ty: Option<P<Ty>>,
1155     /// Initializer expression to set the value, if any
1156     pub init: Option<P<Expr>>,
1157     pub id: NodeId,
1158     pub hir_id: HirId,
1159     pub span: Span,
1160     pub attrs: ThinVec<Attribute>,
1161     pub source: LocalSource,
1162 }
1163
1164 pub type Decl = Spanned<Decl_>;
1165
1166 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1167 pub enum Decl_ {
1168     /// A local (let) binding:
1169     DeclLocal(P<Local>),
1170     /// An item binding:
1171     DeclItem(ItemId),
1172 }
1173
1174 impl Decl_ {
1175     pub fn attrs(&self) -> &[Attribute] {
1176         match *self {
1177             DeclLocal(ref l) => &l.attrs,
1178             DeclItem(_) => &[]
1179         }
1180     }
1181
1182     pub fn is_local(&self) -> bool {
1183         match *self {
1184             Decl_::DeclLocal(_) => true,
1185             _ => false,
1186         }
1187     }
1188 }
1189
1190 /// represents one arm of a 'match'
1191 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1192 pub struct Arm {
1193     pub attrs: HirVec<Attribute>,
1194     pub pats: HirVec<P<Pat>>,
1195     pub guard: Option<P<Expr>>,
1196     pub body: P<Expr>,
1197 }
1198
1199 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1200 pub struct Field {
1201     pub id: NodeId,
1202     pub name: Spanned<Name>,
1203     pub expr: P<Expr>,
1204     pub span: Span,
1205     pub is_shorthand: bool,
1206 }
1207
1208 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1209 pub enum BlockCheckMode {
1210     DefaultBlock,
1211     UnsafeBlock(UnsafeSource),
1212     PushUnsafeBlock(UnsafeSource),
1213     PopUnsafeBlock(UnsafeSource),
1214 }
1215
1216 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1217 pub enum UnsafeSource {
1218     CompilerGenerated,
1219     UserProvided,
1220 }
1221
1222 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1223 pub struct BodyId {
1224     pub node_id: NodeId,
1225 }
1226
1227 /// The body of a function, closure, or constant value. In the case of
1228 /// a function, the body contains not only the function body itself
1229 /// (which is an expression), but also the argument patterns, since
1230 /// those are something that the caller doesn't really care about.
1231 ///
1232 /// # Examples
1233 ///
1234 /// ```
1235 /// fn foo((x, y): (u32, u32)) -> u32 {
1236 ///     x + y
1237 /// }
1238 /// ```
1239 ///
1240 /// Here, the `Body` associated with `foo()` would contain:
1241 ///
1242 /// - an `arguments` array containing the `(x, y)` pattern
1243 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1244 /// - `is_generator` would be false
1245 ///
1246 /// All bodies have an **owner**, which can be accessed via the HIR
1247 /// map using `body_owner_def_id()`.
1248 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1249 pub struct Body {
1250     pub arguments: HirVec<Arg>,
1251     pub value: Expr,
1252     pub is_generator: bool,
1253 }
1254
1255 impl Body {
1256     pub fn id(&self) -> BodyId {
1257         BodyId {
1258             node_id: self.value.id
1259         }
1260     }
1261 }
1262
1263 #[derive(Copy, Clone, Debug)]
1264 pub enum BodyOwnerKind {
1265     /// Functions and methods.
1266     Fn,
1267
1268     /// Constants and associated constants.
1269     Const,
1270
1271     /// Initializer of a `static` item.
1272     Static(Mutability),
1273 }
1274
1275 /// An expression
1276 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1277 pub struct Expr {
1278     pub id: NodeId,
1279     pub span: Span,
1280     pub node: Expr_,
1281     pub attrs: ThinVec<Attribute>,
1282     pub hir_id: HirId,
1283 }
1284
1285 impl Expr {
1286     pub fn precedence(&self) -> ExprPrecedence {
1287         match self.node {
1288             ExprBox(_) => ExprPrecedence::Box,
1289             ExprArray(_) => ExprPrecedence::Array,
1290             ExprCall(..) => ExprPrecedence::Call,
1291             ExprMethodCall(..) => ExprPrecedence::MethodCall,
1292             ExprTup(_) => ExprPrecedence::Tup,
1293             ExprBinary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1294             ExprUnary(..) => ExprPrecedence::Unary,
1295             ExprLit(_) => ExprPrecedence::Lit,
1296             ExprType(..) | ExprCast(..) => ExprPrecedence::Cast,
1297             ExprIf(..) => ExprPrecedence::If,
1298             ExprWhile(..) => ExprPrecedence::While,
1299             ExprLoop(..) => ExprPrecedence::Loop,
1300             ExprMatch(..) => ExprPrecedence::Match,
1301             ExprClosure(..) => ExprPrecedence::Closure,
1302             ExprBlock(..) => ExprPrecedence::Block,
1303             ExprAssign(..) => ExprPrecedence::Assign,
1304             ExprAssignOp(..) => ExprPrecedence::AssignOp,
1305             ExprField(..) => ExprPrecedence::Field,
1306             ExprIndex(..) => ExprPrecedence::Index,
1307             ExprPath(..) => ExprPrecedence::Path,
1308             ExprAddrOf(..) => ExprPrecedence::AddrOf,
1309             ExprBreak(..) => ExprPrecedence::Break,
1310             ExprAgain(..) => ExprPrecedence::Continue,
1311             ExprRet(..) => ExprPrecedence::Ret,
1312             ExprInlineAsm(..) => ExprPrecedence::InlineAsm,
1313             ExprStruct(..) => ExprPrecedence::Struct,
1314             ExprRepeat(..) => ExprPrecedence::Repeat,
1315             ExprYield(..) => ExprPrecedence::Yield,
1316         }
1317     }
1318 }
1319
1320 impl fmt::Debug for Expr {
1321     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1322         write!(f, "expr({}: {})", self.id,
1323                print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1324     }
1325 }
1326
1327 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1328 pub enum Expr_ {
1329     /// A `box x` expression.
1330     ExprBox(P<Expr>),
1331     /// An array (`[a, b, c, d]`)
1332     ExprArray(HirVec<Expr>),
1333     /// A function call
1334     ///
1335     /// The first field resolves to the function itself (usually an `ExprPath`),
1336     /// and the second field is the list of arguments.
1337     /// This also represents calling the constructor of
1338     /// tuple-like ADTs such as tuple structs and enum variants.
1339     ExprCall(P<Expr>, HirVec<Expr>),
1340     /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1341     ///
1342     /// The `PathSegment`/`Span` represent the method name and its generic arguments
1343     /// (within the angle brackets).
1344     /// The first element of the vector of `Expr`s is the expression that evaluates
1345     /// to the object on which the method is being called on (the receiver),
1346     /// and the remaining elements are the rest of the arguments.
1347     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1348     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1349     ExprMethodCall(PathSegment, Span, HirVec<Expr>),
1350     /// A tuple (`(a, b, c ,d)`)
1351     ExprTup(HirVec<Expr>),
1352     /// A binary operation (For example: `a + b`, `a * b`)
1353     ExprBinary(BinOp, P<Expr>, P<Expr>),
1354     /// A unary operation (For example: `!x`, `*x`)
1355     ExprUnary(UnOp, P<Expr>),
1356     /// A literal (For example: `1`, `"foo"`)
1357     ExprLit(P<Lit>),
1358     /// A cast (`foo as f64`)
1359     ExprCast(P<Expr>, P<Ty>),
1360     ExprType(P<Expr>, P<Ty>),
1361     /// An `if` block, with an optional else block
1362     ///
1363     /// `if expr { expr } else { expr }`
1364     ExprIf(P<Expr>, P<Expr>, Option<P<Expr>>),
1365     /// A while loop, with an optional label
1366     ///
1367     /// `'label: while expr { block }`
1368     ExprWhile(P<Expr>, P<Block>, Option<Label>),
1369     /// Conditionless loop (can be exited with break, continue, or return)
1370     ///
1371     /// `'label: loop { block }`
1372     ExprLoop(P<Block>, Option<Label>, LoopSource),
1373     /// A `match` block, with a source that indicates whether or not it is
1374     /// the result of a desugaring, and if so, which kind.
1375     ExprMatch(P<Expr>, HirVec<Arm>, MatchSource),
1376     /// A closure (for example, `move |a, b, c| {a + b + c}`).
1377     ///
1378     /// The final span is the span of the argument block `|...|`
1379     ///
1380     /// This may also be a generator literal, indicated by the final boolean,
1381     /// in that case there is an GeneratorClause.
1382     ExprClosure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1383     /// A block (`'label: { ... }`)
1384     ExprBlock(P<Block>, Option<Label>),
1385
1386     /// An assignment (`a = foo()`)
1387     ExprAssign(P<Expr>, P<Expr>),
1388     /// An assignment with an operator
1389     ///
1390     /// For example, `a += 1`.
1391     ExprAssignOp(BinOp, P<Expr>, P<Expr>),
1392     /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct or tuple field
1393     ExprField(P<Expr>, Spanned<Name>),
1394     /// An indexing operation (`foo[2]`)
1395     ExprIndex(P<Expr>, P<Expr>),
1396
1397     /// Path to a definition, possibly containing lifetime or type parameters.
1398     ExprPath(QPath),
1399
1400     /// A referencing operation (`&a` or `&mut a`)
1401     ExprAddrOf(Mutability, P<Expr>),
1402     /// A `break`, with an optional label to break
1403     ExprBreak(Destination, Option<P<Expr>>),
1404     /// A `continue`, with an optional label
1405     ExprAgain(Destination),
1406     /// A `return`, with an optional value to be returned
1407     ExprRet(Option<P<Expr>>),
1408
1409     /// Inline assembly (from `asm!`), with its outputs and inputs.
1410     ExprInlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1411
1412     /// A struct or struct-like variant literal expression.
1413     ///
1414     /// For example, `Foo {x: 1, y: 2}`, or
1415     /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1416     ExprStruct(QPath, HirVec<Field>, Option<P<Expr>>),
1417
1418     /// An array literal constructed from one repeated element.
1419     ///
1420     /// For example, `[1; 5]`. The first expression is the element
1421     /// to be repeated; the second is the number of times to repeat it.
1422     ExprRepeat(P<Expr>, BodyId),
1423
1424     /// A suspension point for generators. This is `yield <expr>` in Rust.
1425     ExprYield(P<Expr>),
1426 }
1427
1428 /// Optionally `Self`-qualified value/type path or associated extension.
1429 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1430 pub enum QPath {
1431     /// Path to a definition, optionally "fully-qualified" with a `Self`
1432     /// type, if the path points to an associated item in a trait.
1433     ///
1434     /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1435     /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1436     /// even though they both have the same two-segment `Clone::clone` `Path`.
1437     Resolved(Option<P<Ty>>, P<Path>),
1438
1439     /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1440     /// Will be resolved by type-checking to an associated item.
1441     ///
1442     /// UFCS source paths can desugar into this, with `Vec::new` turning into
1443     /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1444     /// the `X` and `Y` nodes each being a `TyPath(QPath::TypeRelative(..))`.
1445     TypeRelative(P<Ty>, P<PathSegment>)
1446 }
1447
1448 /// Hints at the original code for a let statement
1449 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1450 pub enum LocalSource {
1451     /// A `match _ { .. }`
1452     Normal,
1453     /// A desugared `for _ in _ { .. }` loop
1454     ForLoopDesugar,
1455 }
1456
1457 /// Hints at the original code for a `match _ { .. }`
1458 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1459 pub enum MatchSource {
1460     /// A `match _ { .. }`
1461     Normal,
1462     /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1463     IfLetDesugar {
1464         contains_else_clause: bool,
1465     },
1466     /// A `while let _ = _ { .. }` (which was desugared to a
1467     /// `loop { match _ { .. } }`)
1468     WhileLetDesugar,
1469     /// A desugared `for _ in _ { .. }` loop
1470     ForLoopDesugar,
1471     /// A desugared `?` operator
1472     TryDesugar,
1473 }
1474
1475 /// The loop type that yielded an ExprLoop
1476 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1477 pub enum LoopSource {
1478     /// A `loop { .. }` loop
1479     Loop,
1480     /// A `while let _ = _ { .. }` loop
1481     WhileLet,
1482     /// A `for _ in _ { .. }` loop
1483     ForLoop,
1484 }
1485
1486 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1487 pub enum LoopIdError {
1488     OutsideLoopScope,
1489     UnlabeledCfInWhileCondition,
1490     UnresolvedLabel,
1491 }
1492
1493 impl fmt::Display for LoopIdError {
1494     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1495         fmt::Display::fmt(match *self {
1496             LoopIdError::OutsideLoopScope => "not inside loop scope",
1497             LoopIdError::UnlabeledCfInWhileCondition =>
1498                 "unlabeled control flow (break or continue) in while condition",
1499             LoopIdError::UnresolvedLabel => "label not found",
1500         }, f)
1501     }
1502 }
1503
1504 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1505 pub struct Destination {
1506     // This is `Some(_)` iff there is an explicit user-specified `label
1507     pub label: Option<Label>,
1508
1509     // These errors are caught and then reported during the diagnostics pass in
1510     // librustc_passes/loops.rs
1511     pub target_id: Result<NodeId, LoopIdError>,
1512 }
1513
1514 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1515 pub enum GeneratorMovability {
1516     Static,
1517     Movable,
1518 }
1519
1520 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1521 pub enum CaptureClause {
1522     CaptureByValue,
1523     CaptureByRef,
1524 }
1525
1526 // NB: If you change this, you'll probably want to change the corresponding
1527 // type structure in middle/ty.rs as well.
1528 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1529 pub struct MutTy {
1530     pub ty: P<Ty>,
1531     pub mutbl: Mutability,
1532 }
1533
1534 /// Represents a method's signature in a trait declaration or implementation.
1535 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1536 pub struct MethodSig {
1537     pub unsafety: Unsafety,
1538     pub constness: Constness,
1539     pub abi: Abi,
1540     pub decl: P<FnDecl>,
1541 }
1542
1543 // The bodies for items are stored "out of line", in a separate
1544 // hashmap in the `Crate`. Here we just record the node-id of the item
1545 // so it can fetched later.
1546 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1547 pub struct TraitItemId {
1548     pub node_id: NodeId,
1549 }
1550
1551 /// Represents an item declaration within a trait declaration,
1552 /// possibly including a default implementation. A trait item is
1553 /// either required (meaning it doesn't have an implementation, just a
1554 /// signature) or provided (meaning it has a default implementation).
1555 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1556 pub struct TraitItem {
1557     pub id: NodeId,
1558     pub name: Name,
1559     pub hir_id: HirId,
1560     pub attrs: HirVec<Attribute>,
1561     pub generics: Generics,
1562     pub node: TraitItemKind,
1563     pub span: Span,
1564 }
1565
1566 /// A trait method's body (or just argument names).
1567 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1568 pub enum TraitMethod {
1569     /// No default body in the trait, just a signature.
1570     Required(HirVec<Spanned<Name>>),
1571
1572     /// Both signature and body are provided in the trait.
1573     Provided(BodyId),
1574 }
1575
1576 /// Represents a trait method or associated constant or type
1577 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1578 pub enum TraitItemKind {
1579     /// An associated constant with an optional value (otherwise `impl`s
1580     /// must contain a value)
1581     Const(P<Ty>, Option<BodyId>),
1582     /// A method with an optional body
1583     Method(MethodSig, TraitMethod),
1584     /// An associated type with (possibly empty) bounds and optional concrete
1585     /// type
1586     Type(TyParamBounds, Option<P<Ty>>),
1587 }
1588
1589 // The bodies for items are stored "out of line", in a separate
1590 // hashmap in the `Crate`. Here we just record the node-id of the item
1591 // so it can fetched later.
1592 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1593 pub struct ImplItemId {
1594     pub node_id: NodeId,
1595 }
1596
1597 /// Represents anything within an `impl` block
1598 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1599 pub struct ImplItem {
1600     pub id: NodeId,
1601     pub name: Name,
1602     pub hir_id: HirId,
1603     pub vis: Visibility,
1604     pub defaultness: Defaultness,
1605     pub attrs: HirVec<Attribute>,
1606     pub generics: Generics,
1607     pub node: ImplItemKind,
1608     pub span: Span,
1609 }
1610
1611 /// Represents different contents within `impl`s
1612 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1613 pub enum ImplItemKind {
1614     /// An associated constant of the given type, set to the constant result
1615     /// of the expression
1616     Const(P<Ty>, BodyId),
1617     /// A method implementation with the given signature and body
1618     Method(MethodSig, BodyId),
1619     /// An associated type
1620     Type(P<Ty>),
1621 }
1622
1623 // Bind a type to an associated type: `A=Foo`.
1624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1625 pub struct TypeBinding {
1626     pub id: NodeId,
1627     pub name: Name,
1628     pub ty: P<Ty>,
1629     pub span: Span,
1630 }
1631
1632
1633 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1634 pub struct Ty {
1635     pub id: NodeId,
1636     pub node: Ty_,
1637     pub span: Span,
1638     pub hir_id: HirId,
1639 }
1640
1641 impl fmt::Debug for Ty {
1642     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1643         write!(f, "type({})",
1644                print::to_string(print::NO_ANN, |s| s.print_type(self)))
1645     }
1646 }
1647
1648 /// Not represented directly in the AST, referred to by name through a ty_path.
1649 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1650 pub enum PrimTy {
1651     TyInt(IntTy),
1652     TyUint(UintTy),
1653     TyFloat(FloatTy),
1654     TyStr,
1655     TyBool,
1656     TyChar,
1657 }
1658
1659 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1660 pub struct BareFnTy {
1661     pub unsafety: Unsafety,
1662     pub abi: Abi,
1663     pub generic_params: HirVec<GenericParam>,
1664     pub decl: P<FnDecl>,
1665     pub arg_names: HirVec<Spanned<Name>>,
1666 }
1667
1668 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1669 pub struct ExistTy {
1670     pub generics: Generics,
1671     pub bounds: TyParamBounds,
1672 }
1673
1674 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1675 /// The different kinds of types recognized by the compiler
1676 pub enum Ty_ {
1677     /// A variable length slice (`[T]`)
1678     TySlice(P<Ty>),
1679     /// A fixed length array (`[T; n]`)
1680     TyArray(P<Ty>, BodyId),
1681     /// A raw pointer (`*const T` or `*mut T`)
1682     TyPtr(MutTy),
1683     /// A reference (`&'a T` or `&'a mut T`)
1684     TyRptr(Lifetime, MutTy),
1685     /// A bare function (e.g. `fn(usize) -> bool`)
1686     TyBareFn(P<BareFnTy>),
1687     /// The never type (`!`)
1688     TyNever,
1689     /// A tuple (`(A, B, C, D,...)`)
1690     TyTup(HirVec<P<Ty>>),
1691     /// A path to a type definition (`module::module::...::Type`), or an
1692     /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1693     ///
1694     /// Type parameters may be stored in each `PathSegment`.
1695     TyPath(QPath),
1696     /// A trait object type `Bound1 + Bound2 + Bound3`
1697     /// where `Bound` is a trait or a lifetime.
1698     TyTraitObject(HirVec<PolyTraitRef>, Lifetime),
1699     /// An existentially quantified (there exists a type satisfying) `impl
1700     /// Bound1 + Bound2 + Bound3` type where `Bound` is a trait or a lifetime.
1701     ///
1702     /// The `ExistTy` structure emulates an
1703     /// `abstract type Foo<'a, 'b>: MyTrait<'a, 'b>;`.
1704     ///
1705     /// The `HirVec<Lifetime>` is the list of lifetimes applied as parameters
1706     /// to the `abstract type`, e.g. the `'c` and `'d` in `-> Foo<'c, 'd>`.
1707     /// This list is only a list of lifetimes and not type parameters
1708     /// because all in-scope type parameters are captured by `impl Trait`,
1709     /// so they are resolved directly through the parent `Generics`.
1710     TyImplTraitExistential(ExistTy, HirVec<Lifetime>),
1711     /// Unused for now
1712     TyTypeof(BodyId),
1713     /// TyInfer means the type should be inferred instead of it having been
1714     /// specified. This can appear anywhere in a type.
1715     TyInfer,
1716     /// Placeholder for a type that has failed to be defined.
1717     TyErr,
1718 }
1719
1720 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1721 pub struct InlineAsmOutput {
1722     pub constraint: Symbol,
1723     pub is_rw: bool,
1724     pub is_indirect: bool,
1725 }
1726
1727 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1728 pub struct InlineAsm {
1729     pub asm: Symbol,
1730     pub asm_str_style: StrStyle,
1731     pub outputs: HirVec<InlineAsmOutput>,
1732     pub inputs: HirVec<Symbol>,
1733     pub clobbers: HirVec<Symbol>,
1734     pub volatile: bool,
1735     pub alignstack: bool,
1736     pub dialect: AsmDialect,
1737     pub ctxt: SyntaxContext,
1738 }
1739
1740 /// represents an argument in a function header
1741 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1742 pub struct Arg {
1743     pub pat: P<Pat>,
1744     pub id: NodeId,
1745     pub hir_id: HirId,
1746 }
1747
1748 /// Represents the header (not the body) of a function declaration
1749 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1750 pub struct FnDecl {
1751     pub inputs: HirVec<P<Ty>>,
1752     pub output: FunctionRetTy,
1753     pub variadic: bool,
1754     /// True if this function has an `self`, `&self` or `&mut self` receiver
1755     /// (but not a `self: Xxx` one).
1756     pub has_implicit_self: bool,
1757 }
1758
1759 /// Is the trait definition an auto trait?
1760 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1761 pub enum IsAuto {
1762     Yes,
1763     No
1764 }
1765
1766 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1767 pub enum Unsafety {
1768     Unsafe,
1769     Normal,
1770 }
1771
1772 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1773 pub enum Constness {
1774     Const,
1775     NotConst,
1776 }
1777
1778 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1779 pub enum Defaultness {
1780     Default { has_value: bool },
1781     Final,
1782 }
1783
1784 impl Defaultness {
1785     pub fn has_value(&self) -> bool {
1786         match *self {
1787             Defaultness::Default { has_value, .. } => has_value,
1788             Defaultness::Final => true,
1789         }
1790     }
1791
1792     pub fn is_final(&self) -> bool {
1793         *self == Defaultness::Final
1794     }
1795
1796     pub fn is_default(&self) -> bool {
1797         match *self {
1798             Defaultness::Default { .. } => true,
1799             _ => false,
1800         }
1801     }
1802 }
1803
1804 impl fmt::Display for Unsafety {
1805     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1806         fmt::Display::fmt(match *self {
1807                               Unsafety::Normal => "normal",
1808                               Unsafety::Unsafe => "unsafe",
1809                           },
1810                           f)
1811     }
1812 }
1813
1814 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1815 pub enum ImplPolarity {
1816     /// `impl Trait for Type`
1817     Positive,
1818     /// `impl !Trait for Type`
1819     Negative,
1820 }
1821
1822 impl fmt::Debug for ImplPolarity {
1823     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1824         match *self {
1825             ImplPolarity::Positive => "positive".fmt(f),
1826             ImplPolarity::Negative => "negative".fmt(f),
1827         }
1828     }
1829 }
1830
1831
1832 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1833 pub enum FunctionRetTy {
1834     /// Return type is not specified.
1835     ///
1836     /// Functions default to `()` and
1837     /// closures default to inference. Span points to where return
1838     /// type would be inserted.
1839     DefaultReturn(Span),
1840     /// Everything else
1841     Return(P<Ty>),
1842 }
1843
1844 impl FunctionRetTy {
1845     pub fn span(&self) -> Span {
1846         match *self {
1847             DefaultReturn(span) => span,
1848             Return(ref ty) => ty.span,
1849         }
1850     }
1851 }
1852
1853 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1854 pub struct Mod {
1855     /// A span from the first token past `{` to the last token until `}`.
1856     /// For `mod foo;`, the inner span ranges from the first token
1857     /// to the last token in the external file.
1858     pub inner: Span,
1859     pub item_ids: HirVec<ItemId>,
1860 }
1861
1862 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1863 pub struct ForeignMod {
1864     pub abi: Abi,
1865     pub items: HirVec<ForeignItem>,
1866 }
1867
1868 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1869 pub struct GlobalAsm {
1870     pub asm: Symbol,
1871     pub ctxt: SyntaxContext,
1872 }
1873
1874 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1875 pub struct EnumDef {
1876     pub variants: HirVec<Variant>,
1877 }
1878
1879 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1880 pub struct Variant_ {
1881     pub name: Name,
1882     pub attrs: HirVec<Attribute>,
1883     pub data: VariantData,
1884     /// Explicit discriminant, eg `Foo = 1`
1885     pub disr_expr: Option<BodyId>,
1886 }
1887
1888 pub type Variant = Spanned<Variant_>;
1889
1890 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1891 pub enum UseKind {
1892     /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1893     /// Also produced for each element of a list `use`, e.g.
1894     // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1895     Single,
1896
1897     /// Glob import, e.g. `use foo::*`.
1898     Glob,
1899
1900     /// Degenerate list import, e.g. `use foo::{a, b}` produces
1901     /// an additional `use foo::{}` for performing checks such as
1902     /// unstable feature gating. May be removed in the future.
1903     ListStem,
1904 }
1905
1906 /// TraitRef's appear in impls.
1907 ///
1908 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1909 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1910 /// trait being referred to but just a unique NodeId that serves as a key
1911 /// within the DefMap.
1912 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1913 pub struct TraitRef {
1914     pub path: Path,
1915     pub ref_id: NodeId,
1916 }
1917
1918 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1919 pub struct PolyTraitRef {
1920     /// The `'a` in `<'a> Foo<&'a T>`
1921     pub bound_generic_params: HirVec<GenericParam>,
1922
1923     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1924     pub trait_ref: TraitRef,
1925
1926     pub span: Span,
1927 }
1928
1929 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1930 pub enum Visibility {
1931     Public,
1932     Crate,
1933     Restricted { path: P<Path>, id: NodeId },
1934     Inherited,
1935 }
1936
1937 impl Visibility {
1938     pub fn is_pub_restricted(&self) -> bool {
1939         use self::Visibility::*;
1940         match self {
1941             &Public |
1942             &Inherited => false,
1943             &Crate |
1944             &Restricted { .. } => true,
1945         }
1946     }
1947 }
1948
1949 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1950 pub struct StructField {
1951     pub span: Span,
1952     pub name: Name,
1953     pub vis: Visibility,
1954     pub id: NodeId,
1955     pub ty: P<Ty>,
1956     pub attrs: HirVec<Attribute>,
1957 }
1958
1959 impl StructField {
1960     // Still necessary in couple of places
1961     pub fn is_positional(&self) -> bool {
1962         let first = self.name.as_str().as_bytes()[0];
1963         first >= b'0' && first <= b'9'
1964     }
1965 }
1966
1967 /// Fields and Ids of enum variants and structs
1968 ///
1969 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1970 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1971 /// One shared Id can be successfully used for these two purposes.
1972 /// Id of the whole enum lives in `Item`.
1973 ///
1974 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1975 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1976 /// the variant itself" from enum variants.
1977 /// Id of the whole struct lives in `Item`.
1978 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1979 pub enum VariantData {
1980     Struct(HirVec<StructField>, NodeId),
1981     Tuple(HirVec<StructField>, NodeId),
1982     Unit(NodeId),
1983 }
1984
1985 impl VariantData {
1986     pub fn fields(&self) -> &[StructField] {
1987         match *self {
1988             VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1989             _ => &[],
1990         }
1991     }
1992     pub fn id(&self) -> NodeId {
1993         match *self {
1994             VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
1995         }
1996     }
1997     pub fn is_struct(&self) -> bool {
1998         if let VariantData::Struct(..) = *self {
1999             true
2000         } else {
2001             false
2002         }
2003     }
2004     pub fn is_tuple(&self) -> bool {
2005         if let VariantData::Tuple(..) = *self {
2006             true
2007         } else {
2008             false
2009         }
2010     }
2011     pub fn is_unit(&self) -> bool {
2012         if let VariantData::Unit(..) = *self {
2013             true
2014         } else {
2015             false
2016         }
2017     }
2018 }
2019
2020 // The bodies for items are stored "out of line", in a separate
2021 // hashmap in the `Crate`. Here we just record the node-id of the item
2022 // so it can fetched later.
2023 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2024 pub struct ItemId {
2025     pub id: NodeId,
2026 }
2027
2028 /// An item
2029 ///
2030 /// The name might be a dummy name in case of anonymous items
2031 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2032 pub struct Item {
2033     pub name: Name,
2034     pub id: NodeId,
2035     pub hir_id: HirId,
2036     pub attrs: HirVec<Attribute>,
2037     pub node: Item_,
2038     pub vis: Visibility,
2039     pub span: Span,
2040 }
2041
2042 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2043 pub enum Item_ {
2044     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2045     ///
2046     /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2047     ItemExternCrate(Option<Name>),
2048
2049     /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2050     ///
2051     /// or just
2052     ///
2053     /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2054     ItemUse(P<Path>, UseKind),
2055
2056     /// A `static` item
2057     ItemStatic(P<Ty>, Mutability, BodyId),
2058     /// A `const` item
2059     ItemConst(P<Ty>, BodyId),
2060     /// A function declaration
2061     ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, BodyId),
2062     /// A module
2063     ItemMod(Mod),
2064     /// An external module
2065     ItemForeignMod(ForeignMod),
2066     /// Module-level inline assembly (from global_asm!)
2067     ItemGlobalAsm(P<GlobalAsm>),
2068     /// A type alias, e.g. `type Foo = Bar<u8>`
2069     ItemTy(P<Ty>, Generics),
2070     /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
2071     ItemEnum(EnumDef, Generics),
2072     /// A struct definition, e.g. `struct Foo<A> {x: A}`
2073     ItemStruct(VariantData, Generics),
2074     /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
2075     ItemUnion(VariantData, Generics),
2076     /// Represents a Trait Declaration
2077     ItemTrait(IsAuto, Unsafety, Generics, TyParamBounds, HirVec<TraitItemRef>),
2078     /// Represents a Trait Alias Declaration
2079     ItemTraitAlias(Generics, TyParamBounds),
2080
2081     /// An implementation, eg `impl<A> Trait for Foo { .. }`
2082     ItemImpl(Unsafety,
2083              ImplPolarity,
2084              Defaultness,
2085              Generics,
2086              Option<TraitRef>, // (optional) trait this impl implements
2087              P<Ty>, // self
2088              HirVec<ImplItemRef>),
2089 }
2090
2091 impl Item_ {
2092     pub fn descriptive_variant(&self) -> &str {
2093         match *self {
2094             ItemExternCrate(..) => "extern crate",
2095             ItemUse(..) => "use",
2096             ItemStatic(..) => "static item",
2097             ItemConst(..) => "constant item",
2098             ItemFn(..) => "function",
2099             ItemMod(..) => "module",
2100             ItemForeignMod(..) => "foreign module",
2101             ItemGlobalAsm(..) => "global asm",
2102             ItemTy(..) => "type alias",
2103             ItemEnum(..) => "enum",
2104             ItemStruct(..) => "struct",
2105             ItemUnion(..) => "union",
2106             ItemTrait(..) => "trait",
2107             ItemTraitAlias(..) => "trait alias",
2108             ItemImpl(..) => "item",
2109         }
2110     }
2111
2112     pub fn adt_kind(&self) -> Option<AdtKind> {
2113         match *self {
2114             ItemStruct(..) => Some(AdtKind::Struct),
2115             ItemUnion(..) => Some(AdtKind::Union),
2116             ItemEnum(..) => Some(AdtKind::Enum),
2117             _ => None,
2118         }
2119     }
2120
2121     pub fn generics(&self) -> Option<&Generics> {
2122         Some(match *self {
2123             ItemFn(_, _, _, _, ref generics, _) |
2124             ItemTy(_, ref generics) |
2125             ItemEnum(_, ref generics) |
2126             ItemStruct(_, ref generics) |
2127             ItemUnion(_, ref generics) |
2128             ItemTrait(_, _, ref generics, _, _) |
2129             ItemImpl(_, _, _, ref generics, _, _, _)=> generics,
2130             _ => return None
2131         })
2132     }
2133 }
2134
2135 /// A reference from an trait to one of its associated items. This
2136 /// contains the item's id, naturally, but also the item's name and
2137 /// some other high-level details (like whether it is an associated
2138 /// type or method, and whether it is public). This allows other
2139 /// passes to find the impl they want without loading the id (which
2140 /// means fewer edges in the incremental compilation graph).
2141 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2142 pub struct TraitItemRef {
2143     pub id: TraitItemId,
2144     pub name: Name,
2145     pub kind: AssociatedItemKind,
2146     pub span: Span,
2147     pub defaultness: Defaultness,
2148 }
2149
2150 /// A reference from an impl to one of its associated items. This
2151 /// contains the item's id, naturally, but also the item's name and
2152 /// some other high-level details (like whether it is an associated
2153 /// type or method, and whether it is public). This allows other
2154 /// passes to find the impl they want without loading the id (which
2155 /// means fewer edges in the incremental compilation graph).
2156 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2157 pub struct ImplItemRef {
2158     pub id: ImplItemId,
2159     pub name: Name,
2160     pub kind: AssociatedItemKind,
2161     pub span: Span,
2162     pub vis: Visibility,
2163     pub defaultness: Defaultness,
2164 }
2165
2166 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2167 pub enum AssociatedItemKind {
2168     Const,
2169     Method { has_self: bool },
2170     Type,
2171 }
2172
2173 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2174 pub struct ForeignItem {
2175     pub name: Name,
2176     pub attrs: HirVec<Attribute>,
2177     pub node: ForeignItem_,
2178     pub id: NodeId,
2179     pub span: Span,
2180     pub vis: Visibility,
2181 }
2182
2183 /// An item within an `extern` block
2184 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2185 pub enum ForeignItem_ {
2186     /// A foreign function
2187     ForeignItemFn(P<FnDecl>, HirVec<Spanned<Name>>, Generics),
2188     /// A foreign static item (`static ext: u8`), with optional mutability
2189     /// (the boolean is true when mutable)
2190     ForeignItemStatic(P<Ty>, bool),
2191     /// A foreign type
2192     ForeignItemType,
2193 }
2194
2195 impl ForeignItem_ {
2196     pub fn descriptive_variant(&self) -> &str {
2197         match *self {
2198             ForeignItemFn(..) => "foreign function",
2199             ForeignItemStatic(..) => "foreign static item",
2200             ForeignItemType => "foreign type",
2201         }
2202     }
2203 }
2204
2205 /// A free variable referred to in a function.
2206 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2207 pub struct Freevar {
2208     /// The variable being accessed free.
2209     pub def: Def,
2210
2211     // First span where it is accessed (there can be multiple).
2212     pub span: Span
2213 }
2214
2215 impl Freevar {
2216     pub fn var_id(&self) -> NodeId {
2217         match self.def {
2218             Def::Local(id) | Def::Upvar(id, ..) => id,
2219             _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2220         }
2221     }
2222 }
2223
2224 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2225
2226 pub type CaptureModeMap = NodeMap<CaptureClause>;
2227
2228 #[derive(Clone, Debug)]
2229 pub struct TraitCandidate {
2230     pub def_id: DefId,
2231     pub import_id: Option<NodeId>,
2232 }
2233
2234 // Trait method resolution
2235 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2236
2237 // Map from the NodeId of a glob import to a list of items which are actually
2238 // imported.
2239 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2240
2241
2242 pub fn provide(providers: &mut Providers) {
2243     providers.describe_def = map::describe_def;
2244 }
2245
2246 #[derive(Clone, RustcEncodable, RustcDecodable, Hash)]
2247 pub struct TransFnAttrs {
2248     pub flags: TransFnAttrFlags,
2249     pub inline: InlineAttr,
2250     pub export_name: Option<Symbol>,
2251     pub target_features: Vec<Symbol>,
2252     pub linkage: Option<Linkage>,
2253 }
2254
2255 bitflags! {
2256     #[derive(RustcEncodable, RustcDecodable)]
2257     pub struct TransFnAttrFlags: u8 {
2258         const COLD                      = 0b0000_0001;
2259         const ALLOCATOR                 = 0b0000_0010;
2260         const UNWIND                    = 0b0000_0100;
2261         const RUSTC_ALLOCATOR_NOUNWIND  = 0b0000_1000;
2262         const NAKED                     = 0b0001_0000;
2263         const NO_MANGLE                 = 0b0010_0000;
2264         const RUSTC_STD_INTERNAL_SYMBOL = 0b0100_0000;
2265         const NO_DEBUG                  = 0b1000_0000;
2266     }
2267 }
2268
2269 impl TransFnAttrs {
2270     pub fn new() -> TransFnAttrs {
2271         TransFnAttrs {
2272             flags: TransFnAttrFlags::empty(),
2273             inline: InlineAttr::None,
2274             export_name: None,
2275             target_features: vec![],
2276             linkage: None,
2277         }
2278     }
2279
2280     /// True if `#[inline]` or `#[inline(always)]` is present.
2281     pub fn requests_inline(&self) -> bool {
2282         match self.inline {
2283             InlineAttr::Hint | InlineAttr::Always => true,
2284             InlineAttr::None | InlineAttr::Never => false,
2285         }
2286     }
2287
2288     /// True if `#[no_mangle]` or `#[export_name(...)]` is present.
2289     pub fn contains_extern_indicator(&self) -> bool {
2290         self.flags.contains(TransFnAttrFlags::NO_MANGLE) || self.export_name.is_some()
2291     }
2292 }
2293