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