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