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