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