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