]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/hir.rs
c9c670fdd4415e959b47992da1a6ae43e536ccbe
[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<HirId>>,
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, HashStable_Generic)]
765 pub struct MacroDef<'hir> {
766     pub ident: Ident,
767     pub vis: Visibility<'hir>,
768     pub attrs: &'hir [Attribute],
769     pub hir_id: HirId,
770     pub span: Span,
771     pub ast: ast::MacroDef,
772 }
773
774 /// A block of statements `{ .. }`, which may have a label (in this case the
775 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
776 /// the `rules` being anything but `DefaultBlock`.
777 #[derive(Debug, HashStable_Generic)]
778 pub struct Block<'hir> {
779     /// Statements in a block.
780     pub stmts: &'hir [Stmt<'hir>],
781     /// An expression at the end of the block
782     /// without a semicolon, if any.
783     pub expr: Option<&'hir Expr<'hir>>,
784     #[stable_hasher(ignore)]
785     pub hir_id: HirId,
786     /// Distinguishes between `unsafe { ... }` and `{ ... }`.
787     pub rules: BlockCheckMode,
788     pub span: Span,
789     /// If true, then there may exist `break 'a` values that aim to
790     /// break out of this block early.
791     /// Used by `'label: {}` blocks and by `try {}` blocks.
792     pub targeted_by_break: bool,
793 }
794
795 #[derive(Debug, HashStable_Generic)]
796 pub struct Pat<'hir> {
797     #[stable_hasher(ignore)]
798     pub hir_id: HirId,
799     pub kind: PatKind<'hir>,
800     pub span: Span,
801     // Whether to use default binding modes.
802     // At present, this is false only for destructuring assignment.
803     pub default_binding_modes: bool,
804 }
805
806 impl<'hir> Pat<'hir> {
807     // FIXME(#19596) this is a workaround, but there should be a better way
808     fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
809         if !it(self) {
810             return false;
811         }
812
813         use PatKind::*;
814         match &self.kind {
815             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
816             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
817             Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
818             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
819             Slice(before, slice, after) => {
820                 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
821             }
822         }
823     }
824
825     /// Walk the pattern in left-to-right order,
826     /// short circuiting (with `.all(..)`) if `false` is returned.
827     ///
828     /// Note that when visiting e.g. `Tuple(ps)`,
829     /// if visiting `ps[0]` returns `false`,
830     /// then `ps[1]` will not be visited.
831     pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
832         self.walk_short_(&mut it)
833     }
834
835     // FIXME(#19596) this is a workaround, but there should be a better way
836     fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
837         if !it(self) {
838             return;
839         }
840
841         use PatKind::*;
842         match &self.kind {
843             Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
844             Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
845             Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
846             TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
847             Slice(before, slice, after) => {
848                 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
849             }
850         }
851     }
852
853     /// Walk the pattern in left-to-right order.
854     ///
855     /// If `it(pat)` returns `false`, the children are not visited.
856     pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
857         self.walk_(&mut it)
858     }
859
860     /// Walk the pattern in left-to-right order.
861     ///
862     /// If you always want to recurse, prefer this method over `walk`.
863     pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
864         self.walk(|p| {
865             it(p);
866             true
867         })
868     }
869 }
870
871 /// A single field in a struct pattern.
872 ///
873 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
874 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
875 /// except `is_shorthand` is true.
876 #[derive(Debug, HashStable_Generic)]
877 pub struct FieldPat<'hir> {
878     #[stable_hasher(ignore)]
879     pub hir_id: HirId,
880     /// The identifier for the field.
881     #[stable_hasher(project(name))]
882     pub ident: Ident,
883     /// The pattern the field is destructured to.
884     pub pat: &'hir Pat<'hir>,
885     pub is_shorthand: bool,
886     pub span: Span,
887 }
888
889 /// Explicit binding annotations given in the HIR for a binding. Note
890 /// that this is not the final binding *mode* that we infer after type
891 /// inference.
892 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
893 pub enum BindingAnnotation {
894     /// No binding annotation given: this means that the final binding mode
895     /// will depend on whether we have skipped through a `&` reference
896     /// when matching. For example, the `x` in `Some(x)` will have binding
897     /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
898     /// ultimately be inferred to be by-reference.
899     ///
900     /// Note that implicit reference skipping is not implemented yet (#42640).
901     Unannotated,
902
903     /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
904     Mutable,
905
906     /// Annotated as `ref`, like `ref x`
907     Ref,
908
909     /// Annotated as `ref mut x`.
910     RefMut,
911 }
912
913 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
914 pub enum RangeEnd {
915     Included,
916     Excluded,
917 }
918
919 impl fmt::Display for RangeEnd {
920     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
921         f.write_str(match self {
922             RangeEnd::Included => "..=",
923             RangeEnd::Excluded => "..",
924         })
925     }
926 }
927
928 #[derive(Debug, HashStable_Generic)]
929 pub enum PatKind<'hir> {
930     /// Represents a wildcard pattern (i.e., `_`).
931     Wild,
932
933     /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
934     /// The `HirId` is the canonical ID for the variable being bound,
935     /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
936     /// which is the pattern ID of the first `x`.
937     Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
938
939     /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
940     /// The `bool` is `true` in the presence of a `..`.
941     Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
942
943     /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
944     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
945     /// `0 <= position <= subpats.len()`
946     TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
947
948     /// An or-pattern `A | B | C`.
949     /// Invariant: `pats.len() >= 2`.
950     Or(&'hir [&'hir Pat<'hir>]),
951
952     /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
953     Path(QPath<'hir>),
954
955     /// A tuple pattern (e.g., `(a, b)`).
956     /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
957     /// `0 <= position <= subpats.len()`
958     Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
959
960     /// A `box` pattern.
961     Box(&'hir Pat<'hir>),
962
963     /// A reference pattern (e.g., `&mut (a, b)`).
964     Ref(&'hir Pat<'hir>, Mutability),
965
966     /// A literal.
967     Lit(&'hir Expr<'hir>),
968
969     /// A range pattern (e.g., `1..=2` or `1..2`).
970     Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
971
972     /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
973     ///
974     /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
975     /// If `slice` exists, then `after` can be non-empty.
976     ///
977     /// The representation for e.g., `[a, b, .., c, d]` is:
978     /// ```
979     /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
980     /// ```
981     Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
982 }
983
984 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
985 pub enum BinOpKind {
986     /// The `+` operator (addition).
987     Add,
988     /// The `-` operator (subtraction).
989     Sub,
990     /// The `*` operator (multiplication).
991     Mul,
992     /// The `/` operator (division).
993     Div,
994     /// The `%` operator (modulus).
995     Rem,
996     /// The `&&` operator (logical and).
997     And,
998     /// The `||` operator (logical or).
999     Or,
1000     /// The `^` operator (bitwise xor).
1001     BitXor,
1002     /// The `&` operator (bitwise and).
1003     BitAnd,
1004     /// The `|` operator (bitwise or).
1005     BitOr,
1006     /// The `<<` operator (shift left).
1007     Shl,
1008     /// The `>>` operator (shift right).
1009     Shr,
1010     /// The `==` operator (equality).
1011     Eq,
1012     /// The `<` operator (less than).
1013     Lt,
1014     /// The `<=` operator (less than or equal to).
1015     Le,
1016     /// The `!=` operator (not equal to).
1017     Ne,
1018     /// The `>=` operator (greater than or equal to).
1019     Ge,
1020     /// The `>` operator (greater than).
1021     Gt,
1022 }
1023
1024 impl BinOpKind {
1025     pub fn as_str(self) -> &'static str {
1026         match self {
1027             BinOpKind::Add => "+",
1028             BinOpKind::Sub => "-",
1029             BinOpKind::Mul => "*",
1030             BinOpKind::Div => "/",
1031             BinOpKind::Rem => "%",
1032             BinOpKind::And => "&&",
1033             BinOpKind::Or => "||",
1034             BinOpKind::BitXor => "^",
1035             BinOpKind::BitAnd => "&",
1036             BinOpKind::BitOr => "|",
1037             BinOpKind::Shl => "<<",
1038             BinOpKind::Shr => ">>",
1039             BinOpKind::Eq => "==",
1040             BinOpKind::Lt => "<",
1041             BinOpKind::Le => "<=",
1042             BinOpKind::Ne => "!=",
1043             BinOpKind::Ge => ">=",
1044             BinOpKind::Gt => ">",
1045         }
1046     }
1047
1048     pub fn is_lazy(self) -> bool {
1049         matches!(self, BinOpKind::And | BinOpKind::Or)
1050     }
1051
1052     pub fn is_shift(self) -> bool {
1053         matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1054     }
1055
1056     pub fn is_comparison(self) -> bool {
1057         match self {
1058             BinOpKind::Eq
1059             | BinOpKind::Lt
1060             | BinOpKind::Le
1061             | BinOpKind::Ne
1062             | BinOpKind::Gt
1063             | BinOpKind::Ge => true,
1064             BinOpKind::And
1065             | BinOpKind::Or
1066             | BinOpKind::Add
1067             | BinOpKind::Sub
1068             | BinOpKind::Mul
1069             | BinOpKind::Div
1070             | BinOpKind::Rem
1071             | BinOpKind::BitXor
1072             | BinOpKind::BitAnd
1073             | BinOpKind::BitOr
1074             | BinOpKind::Shl
1075             | BinOpKind::Shr => false,
1076         }
1077     }
1078
1079     /// Returns `true` if the binary operator takes its arguments by value.
1080     pub fn is_by_value(self) -> bool {
1081         !self.is_comparison()
1082     }
1083 }
1084
1085 impl Into<ast::BinOpKind> for BinOpKind {
1086     fn into(self) -> ast::BinOpKind {
1087         match self {
1088             BinOpKind::Add => ast::BinOpKind::Add,
1089             BinOpKind::Sub => ast::BinOpKind::Sub,
1090             BinOpKind::Mul => ast::BinOpKind::Mul,
1091             BinOpKind::Div => ast::BinOpKind::Div,
1092             BinOpKind::Rem => ast::BinOpKind::Rem,
1093             BinOpKind::And => ast::BinOpKind::And,
1094             BinOpKind::Or => ast::BinOpKind::Or,
1095             BinOpKind::BitXor => ast::BinOpKind::BitXor,
1096             BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1097             BinOpKind::BitOr => ast::BinOpKind::BitOr,
1098             BinOpKind::Shl => ast::BinOpKind::Shl,
1099             BinOpKind::Shr => ast::BinOpKind::Shr,
1100             BinOpKind::Eq => ast::BinOpKind::Eq,
1101             BinOpKind::Lt => ast::BinOpKind::Lt,
1102             BinOpKind::Le => ast::BinOpKind::Le,
1103             BinOpKind::Ne => ast::BinOpKind::Ne,
1104             BinOpKind::Ge => ast::BinOpKind::Ge,
1105             BinOpKind::Gt => ast::BinOpKind::Gt,
1106         }
1107     }
1108 }
1109
1110 pub type BinOp = Spanned<BinOpKind>;
1111
1112 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1113 pub enum UnOp {
1114     /// The `*` operator (deferencing).
1115     Deref,
1116     /// The `!` operator (logical negation).
1117     Not,
1118     /// The `-` operator (negation).
1119     Neg,
1120 }
1121
1122 impl UnOp {
1123     pub fn as_str(self) -> &'static str {
1124         match self {
1125             Self::Deref => "*",
1126             Self::Not => "!",
1127             Self::Neg => "-",
1128         }
1129     }
1130
1131     /// Returns `true` if the unary operator takes its argument by value.
1132     pub fn is_by_value(self) -> bool {
1133         matches!(self, Self::Neg | Self::Not)
1134     }
1135 }
1136
1137 /// A statement.
1138 #[derive(Debug, HashStable_Generic)]
1139 pub struct Stmt<'hir> {
1140     pub hir_id: HirId,
1141     pub kind: StmtKind<'hir>,
1142     pub span: Span,
1143 }
1144
1145 /// The contents of a statement.
1146 #[derive(Debug, HashStable_Generic)]
1147 pub enum StmtKind<'hir> {
1148     /// A local (`let`) binding.
1149     Local(&'hir Local<'hir>),
1150
1151     /// An item binding.
1152     Item(ItemId),
1153
1154     /// An expression without a trailing semi-colon (must have unit type).
1155     Expr(&'hir Expr<'hir>),
1156
1157     /// An expression with a trailing semi-colon (may have any type).
1158     Semi(&'hir Expr<'hir>),
1159 }
1160
1161 impl<'hir> StmtKind<'hir> {
1162     pub fn attrs(&self, get_item: impl FnOnce(ItemId) -> &'hir Item<'hir>) -> &'hir [Attribute] {
1163         match *self {
1164             StmtKind::Local(ref l) => &l.attrs,
1165             StmtKind::Item(ref item_id) => &get_item(*item_id).attrs,
1166             StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1167         }
1168     }
1169 }
1170
1171 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1172 #[derive(Debug, HashStable_Generic)]
1173 pub struct Local<'hir> {
1174     pub pat: &'hir Pat<'hir>,
1175     /// Type annotation, if any (otherwise the type will be inferred).
1176     pub ty: Option<&'hir Ty<'hir>>,
1177     /// Initializer expression to set the value, if any.
1178     pub init: Option<&'hir Expr<'hir>>,
1179     pub hir_id: HirId,
1180     pub span: Span,
1181     pub attrs: AttrVec,
1182     /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1183     /// desugaring. Otherwise will be `Normal`.
1184     pub source: LocalSource,
1185 }
1186
1187 /// Represents a single arm of a `match` expression, e.g.
1188 /// `<pat> (if <guard>) => <body>`.
1189 #[derive(Debug, HashStable_Generic)]
1190 pub struct Arm<'hir> {
1191     #[stable_hasher(ignore)]
1192     pub hir_id: HirId,
1193     pub span: Span,
1194     pub attrs: &'hir [Attribute],
1195     /// If this pattern and the optional guard matches, then `body` is evaluated.
1196     pub pat: &'hir Pat<'hir>,
1197     /// Optional guard clause.
1198     pub guard: Option<Guard<'hir>>,
1199     /// The expression the arm evaluates to if this arm matches.
1200     pub body: &'hir Expr<'hir>,
1201 }
1202
1203 #[derive(Debug, HashStable_Generic)]
1204 pub enum Guard<'hir> {
1205     If(&'hir Expr<'hir>),
1206     IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1207 }
1208
1209 #[derive(Debug, HashStable_Generic)]
1210 pub struct Field<'hir> {
1211     #[stable_hasher(ignore)]
1212     pub hir_id: HirId,
1213     pub ident: Ident,
1214     pub expr: &'hir Expr<'hir>,
1215     pub span: Span,
1216     pub is_shorthand: bool,
1217 }
1218
1219 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1220 pub enum BlockCheckMode {
1221     DefaultBlock,
1222     UnsafeBlock(UnsafeSource),
1223     PushUnsafeBlock(UnsafeSource),
1224     PopUnsafeBlock(UnsafeSource),
1225 }
1226
1227 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1228 pub enum UnsafeSource {
1229     CompilerGenerated,
1230     UserProvided,
1231 }
1232
1233 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1234 pub struct BodyId {
1235     pub hir_id: HirId,
1236 }
1237
1238 /// The body of a function, closure, or constant value. In the case of
1239 /// a function, the body contains not only the function body itself
1240 /// (which is an expression), but also the argument patterns, since
1241 /// those are something that the caller doesn't really care about.
1242 ///
1243 /// # Examples
1244 ///
1245 /// ```
1246 /// fn foo((x, y): (u32, u32)) -> u32 {
1247 ///     x + y
1248 /// }
1249 /// ```
1250 ///
1251 /// Here, the `Body` associated with `foo()` would contain:
1252 ///
1253 /// - an `params` array containing the `(x, y)` pattern
1254 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1255 /// - `generator_kind` would be `None`
1256 ///
1257 /// All bodies have an **owner**, which can be accessed via the HIR
1258 /// map using `body_owner_def_id()`.
1259 #[derive(Debug)]
1260 pub struct Body<'hir> {
1261     pub params: &'hir [Param<'hir>],
1262     pub value: Expr<'hir>,
1263     pub generator_kind: Option<GeneratorKind>,
1264 }
1265
1266 impl Body<'hir> {
1267     pub fn id(&self) -> BodyId {
1268         BodyId { hir_id: self.value.hir_id }
1269     }
1270
1271     pub fn generator_kind(&self) -> Option<GeneratorKind> {
1272         self.generator_kind
1273     }
1274 }
1275
1276 /// The type of source expression that caused this generator to be created.
1277 #[derive(Clone, PartialEq, Eq, HashStable_Generic, Encodable, Decodable, Debug, Copy)]
1278 pub enum GeneratorKind {
1279     /// An explicit `async` block or the body of an async function.
1280     Async(AsyncGeneratorKind),
1281
1282     /// A generator literal created via a `yield` inside a closure.
1283     Gen,
1284 }
1285
1286 impl fmt::Display for GeneratorKind {
1287     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1288         match self {
1289             GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1290             GeneratorKind::Gen => f.write_str("generator"),
1291         }
1292     }
1293 }
1294
1295 /// In the case of a generator created as part of an async construct,
1296 /// which kind of async construct caused it to be created?
1297 ///
1298 /// This helps error messages but is also used to drive coercions in
1299 /// type-checking (see #60424).
1300 #[derive(Clone, PartialEq, Eq, HashStable_Generic, Encodable, Decodable, Debug, Copy)]
1301 pub enum AsyncGeneratorKind {
1302     /// An explicit `async` block written by the user.
1303     Block,
1304
1305     /// An explicit `async` block written by the user.
1306     Closure,
1307
1308     /// The `async` block generated as the body of an async function.
1309     Fn,
1310 }
1311
1312 impl fmt::Display for AsyncGeneratorKind {
1313     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1314         f.write_str(match self {
1315             AsyncGeneratorKind::Block => "`async` block",
1316             AsyncGeneratorKind::Closure => "`async` closure body",
1317             AsyncGeneratorKind::Fn => "`async fn` body",
1318         })
1319     }
1320 }
1321
1322 #[derive(Copy, Clone, Debug)]
1323 pub enum BodyOwnerKind {
1324     /// Functions and methods.
1325     Fn,
1326
1327     /// Closures
1328     Closure,
1329
1330     /// Constants and associated constants.
1331     Const,
1332
1333     /// Initializer of a `static` item.
1334     Static(Mutability),
1335 }
1336
1337 impl BodyOwnerKind {
1338     pub fn is_fn_or_closure(self) -> bool {
1339         match self {
1340             BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1341             BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1342         }
1343     }
1344 }
1345
1346 /// The kind of an item that requires const-checking.
1347 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1348 pub enum ConstContext {
1349     /// A `const fn`.
1350     ConstFn,
1351
1352     /// A `static` or `static mut`.
1353     Static(Mutability),
1354
1355     /// A `const`, associated `const`, or other const context.
1356     ///
1357     /// Other contexts include:
1358     /// - Array length expressions
1359     /// - Enum discriminants
1360     /// - Const generics
1361     ///
1362     /// For the most part, other contexts are treated just like a regular `const`, so they are
1363     /// lumped into the same category.
1364     Const,
1365 }
1366
1367 impl ConstContext {
1368     /// A description of this const context that can appear between backticks in an error message.
1369     ///
1370     /// E.g. `const` or `static mut`.
1371     pub fn keyword_name(self) -> &'static str {
1372         match self {
1373             Self::Const => "const",
1374             Self::Static(Mutability::Not) => "static",
1375             Self::Static(Mutability::Mut) => "static mut",
1376             Self::ConstFn => "const fn",
1377         }
1378     }
1379 }
1380
1381 /// A colloquial, trivially pluralizable description of this const context for use in error
1382 /// messages.
1383 impl fmt::Display for ConstContext {
1384     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1385         match *self {
1386             Self::Const => write!(f, "constant"),
1387             Self::Static(_) => write!(f, "static"),
1388             Self::ConstFn => write!(f, "constant function"),
1389         }
1390     }
1391 }
1392
1393 /// A literal.
1394 pub type Lit = Spanned<LitKind>;
1395
1396 /// A constant (expression) that's not an item or associated item,
1397 /// but needs its own `DefId` for type-checking, const-eval, etc.
1398 /// These are usually found nested inside types (e.g., array lengths)
1399 /// or expressions (e.g., repeat counts), and also used to define
1400 /// explicit discriminant values for enum variants.
1401 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1402 pub struct AnonConst {
1403     pub hir_id: HirId,
1404     pub body: BodyId,
1405 }
1406
1407 /// An expression.
1408 #[derive(Debug)]
1409 pub struct Expr<'hir> {
1410     pub hir_id: HirId,
1411     pub kind: ExprKind<'hir>,
1412     pub attrs: AttrVec,
1413     pub span: Span,
1414 }
1415
1416 impl Expr<'_> {
1417     pub fn precedence(&self) -> ExprPrecedence {
1418         match self.kind {
1419             ExprKind::Box(_) => ExprPrecedence::Box,
1420             ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1421             ExprKind::Array(_) => ExprPrecedence::Array,
1422             ExprKind::Call(..) => ExprPrecedence::Call,
1423             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1424             ExprKind::Tup(_) => ExprPrecedence::Tup,
1425             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1426             ExprKind::Unary(..) => ExprPrecedence::Unary,
1427             ExprKind::Lit(_) => ExprPrecedence::Lit,
1428             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1429             ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1430             ExprKind::If(..) => ExprPrecedence::If,
1431             ExprKind::Loop(..) => ExprPrecedence::Loop,
1432             ExprKind::Match(..) => ExprPrecedence::Match,
1433             ExprKind::Closure(..) => ExprPrecedence::Closure,
1434             ExprKind::Block(..) => ExprPrecedence::Block,
1435             ExprKind::Assign(..) => ExprPrecedence::Assign,
1436             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1437             ExprKind::Field(..) => ExprPrecedence::Field,
1438             ExprKind::Index(..) => ExprPrecedence::Index,
1439             ExprKind::Path(..) => ExprPrecedence::Path,
1440             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1441             ExprKind::Break(..) => ExprPrecedence::Break,
1442             ExprKind::Continue(..) => ExprPrecedence::Continue,
1443             ExprKind::Ret(..) => ExprPrecedence::Ret,
1444             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1445             ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1446             ExprKind::Struct(..) => ExprPrecedence::Struct,
1447             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1448             ExprKind::Yield(..) => ExprPrecedence::Yield,
1449             ExprKind::Err => ExprPrecedence::Err,
1450         }
1451     }
1452
1453     // Whether this looks like a place expr, without checking for deref
1454     // adjustments.
1455     // This will return `true` in some potentially surprising cases such as
1456     // `CONSTANT.field`.
1457     pub fn is_syntactic_place_expr(&self) -> bool {
1458         self.is_place_expr(|_| true)
1459     }
1460
1461     /// Whether this is a place expression.
1462     ///
1463     /// `allow_projections_from` should return `true` if indexing a field or index expression based
1464     /// on the given expression should be considered a place expression.
1465     pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1466         match self.kind {
1467             ExprKind::Path(QPath::Resolved(_, ref path)) => {
1468                 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1469             }
1470
1471             // Type ascription inherits its place expression kind from its
1472             // operand. See:
1473             // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1474             ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1475
1476             ExprKind::Unary(UnOp::Deref, _) => true,
1477
1478             ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1479                 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1480             }
1481
1482             // Lang item paths cannot currently be local variables or statics.
1483             ExprKind::Path(QPath::LangItem(..)) => false,
1484
1485             // Partially qualified paths in expressions can only legally
1486             // refer to associated items which are always rvalues.
1487             ExprKind::Path(QPath::TypeRelative(..))
1488             | ExprKind::Call(..)
1489             | ExprKind::MethodCall(..)
1490             | ExprKind::Struct(..)
1491             | ExprKind::Tup(..)
1492             | ExprKind::If(..)
1493             | ExprKind::Match(..)
1494             | ExprKind::Closure(..)
1495             | ExprKind::Block(..)
1496             | ExprKind::Repeat(..)
1497             | ExprKind::Array(..)
1498             | ExprKind::Break(..)
1499             | ExprKind::Continue(..)
1500             | ExprKind::Ret(..)
1501             | ExprKind::Loop(..)
1502             | ExprKind::Assign(..)
1503             | ExprKind::InlineAsm(..)
1504             | ExprKind::LlvmInlineAsm(..)
1505             | ExprKind::AssignOp(..)
1506             | ExprKind::Lit(_)
1507             | ExprKind::ConstBlock(..)
1508             | ExprKind::Unary(..)
1509             | ExprKind::Box(..)
1510             | ExprKind::AddrOf(..)
1511             | ExprKind::Binary(..)
1512             | ExprKind::Yield(..)
1513             | ExprKind::Cast(..)
1514             | ExprKind::DropTemps(..)
1515             | ExprKind::Err => false,
1516         }
1517     }
1518
1519     /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1520     /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1521     /// silent, only signaling the ownership system. By doing this, suggestions that check the
1522     /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1523     /// beyond remembering to call this function before doing analysis on it.
1524     pub fn peel_drop_temps(&self) -> &Self {
1525         let mut expr = self;
1526         while let ExprKind::DropTemps(inner) = &expr.kind {
1527             expr = inner;
1528         }
1529         expr
1530     }
1531 }
1532
1533 /// Checks if the specified expression is a built-in range literal.
1534 /// (See: `LoweringContext::lower_expr()`).
1535 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1536     match expr.kind {
1537         // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1538         ExprKind::Struct(ref qpath, _, _) => matches!(
1539             **qpath,
1540             QPath::LangItem(
1541                 LangItem::Range
1542                     | LangItem::RangeTo
1543                     | LangItem::RangeFrom
1544                     | LangItem::RangeFull
1545                     | LangItem::RangeToInclusive,
1546                 _,
1547             )
1548         ),
1549
1550         // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1551         ExprKind::Call(ref func, _) => {
1552             matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1553         }
1554
1555         _ => false,
1556     }
1557 }
1558
1559 #[derive(Debug, HashStable_Generic)]
1560 pub enum ExprKind<'hir> {
1561     /// A `box x` expression.
1562     Box(&'hir Expr<'hir>),
1563     /// Allow anonymous constants from an inline `const` block
1564     ConstBlock(AnonConst),
1565     /// An array (e.g., `[a, b, c, d]`).
1566     Array(&'hir [Expr<'hir>]),
1567     /// A function call.
1568     ///
1569     /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1570     /// and the second field is the list of arguments.
1571     /// This also represents calling the constructor of
1572     /// tuple-like ADTs such as tuple structs and enum variants.
1573     Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1574     /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1575     ///
1576     /// The `PathSegment`/`Span` represent the method name and its generic arguments
1577     /// (within the angle brackets).
1578     /// The first element of the vector of `Expr`s is the expression that evaluates
1579     /// to the object on which the method is being called on (the receiver),
1580     /// and the remaining elements are the rest of the arguments.
1581     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1582     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1583     /// The final `Span` represents the span of the function and arguments
1584     /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1585     ///
1586     /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1587     /// the `hir_id` of the `MethodCall` node itself.
1588     ///
1589     /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1590     MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1591     /// A tuple (e.g., `(a, b, c, d)`).
1592     Tup(&'hir [Expr<'hir>]),
1593     /// A binary operation (e.g., `a + b`, `a * b`).
1594     Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1595     /// A unary operation (e.g., `!x`, `*x`).
1596     Unary(UnOp, &'hir Expr<'hir>),
1597     /// A literal (e.g., `1`, `"foo"`).
1598     Lit(Lit),
1599     /// A cast (e.g., `foo as f64`).
1600     Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1601     /// A type reference (e.g., `Foo`).
1602     Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1603     /// Wraps the expression in a terminating scope.
1604     /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1605     ///
1606     /// This construct only exists to tweak the drop order in HIR lowering.
1607     /// An example of that is the desugaring of `for` loops.
1608     DropTemps(&'hir Expr<'hir>),
1609     /// An `if` block, with an optional else block.
1610     ///
1611     /// I.e., `if <expr> { <expr> } else { <expr> }`.
1612     If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1613     /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1614     ///
1615     /// I.e., `'label: loop { <block> }`.
1616     ///
1617     /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1618     Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1619     /// A `match` block, with a source that indicates whether or not it is
1620     /// the result of a desugaring, and if so, which kind.
1621     Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1622     /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1623     ///
1624     /// The `Span` is the argument block `|...|`.
1625     ///
1626     /// This may also be a generator literal or an `async block` as indicated by the
1627     /// `Option<Movability>`.
1628     Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1629     /// A block (e.g., `'label: { ... }`).
1630     Block(&'hir Block<'hir>, Option<Label>),
1631
1632     /// An assignment (e.g., `a = foo()`).
1633     Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1634     /// An assignment with an operator.
1635     ///
1636     /// E.g., `a += 1`.
1637     AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1638     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1639     Field(&'hir Expr<'hir>, Ident),
1640     /// An indexing operation (`foo[2]`).
1641     Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1642
1643     /// Path to a definition, possibly containing lifetime or type parameters.
1644     Path(QPath<'hir>),
1645
1646     /// A referencing operation (i.e., `&a` or `&mut a`).
1647     AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1648     /// A `break`, with an optional label to break.
1649     Break(Destination, Option<&'hir Expr<'hir>>),
1650     /// A `continue`, with an optional label.
1651     Continue(Destination),
1652     /// A `return`, with an optional value to be returned.
1653     Ret(Option<&'hir Expr<'hir>>),
1654
1655     /// Inline assembly (from `asm!`), with its outputs and inputs.
1656     InlineAsm(&'hir InlineAsm<'hir>),
1657     /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1658     LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1659
1660     /// A struct or struct-like variant literal expression.
1661     ///
1662     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1663     /// where `base` is the `Option<Expr>`.
1664     Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1665
1666     /// An array literal constructed from one repeated element.
1667     ///
1668     /// E.g., `[1; 5]`. The first expression is the element
1669     /// to be repeated; the second is the number of times to repeat it.
1670     Repeat(&'hir Expr<'hir>, AnonConst),
1671
1672     /// A suspension point for generators (i.e., `yield <expr>`).
1673     Yield(&'hir Expr<'hir>, YieldSource),
1674
1675     /// A placeholder for an expression that wasn't syntactically well formed in some way.
1676     Err,
1677 }
1678
1679 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1680 ///
1681 /// To resolve the path to a `DefId`, call [`qpath_res`].
1682 ///
1683 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1684 #[derive(Debug, HashStable_Generic)]
1685 pub enum QPath<'hir> {
1686     /// Path to a definition, optionally "fully-qualified" with a `Self`
1687     /// type, if the path points to an associated item in a trait.
1688     ///
1689     /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1690     /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1691     /// even though they both have the same two-segment `Clone::clone` `Path`.
1692     Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1693
1694     /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1695     /// Will be resolved by type-checking to an associated item.
1696     ///
1697     /// UFCS source paths can desugar into this, with `Vec::new` turning into
1698     /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1699     /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1700     TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1701
1702     /// Reference to a `#[lang = "foo"]` item.
1703     LangItem(LangItem, Span),
1704 }
1705
1706 impl<'hir> QPath<'hir> {
1707     /// Returns the span of this `QPath`.
1708     pub fn span(&self) -> Span {
1709         match *self {
1710             QPath::Resolved(_, path) => path.span,
1711             QPath::TypeRelative(_, ps) => ps.ident.span,
1712             QPath::LangItem(_, span) => span,
1713         }
1714     }
1715
1716     /// Returns the span of the qself of this `QPath`. For example, `()` in
1717     /// `<() as Trait>::method`.
1718     pub fn qself_span(&self) -> Span {
1719         match *self {
1720             QPath::Resolved(_, path) => path.span,
1721             QPath::TypeRelative(qself, _) => qself.span,
1722             QPath::LangItem(_, span) => span,
1723         }
1724     }
1725
1726     /// Returns the span of the last segment of this `QPath`. For example, `method` in
1727     /// `<() as Trait>::method`.
1728     pub fn last_segment_span(&self) -> Span {
1729         match *self {
1730             QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1731             QPath::TypeRelative(_, segment) => segment.ident.span,
1732             QPath::LangItem(_, span) => span,
1733         }
1734     }
1735 }
1736
1737 /// Hints at the original code for a let statement.
1738 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1739 pub enum LocalSource {
1740     /// A `match _ { .. }`.
1741     Normal,
1742     /// A desugared `for _ in _ { .. }` loop.
1743     ForLoopDesugar,
1744     /// When lowering async functions, we create locals within the `async move` so that
1745     /// all parameters are dropped after the future is polled.
1746     ///
1747     /// ```ignore (pseudo-Rust)
1748     /// async fn foo(<pattern> @ x: Type) {
1749     ///     async move {
1750     ///         let <pattern> = x;
1751     ///     }
1752     /// }
1753     /// ```
1754     AsyncFn,
1755     /// A desugared `<expr>.await`.
1756     AwaitDesugar,
1757     /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1758     /// The span is that of the `=` sign.
1759     AssignDesugar(Span),
1760 }
1761
1762 /// Hints at the original code for a `match _ { .. }`.
1763 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1764 #[derive(HashStable_Generic)]
1765 pub enum MatchSource {
1766     /// A `match _ { .. }`.
1767     Normal,
1768     /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1769     IfLetDesugar { contains_else_clause: bool },
1770     /// An `if let _ = _ => { .. }` match guard.
1771     IfLetGuardDesugar,
1772     /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1773     WhileDesugar,
1774     /// A `while let _ = _ { .. }` (which was desugared to a
1775     /// `loop { match _ { .. } }`).
1776     WhileLetDesugar,
1777     /// A desugared `for _ in _ { .. }` loop.
1778     ForLoopDesugar,
1779     /// A desugared `?` operator.
1780     TryDesugar,
1781     /// A desugared `<expr>.await`.
1782     AwaitDesugar,
1783 }
1784
1785 impl MatchSource {
1786     pub fn name(self) -> &'static str {
1787         use MatchSource::*;
1788         match self {
1789             Normal => "match",
1790             IfLetDesugar { .. } | IfLetGuardDesugar => "if",
1791             WhileDesugar | WhileLetDesugar => "while",
1792             ForLoopDesugar => "for",
1793             TryDesugar => "?",
1794             AwaitDesugar => ".await",
1795         }
1796     }
1797 }
1798
1799 /// The loop type that yielded an `ExprKind::Loop`.
1800 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1801 pub enum LoopSource {
1802     /// A `loop { .. }` loop.
1803     Loop,
1804     /// A `while _ { .. }` loop.
1805     While,
1806     /// A `while let _ = _ { .. }` loop.
1807     WhileLet,
1808     /// A `for _ in _ { .. }` loop.
1809     ForLoop,
1810 }
1811
1812 impl LoopSource {
1813     pub fn name(self) -> &'static str {
1814         match self {
1815             LoopSource::Loop => "loop",
1816             LoopSource::While | LoopSource::WhileLet => "while",
1817             LoopSource::ForLoop => "for",
1818         }
1819     }
1820 }
1821
1822 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1823 pub enum LoopIdError {
1824     OutsideLoopScope,
1825     UnlabeledCfInWhileCondition,
1826     UnresolvedLabel,
1827 }
1828
1829 impl fmt::Display for LoopIdError {
1830     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1831         f.write_str(match self {
1832             LoopIdError::OutsideLoopScope => "not inside loop scope",
1833             LoopIdError::UnlabeledCfInWhileCondition => {
1834                 "unlabeled control flow (break or continue) in while condition"
1835             }
1836             LoopIdError::UnresolvedLabel => "label not found",
1837         })
1838     }
1839 }
1840
1841 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1842 pub struct Destination {
1843     // This is `Some(_)` iff there is an explicit user-specified `label
1844     pub label: Option<Label>,
1845
1846     // These errors are caught and then reported during the diagnostics pass in
1847     // librustc_passes/loops.rs
1848     pub target_id: Result<HirId, LoopIdError>,
1849 }
1850
1851 /// The yield kind that caused an `ExprKind::Yield`.
1852 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1853 pub enum YieldSource {
1854     /// An `<expr>.await`.
1855     Await { expr: Option<HirId> },
1856     /// A plain `yield`.
1857     Yield,
1858 }
1859
1860 impl YieldSource {
1861     pub fn is_await(&self) -> bool {
1862         match self {
1863             YieldSource::Await { .. } => true,
1864             YieldSource::Yield => false,
1865         }
1866     }
1867 }
1868
1869 impl fmt::Display for YieldSource {
1870     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1871         f.write_str(match self {
1872             YieldSource::Await { .. } => "`await`",
1873             YieldSource::Yield => "`yield`",
1874         })
1875     }
1876 }
1877
1878 impl From<GeneratorKind> for YieldSource {
1879     fn from(kind: GeneratorKind) -> Self {
1880         match kind {
1881             // Guess based on the kind of the current generator.
1882             GeneratorKind::Gen => Self::Yield,
1883             GeneratorKind::Async(_) => Self::Await { expr: None },
1884         }
1885     }
1886 }
1887
1888 // N.B., if you change this, you'll probably want to change the corresponding
1889 // type structure in middle/ty.rs as well.
1890 #[derive(Debug, HashStable_Generic)]
1891 pub struct MutTy<'hir> {
1892     pub ty: &'hir Ty<'hir>,
1893     pub mutbl: Mutability,
1894 }
1895
1896 /// Represents a function's signature in a trait declaration,
1897 /// trait implementation, or a free function.
1898 #[derive(Debug, HashStable_Generic)]
1899 pub struct FnSig<'hir> {
1900     pub header: FnHeader,
1901     pub decl: &'hir FnDecl<'hir>,
1902     pub span: Span,
1903 }
1904
1905 // The bodies for items are stored "out of line", in a separate
1906 // hashmap in the `Crate`. Here we just record the hir-id of the item
1907 // so it can fetched later.
1908 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1909 pub struct TraitItemId {
1910     pub def_id: LocalDefId,
1911 }
1912
1913 impl TraitItemId {
1914     pub fn hir_id(&self) -> HirId {
1915         // Items are always HIR owners.
1916         HirId::make_owner(self.def_id)
1917     }
1918 }
1919
1920 /// Represents an item declaration within a trait declaration,
1921 /// possibly including a default implementation. A trait item is
1922 /// either required (meaning it doesn't have an implementation, just a
1923 /// signature) or provided (meaning it has a default implementation).
1924 #[derive(Debug)]
1925 pub struct TraitItem<'hir> {
1926     pub ident: Ident,
1927     pub def_id: LocalDefId,
1928     pub attrs: &'hir [Attribute],
1929     pub generics: Generics<'hir>,
1930     pub kind: TraitItemKind<'hir>,
1931     pub span: Span,
1932 }
1933
1934 impl TraitItem<'_> {
1935     pub fn hir_id(&self) -> HirId {
1936         // Items are always HIR owners.
1937         HirId::make_owner(self.def_id)
1938     }
1939
1940     pub fn trait_item_id(&self) -> TraitItemId {
1941         TraitItemId { def_id: self.def_id }
1942     }
1943 }
1944
1945 /// Represents a trait method's body (or just argument names).
1946 #[derive(Encodable, Debug, HashStable_Generic)]
1947 pub enum TraitFn<'hir> {
1948     /// No default body in the trait, just a signature.
1949     Required(&'hir [Ident]),
1950
1951     /// Both signature and body are provided in the trait.
1952     Provided(BodyId),
1953 }
1954
1955 /// Represents a trait method or associated constant or type
1956 #[derive(Debug, HashStable_Generic)]
1957 pub enum TraitItemKind<'hir> {
1958     /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1959     Const(&'hir Ty<'hir>, Option<BodyId>),
1960     /// An associated function with an optional body.
1961     Fn(FnSig<'hir>, TraitFn<'hir>),
1962     /// An associated type with (possibly empty) bounds and optional concrete
1963     /// type.
1964     Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1965 }
1966
1967 // The bodies for items are stored "out of line", in a separate
1968 // hashmap in the `Crate`. Here we just record the hir-id of the item
1969 // so it can fetched later.
1970 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1971 pub struct ImplItemId {
1972     pub def_id: LocalDefId,
1973 }
1974
1975 impl ImplItemId {
1976     pub fn hir_id(&self) -> HirId {
1977         // Items are always HIR owners.
1978         HirId::make_owner(self.def_id)
1979     }
1980 }
1981
1982 /// Represents anything within an `impl` block.
1983 #[derive(Debug)]
1984 pub struct ImplItem<'hir> {
1985     pub ident: Ident,
1986     pub def_id: LocalDefId,
1987     pub vis: Visibility<'hir>,
1988     pub defaultness: Defaultness,
1989     pub attrs: &'hir [Attribute],
1990     pub generics: Generics<'hir>,
1991     pub kind: ImplItemKind<'hir>,
1992     pub span: Span,
1993 }
1994
1995 impl ImplItem<'_> {
1996     pub fn hir_id(&self) -> HirId {
1997         // Items are always HIR owners.
1998         HirId::make_owner(self.def_id)
1999     }
2000
2001     pub fn impl_item_id(&self) -> ImplItemId {
2002         ImplItemId { def_id: self.def_id }
2003     }
2004 }
2005
2006 /// Represents various kinds of content within an `impl`.
2007 #[derive(Debug, HashStable_Generic)]
2008 pub enum ImplItemKind<'hir> {
2009     /// An associated constant of the given type, set to the constant result
2010     /// of the expression.
2011     Const(&'hir Ty<'hir>, BodyId),
2012     /// An associated function implementation with the given signature and body.
2013     Fn(FnSig<'hir>, BodyId),
2014     /// An associated type.
2015     TyAlias(&'hir Ty<'hir>),
2016 }
2017
2018 impl ImplItemKind<'_> {
2019     pub fn namespace(&self) -> Namespace {
2020         match self {
2021             ImplItemKind::TyAlias(..) => Namespace::TypeNS,
2022             ImplItemKind::Const(..) | ImplItemKind::Fn(..) => Namespace::ValueNS,
2023         }
2024     }
2025 }
2026
2027 // The name of the associated type for `Fn` return types.
2028 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2029
2030 /// Bind a type to an associated type (i.e., `A = Foo`).
2031 ///
2032 /// Bindings like `A: Debug` are represented as a special type `A =
2033 /// $::Debug` that is understood by the astconv code.
2034 ///
2035 /// FIXME(alexreg): why have a separate type for the binding case,
2036 /// wouldn't it be better to make the `ty` field an enum like the
2037 /// following?
2038 ///
2039 /// ```
2040 /// enum TypeBindingKind {
2041 ///    Equals(...),
2042 ///    Binding(...),
2043 /// }
2044 /// ```
2045 #[derive(Debug, HashStable_Generic)]
2046 pub struct TypeBinding<'hir> {
2047     pub hir_id: HirId,
2048     #[stable_hasher(project(name))]
2049     pub ident: Ident,
2050     pub gen_args: &'hir GenericArgs<'hir>,
2051     pub kind: TypeBindingKind<'hir>,
2052     pub span: Span,
2053 }
2054
2055 // Represents the two kinds of type bindings.
2056 #[derive(Debug, HashStable_Generic)]
2057 pub enum TypeBindingKind<'hir> {
2058     /// E.g., `Foo<Bar: Send>`.
2059     Constraint { bounds: &'hir [GenericBound<'hir>] },
2060     /// E.g., `Foo<Bar = ()>`.
2061     Equality { ty: &'hir Ty<'hir> },
2062 }
2063
2064 impl TypeBinding<'_> {
2065     pub fn ty(&self) -> &Ty<'_> {
2066         match self.kind {
2067             TypeBindingKind::Equality { ref ty } => ty,
2068             _ => panic!("expected equality type binding for parenthesized generic args"),
2069         }
2070     }
2071 }
2072
2073 #[derive(Debug)]
2074 pub struct Ty<'hir> {
2075     pub hir_id: HirId,
2076     pub kind: TyKind<'hir>,
2077     pub span: Span,
2078 }
2079
2080 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2081 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2082 #[derive(HashStable_Generic)]
2083 pub enum PrimTy {
2084     Int(IntTy),
2085     Uint(UintTy),
2086     Float(FloatTy),
2087     Str,
2088     Bool,
2089     Char,
2090 }
2091
2092 impl PrimTy {
2093     /// All of the primitive types
2094     pub const ALL: [Self; 17] = [
2095         // any changes here should also be reflected in `PrimTy::from_name`
2096         Self::Int(IntTy::I8),
2097         Self::Int(IntTy::I16),
2098         Self::Int(IntTy::I32),
2099         Self::Int(IntTy::I64),
2100         Self::Int(IntTy::I128),
2101         Self::Int(IntTy::Isize),
2102         Self::Uint(UintTy::U8),
2103         Self::Uint(UintTy::U16),
2104         Self::Uint(UintTy::U32),
2105         Self::Uint(UintTy::U64),
2106         Self::Uint(UintTy::U128),
2107         Self::Uint(UintTy::Usize),
2108         Self::Float(FloatTy::F32),
2109         Self::Float(FloatTy::F64),
2110         Self::Bool,
2111         Self::Char,
2112         Self::Str,
2113     ];
2114
2115     pub fn name_str(self) -> &'static str {
2116         match self {
2117             PrimTy::Int(i) => i.name_str(),
2118             PrimTy::Uint(u) => u.name_str(),
2119             PrimTy::Float(f) => f.name_str(),
2120             PrimTy::Str => "str",
2121             PrimTy::Bool => "bool",
2122             PrimTy::Char => "char",
2123         }
2124     }
2125
2126     pub fn name(self) -> Symbol {
2127         match self {
2128             PrimTy::Int(i) => i.name(),
2129             PrimTy::Uint(u) => u.name(),
2130             PrimTy::Float(f) => f.name(),
2131             PrimTy::Str => sym::str,
2132             PrimTy::Bool => sym::bool,
2133             PrimTy::Char => sym::char,
2134         }
2135     }
2136
2137     /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2138     /// Returns `None` if no matching type is found.
2139     pub fn from_name(name: Symbol) -> Option<Self> {
2140         let ty = match name {
2141             // any changes here should also be reflected in `PrimTy::ALL`
2142             sym::i8 => Self::Int(IntTy::I8),
2143             sym::i16 => Self::Int(IntTy::I16),
2144             sym::i32 => Self::Int(IntTy::I32),
2145             sym::i64 => Self::Int(IntTy::I64),
2146             sym::i128 => Self::Int(IntTy::I128),
2147             sym::isize => Self::Int(IntTy::Isize),
2148             sym::u8 => Self::Uint(UintTy::U8),
2149             sym::u16 => Self::Uint(UintTy::U16),
2150             sym::u32 => Self::Uint(UintTy::U32),
2151             sym::u64 => Self::Uint(UintTy::U64),
2152             sym::u128 => Self::Uint(UintTy::U128),
2153             sym::usize => Self::Uint(UintTy::Usize),
2154             sym::f32 => Self::Float(FloatTy::F32),
2155             sym::f64 => Self::Float(FloatTy::F64),
2156             sym::bool => Self::Bool,
2157             sym::char => Self::Char,
2158             sym::str => Self::Str,
2159             _ => return None,
2160         };
2161         Some(ty)
2162     }
2163 }
2164
2165 #[derive(Debug, HashStable_Generic)]
2166 pub struct BareFnTy<'hir> {
2167     pub unsafety: Unsafety,
2168     pub abi: Abi,
2169     pub generic_params: &'hir [GenericParam<'hir>],
2170     pub decl: &'hir FnDecl<'hir>,
2171     pub param_names: &'hir [Ident],
2172 }
2173
2174 #[derive(Debug, HashStable_Generic)]
2175 pub struct OpaqueTy<'hir> {
2176     pub generics: Generics<'hir>,
2177     pub bounds: GenericBounds<'hir>,
2178     pub impl_trait_fn: Option<DefId>,
2179     pub origin: OpaqueTyOrigin,
2180 }
2181
2182 /// From whence the opaque type came.
2183 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2184 pub enum OpaqueTyOrigin {
2185     /// `-> impl Trait`
2186     FnReturn,
2187     /// `async fn`
2188     AsyncFn,
2189     /// `let _: impl Trait = ...`
2190     Binding,
2191     /// Impl trait in type aliases, consts, statics, bounds.
2192     Misc,
2193 }
2194
2195 /// The various kinds of types recognized by the compiler.
2196 #[derive(Debug, HashStable_Generic)]
2197 pub enum TyKind<'hir> {
2198     /// A variable length slice (i.e., `[T]`).
2199     Slice(&'hir Ty<'hir>),
2200     /// A fixed length array (i.e., `[T; n]`).
2201     Array(&'hir Ty<'hir>, AnonConst),
2202     /// A raw pointer (i.e., `*const T` or `*mut T`).
2203     Ptr(MutTy<'hir>),
2204     /// A reference (i.e., `&'a T` or `&'a mut T`).
2205     Rptr(Lifetime, MutTy<'hir>),
2206     /// A bare function (e.g., `fn(usize) -> bool`).
2207     BareFn(&'hir BareFnTy<'hir>),
2208     /// The never type (`!`).
2209     Never,
2210     /// A tuple (`(A, B, C, D, ...)`).
2211     Tup(&'hir [Ty<'hir>]),
2212     /// A path to a type definition (`module::module::...::Type`), or an
2213     /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2214     ///
2215     /// Type parameters may be stored in each `PathSegment`.
2216     Path(QPath<'hir>),
2217     /// A opaque type definition itself. This is currently only used for the
2218     /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2219     ///
2220     /// The generic argument list contains the lifetimes (and in the future
2221     /// possibly parameters) that are actually bound on the `impl Trait`.
2222     OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2223     /// A trait object type `Bound1 + Bound2 + Bound3`
2224     /// where `Bound` is a trait or a lifetime.
2225     TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2226     /// Unused for now.
2227     Typeof(AnonConst),
2228     /// `TyKind::Infer` means the type should be inferred instead of it having been
2229     /// specified. This can appear anywhere in a type.
2230     Infer,
2231     /// Placeholder for a type that has failed to be defined.
2232     Err,
2233 }
2234
2235 #[derive(Debug, HashStable_Generic)]
2236 pub enum InlineAsmOperand<'hir> {
2237     In {
2238         reg: InlineAsmRegOrRegClass,
2239         expr: Expr<'hir>,
2240     },
2241     Out {
2242         reg: InlineAsmRegOrRegClass,
2243         late: bool,
2244         expr: Option<Expr<'hir>>,
2245     },
2246     InOut {
2247         reg: InlineAsmRegOrRegClass,
2248         late: bool,
2249         expr: Expr<'hir>,
2250     },
2251     SplitInOut {
2252         reg: InlineAsmRegOrRegClass,
2253         late: bool,
2254         in_expr: Expr<'hir>,
2255         out_expr: Option<Expr<'hir>>,
2256     },
2257     Const {
2258         expr: Expr<'hir>,
2259     },
2260     Sym {
2261         expr: Expr<'hir>,
2262     },
2263 }
2264
2265 impl<'hir> InlineAsmOperand<'hir> {
2266     pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2267         match *self {
2268             Self::In { reg, .. }
2269             | Self::Out { reg, .. }
2270             | Self::InOut { reg, .. }
2271             | Self::SplitInOut { reg, .. } => Some(reg),
2272             Self::Const { .. } | Self::Sym { .. } => None,
2273         }
2274     }
2275 }
2276
2277 #[derive(Debug, HashStable_Generic)]
2278 pub struct InlineAsm<'hir> {
2279     pub template: &'hir [InlineAsmTemplatePiece],
2280     pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2281     pub options: InlineAsmOptions,
2282     pub line_spans: &'hir [Span],
2283 }
2284
2285 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic, PartialEq)]
2286 pub struct LlvmInlineAsmOutput {
2287     pub constraint: Symbol,
2288     pub is_rw: bool,
2289     pub is_indirect: bool,
2290     pub span: Span,
2291 }
2292
2293 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2294 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2295 // arena-allocated slice.
2296 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic, PartialEq)]
2297 pub struct LlvmInlineAsmInner {
2298     pub asm: Symbol,
2299     pub asm_str_style: StrStyle,
2300     pub outputs: Vec<LlvmInlineAsmOutput>,
2301     pub inputs: Vec<Symbol>,
2302     pub clobbers: Vec<Symbol>,
2303     pub volatile: bool,
2304     pub alignstack: bool,
2305     pub dialect: LlvmAsmDialect,
2306 }
2307
2308 #[derive(Debug, HashStable_Generic)]
2309 pub struct LlvmInlineAsm<'hir> {
2310     pub inner: LlvmInlineAsmInner,
2311     pub outputs_exprs: &'hir [Expr<'hir>],
2312     pub inputs_exprs: &'hir [Expr<'hir>],
2313 }
2314
2315 /// Represents a parameter in a function header.
2316 #[derive(Debug, HashStable_Generic)]
2317 pub struct Param<'hir> {
2318     pub attrs: &'hir [Attribute],
2319     pub hir_id: HirId,
2320     pub pat: &'hir Pat<'hir>,
2321     pub ty_span: Span,
2322     pub span: Span,
2323 }
2324
2325 /// Represents the header (not the body) of a function declaration.
2326 #[derive(Debug, HashStable_Generic)]
2327 pub struct FnDecl<'hir> {
2328     /// The types of the function's parameters.
2329     ///
2330     /// Additional argument data is stored in the function's [body](Body::params).
2331     pub inputs: &'hir [Ty<'hir>],
2332     pub output: FnRetTy<'hir>,
2333     pub c_variadic: bool,
2334     /// Does the function have an implicit self?
2335     pub implicit_self: ImplicitSelfKind,
2336 }
2337
2338 /// Represents what type of implicit self a function has, if any.
2339 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2340 pub enum ImplicitSelfKind {
2341     /// Represents a `fn x(self);`.
2342     Imm,
2343     /// Represents a `fn x(mut self);`.
2344     Mut,
2345     /// Represents a `fn x(&self);`.
2346     ImmRef,
2347     /// Represents a `fn x(&mut self);`.
2348     MutRef,
2349     /// Represents when a function does not have a self argument or
2350     /// when a function has a `self: X` argument.
2351     None,
2352 }
2353
2354 impl ImplicitSelfKind {
2355     /// Does this represent an implicit self?
2356     pub fn has_implicit_self(&self) -> bool {
2357         !matches!(*self, ImplicitSelfKind::None)
2358     }
2359 }
2360
2361 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2362 #[derive(HashStable_Generic)]
2363 pub enum IsAsync {
2364     Async,
2365     NotAsync,
2366 }
2367
2368 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2369 pub enum Defaultness {
2370     Default { has_value: bool },
2371     Final,
2372 }
2373
2374 impl Defaultness {
2375     pub fn has_value(&self) -> bool {
2376         match *self {
2377             Defaultness::Default { has_value } => has_value,
2378             Defaultness::Final => true,
2379         }
2380     }
2381
2382     pub fn is_final(&self) -> bool {
2383         *self == Defaultness::Final
2384     }
2385
2386     pub fn is_default(&self) -> bool {
2387         matches!(*self, Defaultness::Default { .. })
2388     }
2389 }
2390
2391 #[derive(Debug, HashStable_Generic)]
2392 pub enum FnRetTy<'hir> {
2393     /// Return type is not specified.
2394     ///
2395     /// Functions default to `()` and
2396     /// closures default to inference. Span points to where return
2397     /// type would be inserted.
2398     DefaultReturn(Span),
2399     /// Everything else.
2400     Return(&'hir Ty<'hir>),
2401 }
2402
2403 impl FnRetTy<'_> {
2404     pub fn span(&self) -> Span {
2405         match *self {
2406             Self::DefaultReturn(span) => span,
2407             Self::Return(ref ty) => ty.span,
2408         }
2409     }
2410 }
2411
2412 #[derive(Encodable, Debug)]
2413 pub struct Mod<'hir> {
2414     /// A span from the first token past `{` to the last token until `}`.
2415     /// For `mod foo;`, the inner span ranges from the first token
2416     /// to the last token in the external file.
2417     pub inner: Span,
2418     pub item_ids: &'hir [ItemId],
2419 }
2420
2421 #[derive(Encodable, Debug, HashStable_Generic)]
2422 pub struct GlobalAsm {
2423     pub asm: Symbol,
2424 }
2425
2426 #[derive(Debug, HashStable_Generic)]
2427 pub struct EnumDef<'hir> {
2428     pub variants: &'hir [Variant<'hir>],
2429 }
2430
2431 #[derive(Debug, HashStable_Generic)]
2432 pub struct Variant<'hir> {
2433     /// Name of the variant.
2434     #[stable_hasher(project(name))]
2435     pub ident: Ident,
2436     /// Attributes of the variant.
2437     pub attrs: &'hir [Attribute],
2438     /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2439     pub id: HirId,
2440     /// Fields and constructor id of the variant.
2441     pub data: VariantData<'hir>,
2442     /// Explicit discriminant (e.g., `Foo = 1`).
2443     pub disr_expr: Option<AnonConst>,
2444     /// Span
2445     pub span: Span,
2446 }
2447
2448 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2449 pub enum UseKind {
2450     /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2451     /// Also produced for each element of a list `use`, e.g.
2452     /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2453     Single,
2454
2455     /// Glob import, e.g., `use foo::*`.
2456     Glob,
2457
2458     /// Degenerate list import, e.g., `use foo::{a, b}` produces
2459     /// an additional `use foo::{}` for performing checks such as
2460     /// unstable feature gating. May be removed in the future.
2461     ListStem,
2462 }
2463
2464 /// References to traits in impls.
2465 ///
2466 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2467 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2468 /// trait being referred to but just a unique `HirId` that serves as a key
2469 /// within the resolution map.
2470 #[derive(Debug, HashStable_Generic)]
2471 pub struct TraitRef<'hir> {
2472     pub path: &'hir Path<'hir>,
2473     // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2474     #[stable_hasher(ignore)]
2475     pub hir_ref_id: HirId,
2476 }
2477
2478 impl TraitRef<'_> {
2479     /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2480     pub fn trait_def_id(&self) -> Option<DefId> {
2481         match self.path.res {
2482             Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2483             Res::Err => None,
2484             _ => unreachable!(),
2485         }
2486     }
2487 }
2488
2489 #[derive(Debug, HashStable_Generic)]
2490 pub struct PolyTraitRef<'hir> {
2491     /// The `'a` in `for<'a> Foo<&'a T>`.
2492     pub bound_generic_params: &'hir [GenericParam<'hir>],
2493
2494     /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2495     pub trait_ref: TraitRef<'hir>,
2496
2497     pub span: Span,
2498 }
2499
2500 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2501
2502 #[derive(Debug)]
2503 pub enum VisibilityKind<'hir> {
2504     Public,
2505     Crate(CrateSugar),
2506     Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2507     Inherited,
2508 }
2509
2510 impl VisibilityKind<'_> {
2511     pub fn is_pub(&self) -> bool {
2512         matches!(*self, VisibilityKind::Public)
2513     }
2514
2515     pub fn is_pub_restricted(&self) -> bool {
2516         match *self {
2517             VisibilityKind::Public | VisibilityKind::Inherited => false,
2518             VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2519         }
2520     }
2521 }
2522
2523 #[derive(Debug, HashStable_Generic)]
2524 pub struct StructField<'hir> {
2525     pub span: Span,
2526     #[stable_hasher(project(name))]
2527     pub ident: Ident,
2528     pub vis: Visibility<'hir>,
2529     pub hir_id: HirId,
2530     pub ty: &'hir Ty<'hir>,
2531     pub attrs: &'hir [Attribute],
2532 }
2533
2534 impl StructField<'_> {
2535     // Still necessary in couple of places
2536     pub fn is_positional(&self) -> bool {
2537         let first = self.ident.as_str().as_bytes()[0];
2538         (b'0'..=b'9').contains(&first)
2539     }
2540 }
2541
2542 /// Fields and constructor IDs of enum variants and structs.
2543 #[derive(Debug, HashStable_Generic)]
2544 pub enum VariantData<'hir> {
2545     /// A struct variant.
2546     ///
2547     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2548     Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2549     /// A tuple variant.
2550     ///
2551     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2552     Tuple(&'hir [StructField<'hir>], HirId),
2553     /// A unit variant.
2554     ///
2555     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2556     Unit(HirId),
2557 }
2558
2559 impl VariantData<'hir> {
2560     /// Return the fields of this variant.
2561     pub fn fields(&self) -> &'hir [StructField<'hir>] {
2562         match *self {
2563             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2564             _ => &[],
2565         }
2566     }
2567
2568     /// Return the `HirId` of this variant's constructor, if it has one.
2569     pub fn ctor_hir_id(&self) -> Option<HirId> {
2570         match *self {
2571             VariantData::Struct(_, _) => None,
2572             VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2573         }
2574     }
2575 }
2576
2577 // The bodies for items are stored "out of line", in a separate
2578 // hashmap in the `Crate`. Here we just record the hir-id of the item
2579 // so it can fetched later.
2580 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)]
2581 pub struct ItemId {
2582     pub def_id: LocalDefId,
2583 }
2584
2585 impl ItemId {
2586     pub fn hir_id(&self) -> HirId {
2587         // Items are always HIR owners.
2588         HirId::make_owner(self.def_id)
2589     }
2590 }
2591
2592 /// An item
2593 ///
2594 /// The name might be a dummy name in case of anonymous items
2595 #[derive(Debug)]
2596 pub struct Item<'hir> {
2597     pub ident: Ident,
2598     pub def_id: LocalDefId,
2599     pub attrs: &'hir [Attribute],
2600     pub kind: ItemKind<'hir>,
2601     pub vis: Visibility<'hir>,
2602     pub span: Span,
2603 }
2604
2605 impl Item<'_> {
2606     pub fn hir_id(&self) -> HirId {
2607         // Items are always HIR owners.
2608         HirId::make_owner(self.def_id)
2609     }
2610
2611     pub fn item_id(&self) -> ItemId {
2612         ItemId { def_id: self.def_id }
2613     }
2614 }
2615
2616 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2617 #[derive(Encodable, Decodable, HashStable_Generic)]
2618 pub enum Unsafety {
2619     Unsafe,
2620     Normal,
2621 }
2622
2623 impl Unsafety {
2624     pub fn prefix_str(&self) -> &'static str {
2625         match self {
2626             Self::Unsafe => "unsafe ",
2627             Self::Normal => "",
2628         }
2629     }
2630 }
2631
2632 impl fmt::Display for Unsafety {
2633     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2634         f.write_str(match *self {
2635             Self::Unsafe => "unsafe",
2636             Self::Normal => "normal",
2637         })
2638     }
2639 }
2640
2641 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2642 #[derive(Encodable, Decodable, HashStable_Generic)]
2643 pub enum Constness {
2644     Const,
2645     NotConst,
2646 }
2647
2648 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2649 pub struct FnHeader {
2650     pub unsafety: Unsafety,
2651     pub constness: Constness,
2652     pub asyncness: IsAsync,
2653     pub abi: Abi,
2654 }
2655
2656 impl FnHeader {
2657     pub fn is_const(&self) -> bool {
2658         matches!(&self.constness, Constness::Const)
2659     }
2660 }
2661
2662 #[derive(Debug, HashStable_Generic)]
2663 pub enum ItemKind<'hir> {
2664     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2665     ///
2666     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2667     ExternCrate(Option<Symbol>),
2668
2669     /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2670     ///
2671     /// or just
2672     ///
2673     /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2674     Use(&'hir Path<'hir>, UseKind),
2675
2676     /// A `static` item.
2677     Static(&'hir Ty<'hir>, Mutability, BodyId),
2678     /// A `const` item.
2679     Const(&'hir Ty<'hir>, BodyId),
2680     /// A function declaration.
2681     Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2682     /// A module.
2683     Mod(Mod<'hir>),
2684     /// An external module, e.g. `extern { .. }`.
2685     ForeignMod { abi: Abi, items: &'hir [ForeignItemRef<'hir>] },
2686     /// Module-level inline assembly (from `global_asm!`).
2687     GlobalAsm(&'hir GlobalAsm),
2688     /// A type alias, e.g., `type Foo = Bar<u8>`.
2689     TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2690     /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2691     OpaqueTy(OpaqueTy<'hir>),
2692     /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2693     Enum(EnumDef<'hir>, Generics<'hir>),
2694     /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2695     Struct(VariantData<'hir>, Generics<'hir>),
2696     /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2697     Union(VariantData<'hir>, Generics<'hir>),
2698     /// A trait definition.
2699     Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2700     /// A trait alias.
2701     TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2702
2703     /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2704     Impl(Impl<'hir>),
2705 }
2706
2707 #[derive(Debug, HashStable_Generic)]
2708 pub struct Impl<'hir> {
2709     pub unsafety: Unsafety,
2710     pub polarity: ImplPolarity,
2711     pub defaultness: Defaultness,
2712     // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2713     // decoding as `Span`s cannot be decoded when a `Session` is not available.
2714     pub defaultness_span: Option<Span>,
2715     pub constness: Constness,
2716     pub generics: Generics<'hir>,
2717
2718     /// The trait being implemented, if any.
2719     pub of_trait: Option<TraitRef<'hir>>,
2720
2721     pub self_ty: &'hir Ty<'hir>,
2722     pub items: &'hir [ImplItemRef<'hir>],
2723 }
2724
2725 impl ItemKind<'_> {
2726     pub fn generics(&self) -> Option<&Generics<'_>> {
2727         Some(match *self {
2728             ItemKind::Fn(_, ref generics, _)
2729             | ItemKind::TyAlias(_, ref generics)
2730             | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2731             | ItemKind::Enum(_, ref generics)
2732             | ItemKind::Struct(_, ref generics)
2733             | ItemKind::Union(_, ref generics)
2734             | ItemKind::Trait(_, _, ref generics, _, _)
2735             | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2736             _ => return None,
2737         })
2738     }
2739 }
2740
2741 /// A reference from an trait to one of its associated items. This
2742 /// contains the item's id, naturally, but also the item's name and
2743 /// some other high-level details (like whether it is an associated
2744 /// type or method, and whether it is public). This allows other
2745 /// passes to find the impl they want without loading the ID (which
2746 /// means fewer edges in the incremental compilation graph).
2747 #[derive(Encodable, Debug, HashStable_Generic)]
2748 pub struct TraitItemRef {
2749     pub id: TraitItemId,
2750     #[stable_hasher(project(name))]
2751     pub ident: Ident,
2752     pub kind: AssocItemKind,
2753     pub span: Span,
2754     pub defaultness: Defaultness,
2755 }
2756
2757 /// A reference from an impl to one of its associated items. This
2758 /// contains the item's ID, naturally, but also the item's name and
2759 /// some other high-level details (like whether it is an associated
2760 /// type or method, and whether it is public). This allows other
2761 /// passes to find the impl they want without loading the ID (which
2762 /// means fewer edges in the incremental compilation graph).
2763 #[derive(Debug, HashStable_Generic)]
2764 pub struct ImplItemRef<'hir> {
2765     pub id: ImplItemId,
2766     #[stable_hasher(project(name))]
2767     pub ident: Ident,
2768     pub kind: AssocItemKind,
2769     pub span: Span,
2770     pub vis: Visibility<'hir>,
2771     pub defaultness: Defaultness,
2772 }
2773
2774 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2775 pub enum AssocItemKind {
2776     Const,
2777     Fn { has_self: bool },
2778     Type,
2779 }
2780
2781 // The bodies for items are stored "out of line", in a separate
2782 // hashmap in the `Crate`. Here we just record the hir-id of the item
2783 // so it can fetched later.
2784 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2785 pub struct ForeignItemId {
2786     pub def_id: LocalDefId,
2787 }
2788
2789 impl ForeignItemId {
2790     pub fn hir_id(&self) -> HirId {
2791         // Items are always HIR owners.
2792         HirId::make_owner(self.def_id)
2793     }
2794 }
2795
2796 /// A reference from a foreign block to one of its items. This
2797 /// contains the item's ID, naturally, but also the item's name and
2798 /// some other high-level details (like whether it is an associated
2799 /// type or method, and whether it is public). This allows other
2800 /// passes to find the impl they want without loading the ID (which
2801 /// means fewer edges in the incremental compilation graph).
2802 #[derive(Debug, HashStable_Generic)]
2803 pub struct ForeignItemRef<'hir> {
2804     pub id: ForeignItemId,
2805     #[stable_hasher(project(name))]
2806     pub ident: Ident,
2807     pub span: Span,
2808     pub vis: Visibility<'hir>,
2809 }
2810
2811 #[derive(Debug)]
2812 pub struct ForeignItem<'hir> {
2813     pub ident: Ident,
2814     pub attrs: &'hir [Attribute],
2815     pub kind: ForeignItemKind<'hir>,
2816     pub def_id: LocalDefId,
2817     pub span: Span,
2818     pub vis: Visibility<'hir>,
2819 }
2820
2821 impl ForeignItem<'_> {
2822     pub fn hir_id(&self) -> HirId {
2823         // Items are always HIR owners.
2824         HirId::make_owner(self.def_id)
2825     }
2826
2827     pub fn foreign_item_id(&self) -> ForeignItemId {
2828         ForeignItemId { def_id: self.def_id }
2829     }
2830 }
2831
2832 /// An item within an `extern` block.
2833 #[derive(Debug, HashStable_Generic)]
2834 pub enum ForeignItemKind<'hir> {
2835     /// A foreign function.
2836     Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2837     /// A foreign static item (`static ext: u8`).
2838     Static(&'hir Ty<'hir>, Mutability),
2839     /// A foreign type.
2840     Type,
2841 }
2842
2843 /// A variable captured by a closure.
2844 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2845 pub struct Upvar {
2846     // First span where it is accessed (there can be multiple).
2847     pub span: Span,
2848 }
2849
2850 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2851 // has length > 0 if the trait is found through an chain of imports, starting with the
2852 // import/use statement in the scope where the trait is used.
2853 #[derive(Encodable, Decodable, Clone, Debug)]
2854 pub struct TraitCandidate {
2855     pub def_id: DefId,
2856     pub import_ids: SmallVec<[LocalDefId; 1]>,
2857 }
2858
2859 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2860 pub enum Node<'hir> {
2861     Param(&'hir Param<'hir>),
2862     Item(&'hir Item<'hir>),
2863     ForeignItem(&'hir ForeignItem<'hir>),
2864     TraitItem(&'hir TraitItem<'hir>),
2865     ImplItem(&'hir ImplItem<'hir>),
2866     Variant(&'hir Variant<'hir>),
2867     Field(&'hir StructField<'hir>),
2868     AnonConst(&'hir AnonConst),
2869     Expr(&'hir Expr<'hir>),
2870     Stmt(&'hir Stmt<'hir>),
2871     PathSegment(&'hir PathSegment<'hir>),
2872     Ty(&'hir Ty<'hir>),
2873     TraitRef(&'hir TraitRef<'hir>),
2874     Binding(&'hir Pat<'hir>),
2875     Pat(&'hir Pat<'hir>),
2876     Arm(&'hir Arm<'hir>),
2877     Block(&'hir Block<'hir>),
2878     Local(&'hir Local<'hir>),
2879     MacroDef(&'hir MacroDef<'hir>),
2880
2881     /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2882     /// with synthesized constructors.
2883     Ctor(&'hir VariantData<'hir>),
2884
2885     Lifetime(&'hir Lifetime),
2886     GenericParam(&'hir GenericParam<'hir>),
2887     Visibility(&'hir Visibility<'hir>),
2888
2889     Crate(&'hir CrateItem<'hir>),
2890 }
2891
2892 impl<'hir> Node<'hir> {
2893     pub fn ident(&self) -> Option<Ident> {
2894         match self {
2895             Node::TraitItem(TraitItem { ident, .. })
2896             | Node::ImplItem(ImplItem { ident, .. })
2897             | Node::ForeignItem(ForeignItem { ident, .. })
2898             | Node::Field(StructField { ident, .. })
2899             | Node::Variant(Variant { ident, .. })
2900             | Node::MacroDef(MacroDef { ident, .. })
2901             | Node::Item(Item { ident, .. }) => Some(*ident),
2902             _ => None,
2903         }
2904     }
2905
2906     pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
2907         match self {
2908             Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2909             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2910             | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2911             Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
2912                 Some(fn_decl)
2913             }
2914             _ => None,
2915         }
2916     }
2917
2918     pub fn body_id(&self) -> Option<BodyId> {
2919         match self {
2920             Node::TraitItem(TraitItem {
2921                 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
2922                 ..
2923             })
2924             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
2925             | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
2926             _ => None,
2927         }
2928     }
2929
2930     pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
2931         match self {
2932             Node::TraitItem(TraitItem { generics, .. })
2933             | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
2934             Node::Item(item) => item.kind.generics(),
2935             _ => None,
2936         }
2937     }
2938
2939     pub fn hir_id(&self) -> Option<HirId> {
2940         match self {
2941             Node::Item(Item { def_id, .. })
2942             | Node::TraitItem(TraitItem { def_id, .. })
2943             | Node::ImplItem(ImplItem { def_id, .. })
2944             | Node::ForeignItem(ForeignItem { def_id, .. }) => Some(HirId::make_owner(*def_id)),
2945             Node::Field(StructField { hir_id, .. })
2946             | Node::AnonConst(AnonConst { hir_id, .. })
2947             | Node::Expr(Expr { hir_id, .. })
2948             | Node::Stmt(Stmt { hir_id, .. })
2949             | Node::Ty(Ty { hir_id, .. })
2950             | Node::Binding(Pat { hir_id, .. })
2951             | Node::Pat(Pat { hir_id, .. })
2952             | Node::Arm(Arm { hir_id, .. })
2953             | Node::Block(Block { hir_id, .. })
2954             | Node::Local(Local { hir_id, .. })
2955             | Node::MacroDef(MacroDef { hir_id, .. })
2956             | Node::Lifetime(Lifetime { hir_id, .. })
2957             | Node::Param(Param { hir_id, .. })
2958             | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
2959             Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
2960             Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
2961             Node::Variant(Variant { id, .. }) => Some(*id),
2962             Node::Ctor(variant) => variant.ctor_hir_id(),
2963             Node::Crate(_) | Node::Visibility(_) => None,
2964         }
2965     }
2966 }
2967
2968 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
2969 #[cfg(target_arch = "x86_64")]
2970 mod size_asserts {
2971     rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
2972     rustc_data_structures::static_assert_size!(super::Expr<'static>, 72);
2973     rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
2974     rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
2975     rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
2976
2977     rustc_data_structures::static_assert_size!(super::Item<'static>, 200);
2978     rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 144);
2979     rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 168);
2980     rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 152);
2981 }