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