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