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