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