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