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