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