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