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