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