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