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