]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/hir.rs
Auto merge of #96770 - flip1995:fix-trait-type-in-bounds, r=cjgillot
[rust.git] / compiler / rustc_hir / src / hir.rs
1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::DefId;
3 crate use crate::hir_id::{HirId, ItemLocalId};
4 use crate::intravisit::FnKind;
5 use crate::LangItem;
6
7 use rustc_ast as ast;
8 use rustc_ast::util::parser::ExprPrecedence;
9 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, TraitObjectSyntax, 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::fingerprint::Fingerprint;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::sorted_map::SortedMap;
16 use rustc_error_messages::MultiSpan;
17 use rustc_index::vec::IndexVec;
18 use rustc_macros::HashStable_Generic;
19 use rustc_span::hygiene::MacroKind;
20 use rustc_span::source_map::Spanned;
21 use rustc_span::symbol::{kw, sym, Ident, Symbol};
22 use rustc_span::{def_id::LocalDefId, BytePos, Span, DUMMY_SP};
23 use rustc_target::asm::InlineAsmRegOrRegClass;
24 use rustc_target::spec::abi::Abi;
25
26 use smallvec::SmallVec;
27 use std::fmt;
28
29 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
30 pub struct Lifetime {
31     pub hir_id: HirId,
32     pub span: Span,
33
34     /// Either "`'a`", referring to a named lifetime definition,
35     /// or "``" (i.e., `kw::Empty`), for elision placeholders.
36     ///
37     /// HIR lowering inserts these placeholders in type paths that
38     /// refer to type definitions needing lifetime parameters,
39     /// `&T` and `&mut T`, and trait objects without `... + 'a`.
40     pub name: LifetimeName,
41 }
42
43 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
44 #[derive(HashStable_Generic)]
45 pub enum ParamName {
46     /// Some user-given name like `T` or `'x`.
47     Plain(Ident),
48
49     /// Synthetic name generated when user elided a lifetime in an impl header.
50     ///
51     /// E.g., the lifetimes in cases like these:
52     /// ```ignore (fragment)
53     /// impl Foo for &u32
54     /// impl Foo<'_> for u32
55     /// ```
56     /// in that case, we rewrite to
57     /// ```ignore (fragment)
58     /// impl<'f> Foo for &'f u32
59     /// impl<'f> Foo<'f> for u32
60     /// ```
61     /// where `'f` is something like `Fresh(0)`. The indices are
62     /// unique per impl, but not necessarily continuous.
63     Fresh(LocalDefId),
64
65     /// Indicates an illegal name was given and an error has been
66     /// reported (so we should squelch other derived errors). Occurs
67     /// when, e.g., `'_` is used in the wrong place.
68     Error,
69 }
70
71 impl ParamName {
72     pub fn ident(&self) -> Ident {
73         match *self {
74             ParamName::Plain(ident) => ident,
75             ParamName::Fresh(_) | ParamName::Error => {
76                 Ident::with_dummy_span(kw::UnderscoreLifetime)
77             }
78         }
79     }
80
81     pub fn normalize_to_macros_2_0(&self) -> ParamName {
82         match *self {
83             ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
84             param_name => param_name,
85         }
86     }
87 }
88
89 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
90 #[derive(HashStable_Generic)]
91 pub enum LifetimeName {
92     /// User-given names or fresh (synthetic) names.
93     Param(ParamName),
94
95     /// User wrote nothing (e.g., the lifetime in `&u32`).
96     Implicit,
97
98     /// Implicit lifetime in a context like `dyn Foo`. This is
99     /// distinguished from implicit lifetimes elsewhere because the
100     /// lifetime that they default to must appear elsewhere within the
101     /// enclosing type.  This means that, in an `impl Trait` context, we
102     /// don't have to create a parameter for them. That is, `impl
103     /// Trait<Item = &u32>` expands to an opaque type like `type
104     /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
105     /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
106     /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
107     /// that surrounding code knows not to create a lifetime
108     /// parameter.
109     ImplicitObjectLifetimeDefault,
110
111     /// Indicates an error during lowering (usually `'_` in wrong place)
112     /// that was already reported.
113     Error,
114
115     /// User wrote specifies `'_`.
116     Underscore,
117
118     /// User wrote `'static`.
119     Static,
120 }
121
122 impl LifetimeName {
123     pub fn ident(&self) -> Ident {
124         match *self {
125             LifetimeName::ImplicitObjectLifetimeDefault
126             | LifetimeName::Implicit
127             | LifetimeName::Error => Ident::empty(),
128             LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
129             LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
130             LifetimeName::Param(param_name) => param_name.ident(),
131         }
132     }
133
134     pub fn is_elided(&self) -> bool {
135         match self {
136             LifetimeName::ImplicitObjectLifetimeDefault
137             | LifetimeName::Implicit
138             | LifetimeName::Underscore => true,
139
140             // It might seem surprising that `Fresh(_)` counts as
141             // *not* elided -- but this is because, as far as the code
142             // in the compiler is concerned -- `Fresh(_)` variants act
143             // equivalently to "some fresh name". They correspond to
144             // early-bound regions on an impl, in other words.
145             LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
146         }
147     }
148
149     fn is_static(&self) -> bool {
150         self == &LifetimeName::Static
151     }
152
153     pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
154         match *self {
155             LifetimeName::Param(param_name) => {
156                 LifetimeName::Param(param_name.normalize_to_macros_2_0())
157             }
158             lifetime_name => lifetime_name,
159         }
160     }
161 }
162
163 impl fmt::Display for Lifetime {
164     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165         self.name.ident().fmt(f)
166     }
167 }
168
169 impl fmt::Debug for Lifetime {
170     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171         write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
172     }
173 }
174
175 impl Lifetime {
176     pub fn is_elided(&self) -> bool {
177         self.name.is_elided()
178     }
179
180     pub fn is_static(&self) -> bool {
181         self.name.is_static()
182     }
183 }
184
185 /// A `Path` is essentially Rust's notion of a name; for instance,
186 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
187 /// along with a bunch of supporting information.
188 #[derive(Debug, HashStable_Generic)]
189 pub struct Path<'hir> {
190     pub span: Span,
191     /// The resolution for the path.
192     pub res: Res,
193     /// The segments in the path: the things separated by `::`.
194     pub segments: &'hir [PathSegment<'hir>],
195 }
196
197 impl Path<'_> {
198     pub fn is_global(&self) -> bool {
199         !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
200     }
201 }
202
203 /// A segment of a path: an identifier, an optional lifetime, and a set of
204 /// types.
205 #[derive(Debug, HashStable_Generic)]
206 pub struct PathSegment<'hir> {
207     /// The identifier portion of this path segment.
208     pub ident: Ident,
209     // `id` and `res` are optional. We currently only use these in save-analysis,
210     // any path segments without these will not have save-analysis info and
211     // therefore will not have 'jump to def' in IDEs, but otherwise will not be
212     // affected. (In general, we don't bother to get the defs for synthesized
213     // segments, only for segments which have come from the AST).
214     pub hir_id: Option<HirId>,
215     pub res: Option<Res>,
216
217     /// Type/lifetime parameters attached to this path. They come in
218     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
219     /// this is more than just simple syntactic sugar; the use of
220     /// parens affects the region binding rules, so we preserve the
221     /// distinction.
222     pub args: Option<&'hir GenericArgs<'hir>>,
223
224     /// Whether to infer remaining type parameters, if any.
225     /// This only applies to expression and pattern paths, and
226     /// out of those only the segments with no type parameters
227     /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
228     pub infer_args: bool,
229 }
230
231 impl<'hir> PathSegment<'hir> {
232     /// Converts an identifier to the corresponding segment.
233     pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
234         PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
235     }
236
237     pub fn invalid() -> Self {
238         Self::from_ident(Ident::empty())
239     }
240
241     pub fn args(&self) -> &GenericArgs<'hir> {
242         if let Some(ref args) = self.args {
243             args
244         } else {
245             const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
246             DUMMY
247         }
248     }
249 }
250
251 #[derive(Encodable, Debug, HashStable_Generic)]
252 pub struct ConstArg {
253     pub value: AnonConst,
254     pub span: Span,
255 }
256
257 #[derive(Encodable, Debug, HashStable_Generic)]
258 pub struct InferArg {
259     pub hir_id: HirId,
260     pub span: Span,
261 }
262
263 impl InferArg {
264     pub fn to_ty(&self) -> Ty<'_> {
265         Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
266     }
267 }
268
269 #[derive(Debug, HashStable_Generic)]
270 pub enum GenericArg<'hir> {
271     Lifetime(Lifetime),
272     Type(Ty<'hir>),
273     Const(ConstArg),
274     Infer(InferArg),
275 }
276
277 impl GenericArg<'_> {
278     pub fn span(&self) -> Span {
279         match self {
280             GenericArg::Lifetime(l) => l.span,
281             GenericArg::Type(t) => t.span,
282             GenericArg::Const(c) => c.span,
283             GenericArg::Infer(i) => i.span,
284         }
285     }
286
287     pub fn id(&self) -> HirId {
288         match self {
289             GenericArg::Lifetime(l) => l.hir_id,
290             GenericArg::Type(t) => t.hir_id,
291             GenericArg::Const(c) => c.value.hir_id,
292             GenericArg::Infer(i) => i.hir_id,
293         }
294     }
295
296     pub fn is_synthetic(&self) -> bool {
297         matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::empty())
298     }
299
300     pub fn descr(&self) -> &'static str {
301         match self {
302             GenericArg::Lifetime(_) => "lifetime",
303             GenericArg::Type(_) => "type",
304             GenericArg::Const(_) => "constant",
305             GenericArg::Infer(_) => "inferred",
306         }
307     }
308
309     pub fn to_ord(&self) -> ast::ParamKindOrd {
310         match self {
311             GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
312             GenericArg::Type(_) => ast::ParamKindOrd::Type,
313             GenericArg::Const(_) => ast::ParamKindOrd::Const,
314             GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
315         }
316     }
317
318     pub fn is_ty_or_const(&self) -> bool {
319         match self {
320             GenericArg::Lifetime(_) => false,
321             GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => true,
322         }
323     }
324 }
325
326 #[derive(Debug, HashStable_Generic)]
327 pub struct GenericArgs<'hir> {
328     /// The generic arguments for this path segment.
329     pub args: &'hir [GenericArg<'hir>],
330     /// Bindings (equality constraints) on associated types, if present.
331     /// E.g., `Foo<A = Bar>`.
332     pub bindings: &'hir [TypeBinding<'hir>],
333     /// Were arguments written in parenthesized form `Fn(T) -> U`?
334     /// This is required mostly for pretty-printing and diagnostics,
335     /// but also for changing lifetime elision rules to be "function-like".
336     pub parenthesized: bool,
337     /// The span encompassing arguments and the surrounding brackets `<>` or `()`
338     ///       Foo<A, B, AssocTy = D>           Fn(T, U, V) -> W
339     ///          ^^^^^^^^^^^^^^^^^^^             ^^^^^^^^^
340     /// Note that this may be:
341     /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
342     /// - dummy, if this was generated while desugaring
343     pub span_ext: Span,
344 }
345
346 impl GenericArgs<'_> {
347     pub const fn none() -> Self {
348         Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
349     }
350
351     pub fn inputs(&self) -> &[Ty<'_>] {
352         if self.parenthesized {
353             for arg in self.args {
354                 match arg {
355                     GenericArg::Lifetime(_) => {}
356                     GenericArg::Type(ref ty) => {
357                         if let TyKind::Tup(ref tys) = ty.kind {
358                             return tys;
359                         }
360                         break;
361                     }
362                     GenericArg::Const(_) => {}
363                     GenericArg::Infer(_) => {}
364                 }
365             }
366         }
367         panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
368     }
369
370     #[inline]
371     pub fn has_type_params(&self) -> bool {
372         self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
373     }
374
375     pub fn has_err(&self) -> bool {
376         self.args.iter().any(|arg| match arg {
377             GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
378             _ => false,
379         }) || self.bindings.iter().any(|arg| match arg.kind {
380             TypeBindingKind::Equality { term: Term::Ty(ty) } => matches!(ty.kind, TyKind::Err),
381             _ => false,
382         })
383     }
384
385     #[inline]
386     pub fn num_type_params(&self) -> usize {
387         self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
388     }
389
390     #[inline]
391     pub fn num_lifetime_params(&self) -> usize {
392         self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
393     }
394
395     #[inline]
396     pub fn has_lifetime_params(&self) -> bool {
397         self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
398     }
399
400     #[inline]
401     pub fn num_generic_params(&self) -> usize {
402         self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
403     }
404
405     /// The span encompassing the text inside the surrounding brackets.
406     /// It will also include bindings if they aren't in the form `-> Ret`
407     /// Returns `None` if the span is empty (e.g. no brackets) or dummy
408     pub fn span(&self) -> Option<Span> {
409         let span_ext = self.span_ext()?;
410         Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
411     }
412
413     /// Returns span encompassing arguments and their surrounding `<>` or `()`
414     pub fn span_ext(&self) -> Option<Span> {
415         Some(self.span_ext).filter(|span| !span.is_empty())
416     }
417
418     pub fn is_empty(&self) -> bool {
419         self.args.is_empty()
420     }
421 }
422
423 /// A modifier on a bound, currently this is only used for `?Sized`, where the
424 /// modifier is `Maybe`. Negative bounds should also be handled here.
425 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
426 #[derive(HashStable_Generic)]
427 pub enum TraitBoundModifier {
428     None,
429     Maybe,
430     MaybeConst,
431 }
432
433 /// The AST represents all type param bounds as types.
434 /// `typeck::collect::compute_bounds` matches these against
435 /// the "special" built-in traits (see `middle::lang_items`) and
436 /// detects `Copy`, `Send` and `Sync`.
437 #[derive(Clone, Debug, HashStable_Generic)]
438 pub enum GenericBound<'hir> {
439     Trait(PolyTraitRef<'hir>, TraitBoundModifier),
440     // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
441     LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
442     Outlives(Lifetime),
443 }
444
445 impl GenericBound<'_> {
446     pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
447         match self {
448             GenericBound::Trait(data, _) => Some(&data.trait_ref),
449             _ => None,
450         }
451     }
452
453     pub fn span(&self) -> Span {
454         match self {
455             GenericBound::Trait(t, ..) => t.span,
456             GenericBound::LangItemTrait(_, span, ..) => *span,
457             GenericBound::Outlives(l) => l.span,
458         }
459     }
460 }
461
462 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
463
464 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
465 pub enum LifetimeParamKind {
466     // Indicates that the lifetime definition was explicitly declared (e.g., in
467     // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
468     Explicit,
469
470     // Indication that the lifetime was elided (e.g., in both cases in
471     // `fn foo(x: &u8) -> &'_ u8 { x }`).
472     Elided,
473
474     // Indication that the lifetime name was somehow in error.
475     Error,
476 }
477
478 #[derive(Debug, HashStable_Generic)]
479 pub enum GenericParamKind<'hir> {
480     /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
481     Lifetime {
482         kind: LifetimeParamKind,
483     },
484     Type {
485         default: Option<&'hir Ty<'hir>>,
486         synthetic: bool,
487     },
488     Const {
489         ty: &'hir Ty<'hir>,
490         /// Optional default value for the const generic param
491         default: Option<AnonConst>,
492     },
493 }
494
495 #[derive(Debug, HashStable_Generic)]
496 pub struct GenericParam<'hir> {
497     pub hir_id: HirId,
498     pub name: ParamName,
499     pub span: Span,
500     pub pure_wrt_drop: bool,
501     pub kind: GenericParamKind<'hir>,
502     pub colon_span: Option<Span>,
503 }
504
505 impl<'hir> GenericParam<'hir> {
506     /// Synthetic type-parameters are inserted after normal ones.
507     /// In order for normal parameters to be able to refer to synthetic ones,
508     /// scans them first.
509     pub fn is_impl_trait(&self) -> bool {
510         matches!(self.kind, GenericParamKind::Type { synthetic: true, .. })
511     }
512
513     /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
514     ///
515     /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
516     pub fn is_elided_lifetime(&self) -> bool {
517         matches!(self.kind, GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided })
518     }
519 }
520
521 #[derive(Default)]
522 pub struct GenericParamCount {
523     pub lifetimes: usize,
524     pub types: usize,
525     pub consts: usize,
526     pub infer: usize,
527 }
528
529 /// Represents lifetimes and type parameters attached to a declaration
530 /// of a function, enum, trait, etc.
531 #[derive(Debug, HashStable_Generic)]
532 pub struct Generics<'hir> {
533     pub params: &'hir [GenericParam<'hir>],
534     pub predicates: &'hir [WherePredicate<'hir>],
535     pub has_where_clause: bool,
536     pub where_clause_span: Span,
537     pub span: Span,
538 }
539
540 impl<'hir> Generics<'hir> {
541     pub const fn empty() -> &'hir Generics<'hir> {
542         const NOPE: Generics<'_> = Generics {
543             params: &[],
544             predicates: &[],
545             has_where_clause: false,
546             where_clause_span: DUMMY_SP,
547             span: DUMMY_SP,
548         };
549         &NOPE
550     }
551
552     pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
553         for param in self.params {
554             if name == param.name.ident().name {
555                 return Some(param);
556             }
557         }
558         None
559     }
560
561     pub fn spans(&self) -> MultiSpan {
562         if self.params.is_empty() {
563             self.span.into()
564         } else {
565             self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
566         }
567     }
568
569     /// If there are generic parameters, return where to introduce a new one.
570     pub fn span_for_param_suggestion(&self) -> Option<Span> {
571         if self.params.iter().any(|p| self.span.contains(p.span)) {
572             // `fn foo<A>(t: impl Trait)`
573             //          ^ suggest `, T: Trait` here
574             let span = self.span.with_lo(self.span.hi() - BytePos(1)).shrink_to_lo();
575             Some(span)
576         } else {
577             None
578         }
579     }
580
581     pub fn where_clause_span(&self) -> Option<Span> {
582         if self.predicates.is_empty() { None } else { Some(self.where_clause_span) }
583     }
584
585     /// The `where_span` under normal circumstances points at either the predicates or the empty
586     /// space where the `where` clause should be. Only of use for diagnostic suggestions.
587     pub fn span_for_predicates_or_empty_place(&self) -> Span {
588         self.where_clause_span
589     }
590
591     /// `Span` where further predicates would be suggested, accounting for trailing commas, like
592     ///  in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
593     pub fn tail_span_for_predicate_suggestion(&self) -> Span {
594         let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
595         if self.has_where_clause {
596             self.predicates
597                 .iter()
598                 .filter(|p| p.in_where_clause())
599                 .last()
600                 .map_or(end, |p| p.span())
601                 .shrink_to_hi()
602                 .to(end)
603         } else {
604             end
605         }
606     }
607
608     pub fn bounds_for_param(
609         &self,
610         param_def_id: LocalDefId,
611     ) -> impl Iterator<Item = &WhereBoundPredicate<'_>> {
612         self.predicates.iter().filter_map(move |pred| match pred {
613             WherePredicate::BoundPredicate(bp) if bp.is_param_bound(param_def_id.to_def_id()) => {
614                 Some(bp)
615             }
616             _ => None,
617         })
618     }
619
620     pub fn bounds_span_for_suggestions(&self, param_def_id: LocalDefId) -> Option<Span> {
621         self.bounds_for_param(param_def_id).flat_map(|bp| bp.bounds.iter().rev()).find_map(
622             |bound| {
623                 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
624                 // as we use this method to get a span appropriate for suggestions.
625                 let bs = bound.span();
626                 if bs.can_be_used_for_suggestions() { Some(bs.shrink_to_hi()) } else { None }
627             },
628         )
629     }
630
631     pub fn span_for_predicate_removal(&self, pos: usize) -> Span {
632         let predicate = &self.predicates[pos];
633         let span = predicate.span();
634
635         if !predicate.in_where_clause() {
636             // <T: ?Sized, U>
637             //   ^^^^^^^^
638             return span;
639         }
640
641         // We need to find out which comma to remove.
642         if pos < self.predicates.len() - 1 {
643             let next_pred = &self.predicates[pos + 1];
644             if next_pred.in_where_clause() {
645                 // where T: ?Sized, Foo: Bar,
646                 //       ^^^^^^^^^^^
647                 return span.until(next_pred.span());
648             }
649         }
650
651         if pos > 0 {
652             let prev_pred = &self.predicates[pos - 1];
653             if prev_pred.in_where_clause() {
654                 // where Foo: Bar, T: ?Sized,
655                 //               ^^^^^^^^^^^
656                 return prev_pred.span().shrink_to_hi().to(span);
657             }
658         }
659
660         // This is the only predicate in the where clause.
661         // where T: ?Sized
662         // ^^^^^^^^^^^^^^^
663         self.where_clause_span
664     }
665
666     pub fn span_for_bound_removal(&self, predicate_pos: usize, bound_pos: usize) -> Span {
667         let predicate = &self.predicates[predicate_pos];
668         let bounds = predicate.bounds();
669
670         if bounds.len() == 1 {
671             return self.span_for_predicate_removal(predicate_pos);
672         }
673
674         let span = bounds[bound_pos].span();
675         if bound_pos == 0 {
676             // where T: ?Sized + Bar, Foo: Bar,
677             //          ^^^^^^^^^
678             span.to(bounds[1].span().shrink_to_lo())
679         } else {
680             // where T: Bar + ?Sized, Foo: Bar,
681             //             ^^^^^^^^^
682             bounds[bound_pos - 1].span().shrink_to_hi().to(span)
683         }
684     }
685 }
686
687 /// A single predicate in a where-clause.
688 #[derive(Debug, HashStable_Generic)]
689 pub enum WherePredicate<'hir> {
690     /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
691     BoundPredicate(WhereBoundPredicate<'hir>),
692     /// A lifetime predicate (e.g., `'a: 'b + 'c`).
693     RegionPredicate(WhereRegionPredicate<'hir>),
694     /// An equality predicate (unsupported).
695     EqPredicate(WhereEqPredicate<'hir>),
696 }
697
698 impl<'hir> WherePredicate<'hir> {
699     pub fn span(&self) -> Span {
700         match self {
701             WherePredicate::BoundPredicate(p) => p.span,
702             WherePredicate::RegionPredicate(p) => p.span,
703             WherePredicate::EqPredicate(p) => p.span,
704         }
705     }
706
707     pub fn in_where_clause(&self) -> bool {
708         match self {
709             WherePredicate::BoundPredicate(p) => p.origin == PredicateOrigin::WhereClause,
710             WherePredicate::RegionPredicate(p) => p.in_where_clause,
711             WherePredicate::EqPredicate(_) => false,
712         }
713     }
714
715     pub fn bounds(&self) -> GenericBounds<'hir> {
716         match self {
717             WherePredicate::BoundPredicate(p) => p.bounds,
718             WherePredicate::RegionPredicate(p) => p.bounds,
719             WherePredicate::EqPredicate(_) => &[],
720         }
721     }
722 }
723
724 #[derive(Debug, HashStable_Generic, PartialEq, Eq)]
725 pub enum PredicateOrigin {
726     WhereClause,
727     GenericParam,
728     ImplTrait,
729 }
730
731 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
732 #[derive(Debug, HashStable_Generic)]
733 pub struct WhereBoundPredicate<'hir> {
734     pub span: Span,
735     /// Origin of the predicate.
736     pub origin: PredicateOrigin,
737     /// Any generics from a `for` binding.
738     pub bound_generic_params: &'hir [GenericParam<'hir>],
739     /// The type being bounded.
740     pub bounded_ty: &'hir Ty<'hir>,
741     /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
742     pub bounds: GenericBounds<'hir>,
743 }
744
745 impl<'hir> WhereBoundPredicate<'hir> {
746     /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
747     pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
748         self.bounded_ty.as_generic_param().map_or(false, |(def_id, _)| def_id == param_def_id)
749     }
750 }
751
752 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
753 #[derive(Debug, HashStable_Generic)]
754 pub struct WhereRegionPredicate<'hir> {
755     pub span: Span,
756     pub in_where_clause: bool,
757     pub lifetime: Lifetime,
758     pub bounds: GenericBounds<'hir>,
759 }
760
761 /// An equality predicate (e.g., `T = int`); currently unsupported.
762 #[derive(Debug, HashStable_Generic)]
763 pub struct WhereEqPredicate<'hir> {
764     pub hir_id: HirId,
765     pub span: Span,
766     pub lhs_ty: &'hir Ty<'hir>,
767     pub rhs_ty: &'hir Ty<'hir>,
768 }
769
770 /// HIR node coupled with its parent's id in the same HIR owner.
771 ///
772 /// The parent is trash when the node is a HIR owner.
773 #[derive(Clone, Debug)]
774 pub struct ParentedNode<'tcx> {
775     pub parent: ItemLocalId,
776     pub node: Node<'tcx>,
777 }
778
779 /// Attributes owned by a HIR owner.
780 #[derive(Debug)]
781 pub struct AttributeMap<'tcx> {
782     pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
783     pub hash: Fingerprint,
784 }
785
786 impl<'tcx> AttributeMap<'tcx> {
787     pub const EMPTY: &'static AttributeMap<'static> =
788         &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
789
790     #[inline]
791     pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
792         self.map.get(&id).copied().unwrap_or(&[])
793     }
794 }
795
796 /// Map of all HIR nodes inside the current owner.
797 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
798 /// The HIR tree, including bodies, is pre-hashed.
799 #[derive(Debug)]
800 pub struct OwnerNodes<'tcx> {
801     /// Pre-computed hash of the full HIR.
802     pub hash_including_bodies: Fingerprint,
803     /// Pre-computed hash of the item signature, sithout recursing into the body.
804     pub hash_without_bodies: Fingerprint,
805     /// Full HIR for the current owner.
806     // The zeroth node's parent should never be accessed: the owner's parent is computed by the
807     // hir_owner_parent query.  It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
808     // used.
809     pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
810     /// Content of local bodies.
811     pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
812     /// Non-owning definitions contained in this owner.
813     pub local_id_to_def_id: SortedMap<ItemLocalId, LocalDefId>,
814 }
815
816 impl<'tcx> OwnerNodes<'tcx> {
817     pub fn node(&self) -> OwnerNode<'tcx> {
818         use rustc_index::vec::Idx;
819         let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
820         let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
821         node
822     }
823 }
824
825 /// Full information resulting from lowering an AST node.
826 #[derive(Debug, HashStable_Generic)]
827 pub struct OwnerInfo<'hir> {
828     /// Contents of the HIR.
829     pub nodes: OwnerNodes<'hir>,
830     /// Map from each nested owner to its parent's local id.
831     pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
832     /// Collected attributes of the HIR nodes.
833     pub attrs: AttributeMap<'hir>,
834     /// Map indicating what traits are in scope for places where this
835     /// is relevant; generated by resolve.
836     pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
837 }
838
839 impl<'tcx> OwnerInfo<'tcx> {
840     #[inline]
841     pub fn node(&self) -> OwnerNode<'tcx> {
842         self.nodes.node()
843     }
844 }
845
846 #[derive(Copy, Clone, Debug, HashStable_Generic)]
847 pub enum MaybeOwner<T> {
848     Owner(T),
849     NonOwner(HirId),
850     /// Used as a placeholder for unused LocalDefId.
851     Phantom,
852 }
853
854 impl<T> MaybeOwner<T> {
855     pub fn as_owner(self) -> Option<T> {
856         match self {
857             MaybeOwner::Owner(i) => Some(i),
858             MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => None,
859         }
860     }
861
862     pub fn map<U>(self, f: impl FnOnce(T) -> U) -> MaybeOwner<U> {
863         match self {
864             MaybeOwner::Owner(i) => MaybeOwner::Owner(f(i)),
865             MaybeOwner::NonOwner(hir_id) => MaybeOwner::NonOwner(hir_id),
866             MaybeOwner::Phantom => MaybeOwner::Phantom,
867         }
868     }
869
870     pub fn unwrap(self) -> T {
871         match self {
872             MaybeOwner::Owner(i) => i,
873             MaybeOwner::NonOwner(_) | MaybeOwner::Phantom => panic!("Not a HIR owner"),
874         }
875     }
876 }
877
878 /// The top-level data structure that stores the entire contents of
879 /// the crate currently being compiled.
880 ///
881 /// For more details, see the [rustc dev guide].
882 ///
883 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
884 #[derive(Debug)]
885 pub struct Crate<'hir> {
886     pub owners: IndexVec<LocalDefId, MaybeOwner<&'hir OwnerInfo<'hir>>>,
887     pub hir_hash: Fingerprint,
888 }
889
890 /// A block of statements `{ .. }`, which may have a label (in this case the
891 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
892 /// the `rules` being anything but `DefaultBlock`.
893 #[derive(Debug, HashStable_Generic)]
894 pub struct Block<'hir> {
895     /// Statements in a block.
896     pub stmts: &'hir [Stmt<'hir>],
897     /// An expression at the end of the block
898     /// without a semicolon, if any.
899     pub expr: Option<&'hir Expr<'hir>>,
900     #[stable_hasher(ignore)]
901     pub hir_id: HirId,
902     /// Distinguishes between `unsafe { ... }` and `{ ... }`.
903     pub rules: BlockCheckMode,
904     pub span: Span,
905     /// If true, then there may exist `break 'a` values that aim to
906     /// break out of this block early.
907     /// Used by `'label: {}` blocks and by `try {}` blocks.
908     pub targeted_by_break: bool,
909 }
910
911 #[derive(Debug, HashStable_Generic)]
912 pub struct Pat<'hir> {
913     #[stable_hasher(ignore)]
914     pub hir_id: HirId,
915     pub kind: PatKind<'hir>,
916     pub span: Span,
917     // Whether to use default binding modes.
918     // At present, this is false only for destructuring assignment.
919     pub default_binding_modes: bool,
920 }
921
922 impl<'hir> Pat<'hir> {
923     // FIXME(#19596) this is a workaround, but there should be a better way
924     fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
925         if !it(self) {
926             return false;
927         }
928
929         use PatKind::*;
930         match self.kind {
931             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
932             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
933             Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
934             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
935             Slice(before, slice, after) => {
936                 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
937             }
938         }
939     }
940
941     /// Walk the pattern in left-to-right order,
942     /// short circuiting (with `.all(..)`) if `false` is returned.
943     ///
944     /// Note that when visiting e.g. `Tuple(ps)`,
945     /// if visiting `ps[0]` returns `false`,
946     /// then `ps[1]` will not be visited.
947     pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
948         self.walk_short_(&mut it)
949     }
950
951     // FIXME(#19596) this is a workaround, but there should be a better way
952     fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
953         if !it(self) {
954             return;
955         }
956
957         use PatKind::*;
958         match self.kind {
959             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
960             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
961             Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
962             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
963             Slice(before, slice, after) => {
964                 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
965             }
966         }
967     }
968
969     /// Walk the pattern in left-to-right order.
970     ///
971     /// If `it(pat)` returns `false`, the children are not visited.
972     pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
973         self.walk_(&mut it)
974     }
975
976     /// Walk the pattern in left-to-right order.
977     ///
978     /// If you always want to recurse, prefer this method over `walk`.
979     pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
980         self.walk(|p| {
981             it(p);
982             true
983         })
984     }
985 }
986
987 /// A single field in a struct pattern.
988 ///
989 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
990 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
991 /// except `is_shorthand` is true.
992 #[derive(Debug, HashStable_Generic)]
993 pub struct PatField<'hir> {
994     #[stable_hasher(ignore)]
995     pub hir_id: HirId,
996     /// The identifier for the field.
997     pub ident: Ident,
998     /// The pattern the field is destructured to.
999     pub pat: &'hir Pat<'hir>,
1000     pub is_shorthand: bool,
1001     pub span: Span,
1002 }
1003
1004 /// Explicit binding annotations given in the HIR for a binding. Note
1005 /// that this is not the final binding *mode* that we infer after type
1006 /// inference.
1007 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1008 pub enum BindingAnnotation {
1009     /// No binding annotation given: this means that the final binding mode
1010     /// will depend on whether we have skipped through a `&` reference
1011     /// when matching. For example, the `x` in `Some(x)` will have binding
1012     /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
1013     /// ultimately be inferred to be by-reference.
1014     ///
1015     /// Note that implicit reference skipping is not implemented yet (#42640).
1016     Unannotated,
1017
1018     /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
1019     Mutable,
1020
1021     /// Annotated as `ref`, like `ref x`
1022     Ref,
1023
1024     /// Annotated as `ref mut x`.
1025     RefMut,
1026 }
1027
1028 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1029 pub enum RangeEnd {
1030     Included,
1031     Excluded,
1032 }
1033
1034 impl fmt::Display for RangeEnd {
1035     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036         f.write_str(match self {
1037             RangeEnd::Included => "..=",
1038             RangeEnd::Excluded => "..",
1039         })
1040     }
1041 }
1042
1043 #[derive(Debug, HashStable_Generic)]
1044 pub enum PatKind<'hir> {
1045     /// Represents a wildcard pattern (i.e., `_`).
1046     Wild,
1047
1048     /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
1049     /// The `HirId` is the canonical ID for the variable being bound,
1050     /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
1051     /// which is the pattern ID of the first `x`.
1052     Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
1053
1054     /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
1055     /// The `bool` is `true` in the presence of a `..`.
1056     Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
1057
1058     /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
1059     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1060     /// `0 <= position <= subpats.len()`
1061     TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
1062
1063     /// An or-pattern `A | B | C`.
1064     /// Invariant: `pats.len() >= 2`.
1065     Or(&'hir [Pat<'hir>]),
1066
1067     /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
1068     Path(QPath<'hir>),
1069
1070     /// A tuple pattern (e.g., `(a, b)`).
1071     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
1072     /// `0 <= position <= subpats.len()`
1073     Tuple(&'hir [Pat<'hir>], Option<usize>),
1074
1075     /// A `box` pattern.
1076     Box(&'hir Pat<'hir>),
1077
1078     /// A reference pattern (e.g., `&mut (a, b)`).
1079     Ref(&'hir Pat<'hir>, Mutability),
1080
1081     /// A literal.
1082     Lit(&'hir Expr<'hir>),
1083
1084     /// A range pattern (e.g., `1..=2` or `1..2`).
1085     Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
1086
1087     /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
1088     ///
1089     /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
1090     /// If `slice` exists, then `after` can be non-empty.
1091     ///
1092     /// The representation for e.g., `[a, b, .., c, d]` is:
1093     /// ```ignore (illustrative)
1094     /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
1095     /// ```
1096     Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
1097 }
1098
1099 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1100 pub enum BinOpKind {
1101     /// The `+` operator (addition).
1102     Add,
1103     /// The `-` operator (subtraction).
1104     Sub,
1105     /// The `*` operator (multiplication).
1106     Mul,
1107     /// The `/` operator (division).
1108     Div,
1109     /// The `%` operator (modulus).
1110     Rem,
1111     /// The `&&` operator (logical and).
1112     And,
1113     /// The `||` operator (logical or).
1114     Or,
1115     /// The `^` operator (bitwise xor).
1116     BitXor,
1117     /// The `&` operator (bitwise and).
1118     BitAnd,
1119     /// The `|` operator (bitwise or).
1120     BitOr,
1121     /// The `<<` operator (shift left).
1122     Shl,
1123     /// The `>>` operator (shift right).
1124     Shr,
1125     /// The `==` operator (equality).
1126     Eq,
1127     /// The `<` operator (less than).
1128     Lt,
1129     /// The `<=` operator (less than or equal to).
1130     Le,
1131     /// The `!=` operator (not equal to).
1132     Ne,
1133     /// The `>=` operator (greater than or equal to).
1134     Ge,
1135     /// The `>` operator (greater than).
1136     Gt,
1137 }
1138
1139 impl BinOpKind {
1140     pub fn as_str(self) -> &'static str {
1141         match self {
1142             BinOpKind::Add => "+",
1143             BinOpKind::Sub => "-",
1144             BinOpKind::Mul => "*",
1145             BinOpKind::Div => "/",
1146             BinOpKind::Rem => "%",
1147             BinOpKind::And => "&&",
1148             BinOpKind::Or => "||",
1149             BinOpKind::BitXor => "^",
1150             BinOpKind::BitAnd => "&",
1151             BinOpKind::BitOr => "|",
1152             BinOpKind::Shl => "<<",
1153             BinOpKind::Shr => ">>",
1154             BinOpKind::Eq => "==",
1155             BinOpKind::Lt => "<",
1156             BinOpKind::Le => "<=",
1157             BinOpKind::Ne => "!=",
1158             BinOpKind::Ge => ">=",
1159             BinOpKind::Gt => ">",
1160         }
1161     }
1162
1163     pub fn is_lazy(self) -> bool {
1164         matches!(self, BinOpKind::And | BinOpKind::Or)
1165     }
1166
1167     pub fn is_shift(self) -> bool {
1168         matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1169     }
1170
1171     pub fn is_comparison(self) -> bool {
1172         match self {
1173             BinOpKind::Eq
1174             | BinOpKind::Lt
1175             | BinOpKind::Le
1176             | BinOpKind::Ne
1177             | BinOpKind::Gt
1178             | BinOpKind::Ge => true,
1179             BinOpKind::And
1180             | BinOpKind::Or
1181             | BinOpKind::Add
1182             | BinOpKind::Sub
1183             | BinOpKind::Mul
1184             | BinOpKind::Div
1185             | BinOpKind::Rem
1186             | BinOpKind::BitXor
1187             | BinOpKind::BitAnd
1188             | BinOpKind::BitOr
1189             | BinOpKind::Shl
1190             | BinOpKind::Shr => false,
1191         }
1192     }
1193
1194     /// Returns `true` if the binary operator takes its arguments by value.
1195     pub fn is_by_value(self) -> bool {
1196         !self.is_comparison()
1197     }
1198 }
1199
1200 impl Into<ast::BinOpKind> for BinOpKind {
1201     fn into(self) -> ast::BinOpKind {
1202         match self {
1203             BinOpKind::Add => ast::BinOpKind::Add,
1204             BinOpKind::Sub => ast::BinOpKind::Sub,
1205             BinOpKind::Mul => ast::BinOpKind::Mul,
1206             BinOpKind::Div => ast::BinOpKind::Div,
1207             BinOpKind::Rem => ast::BinOpKind::Rem,
1208             BinOpKind::And => ast::BinOpKind::And,
1209             BinOpKind::Or => ast::BinOpKind::Or,
1210             BinOpKind::BitXor => ast::BinOpKind::BitXor,
1211             BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1212             BinOpKind::BitOr => ast::BinOpKind::BitOr,
1213             BinOpKind::Shl => ast::BinOpKind::Shl,
1214             BinOpKind::Shr => ast::BinOpKind::Shr,
1215             BinOpKind::Eq => ast::BinOpKind::Eq,
1216             BinOpKind::Lt => ast::BinOpKind::Lt,
1217             BinOpKind::Le => ast::BinOpKind::Le,
1218             BinOpKind::Ne => ast::BinOpKind::Ne,
1219             BinOpKind::Ge => ast::BinOpKind::Ge,
1220             BinOpKind::Gt => ast::BinOpKind::Gt,
1221         }
1222     }
1223 }
1224
1225 pub type BinOp = Spanned<BinOpKind>;
1226
1227 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1228 pub enum UnOp {
1229     /// The `*` operator (dereferencing).
1230     Deref,
1231     /// The `!` operator (logical negation).
1232     Not,
1233     /// The `-` operator (negation).
1234     Neg,
1235 }
1236
1237 impl UnOp {
1238     pub fn as_str(self) -> &'static str {
1239         match self {
1240             Self::Deref => "*",
1241             Self::Not => "!",
1242             Self::Neg => "-",
1243         }
1244     }
1245
1246     /// Returns `true` if the unary operator takes its argument by value.
1247     pub fn is_by_value(self) -> bool {
1248         matches!(self, Self::Neg | Self::Not)
1249     }
1250 }
1251
1252 /// A statement.
1253 #[derive(Debug, HashStable_Generic)]
1254 pub struct Stmt<'hir> {
1255     pub hir_id: HirId,
1256     pub kind: StmtKind<'hir>,
1257     pub span: Span,
1258 }
1259
1260 /// The contents of a statement.
1261 #[derive(Debug, HashStable_Generic)]
1262 pub enum StmtKind<'hir> {
1263     /// A local (`let`) binding.
1264     Local(&'hir Local<'hir>),
1265
1266     /// An item binding.
1267     Item(ItemId),
1268
1269     /// An expression without a trailing semi-colon (must have unit type).
1270     Expr(&'hir Expr<'hir>),
1271
1272     /// An expression with a trailing semi-colon (may have any type).
1273     Semi(&'hir Expr<'hir>),
1274 }
1275
1276 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1277 #[derive(Debug, HashStable_Generic)]
1278 pub struct Local<'hir> {
1279     pub pat: &'hir Pat<'hir>,
1280     /// Type annotation, if any (otherwise the type will be inferred).
1281     pub ty: Option<&'hir Ty<'hir>>,
1282     /// Initializer expression to set the value, if any.
1283     pub init: Option<&'hir Expr<'hir>>,
1284     pub hir_id: HirId,
1285     pub span: Span,
1286     /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1287     /// desugaring. Otherwise will be `Normal`.
1288     pub source: LocalSource,
1289 }
1290
1291 /// Represents a single arm of a `match` expression, e.g.
1292 /// `<pat> (if <guard>) => <body>`.
1293 #[derive(Debug, HashStable_Generic)]
1294 pub struct Arm<'hir> {
1295     #[stable_hasher(ignore)]
1296     pub hir_id: HirId,
1297     pub span: Span,
1298     /// If this pattern and the optional guard matches, then `body` is evaluated.
1299     pub pat: &'hir Pat<'hir>,
1300     /// Optional guard clause.
1301     pub guard: Option<Guard<'hir>>,
1302     /// The expression the arm evaluates to if this arm matches.
1303     pub body: &'hir Expr<'hir>,
1304 }
1305
1306 /// Represents a `let <pat>[: <ty>] = <expr>` expression (not a Local), occurring in an `if-let` or
1307 /// `let-else`, evaluating to a boolean. Typically the pattern is refutable.
1308 ///
1309 /// In an if-let, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of the
1310 /// desugaring to if-let. Only let-else supports the type annotation at present.
1311 #[derive(Debug, HashStable_Generic)]
1312 pub struct Let<'hir> {
1313     pub hir_id: HirId,
1314     pub span: Span,
1315     pub pat: &'hir Pat<'hir>,
1316     pub ty: Option<&'hir Ty<'hir>>,
1317     pub init: &'hir Expr<'hir>,
1318 }
1319
1320 #[derive(Debug, HashStable_Generic)]
1321 pub enum Guard<'hir> {
1322     If(&'hir Expr<'hir>),
1323     // FIXME use hir::Let for this.
1324     IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1325 }
1326
1327 #[derive(Debug, HashStable_Generic)]
1328 pub struct ExprField<'hir> {
1329     #[stable_hasher(ignore)]
1330     pub hir_id: HirId,
1331     pub ident: Ident,
1332     pub expr: &'hir Expr<'hir>,
1333     pub span: Span,
1334     pub is_shorthand: bool,
1335 }
1336
1337 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1338 pub enum BlockCheckMode {
1339     DefaultBlock,
1340     UnsafeBlock(UnsafeSource),
1341 }
1342
1343 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1344 pub enum UnsafeSource {
1345     CompilerGenerated,
1346     UserProvided,
1347 }
1348
1349 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1350 pub struct BodyId {
1351     pub hir_id: HirId,
1352 }
1353
1354 /// The body of a function, closure, or constant value. In the case of
1355 /// a function, the body contains not only the function body itself
1356 /// (which is an expression), but also the argument patterns, since
1357 /// those are something that the caller doesn't really care about.
1358 ///
1359 /// # Examples
1360 ///
1361 /// ```
1362 /// fn foo((x, y): (u32, u32)) -> u32 {
1363 ///     x + y
1364 /// }
1365 /// ```
1366 ///
1367 /// Here, the `Body` associated with `foo()` would contain:
1368 ///
1369 /// - an `params` array containing the `(x, y)` pattern
1370 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1371 /// - `generator_kind` would be `None`
1372 ///
1373 /// All bodies have an **owner**, which can be accessed via the HIR
1374 /// map using `body_owner_def_id()`.
1375 #[derive(Debug, HashStable_Generic)]
1376 pub struct Body<'hir> {
1377     pub params: &'hir [Param<'hir>],
1378     pub value: Expr<'hir>,
1379     pub generator_kind: Option<GeneratorKind>,
1380 }
1381
1382 impl<'hir> Body<'hir> {
1383     pub fn id(&self) -> BodyId {
1384         BodyId { hir_id: self.value.hir_id }
1385     }
1386
1387     pub fn generator_kind(&self) -> Option<GeneratorKind> {
1388         self.generator_kind
1389     }
1390 }
1391
1392 /// The type of source expression that caused this generator to be created.
1393 #[derive(
1394     Clone,
1395     PartialEq,
1396     PartialOrd,
1397     Eq,
1398     Hash,
1399     HashStable_Generic,
1400     Encodable,
1401     Decodable,
1402     Debug,
1403     Copy
1404 )]
1405 pub enum GeneratorKind {
1406     /// An explicit `async` block or the body of an async function.
1407     Async(AsyncGeneratorKind),
1408
1409     /// A generator literal created via a `yield` inside a closure.
1410     Gen,
1411 }
1412
1413 impl fmt::Display for GeneratorKind {
1414     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1415         match self {
1416             GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1417             GeneratorKind::Gen => f.write_str("generator"),
1418         }
1419     }
1420 }
1421
1422 impl GeneratorKind {
1423     pub fn descr(&self) -> &'static str {
1424         match self {
1425             GeneratorKind::Async(ask) => ask.descr(),
1426             GeneratorKind::Gen => "generator",
1427         }
1428     }
1429 }
1430
1431 /// In the case of a generator created as part of an async construct,
1432 /// which kind of async construct caused it to be created?
1433 ///
1434 /// This helps error messages but is also used to drive coercions in
1435 /// type-checking (see #60424).
1436 #[derive(
1437     Clone,
1438     PartialEq,
1439     PartialOrd,
1440     Eq,
1441     Hash,
1442     HashStable_Generic,
1443     Encodable,
1444     Decodable,
1445     Debug,
1446     Copy
1447 )]
1448 pub enum AsyncGeneratorKind {
1449     /// An explicit `async` block written by the user.
1450     Block,
1451
1452     /// An explicit `async` closure written by the user.
1453     Closure,
1454
1455     /// The `async` block generated as the body of an async function.
1456     Fn,
1457 }
1458
1459 impl fmt::Display for AsyncGeneratorKind {
1460     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1461         f.write_str(match self {
1462             AsyncGeneratorKind::Block => "`async` block",
1463             AsyncGeneratorKind::Closure => "`async` closure body",
1464             AsyncGeneratorKind::Fn => "`async fn` body",
1465         })
1466     }
1467 }
1468
1469 impl AsyncGeneratorKind {
1470     pub fn descr(&self) -> &'static str {
1471         match self {
1472             AsyncGeneratorKind::Block => "`async` block",
1473             AsyncGeneratorKind::Closure => "`async` closure body",
1474             AsyncGeneratorKind::Fn => "`async fn` body",
1475         }
1476     }
1477 }
1478
1479 #[derive(Copy, Clone, Debug)]
1480 pub enum BodyOwnerKind {
1481     /// Functions and methods.
1482     Fn,
1483
1484     /// Closures
1485     Closure,
1486
1487     /// Constants and associated constants.
1488     Const,
1489
1490     /// Initializer of a `static` item.
1491     Static(Mutability),
1492 }
1493
1494 impl BodyOwnerKind {
1495     pub fn is_fn_or_closure(self) -> bool {
1496         match self {
1497             BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1498             BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1499         }
1500     }
1501 }
1502
1503 /// The kind of an item that requires const-checking.
1504 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1505 pub enum ConstContext {
1506     /// A `const fn`.
1507     ConstFn,
1508
1509     /// A `static` or `static mut`.
1510     Static(Mutability),
1511
1512     /// A `const`, associated `const`, or other const context.
1513     ///
1514     /// Other contexts include:
1515     /// - Array length expressions
1516     /// - Enum discriminants
1517     /// - Const generics
1518     ///
1519     /// For the most part, other contexts are treated just like a regular `const`, so they are
1520     /// lumped into the same category.
1521     Const,
1522 }
1523
1524 impl ConstContext {
1525     /// A description of this const context that can appear between backticks in an error message.
1526     ///
1527     /// E.g. `const` or `static mut`.
1528     pub fn keyword_name(self) -> &'static str {
1529         match self {
1530             Self::Const => "const",
1531             Self::Static(Mutability::Not) => "static",
1532             Self::Static(Mutability::Mut) => "static mut",
1533             Self::ConstFn => "const fn",
1534         }
1535     }
1536 }
1537
1538 /// A colloquial, trivially pluralizable description of this const context for use in error
1539 /// messages.
1540 impl fmt::Display for ConstContext {
1541     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1542         match *self {
1543             Self::Const => write!(f, "constant"),
1544             Self::Static(_) => write!(f, "static"),
1545             Self::ConstFn => write!(f, "constant function"),
1546         }
1547     }
1548 }
1549
1550 /// A literal.
1551 pub type Lit = Spanned<LitKind>;
1552
1553 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1554 pub enum ArrayLen {
1555     Infer(HirId, Span),
1556     Body(AnonConst),
1557 }
1558
1559 impl ArrayLen {
1560     pub fn hir_id(&self) -> HirId {
1561         match self {
1562             &ArrayLen::Infer(hir_id, _) | &ArrayLen::Body(AnonConst { hir_id, body: _ }) => hir_id,
1563         }
1564     }
1565 }
1566
1567 /// A constant (expression) that's not an item or associated item,
1568 /// but needs its own `DefId` for type-checking, const-eval, etc.
1569 /// These are usually found nested inside types (e.g., array lengths)
1570 /// or expressions (e.g., repeat counts), and also used to define
1571 /// explicit discriminant values for enum variants.
1572 ///
1573 /// You can check if this anon const is a default in a const param
1574 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1575 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1576 pub struct AnonConst {
1577     pub hir_id: HirId,
1578     pub body: BodyId,
1579 }
1580
1581 /// An expression.
1582 #[derive(Debug)]
1583 pub struct Expr<'hir> {
1584     pub hir_id: HirId,
1585     pub kind: ExprKind<'hir>,
1586     pub span: Span,
1587 }
1588
1589 impl Expr<'_> {
1590     pub fn precedence(&self) -> ExprPrecedence {
1591         match self.kind {
1592             ExprKind::Box(_) => ExprPrecedence::Box,
1593             ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1594             ExprKind::Array(_) => ExprPrecedence::Array,
1595             ExprKind::Call(..) => ExprPrecedence::Call,
1596             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1597             ExprKind::Tup(_) => ExprPrecedence::Tup,
1598             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1599             ExprKind::Unary(..) => ExprPrecedence::Unary,
1600             ExprKind::Lit(_) => ExprPrecedence::Lit,
1601             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1602             ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1603             ExprKind::If(..) => ExprPrecedence::If,
1604             ExprKind::Let(..) => ExprPrecedence::Let,
1605             ExprKind::Loop(..) => ExprPrecedence::Loop,
1606             ExprKind::Match(..) => ExprPrecedence::Match,
1607             ExprKind::Closure(..) => ExprPrecedence::Closure,
1608             ExprKind::Block(..) => ExprPrecedence::Block,
1609             ExprKind::Assign(..) => ExprPrecedence::Assign,
1610             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1611             ExprKind::Field(..) => ExprPrecedence::Field,
1612             ExprKind::Index(..) => ExprPrecedence::Index,
1613             ExprKind::Path(..) => ExprPrecedence::Path,
1614             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1615             ExprKind::Break(..) => ExprPrecedence::Break,
1616             ExprKind::Continue(..) => ExprPrecedence::Continue,
1617             ExprKind::Ret(..) => ExprPrecedence::Ret,
1618             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1619             ExprKind::Struct(..) => ExprPrecedence::Struct,
1620             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1621             ExprKind::Yield(..) => ExprPrecedence::Yield,
1622             ExprKind::Err => ExprPrecedence::Err,
1623         }
1624     }
1625
1626     // Whether this looks like a place expr, without checking for deref
1627     // adjustments.
1628     // This will return `true` in some potentially surprising cases such as
1629     // `CONSTANT.field`.
1630     pub fn is_syntactic_place_expr(&self) -> bool {
1631         self.is_place_expr(|_| true)
1632     }
1633
1634     /// Whether this is a place expression.
1635     ///
1636     /// `allow_projections_from` should return `true` if indexing a field or index expression based
1637     /// on the given expression should be considered a place expression.
1638     pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1639         match self.kind {
1640             ExprKind::Path(QPath::Resolved(_, ref path)) => {
1641                 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static(_), _) | Res::Err)
1642             }
1643
1644             // Type ascription inherits its place expression kind from its
1645             // operand. See:
1646             // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1647             ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1648
1649             ExprKind::Unary(UnOp::Deref, _) => true,
1650
1651             ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1652                 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1653             }
1654
1655             // Lang item paths cannot currently be local variables or statics.
1656             ExprKind::Path(QPath::LangItem(..)) => false,
1657
1658             // Partially qualified paths in expressions can only legally
1659             // refer to associated items which are always rvalues.
1660             ExprKind::Path(QPath::TypeRelative(..))
1661             | ExprKind::Call(..)
1662             | ExprKind::MethodCall(..)
1663             | ExprKind::Struct(..)
1664             | ExprKind::Tup(..)
1665             | ExprKind::If(..)
1666             | ExprKind::Match(..)
1667             | ExprKind::Closure(..)
1668             | ExprKind::Block(..)
1669             | ExprKind::Repeat(..)
1670             | ExprKind::Array(..)
1671             | ExprKind::Break(..)
1672             | ExprKind::Continue(..)
1673             | ExprKind::Ret(..)
1674             | ExprKind::Let(..)
1675             | ExprKind::Loop(..)
1676             | ExprKind::Assign(..)
1677             | ExprKind::InlineAsm(..)
1678             | ExprKind::AssignOp(..)
1679             | ExprKind::Lit(_)
1680             | ExprKind::ConstBlock(..)
1681             | ExprKind::Unary(..)
1682             | ExprKind::Box(..)
1683             | ExprKind::AddrOf(..)
1684             | ExprKind::Binary(..)
1685             | ExprKind::Yield(..)
1686             | ExprKind::Cast(..)
1687             | ExprKind::DropTemps(..)
1688             | ExprKind::Err => false,
1689         }
1690     }
1691
1692     /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1693     /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1694     /// silent, only signaling the ownership system. By doing this, suggestions that check the
1695     /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1696     /// beyond remembering to call this function before doing analysis on it.
1697     pub fn peel_drop_temps(&self) -> &Self {
1698         let mut expr = self;
1699         while let ExprKind::DropTemps(inner) = &expr.kind {
1700             expr = inner;
1701         }
1702         expr
1703     }
1704
1705     pub fn peel_blocks(&self) -> &Self {
1706         let mut expr = self;
1707         while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1708             expr = inner;
1709         }
1710         expr
1711     }
1712
1713     pub fn can_have_side_effects(&self) -> bool {
1714         match self.peel_drop_temps().kind {
1715             ExprKind::Path(_) | ExprKind::Lit(_) => false,
1716             ExprKind::Type(base, _)
1717             | ExprKind::Unary(_, base)
1718             | ExprKind::Field(base, _)
1719             | ExprKind::Index(base, _)
1720             | ExprKind::AddrOf(.., base)
1721             | ExprKind::Cast(base, _) => {
1722                 // This isn't exactly true for `Index` and all `Unary`, but we are using this
1723                 // method exclusively for diagnostics and there's a *cultural* pressure against
1724                 // them being used only for its side-effects.
1725                 base.can_have_side_effects()
1726             }
1727             ExprKind::Struct(_, fields, init) => fields
1728                 .iter()
1729                 .map(|field| field.expr)
1730                 .chain(init.into_iter())
1731                 .all(|e| e.can_have_side_effects()),
1732
1733             ExprKind::Array(args)
1734             | ExprKind::Tup(args)
1735             | ExprKind::Call(
1736                 Expr {
1737                     kind:
1738                         ExprKind::Path(QPath::Resolved(
1739                             None,
1740                             Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1741                         )),
1742                     ..
1743                 },
1744                 args,
1745             ) => args.iter().all(|arg| arg.can_have_side_effects()),
1746             ExprKind::If(..)
1747             | ExprKind::Match(..)
1748             | ExprKind::MethodCall(..)
1749             | ExprKind::Call(..)
1750             | ExprKind::Closure(..)
1751             | ExprKind::Block(..)
1752             | ExprKind::Repeat(..)
1753             | ExprKind::Break(..)
1754             | ExprKind::Continue(..)
1755             | ExprKind::Ret(..)
1756             | ExprKind::Let(..)
1757             | ExprKind::Loop(..)
1758             | ExprKind::Assign(..)
1759             | ExprKind::InlineAsm(..)
1760             | ExprKind::AssignOp(..)
1761             | ExprKind::ConstBlock(..)
1762             | ExprKind::Box(..)
1763             | ExprKind::Binary(..)
1764             | ExprKind::Yield(..)
1765             | ExprKind::DropTemps(..)
1766             | ExprKind::Err => true,
1767         }
1768     }
1769 }
1770
1771 /// Checks if the specified expression is a built-in range literal.
1772 /// (See: `LoweringContext::lower_expr()`).
1773 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1774     match expr.kind {
1775         // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1776         ExprKind::Struct(ref qpath, _, _) => matches!(
1777             **qpath,
1778             QPath::LangItem(
1779                 LangItem::Range
1780                     | LangItem::RangeTo
1781                     | LangItem::RangeFrom
1782                     | LangItem::RangeFull
1783                     | LangItem::RangeToInclusive,
1784                 ..
1785             )
1786         ),
1787
1788         // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1789         ExprKind::Call(ref func, _) => {
1790             matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)))
1791         }
1792
1793         _ => false,
1794     }
1795 }
1796
1797 #[derive(Debug, HashStable_Generic)]
1798 pub enum ExprKind<'hir> {
1799     /// A `box x` expression.
1800     Box(&'hir Expr<'hir>),
1801     /// Allow anonymous constants from an inline `const` block
1802     ConstBlock(AnonConst),
1803     /// An array (e.g., `[a, b, c, d]`).
1804     Array(&'hir [Expr<'hir>]),
1805     /// A function call.
1806     ///
1807     /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1808     /// and the second field is the list of arguments.
1809     /// This also represents calling the constructor of
1810     /// tuple-like ADTs such as tuple structs and enum variants.
1811     Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1812     /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1813     ///
1814     /// The `PathSegment` represents the method name and its generic arguments
1815     /// (within the angle brackets).
1816     /// The first element of the `&[Expr]` is the expression that evaluates
1817     /// to the object on which the method is being called on (the receiver),
1818     /// and the remaining elements are the rest of the arguments.
1819     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1820     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d], span)`.
1821     /// The final `Span` represents the span of the function and arguments
1822     /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1823     ///
1824     /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1825     /// the `hir_id` of the `MethodCall` node itself.
1826     ///
1827     /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1828     MethodCall(&'hir PathSegment<'hir>, &'hir [Expr<'hir>], Span),
1829     /// A tuple (e.g., `(a, b, c, d)`).
1830     Tup(&'hir [Expr<'hir>]),
1831     /// A binary operation (e.g., `a + b`, `a * b`).
1832     Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1833     /// A unary operation (e.g., `!x`, `*x`).
1834     Unary(UnOp, &'hir Expr<'hir>),
1835     /// A literal (e.g., `1`, `"foo"`).
1836     Lit(Lit),
1837     /// A cast (e.g., `foo as f64`).
1838     Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1839     /// A type reference (e.g., `Foo`).
1840     Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1841     /// Wraps the expression in a terminating scope.
1842     /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1843     ///
1844     /// This construct only exists to tweak the drop order in HIR lowering.
1845     /// An example of that is the desugaring of `for` loops.
1846     DropTemps(&'hir Expr<'hir>),
1847     /// A `let $pat = $expr` expression.
1848     ///
1849     /// These are not `Local` and only occur as expressions.
1850     /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1851     Let(&'hir Let<'hir>),
1852     /// An `if` block, with an optional else block.
1853     ///
1854     /// I.e., `if <expr> { <expr> } else { <expr> }`.
1855     If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1856     /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1857     ///
1858     /// I.e., `'label: loop { <block> }`.
1859     ///
1860     /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1861     Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1862     /// A `match` block, with a source that indicates whether or not it is
1863     /// the result of a desugaring, and if so, which kind.
1864     Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1865     /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1866     ///
1867     /// The `Span` is the argument block `|...|`.
1868     ///
1869     /// This may also be a generator literal or an `async block` as indicated by the
1870     /// `Option<Movability>`.
1871     Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1872     /// A block (e.g., `'label: { ... }`).
1873     Block(&'hir Block<'hir>, Option<Label>),
1874
1875     /// An assignment (e.g., `a = foo()`).
1876     Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1877     /// An assignment with an operator.
1878     ///
1879     /// E.g., `a += 1`.
1880     AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1881     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1882     Field(&'hir Expr<'hir>, Ident),
1883     /// An indexing operation (`foo[2]`).
1884     Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1885
1886     /// Path to a definition, possibly containing lifetime or type parameters.
1887     Path(QPath<'hir>),
1888
1889     /// A referencing operation (i.e., `&a` or `&mut a`).
1890     AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1891     /// A `break`, with an optional label to break.
1892     Break(Destination, Option<&'hir Expr<'hir>>),
1893     /// A `continue`, with an optional label.
1894     Continue(Destination),
1895     /// A `return`, with an optional value to be returned.
1896     Ret(Option<&'hir Expr<'hir>>),
1897
1898     /// Inline assembly (from `asm!`), with its outputs and inputs.
1899     InlineAsm(&'hir InlineAsm<'hir>),
1900
1901     /// A struct or struct-like variant literal expression.
1902     ///
1903     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1904     /// where `base` is the `Option<Expr>`.
1905     Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1906
1907     /// An array literal constructed from one repeated element.
1908     ///
1909     /// E.g., `[1; 5]`. The first expression is the element
1910     /// to be repeated; the second is the number of times to repeat it.
1911     Repeat(&'hir Expr<'hir>, ArrayLen),
1912
1913     /// A suspension point for generators (i.e., `yield <expr>`).
1914     Yield(&'hir Expr<'hir>, YieldSource),
1915
1916     /// A placeholder for an expression that wasn't syntactically well formed in some way.
1917     Err,
1918 }
1919
1920 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1921 ///
1922 /// To resolve the path to a `DefId`, call [`qpath_res`].
1923 ///
1924 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1925 #[derive(Debug, HashStable_Generic)]
1926 pub enum QPath<'hir> {
1927     /// Path to a definition, optionally "fully-qualified" with a `Self`
1928     /// type, if the path points to an associated item in a trait.
1929     ///
1930     /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1931     /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1932     /// even though they both have the same two-segment `Clone::clone` `Path`.
1933     Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1934
1935     /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1936     /// Will be resolved by type-checking to an associated item.
1937     ///
1938     /// UFCS source paths can desugar into this, with `Vec::new` turning into
1939     /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1940     /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1941     TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1942
1943     /// Reference to a `#[lang = "foo"]` item. `HirId` of the inner expr.
1944     LangItem(LangItem, Span, Option<HirId>),
1945 }
1946
1947 impl<'hir> QPath<'hir> {
1948     /// Returns the span of this `QPath`.
1949     pub fn span(&self) -> Span {
1950         match *self {
1951             QPath::Resolved(_, path) => path.span,
1952             QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1953             QPath::LangItem(_, span, _) => span,
1954         }
1955     }
1956
1957     /// Returns the span of the qself of this `QPath`. For example, `()` in
1958     /// `<() as Trait>::method`.
1959     pub fn qself_span(&self) -> Span {
1960         match *self {
1961             QPath::Resolved(_, path) => path.span,
1962             QPath::TypeRelative(qself, _) => qself.span,
1963             QPath::LangItem(_, span, _) => span,
1964         }
1965     }
1966
1967     /// Returns the span of the last segment of this `QPath`. For example, `method` in
1968     /// `<() as Trait>::method`.
1969     pub fn last_segment_span(&self) -> Span {
1970         match *self {
1971             QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1972             QPath::TypeRelative(_, segment) => segment.ident.span,
1973             QPath::LangItem(_, span, _) => span,
1974         }
1975     }
1976 }
1977
1978 /// Hints at the original code for a let statement.
1979 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1980 pub enum LocalSource {
1981     /// A `match _ { .. }`.
1982     Normal,
1983     /// When lowering async functions, we create locals within the `async move` so that
1984     /// all parameters are dropped after the future is polled.
1985     ///
1986     /// ```ignore (pseudo-Rust)
1987     /// async fn foo(<pattern> @ x: Type) {
1988     ///     async move {
1989     ///         let <pattern> = x;
1990     ///     }
1991     /// }
1992     /// ```
1993     AsyncFn,
1994     /// A desugared `<expr>.await`.
1995     AwaitDesugar,
1996     /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1997     /// The span is that of the `=` sign.
1998     AssignDesugar(Span),
1999 }
2000
2001 /// Hints at the original code for a `match _ { .. }`.
2002 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
2003 #[derive(HashStable_Generic)]
2004 pub enum MatchSource {
2005     /// A `match _ { .. }`.
2006     Normal,
2007     /// A desugared `for _ in _ { .. }` loop.
2008     ForLoopDesugar,
2009     /// A desugared `?` operator.
2010     TryDesugar,
2011     /// A desugared `<expr>.await`.
2012     AwaitDesugar,
2013 }
2014
2015 impl MatchSource {
2016     #[inline]
2017     pub const fn name(self) -> &'static str {
2018         use MatchSource::*;
2019         match self {
2020             Normal => "match",
2021             ForLoopDesugar => "for",
2022             TryDesugar => "?",
2023             AwaitDesugar => ".await",
2024         }
2025     }
2026 }
2027
2028 /// The loop type that yielded an `ExprKind::Loop`.
2029 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2030 pub enum LoopSource {
2031     /// A `loop { .. }` loop.
2032     Loop,
2033     /// A `while _ { .. }` loop.
2034     While,
2035     /// A `for _ in _ { .. }` loop.
2036     ForLoop,
2037 }
2038
2039 impl LoopSource {
2040     pub fn name(self) -> &'static str {
2041         match self {
2042             LoopSource::Loop => "loop",
2043             LoopSource::While => "while",
2044             LoopSource::ForLoop => "for",
2045         }
2046     }
2047 }
2048
2049 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2050 pub enum LoopIdError {
2051     OutsideLoopScope,
2052     UnlabeledCfInWhileCondition,
2053     UnresolvedLabel,
2054 }
2055
2056 impl fmt::Display for LoopIdError {
2057     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2058         f.write_str(match self {
2059             LoopIdError::OutsideLoopScope => "not inside loop scope",
2060             LoopIdError::UnlabeledCfInWhileCondition => {
2061                 "unlabeled control flow (break or continue) in while condition"
2062             }
2063             LoopIdError::UnresolvedLabel => "label not found",
2064         })
2065     }
2066 }
2067
2068 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2069 pub struct Destination {
2070     // This is `Some(_)` iff there is an explicit user-specified `label
2071     pub label: Option<Label>,
2072
2073     // These errors are caught and then reported during the diagnostics pass in
2074     // librustc_passes/loops.rs
2075     pub target_id: Result<HirId, LoopIdError>,
2076 }
2077
2078 /// The yield kind that caused an `ExprKind::Yield`.
2079 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
2080 pub enum YieldSource {
2081     /// An `<expr>.await`.
2082     Await { expr: Option<HirId> },
2083     /// A plain `yield`.
2084     Yield,
2085 }
2086
2087 impl YieldSource {
2088     pub fn is_await(&self) -> bool {
2089         matches!(self, YieldSource::Await { .. })
2090     }
2091 }
2092
2093 impl fmt::Display for YieldSource {
2094     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2095         f.write_str(match self {
2096             YieldSource::Await { .. } => "`await`",
2097             YieldSource::Yield => "`yield`",
2098         })
2099     }
2100 }
2101
2102 impl From<GeneratorKind> for YieldSource {
2103     fn from(kind: GeneratorKind) -> Self {
2104         match kind {
2105             // Guess based on the kind of the current generator.
2106             GeneratorKind::Gen => Self::Yield,
2107             GeneratorKind::Async(_) => Self::Await { expr: None },
2108         }
2109     }
2110 }
2111
2112 // N.B., if you change this, you'll probably want to change the corresponding
2113 // type structure in middle/ty.rs as well.
2114 #[derive(Debug, HashStable_Generic)]
2115 pub struct MutTy<'hir> {
2116     pub ty: &'hir Ty<'hir>,
2117     pub mutbl: Mutability,
2118 }
2119
2120 /// Represents a function's signature in a trait declaration,
2121 /// trait implementation, or a free function.
2122 #[derive(Debug, HashStable_Generic)]
2123 pub struct FnSig<'hir> {
2124     pub header: FnHeader,
2125     pub decl: &'hir FnDecl<'hir>,
2126     pub span: Span,
2127 }
2128
2129 // The bodies for items are stored "out of line", in a separate
2130 // hashmap in the `Crate`. Here we just record the hir-id of the item
2131 // so it can fetched later.
2132 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
2133 pub struct TraitItemId {
2134     pub def_id: LocalDefId,
2135 }
2136
2137 impl TraitItemId {
2138     #[inline]
2139     pub fn hir_id(&self) -> HirId {
2140         // Items are always HIR owners.
2141         HirId::make_owner(self.def_id)
2142     }
2143 }
2144
2145 /// Represents an item declaration within a trait declaration,
2146 /// possibly including a default implementation. A trait item is
2147 /// either required (meaning it doesn't have an implementation, just a
2148 /// signature) or provided (meaning it has a default implementation).
2149 #[derive(Debug, HashStable_Generic)]
2150 pub struct TraitItem<'hir> {
2151     pub ident: Ident,
2152     pub def_id: LocalDefId,
2153     pub generics: &'hir Generics<'hir>,
2154     pub kind: TraitItemKind<'hir>,
2155     pub span: Span,
2156 }
2157
2158 impl TraitItem<'_> {
2159     #[inline]
2160     pub fn hir_id(&self) -> HirId {
2161         // Items are always HIR owners.
2162         HirId::make_owner(self.def_id)
2163     }
2164
2165     pub fn trait_item_id(&self) -> TraitItemId {
2166         TraitItemId { def_id: self.def_id }
2167     }
2168 }
2169
2170 /// Represents a trait method's body (or just argument names).
2171 #[derive(Encodable, Debug, HashStable_Generic)]
2172 pub enum TraitFn<'hir> {
2173     /// No default body in the trait, just a signature.
2174     Required(&'hir [Ident]),
2175
2176     /// Both signature and body are provided in the trait.
2177     Provided(BodyId),
2178 }
2179
2180 /// Represents a trait method or associated constant or type
2181 #[derive(Debug, HashStable_Generic)]
2182 pub enum TraitItemKind<'hir> {
2183     /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2184     Const(&'hir Ty<'hir>, Option<BodyId>),
2185     /// An associated function with an optional body.
2186     Fn(FnSig<'hir>, TraitFn<'hir>),
2187     /// An associated type with (possibly empty) bounds and optional concrete
2188     /// type.
2189     Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2190 }
2191
2192 // The bodies for items are stored "out of line", in a separate
2193 // hashmap in the `Crate`. Here we just record the hir-id of the item
2194 // so it can fetched later.
2195 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
2196 pub struct ImplItemId {
2197     pub def_id: LocalDefId,
2198 }
2199
2200 impl ImplItemId {
2201     #[inline]
2202     pub fn hir_id(&self) -> HirId {
2203         // Items are always HIR owners.
2204         HirId::make_owner(self.def_id)
2205     }
2206 }
2207
2208 /// Represents anything within an `impl` block.
2209 #[derive(Debug, HashStable_Generic)]
2210 pub struct ImplItem<'hir> {
2211     pub ident: Ident,
2212     pub def_id: LocalDefId,
2213     pub generics: &'hir Generics<'hir>,
2214     pub kind: ImplItemKind<'hir>,
2215     pub span: Span,
2216     pub vis_span: Span,
2217 }
2218
2219 impl ImplItem<'_> {
2220     #[inline]
2221     pub fn hir_id(&self) -> HirId {
2222         // Items are always HIR owners.
2223         HirId::make_owner(self.def_id)
2224     }
2225
2226     pub fn impl_item_id(&self) -> ImplItemId {
2227         ImplItemId { def_id: self.def_id }
2228     }
2229 }
2230
2231 /// Represents various kinds of content within an `impl`.
2232 #[derive(Debug, HashStable_Generic)]
2233 pub enum ImplItemKind<'hir> {
2234     /// An associated constant of the given type, set to the constant result
2235     /// of the expression.
2236     Const(&'hir Ty<'hir>, BodyId),
2237     /// An associated function implementation with the given signature and body.
2238     Fn(FnSig<'hir>, BodyId),
2239     /// An associated type.
2240     TyAlias(&'hir Ty<'hir>),
2241 }
2242
2243 // The name of the associated type for `Fn` return types.
2244 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2245
2246 /// Bind a type to an associated type (i.e., `A = Foo`).
2247 ///
2248 /// Bindings like `A: Debug` are represented as a special type `A =
2249 /// $::Debug` that is understood by the astconv code.
2250 ///
2251 /// FIXME(alexreg): why have a separate type for the binding case,
2252 /// wouldn't it be better to make the `ty` field an enum like the
2253 /// following?
2254 ///
2255 /// ```ignore (pseudo-rust)
2256 /// enum TypeBindingKind {
2257 ///    Equals(...),
2258 ///    Binding(...),
2259 /// }
2260 /// ```
2261 #[derive(Debug, HashStable_Generic)]
2262 pub struct TypeBinding<'hir> {
2263     pub hir_id: HirId,
2264     pub ident: Ident,
2265     pub gen_args: &'hir GenericArgs<'hir>,
2266     pub kind: TypeBindingKind<'hir>,
2267     pub span: Span,
2268 }
2269
2270 #[derive(Debug, HashStable_Generic)]
2271 pub enum Term<'hir> {
2272     Ty(&'hir Ty<'hir>),
2273     Const(AnonConst),
2274 }
2275
2276 impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> {
2277     fn from(ty: &'hir Ty<'hir>) -> Self {
2278         Term::Ty(ty)
2279     }
2280 }
2281
2282 impl<'hir> From<AnonConst> for Term<'hir> {
2283     fn from(c: AnonConst) -> Self {
2284         Term::Const(c)
2285     }
2286 }
2287
2288 // Represents the two kinds of type bindings.
2289 #[derive(Debug, HashStable_Generic)]
2290 pub enum TypeBindingKind<'hir> {
2291     /// E.g., `Foo<Bar: Send>`.
2292     Constraint { bounds: &'hir [GenericBound<'hir>] },
2293     /// E.g., `Foo<Bar = ()>`, `Foo<Bar = ()>`
2294     Equality { term: Term<'hir> },
2295 }
2296
2297 impl TypeBinding<'_> {
2298     pub fn ty(&self) -> &Ty<'_> {
2299         match self.kind {
2300             TypeBindingKind::Equality { term: Term::Ty(ref ty) } => ty,
2301             _ => panic!("expected equality type binding for parenthesized generic args"),
2302         }
2303     }
2304     pub fn opt_const(&self) -> Option<&'_ AnonConst> {
2305         match self.kind {
2306             TypeBindingKind::Equality { term: Term::Const(ref c) } => Some(c),
2307             _ => None,
2308         }
2309     }
2310 }
2311
2312 #[derive(Debug)]
2313 pub struct Ty<'hir> {
2314     pub hir_id: HirId,
2315     pub kind: TyKind<'hir>,
2316     pub span: Span,
2317 }
2318
2319 impl<'hir> Ty<'hir> {
2320     /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
2321     pub fn as_generic_param(&self) -> Option<(DefId, Ident)> {
2322         let TyKind::Path(QPath::Resolved(None, path)) = self.kind else {
2323             return None;
2324         };
2325         let [segment] = &path.segments else {
2326             return None;
2327         };
2328         match path.res {
2329             Res::Def(DefKind::TyParam, def_id)
2330             | Res::SelfTy { trait_: Some(def_id), alias_to: None } => Some((def_id, segment.ident)),
2331             _ => None,
2332         }
2333     }
2334 }
2335
2336 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2337 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2338 #[derive(HashStable_Generic)]
2339 pub enum PrimTy {
2340     Int(IntTy),
2341     Uint(UintTy),
2342     Float(FloatTy),
2343     Str,
2344     Bool,
2345     Char,
2346 }
2347
2348 impl PrimTy {
2349     /// All of the primitive types
2350     pub const ALL: [Self; 17] = [
2351         // any changes here should also be reflected in `PrimTy::from_name`
2352         Self::Int(IntTy::I8),
2353         Self::Int(IntTy::I16),
2354         Self::Int(IntTy::I32),
2355         Self::Int(IntTy::I64),
2356         Self::Int(IntTy::I128),
2357         Self::Int(IntTy::Isize),
2358         Self::Uint(UintTy::U8),
2359         Self::Uint(UintTy::U16),
2360         Self::Uint(UintTy::U32),
2361         Self::Uint(UintTy::U64),
2362         Self::Uint(UintTy::U128),
2363         Self::Uint(UintTy::Usize),
2364         Self::Float(FloatTy::F32),
2365         Self::Float(FloatTy::F64),
2366         Self::Bool,
2367         Self::Char,
2368         Self::Str,
2369     ];
2370
2371     /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2372     ///
2373     /// Used by clippy.
2374     pub fn name_str(self) -> &'static str {
2375         match self {
2376             PrimTy::Int(i) => i.name_str(),
2377             PrimTy::Uint(u) => u.name_str(),
2378             PrimTy::Float(f) => f.name_str(),
2379             PrimTy::Str => "str",
2380             PrimTy::Bool => "bool",
2381             PrimTy::Char => "char",
2382         }
2383     }
2384
2385     pub fn name(self) -> Symbol {
2386         match self {
2387             PrimTy::Int(i) => i.name(),
2388             PrimTy::Uint(u) => u.name(),
2389             PrimTy::Float(f) => f.name(),
2390             PrimTy::Str => sym::str,
2391             PrimTy::Bool => sym::bool,
2392             PrimTy::Char => sym::char,
2393         }
2394     }
2395
2396     /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2397     /// Returns `None` if no matching type is found.
2398     pub fn from_name(name: Symbol) -> Option<Self> {
2399         let ty = match name {
2400             // any changes here should also be reflected in `PrimTy::ALL`
2401             sym::i8 => Self::Int(IntTy::I8),
2402             sym::i16 => Self::Int(IntTy::I16),
2403             sym::i32 => Self::Int(IntTy::I32),
2404             sym::i64 => Self::Int(IntTy::I64),
2405             sym::i128 => Self::Int(IntTy::I128),
2406             sym::isize => Self::Int(IntTy::Isize),
2407             sym::u8 => Self::Uint(UintTy::U8),
2408             sym::u16 => Self::Uint(UintTy::U16),
2409             sym::u32 => Self::Uint(UintTy::U32),
2410             sym::u64 => Self::Uint(UintTy::U64),
2411             sym::u128 => Self::Uint(UintTy::U128),
2412             sym::usize => Self::Uint(UintTy::Usize),
2413             sym::f32 => Self::Float(FloatTy::F32),
2414             sym::f64 => Self::Float(FloatTy::F64),
2415             sym::bool => Self::Bool,
2416             sym::char => Self::Char,
2417             sym::str => Self::Str,
2418             _ => return None,
2419         };
2420         Some(ty)
2421     }
2422 }
2423
2424 #[derive(Debug, HashStable_Generic)]
2425 pub struct BareFnTy<'hir> {
2426     pub unsafety: Unsafety,
2427     pub abi: Abi,
2428     pub generic_params: &'hir [GenericParam<'hir>],
2429     pub decl: &'hir FnDecl<'hir>,
2430     pub param_names: &'hir [Ident],
2431 }
2432
2433 #[derive(Debug, HashStable_Generic)]
2434 pub struct OpaqueTy<'hir> {
2435     pub generics: &'hir Generics<'hir>,
2436     pub bounds: GenericBounds<'hir>,
2437     pub origin: OpaqueTyOrigin,
2438 }
2439
2440 /// From whence the opaque type came.
2441 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2442 pub enum OpaqueTyOrigin {
2443     /// `-> impl Trait`
2444     FnReturn(LocalDefId),
2445     /// `async fn`
2446     AsyncFn(LocalDefId),
2447     /// type aliases: `type Foo = impl Trait;`
2448     TyAlias,
2449 }
2450
2451 /// The various kinds of types recognized by the compiler.
2452 #[derive(Debug, HashStable_Generic)]
2453 pub enum TyKind<'hir> {
2454     /// A variable length slice (i.e., `[T]`).
2455     Slice(&'hir Ty<'hir>),
2456     /// A fixed length array (i.e., `[T; n]`).
2457     Array(&'hir Ty<'hir>, ArrayLen),
2458     /// A raw pointer (i.e., `*const T` or `*mut T`).
2459     Ptr(MutTy<'hir>),
2460     /// A reference (i.e., `&'a T` or `&'a mut T`).
2461     Rptr(Lifetime, MutTy<'hir>),
2462     /// A bare function (e.g., `fn(usize) -> bool`).
2463     BareFn(&'hir BareFnTy<'hir>),
2464     /// The never type (`!`).
2465     Never,
2466     /// A tuple (`(A, B, C, D, ...)`).
2467     Tup(&'hir [Ty<'hir>]),
2468     /// A path to a type definition (`module::module::...::Type`), or an
2469     /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2470     ///
2471     /// Type parameters may be stored in each `PathSegment`.
2472     Path(QPath<'hir>),
2473     /// An opaque type definition itself. This is only used for `impl Trait`.
2474     ///
2475     /// The generic argument list contains the lifetimes (and in the future
2476     /// possibly parameters) that are actually bound on the `impl Trait`.
2477     OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2478     /// A trait object type `Bound1 + Bound2 + Bound3`
2479     /// where `Bound` is a trait or a lifetime.
2480     TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2481     /// Unused for now.
2482     Typeof(AnonConst),
2483     /// `TyKind::Infer` means the type should be inferred instead of it having been
2484     /// specified. This can appear anywhere in a type.
2485     Infer,
2486     /// Placeholder for a type that has failed to be defined.
2487     Err,
2488 }
2489
2490 #[derive(Debug, HashStable_Generic)]
2491 pub enum InlineAsmOperand<'hir> {
2492     In {
2493         reg: InlineAsmRegOrRegClass,
2494         expr: Expr<'hir>,
2495     },
2496     Out {
2497         reg: InlineAsmRegOrRegClass,
2498         late: bool,
2499         expr: Option<Expr<'hir>>,
2500     },
2501     InOut {
2502         reg: InlineAsmRegOrRegClass,
2503         late: bool,
2504         expr: Expr<'hir>,
2505     },
2506     SplitInOut {
2507         reg: InlineAsmRegOrRegClass,
2508         late: bool,
2509         in_expr: Expr<'hir>,
2510         out_expr: Option<Expr<'hir>>,
2511     },
2512     Const {
2513         anon_const: AnonConst,
2514     },
2515     SymFn {
2516         anon_const: AnonConst,
2517     },
2518     SymStatic {
2519         path: QPath<'hir>,
2520         def_id: DefId,
2521     },
2522 }
2523
2524 impl<'hir> InlineAsmOperand<'hir> {
2525     pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2526         match *self {
2527             Self::In { reg, .. }
2528             | Self::Out { reg, .. }
2529             | Self::InOut { reg, .. }
2530             | Self::SplitInOut { reg, .. } => Some(reg),
2531             Self::Const { .. } | Self::SymFn { .. } | Self::SymStatic { .. } => None,
2532         }
2533     }
2534
2535     pub fn is_clobber(&self) -> bool {
2536         matches!(
2537             self,
2538             InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2539         )
2540     }
2541 }
2542
2543 #[derive(Debug, HashStable_Generic)]
2544 pub struct InlineAsm<'hir> {
2545     pub template: &'hir [InlineAsmTemplatePiece],
2546     pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2547     pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2548     pub options: InlineAsmOptions,
2549     pub line_spans: &'hir [Span],
2550 }
2551
2552 /// Represents a parameter in a function header.
2553 #[derive(Debug, HashStable_Generic)]
2554 pub struct Param<'hir> {
2555     pub hir_id: HirId,
2556     pub pat: &'hir Pat<'hir>,
2557     pub ty_span: Span,
2558     pub span: Span,
2559 }
2560
2561 /// Represents the header (not the body) of a function declaration.
2562 #[derive(Debug, HashStable_Generic)]
2563 pub struct FnDecl<'hir> {
2564     /// The types of the function's parameters.
2565     ///
2566     /// Additional argument data is stored in the function's [body](Body::params).
2567     pub inputs: &'hir [Ty<'hir>],
2568     pub output: FnRetTy<'hir>,
2569     pub c_variadic: bool,
2570     /// Does the function have an implicit self?
2571     pub implicit_self: ImplicitSelfKind,
2572 }
2573
2574 /// Represents what type of implicit self a function has, if any.
2575 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2576 pub enum ImplicitSelfKind {
2577     /// Represents a `fn x(self);`.
2578     Imm,
2579     /// Represents a `fn x(mut self);`.
2580     Mut,
2581     /// Represents a `fn x(&self);`.
2582     ImmRef,
2583     /// Represents a `fn x(&mut self);`.
2584     MutRef,
2585     /// Represents when a function does not have a self argument or
2586     /// when a function has a `self: X` argument.
2587     None,
2588 }
2589
2590 impl ImplicitSelfKind {
2591     /// Does this represent an implicit self?
2592     pub fn has_implicit_self(&self) -> bool {
2593         !matches!(*self, ImplicitSelfKind::None)
2594     }
2595 }
2596
2597 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2598 #[derive(HashStable_Generic)]
2599 pub enum IsAsync {
2600     Async,
2601     NotAsync,
2602 }
2603
2604 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2605 pub enum Defaultness {
2606     Default { has_value: bool },
2607     Final,
2608 }
2609
2610 impl Defaultness {
2611     pub fn has_value(&self) -> bool {
2612         match *self {
2613             Defaultness::Default { has_value } => has_value,
2614             Defaultness::Final => true,
2615         }
2616     }
2617
2618     pub fn is_final(&self) -> bool {
2619         *self == Defaultness::Final
2620     }
2621
2622     pub fn is_default(&self) -> bool {
2623         matches!(*self, Defaultness::Default { .. })
2624     }
2625 }
2626
2627 #[derive(Debug, HashStable_Generic)]
2628 pub enum FnRetTy<'hir> {
2629     /// Return type is not specified.
2630     ///
2631     /// Functions default to `()` and
2632     /// closures default to inference. Span points to where return
2633     /// type would be inserted.
2634     DefaultReturn(Span),
2635     /// Everything else.
2636     Return(&'hir Ty<'hir>),
2637 }
2638
2639 impl FnRetTy<'_> {
2640     #[inline]
2641     pub fn span(&self) -> Span {
2642         match *self {
2643             Self::DefaultReturn(span) => span,
2644             Self::Return(ref ty) => ty.span,
2645         }
2646     }
2647 }
2648
2649 #[derive(Encodable, Debug, HashStable_Generic)]
2650 pub struct Mod<'hir> {
2651     pub spans: ModSpans,
2652     pub item_ids: &'hir [ItemId],
2653 }
2654
2655 #[derive(Copy, Clone, Debug, HashStable_Generic, Encodable)]
2656 pub struct ModSpans {
2657     /// A span from the first token past `{` to the last token until `}`.
2658     /// For `mod foo;`, the inner span ranges from the first token
2659     /// to the last token in the external file.
2660     pub inner_span: Span,
2661     pub inject_use_span: Span,
2662 }
2663
2664 #[derive(Debug, HashStable_Generic)]
2665 pub struct EnumDef<'hir> {
2666     pub variants: &'hir [Variant<'hir>],
2667 }
2668
2669 #[derive(Debug, HashStable_Generic)]
2670 pub struct Variant<'hir> {
2671     /// Name of the variant.
2672     pub ident: Ident,
2673     /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2674     pub id: HirId,
2675     /// Fields and constructor id of the variant.
2676     pub data: VariantData<'hir>,
2677     /// Explicit discriminant (e.g., `Foo = 1`).
2678     pub disr_expr: Option<AnonConst>,
2679     /// Span
2680     pub span: Span,
2681 }
2682
2683 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2684 pub enum UseKind {
2685     /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2686     /// Also produced for each element of a list `use`, e.g.
2687     /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2688     Single,
2689
2690     /// Glob import, e.g., `use foo::*`.
2691     Glob,
2692
2693     /// Degenerate list import, e.g., `use foo::{a, b}` produces
2694     /// an additional `use foo::{}` for performing checks such as
2695     /// unstable feature gating. May be removed in the future.
2696     ListStem,
2697 }
2698
2699 /// References to traits in impls.
2700 ///
2701 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2702 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2703 /// trait being referred to but just a unique `HirId` that serves as a key
2704 /// within the resolution map.
2705 #[derive(Clone, Debug, HashStable_Generic)]
2706 pub struct TraitRef<'hir> {
2707     pub path: &'hir Path<'hir>,
2708     // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2709     #[stable_hasher(ignore)]
2710     pub hir_ref_id: HirId,
2711 }
2712
2713 impl TraitRef<'_> {
2714     /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2715     pub fn trait_def_id(&self) -> Option<DefId> {
2716         match self.path.res {
2717             Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2718             Res::Err => None,
2719             _ => unreachable!(),
2720         }
2721     }
2722 }
2723
2724 #[derive(Clone, Debug, HashStable_Generic)]
2725 pub struct PolyTraitRef<'hir> {
2726     /// The `'a` in `for<'a> Foo<&'a T>`.
2727     pub bound_generic_params: &'hir [GenericParam<'hir>],
2728
2729     /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2730     pub trait_ref: TraitRef<'hir>,
2731
2732     pub span: Span,
2733 }
2734
2735 #[derive(Debug, HashStable_Generic)]
2736 pub struct FieldDef<'hir> {
2737     pub span: Span,
2738     pub vis_span: Span,
2739     pub ident: Ident,
2740     pub hir_id: HirId,
2741     pub ty: &'hir Ty<'hir>,
2742 }
2743
2744 impl FieldDef<'_> {
2745     // Still necessary in couple of places
2746     pub fn is_positional(&self) -> bool {
2747         let first = self.ident.as_str().as_bytes()[0];
2748         (b'0'..=b'9').contains(&first)
2749     }
2750 }
2751
2752 /// Fields and constructor IDs of enum variants and structs.
2753 #[derive(Debug, HashStable_Generic)]
2754 pub enum VariantData<'hir> {
2755     /// A struct variant.
2756     ///
2757     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2758     Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2759     /// A tuple variant.
2760     ///
2761     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2762     Tuple(&'hir [FieldDef<'hir>], HirId),
2763     /// A unit variant.
2764     ///
2765     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2766     Unit(HirId),
2767 }
2768
2769 impl<'hir> VariantData<'hir> {
2770     /// Return the fields of this variant.
2771     pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2772         match *self {
2773             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2774             _ => &[],
2775         }
2776     }
2777
2778     /// Return the `HirId` of this variant's constructor, if it has one.
2779     pub fn ctor_hir_id(&self) -> Option<HirId> {
2780         match *self {
2781             VariantData::Struct(_, _) => None,
2782             VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2783         }
2784     }
2785 }
2786
2787 // The bodies for items are stored "out of line", in a separate
2788 // hashmap in the `Crate`. Here we just record the hir-id of the item
2789 // so it can fetched later.
2790 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, Hash, HashStable_Generic)]
2791 pub struct ItemId {
2792     pub def_id: LocalDefId,
2793 }
2794
2795 impl ItemId {
2796     #[inline]
2797     pub fn hir_id(&self) -> HirId {
2798         // Items are always HIR owners.
2799         HirId::make_owner(self.def_id)
2800     }
2801 }
2802
2803 /// An item
2804 ///
2805 /// The name might be a dummy name in case of anonymous items
2806 #[derive(Debug, HashStable_Generic)]
2807 pub struct Item<'hir> {
2808     pub ident: Ident,
2809     pub def_id: LocalDefId,
2810     pub kind: ItemKind<'hir>,
2811     pub span: Span,
2812     pub vis_span: Span,
2813 }
2814
2815 impl Item<'_> {
2816     #[inline]
2817     pub fn hir_id(&self) -> HirId {
2818         // Items are always HIR owners.
2819         HirId::make_owner(self.def_id)
2820     }
2821
2822     pub fn item_id(&self) -> ItemId {
2823         ItemId { def_id: self.def_id }
2824     }
2825 }
2826
2827 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2828 #[derive(Encodable, Decodable, HashStable_Generic)]
2829 pub enum Unsafety {
2830     Unsafe,
2831     Normal,
2832 }
2833
2834 impl Unsafety {
2835     pub fn prefix_str(&self) -> &'static str {
2836         match self {
2837             Self::Unsafe => "unsafe ",
2838             Self::Normal => "",
2839         }
2840     }
2841 }
2842
2843 impl fmt::Display for Unsafety {
2844     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2845         f.write_str(match *self {
2846             Self::Unsafe => "unsafe",
2847             Self::Normal => "normal",
2848         })
2849     }
2850 }
2851
2852 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2853 #[derive(Encodable, Decodable, HashStable_Generic)]
2854 pub enum Constness {
2855     Const,
2856     NotConst,
2857 }
2858
2859 impl fmt::Display for Constness {
2860     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2861         f.write_str(match *self {
2862             Self::Const => "const",
2863             Self::NotConst => "non-const",
2864         })
2865     }
2866 }
2867
2868 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2869 pub struct FnHeader {
2870     pub unsafety: Unsafety,
2871     pub constness: Constness,
2872     pub asyncness: IsAsync,
2873     pub abi: Abi,
2874 }
2875
2876 impl FnHeader {
2877     pub fn is_async(&self) -> bool {
2878         matches!(&self.asyncness, IsAsync::Async)
2879     }
2880
2881     pub fn is_const(&self) -> bool {
2882         matches!(&self.constness, Constness::Const)
2883     }
2884
2885     pub fn is_unsafe(&self) -> bool {
2886         matches!(&self.unsafety, Unsafety::Unsafe)
2887     }
2888 }
2889
2890 #[derive(Debug, HashStable_Generic)]
2891 pub enum ItemKind<'hir> {
2892     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2893     ///
2894     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2895     ExternCrate(Option<Symbol>),
2896
2897     /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2898     ///
2899     /// or just
2900     ///
2901     /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2902     Use(&'hir Path<'hir>, UseKind),
2903
2904     /// A `static` item.
2905     Static(&'hir Ty<'hir>, Mutability, BodyId),
2906     /// A `const` item.
2907     Const(&'hir Ty<'hir>, BodyId),
2908     /// A function declaration.
2909     Fn(FnSig<'hir>, &'hir Generics<'hir>, BodyId),
2910     /// A MBE macro definition (`macro_rules!` or `macro`).
2911     Macro(ast::MacroDef, MacroKind),
2912     /// A module.
2913     Mod(Mod<'hir>),
2914     /// An external module, e.g. `extern { .. }`.
2915     ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
2916     /// Module-level inline assembly (from `global_asm!`).
2917     GlobalAsm(&'hir InlineAsm<'hir>),
2918     /// A type alias, e.g., `type Foo = Bar<u8>`.
2919     TyAlias(&'hir Ty<'hir>, &'hir Generics<'hir>),
2920     /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2921     OpaqueTy(OpaqueTy<'hir>),
2922     /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2923     Enum(EnumDef<'hir>, &'hir Generics<'hir>),
2924     /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2925     Struct(VariantData<'hir>, &'hir Generics<'hir>),
2926     /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2927     Union(VariantData<'hir>, &'hir Generics<'hir>),
2928     /// A trait definition.
2929     Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2930     /// A trait alias.
2931     TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
2932
2933     /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2934     Impl(&'hir Impl<'hir>),
2935 }
2936
2937 #[derive(Debug, HashStable_Generic)]
2938 pub struct Impl<'hir> {
2939     pub unsafety: Unsafety,
2940     pub polarity: ImplPolarity,
2941     pub defaultness: Defaultness,
2942     // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2943     // decoding as `Span`s cannot be decoded when a `Session` is not available.
2944     pub defaultness_span: Option<Span>,
2945     pub constness: Constness,
2946     pub generics: &'hir Generics<'hir>,
2947
2948     /// The trait being implemented, if any.
2949     pub of_trait: Option<TraitRef<'hir>>,
2950
2951     pub self_ty: &'hir Ty<'hir>,
2952     pub items: &'hir [ImplItemRef],
2953 }
2954
2955 impl ItemKind<'_> {
2956     pub fn generics(&self) -> Option<&Generics<'_>> {
2957         Some(match *self {
2958             ItemKind::Fn(_, ref generics, _)
2959             | ItemKind::TyAlias(_, ref generics)
2960             | ItemKind::OpaqueTy(OpaqueTy {
2961                 ref generics, origin: OpaqueTyOrigin::TyAlias, ..
2962             })
2963             | ItemKind::Enum(_, ref generics)
2964             | ItemKind::Struct(_, ref generics)
2965             | ItemKind::Union(_, ref generics)
2966             | ItemKind::Trait(_, _, ref generics, _, _)
2967             | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2968             _ => return None,
2969         })
2970     }
2971
2972     pub fn descr(&self) -> &'static str {
2973         match self {
2974             ItemKind::ExternCrate(..) => "extern crate",
2975             ItemKind::Use(..) => "`use` import",
2976             ItemKind::Static(..) => "static item",
2977             ItemKind::Const(..) => "constant item",
2978             ItemKind::Fn(..) => "function",
2979             ItemKind::Macro(..) => "macro",
2980             ItemKind::Mod(..) => "module",
2981             ItemKind::ForeignMod { .. } => "extern block",
2982             ItemKind::GlobalAsm(..) => "global asm item",
2983             ItemKind::TyAlias(..) => "type alias",
2984             ItemKind::OpaqueTy(..) => "opaque type",
2985             ItemKind::Enum(..) => "enum",
2986             ItemKind::Struct(..) => "struct",
2987             ItemKind::Union(..) => "union",
2988             ItemKind::Trait(..) => "trait",
2989             ItemKind::TraitAlias(..) => "trait alias",
2990             ItemKind::Impl(..) => "implementation",
2991         }
2992     }
2993 }
2994
2995 /// A reference from an trait to one of its associated items. This
2996 /// contains the item's id, naturally, but also the item's name and
2997 /// some other high-level details (like whether it is an associated
2998 /// type or method, and whether it is public). This allows other
2999 /// passes to find the impl they want without loading the ID (which
3000 /// means fewer edges in the incremental compilation graph).
3001 #[derive(Encodable, Debug, HashStable_Generic)]
3002 pub struct TraitItemRef {
3003     pub id: TraitItemId,
3004     pub ident: Ident,
3005     pub kind: AssocItemKind,
3006     pub span: Span,
3007     pub defaultness: Defaultness,
3008 }
3009
3010 /// A reference from an impl to one of its associated items. This
3011 /// contains the item's ID, naturally, but also the item's name and
3012 /// some other high-level details (like whether it is an associated
3013 /// type or method, and whether it is public). This allows other
3014 /// passes to find the impl they want without loading the ID (which
3015 /// means fewer edges in the incremental compilation graph).
3016 #[derive(Debug, HashStable_Generic)]
3017 pub struct ImplItemRef {
3018     pub id: ImplItemId,
3019     pub ident: Ident,
3020     pub kind: AssocItemKind,
3021     pub span: Span,
3022     pub defaultness: Defaultness,
3023     /// When we are in a trait impl, link to the trait-item's id.
3024     pub trait_item_def_id: Option<DefId>,
3025 }
3026
3027 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
3028 pub enum AssocItemKind {
3029     Const,
3030     Fn { has_self: bool },
3031     Type,
3032 }
3033
3034 // The bodies for items are stored "out of line", in a separate
3035 // hashmap in the `Crate`. Here we just record the hir-id of the item
3036 // so it can fetched later.
3037 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
3038 pub struct ForeignItemId {
3039     pub def_id: LocalDefId,
3040 }
3041
3042 impl ForeignItemId {
3043     #[inline]
3044     pub fn hir_id(&self) -> HirId {
3045         // Items are always HIR owners.
3046         HirId::make_owner(self.def_id)
3047     }
3048 }
3049
3050 /// A reference from a foreign block to one of its items. This
3051 /// contains the item's ID, naturally, but also the item's name and
3052 /// some other high-level details (like whether it is an associated
3053 /// type or method, and whether it is public). This allows other
3054 /// passes to find the impl they want without loading the ID (which
3055 /// means fewer edges in the incremental compilation graph).
3056 #[derive(Debug, HashStable_Generic)]
3057 pub struct ForeignItemRef {
3058     pub id: ForeignItemId,
3059     pub ident: Ident,
3060     pub span: Span,
3061 }
3062
3063 #[derive(Debug, HashStable_Generic)]
3064 pub struct ForeignItem<'hir> {
3065     pub ident: Ident,
3066     pub kind: ForeignItemKind<'hir>,
3067     pub def_id: LocalDefId,
3068     pub span: Span,
3069     pub vis_span: Span,
3070 }
3071
3072 impl ForeignItem<'_> {
3073     #[inline]
3074     pub fn hir_id(&self) -> HirId {
3075         // Items are always HIR owners.
3076         HirId::make_owner(self.def_id)
3077     }
3078
3079     pub fn foreign_item_id(&self) -> ForeignItemId {
3080         ForeignItemId { def_id: self.def_id }
3081     }
3082 }
3083
3084 /// An item within an `extern` block.
3085 #[derive(Debug, HashStable_Generic)]
3086 pub enum ForeignItemKind<'hir> {
3087     /// A foreign function.
3088     Fn(&'hir FnDecl<'hir>, &'hir [Ident], &'hir Generics<'hir>),
3089     /// A foreign static item (`static ext: u8`).
3090     Static(&'hir Ty<'hir>, Mutability),
3091     /// A foreign type.
3092     Type,
3093 }
3094
3095 /// A variable captured by a closure.
3096 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
3097 pub struct Upvar {
3098     // First span where it is accessed (there can be multiple).
3099     pub span: Span,
3100 }
3101
3102 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
3103 // has length > 0 if the trait is found through an chain of imports, starting with the
3104 // import/use statement in the scope where the trait is used.
3105 #[derive(Encodable, Decodable, Clone, Debug, HashStable_Generic)]
3106 pub struct TraitCandidate {
3107     pub def_id: DefId,
3108     pub import_ids: SmallVec<[LocalDefId; 1]>,
3109 }
3110
3111 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3112 pub enum OwnerNode<'hir> {
3113     Item(&'hir Item<'hir>),
3114     ForeignItem(&'hir ForeignItem<'hir>),
3115     TraitItem(&'hir TraitItem<'hir>),
3116     ImplItem(&'hir ImplItem<'hir>),
3117     Crate(&'hir Mod<'hir>),
3118 }
3119
3120 impl<'hir> OwnerNode<'hir> {
3121     pub fn ident(&self) -> Option<Ident> {
3122         match self {
3123             OwnerNode::Item(Item { ident, .. })
3124             | OwnerNode::ForeignItem(ForeignItem { ident, .. })
3125             | OwnerNode::ImplItem(ImplItem { ident, .. })
3126             | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
3127             OwnerNode::Crate(..) => None,
3128         }
3129     }
3130
3131     pub fn span(&self) -> Span {
3132         match self {
3133             OwnerNode::Item(Item { span, .. })
3134             | OwnerNode::ForeignItem(ForeignItem { span, .. })
3135             | OwnerNode::ImplItem(ImplItem { span, .. })
3136             | OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3137             OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3138         }
3139     }
3140
3141     pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3142         match self {
3143             OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3144             | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3145             | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3146             OwnerNode::ForeignItem(ForeignItem {
3147                 kind: ForeignItemKind::Fn(fn_decl, _, _),
3148                 ..
3149             }) => Some(fn_decl),
3150             _ => None,
3151         }
3152     }
3153
3154     pub fn body_id(&self) -> Option<BodyId> {
3155         match self {
3156             OwnerNode::TraitItem(TraitItem {
3157                 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3158                 ..
3159             })
3160             | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3161             | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3162             _ => None,
3163         }
3164     }
3165
3166     pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3167         match self {
3168             OwnerNode::TraitItem(TraitItem { generics, .. })
3169             | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
3170             OwnerNode::Item(item) => item.kind.generics(),
3171             _ => None,
3172         }
3173     }
3174
3175     pub fn def_id(self) -> LocalDefId {
3176         match self {
3177             OwnerNode::Item(Item { def_id, .. })
3178             | OwnerNode::TraitItem(TraitItem { def_id, .. })
3179             | OwnerNode::ImplItem(ImplItem { def_id, .. })
3180             | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
3181             OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3182         }
3183     }
3184
3185     pub fn expect_item(self) -> &'hir Item<'hir> {
3186         match self {
3187             OwnerNode::Item(n) => n,
3188             _ => panic!(),
3189         }
3190     }
3191
3192     pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3193         match self {
3194             OwnerNode::ForeignItem(n) => n,
3195             _ => panic!(),
3196         }
3197     }
3198
3199     pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3200         match self {
3201             OwnerNode::ImplItem(n) => n,
3202             _ => panic!(),
3203         }
3204     }
3205
3206     pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3207         match self {
3208             OwnerNode::TraitItem(n) => n,
3209             _ => panic!(),
3210         }
3211     }
3212 }
3213
3214 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
3215     fn into(self) -> OwnerNode<'hir> {
3216         OwnerNode::Item(self)
3217     }
3218 }
3219
3220 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
3221     fn into(self) -> OwnerNode<'hir> {
3222         OwnerNode::ForeignItem(self)
3223     }
3224 }
3225
3226 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
3227     fn into(self) -> OwnerNode<'hir> {
3228         OwnerNode::ImplItem(self)
3229     }
3230 }
3231
3232 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
3233     fn into(self) -> OwnerNode<'hir> {
3234         OwnerNode::TraitItem(self)
3235     }
3236 }
3237
3238 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
3239     fn into(self) -> Node<'hir> {
3240         match self {
3241             OwnerNode::Item(n) => Node::Item(n),
3242             OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3243             OwnerNode::ImplItem(n) => Node::ImplItem(n),
3244             OwnerNode::TraitItem(n) => Node::TraitItem(n),
3245             OwnerNode::Crate(n) => Node::Crate(n),
3246         }
3247     }
3248 }
3249
3250 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3251 pub enum Node<'hir> {
3252     Param(&'hir Param<'hir>),
3253     Item(&'hir Item<'hir>),
3254     ForeignItem(&'hir ForeignItem<'hir>),
3255     TraitItem(&'hir TraitItem<'hir>),
3256     ImplItem(&'hir ImplItem<'hir>),
3257     Variant(&'hir Variant<'hir>),
3258     Field(&'hir FieldDef<'hir>),
3259     AnonConst(&'hir AnonConst),
3260     Expr(&'hir Expr<'hir>),
3261     Stmt(&'hir Stmt<'hir>),
3262     PathSegment(&'hir PathSegment<'hir>),
3263     Ty(&'hir Ty<'hir>),
3264     TraitRef(&'hir TraitRef<'hir>),
3265     Binding(&'hir Pat<'hir>),
3266     Pat(&'hir Pat<'hir>),
3267     Arm(&'hir Arm<'hir>),
3268     Block(&'hir Block<'hir>),
3269     Local(&'hir Local<'hir>),
3270
3271     /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3272     /// with synthesized constructors.
3273     Ctor(&'hir VariantData<'hir>),
3274
3275     Lifetime(&'hir Lifetime),
3276     GenericParam(&'hir GenericParam<'hir>),
3277
3278     Crate(&'hir Mod<'hir>),
3279
3280     Infer(&'hir InferArg),
3281 }
3282
3283 impl<'hir> Node<'hir> {
3284     /// Get the identifier of this `Node`, if applicable.
3285     ///
3286     /// # Edge cases
3287     ///
3288     /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3289     /// because `Ctor`s do not have identifiers themselves.
3290     /// Instead, call `.ident()` on the parent struct/variant, like so:
3291     ///
3292     /// ```ignore (illustrative)
3293     /// ctor
3294     ///     .ctor_hir_id()
3295     ///     .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3296     ///     .and_then(|parent| parent.ident())
3297     /// ```
3298     pub fn ident(&self) -> Option<Ident> {
3299         match self {
3300             Node::TraitItem(TraitItem { ident, .. })
3301             | Node::ImplItem(ImplItem { ident, .. })
3302             | Node::ForeignItem(ForeignItem { ident, .. })
3303             | Node::Field(FieldDef { ident, .. })
3304             | Node::Variant(Variant { ident, .. })
3305             | Node::Item(Item { ident, .. })
3306             | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3307             Node::Lifetime(lt) => Some(lt.name.ident()),
3308             Node::GenericParam(p) => Some(p.name.ident()),
3309             Node::Param(..)
3310             | Node::AnonConst(..)
3311             | Node::Expr(..)
3312             | Node::Stmt(..)
3313             | Node::Block(..)
3314             | Node::Ctor(..)
3315             | Node::Pat(..)
3316             | Node::Binding(..)
3317             | Node::Arm(..)
3318             | Node::Local(..)
3319             | Node::Crate(..)
3320             | Node::Ty(..)
3321             | Node::TraitRef(..)
3322             | Node::Infer(..) => None,
3323         }
3324     }
3325
3326     pub fn fn_decl(&self) -> Option<&'hir FnDecl<'hir>> {
3327         match self {
3328             Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3329             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3330             | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3331             Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3332                 Some(fn_decl)
3333             }
3334             _ => None,
3335         }
3336     }
3337
3338     pub fn fn_sig(&self) -> Option<&'hir FnSig<'hir>> {
3339         match self {
3340             Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3341             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3342             | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3343             _ => None,
3344         }
3345     }
3346
3347     pub fn body_id(&self) -> Option<BodyId> {
3348         match self {
3349             Node::TraitItem(TraitItem {
3350                 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3351                 ..
3352             })
3353             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3354             | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3355             _ => None,
3356         }
3357     }
3358
3359     pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3360         match self {
3361             Node::TraitItem(TraitItem { generics, .. })
3362             | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3363             Node::Item(item) => item.kind.generics(),
3364             _ => None,
3365         }
3366     }
3367
3368     pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3369         match self {
3370             Node::Item(i) => Some(OwnerNode::Item(i)),
3371             Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3372             Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3373             Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3374             Node::Crate(i) => Some(OwnerNode::Crate(i)),
3375             _ => None,
3376         }
3377     }
3378
3379     pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3380         match self {
3381             Node::Item(i) => match i.kind {
3382                 ItemKind::Fn(ref sig, ref generics, _) => {
3383                     Some(FnKind::ItemFn(i.ident, generics, sig.header))
3384                 }
3385                 _ => None,
3386             },
3387             Node::TraitItem(ti) => match ti.kind {
3388                 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3389                     Some(FnKind::Method(ti.ident, sig))
3390                 }
3391                 _ => None,
3392             },
3393             Node::ImplItem(ii) => match ii.kind {
3394                 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig)),
3395                 _ => None,
3396             },
3397             Node::Expr(e) => match e.kind {
3398                 ExprKind::Closure(..) => Some(FnKind::Closure),
3399                 _ => None,
3400             },
3401             _ => None,
3402         }
3403     }
3404
3405     /// Get the fields for the tuple-constructor,
3406     /// if this node is a tuple constructor, otherwise None
3407     pub fn tuple_fields(&self) -> Option<&'hir [FieldDef<'hir>]> {
3408         if let Node::Ctor(&VariantData::Tuple(fields, _)) = self { Some(fields) } else { None }
3409     }
3410 }
3411
3412 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3413 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3414 mod size_asserts {
3415     rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3416     rustc_data_structures::static_assert_size!(super::Expr<'static>, 56);
3417     rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3418     rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3419     rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3420     rustc_data_structures::static_assert_size!(super::GenericBound<'_>, 48);
3421     rustc_data_structures::static_assert_size!(super::Generics<'static>, 56);
3422     rustc_data_structures::static_assert_size!(super::Impl<'static>, 80);
3423
3424     rustc_data_structures::static_assert_size!(super::Item<'static>, 80);
3425     rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 88);
3426     rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 80);
3427     rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 72);
3428 }