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