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