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