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