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