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