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