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