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