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