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