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