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