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