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