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