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