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