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