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