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