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