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