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