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