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