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.
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.
13 pub use self::BinOp_::*;
14 pub use self::BlockCheckMode::*;
15 pub use self::CaptureClause::*;
16 pub use self::Decl_::*;
17 pub use self::Expr_::*;
18 pub use self::FunctionRetTy::*;
19 pub use self::ForeignItem_::*;
20 pub use self::Item_::*;
21 pub use self::Mutability::*;
22 pub use self::PrimTy::*;
23 pub use self::Stmt_::*;
25 pub use self::TyParamBound::*;
26 pub use self::UnOp::*;
27 pub use self::UnsafeSource::*;
28 pub use self::Visibility::{Public, Inherited};
31 use hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
32 use util::nodemap::{NodeMap, FxHashSet};
34 use syntax_pos::{Span, DUMMY_SP};
35 use syntax::codemap::{self, Spanned};
37 use syntax::ast::{Ident, Name, NodeId, DUMMY_NODE_ID, AsmDialect};
38 use syntax::ast::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy, MetaItem};
39 use syntax::ext::hygiene::SyntaxContext;
41 use syntax::symbol::{Symbol, keywords};
42 use syntax::tokenstream::TokenStream;
43 use syntax::util::ThinVec;
46 use rustc_data_structures::indexed_vec;
48 use std::collections::BTreeMap;
51 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
52 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
53 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
54 /// of `Vec` to avoid keeping extra capacity.
55 pub type HirVec<T> = P<[T]>;
57 macro_rules! hir_vec {
58 ($elem:expr; $n:expr) => (
59 $crate::hir::HirVec::from(vec![$elem; $n])
62 $crate::hir::HirVec::from(vec![$($x),*])
64 ($($x:expr,)*) => (hir_vec![$($x),*])
71 pub mod itemlikevisit;
78 /// A HirId uniquely identifies a node in the HIR of the current crate. It is
79 /// composed of the `owner`, which is the DefIndex of the directly enclosing
80 /// hir::Item, hir::TraitItem, or hir::ImplItem (i.e. the closest "item-like"),
81 /// and the `local_id` which is unique within the given owner.
83 /// This two-level structure makes for more stable values: One can move an item
84 /// around within the source code, or add or remove stuff before it, without
85 /// the local_id part of the HirId changing, which is a very useful property in
86 /// incremental compilation where we have to persist things through changes to
88 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug,
89 RustcEncodable, RustcDecodable)]
92 pub local_id: ItemLocalId,
95 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
96 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
97 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
98 /// the node's position within the owning item in any way, but there is a
99 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
100 /// integers starting at zero, so a mapping that maps all or most nodes within
101 /// an "item-like" to something else can be implement by a `Vec` instead of a
102 /// tree or hash map.
103 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug,
104 RustcEncodable, RustcDecodable)]
105 pub struct ItemLocalId(pub u32);
108 pub fn as_usize(&self) -> usize {
113 impl indexed_vec::Idx for ItemLocalId {
114 fn new(idx: usize) -> Self {
115 debug_assert!((idx as u32) as usize == idx);
116 ItemLocalId(idx as u32)
119 fn index(self) -> usize {
124 /// The `HirId` corresponding to CRATE_NODE_ID and CRATE_DEF_INDEX
125 pub const CRATE_HIR_ID: HirId = HirId {
126 owner: CRATE_DEF_INDEX,
127 local_id: ItemLocalId(0)
130 pub const DUMMY_HIR_ID: HirId = HirId {
131 owner: CRATE_DEF_INDEX,
132 local_id: DUMMY_ITEM_LOCAL_ID,
135 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId(!0);
137 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
138 pub struct Lifetime {
142 /// Either "'a", referring to a named lifetime definition,
143 /// or "" (aka keywords::Invalid), for elision placeholders.
145 /// HIR lowering inserts these placeholders in type paths that
146 /// refer to type definitions needing lifetime parameters,
147 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
151 impl fmt::Debug for Lifetime {
152 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
156 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
161 pub fn is_elided(&self) -> bool {
162 self.name == keywords::Invalid.name() ||
166 pub fn is_static(&self) -> bool {
167 self.name == "'static"
171 /// A lifetime definition, eg `'a: 'b+'c+'d`
172 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
173 pub struct LifetimeDef {
174 pub lifetime: Lifetime,
175 pub bounds: HirVec<Lifetime>,
176 pub pure_wrt_drop: bool,
179 /// A "Path" is essentially Rust's notion of a name; for instance:
180 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
181 /// along with a bunch of supporting information.
182 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
185 /// The definition that the path resolved to.
187 /// The segments in the path: the things separated by `::`.
188 pub segments: HirVec<PathSegment>,
192 pub fn is_global(&self) -> bool {
193 !self.segments.is_empty() && self.segments[0].name == keywords::CrateRoot.name()
197 impl fmt::Debug for Path {
198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
199 write!(f, "path({})",
200 print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
204 /// A segment of a path: an identifier, an optional lifetime, and a set of
206 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
207 pub struct PathSegment {
208 /// The identifier portion of this path segment.
211 /// Type/lifetime parameters attached to this path. They come in
212 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
213 /// this is more than just simple syntactic sugar; the use of
214 /// parens affects the region binding rules, so we preserve the
216 pub parameters: PathParameters,
220 /// Convert an identifier to the corresponding segment.
221 pub fn from_name(name: Name) -> PathSegment {
224 parameters: PathParameters::none()
229 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
230 pub struct PathParameters {
231 /// The lifetime parameters for this path segment.
232 pub lifetimes: HirVec<Lifetime>,
233 /// The type parameters for this path segment, if present.
234 pub types: HirVec<P<Ty>>,
235 /// Whether to infer remaining type parameters, if any.
236 /// This only applies to expression and pattern paths, and
237 /// out of those only the segments with no type parameters
238 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
239 pub infer_types: bool,
240 /// Bindings (equality constraints) on associated types, if present.
241 /// E.g., `Foo<A=Bar>`.
242 pub bindings: HirVec<TypeBinding>,
243 /// Were parameters written in parenthesized form `Fn(T) -> U`?
244 /// This is required mostly for pretty-printing and diagnostics,
245 /// but also for changing lifetime elision rules to be "function-like".
246 pub parenthesized: bool,
249 impl PathParameters {
250 pub fn none() -> Self {
252 lifetimes: HirVec::new(),
253 types: HirVec::new(),
255 bindings: HirVec::new(),
256 parenthesized: false,
260 pub fn inputs(&self) -> &[P<Ty>] {
261 if self.parenthesized {
262 if let Some(ref ty) = self.types.get(0) {
263 if let TyTup(ref tys) = ty.node {
268 bug!("PathParameters::inputs: not a `Fn(T) -> U`");
272 /// The AST represents all type param bounds as types.
273 /// typeck::collect::compute_bounds matches these against
274 /// the "special" built-in traits (see middle::lang_items) and
275 /// detects Copy, Send and Sync.
276 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
277 pub enum TyParamBound {
278 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
279 RegionTyParamBound(Lifetime),
282 /// A modifier on a bound, currently this is only used for `?Sized`, where the
283 /// modifier is `Maybe`. Negative bounds should also be handled here.
284 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
285 pub enum TraitBoundModifier {
290 pub type TyParamBounds = HirVec<TyParamBound>;
292 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
296 pub bounds: TyParamBounds,
297 pub default: Option<P<Ty>>,
299 pub pure_wrt_drop: bool,
302 /// Represents lifetimes and type parameters attached to a declaration
303 /// of a function, enum, trait, etc.
304 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
305 pub struct Generics {
306 pub lifetimes: HirVec<LifetimeDef>,
307 pub ty_params: HirVec<TyParam>,
308 pub where_clause: WhereClause,
313 pub fn empty() -> Generics {
315 lifetimes: HirVec::new(),
316 ty_params: HirVec::new(),
317 where_clause: WhereClause {
319 predicates: HirVec::new(),
325 pub fn is_lt_parameterized(&self) -> bool {
326 !self.lifetimes.is_empty()
329 pub fn is_type_parameterized(&self) -> bool {
330 !self.ty_params.is_empty()
333 pub fn is_parameterized(&self) -> bool {
334 self.is_lt_parameterized() || self.is_type_parameterized()
338 pub enum UnsafeGeneric {
339 Region(LifetimeDef, &'static str),
340 Type(TyParam, &'static str),
344 pub fn attr_name(&self) -> &'static str {
346 UnsafeGeneric::Region(_, s) => s,
347 UnsafeGeneric::Type(_, s) => s,
353 pub fn carries_unsafe_attr(&self) -> Option<UnsafeGeneric> {
354 for r in &self.lifetimes {
356 return Some(UnsafeGeneric::Region(r.clone(), "may_dangle"));
359 for t in &self.ty_params {
361 return Some(UnsafeGeneric::Type(t.clone(), "may_dangle"));
368 /// A `where` clause in a definition
369 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
370 pub struct WhereClause {
372 pub predicates: HirVec<WherePredicate>,
375 /// A single predicate in a `where` clause
376 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
377 pub enum WherePredicate {
378 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
379 BoundPredicate(WhereBoundPredicate),
380 /// A lifetime predicate, e.g. `'a: 'b+'c`
381 RegionPredicate(WhereRegionPredicate),
382 /// An equality predicate (unsupported)
383 EqPredicate(WhereEqPredicate),
386 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
387 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
388 pub struct WhereBoundPredicate {
390 /// Any lifetimes from a `for` binding
391 pub bound_lifetimes: HirVec<LifetimeDef>,
392 /// The type being bounded
393 pub bounded_ty: P<Ty>,
394 /// Trait and lifetime bounds (`Clone+Send+'static`)
395 pub bounds: TyParamBounds,
398 /// A lifetime predicate, e.g. `'a: 'b+'c`
399 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
400 pub struct WhereRegionPredicate {
402 pub lifetime: Lifetime,
403 pub bounds: HirVec<Lifetime>,
406 /// An equality predicate (unsupported), e.g. `T=int`
407 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
408 pub struct WhereEqPredicate {
415 pub type CrateConfig = HirVec<P<MetaItem>>;
417 /// The top-level data structure that stores the entire contents of
418 /// the crate currently being compiled.
420 /// For more details, see [the module-level README](README.md).
421 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
424 pub attrs: HirVec<Attribute>,
426 pub exported_macros: HirVec<MacroDef>,
428 // NB: We use a BTreeMap here so that `visit_all_items` iterates
429 // over the ids in increasing order. In principle it should not
430 // matter what order we visit things in, but in *practice* it
431 // does, because it can affect the order in which errors are
432 // detected, which in turn can make compile-fail tests yield
433 // slightly different results.
434 pub items: BTreeMap<NodeId, Item>,
436 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
437 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
438 pub bodies: BTreeMap<BodyId, Body>,
439 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
440 pub trait_default_impl: BTreeMap<DefId, NodeId>,
442 /// A list of the body ids written out in the order in which they
443 /// appear in the crate. If you're going to process all the bodies
444 /// in the crate, you should iterate over this list rather than the keys
446 pub body_ids: Vec<BodyId>,
450 pub fn item(&self, id: NodeId) -> &Item {
454 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
455 &self.trait_items[&id]
458 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
459 &self.impl_items[&id]
462 /// Visits all items in the crate in some deterministic (but
463 /// unspecified) order. If you just need to process every item,
464 /// but don't care about nesting, this method is the best choice.
466 /// If you do care about nesting -- usually because your algorithm
467 /// follows lexical scoping rules -- then you want a different
468 /// approach. You should override `visit_nested_item` in your
469 /// visitor and then call `intravisit::walk_crate` instead.
470 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
471 where V: itemlikevisit::ItemLikeVisitor<'hir>
473 for (_, item) in &self.items {
474 visitor.visit_item(item);
477 for (_, trait_item) in &self.trait_items {
478 visitor.visit_trait_item(trait_item);
481 for (_, impl_item) in &self.impl_items {
482 visitor.visit_impl_item(impl_item);
486 pub fn body(&self, id: BodyId) -> &Body {
491 /// A macro definition, in this crate or imported from another.
493 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
494 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
495 pub struct MacroDef {
498 pub attrs: HirVec<Attribute>,
501 pub body: TokenStream,
505 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
507 /// Statements in a block
508 pub stmts: HirVec<Stmt>,
509 /// An expression at the end of the block
510 /// without a semicolon, if any
511 pub expr: Option<P<Expr>>,
514 /// Distinguishes between `unsafe { ... }` and `{ ... }`
515 pub rules: BlockCheckMode,
517 /// If true, then there may exist `break 'a` values that aim to
518 /// break out of this block early. As of this writing, this is not
519 /// currently permitted in Rust itself, but it is generated as
520 /// part of `catch` statements.
521 pub targeted_by_break: bool,
524 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
532 impl fmt::Debug for Pat {
533 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
534 write!(f, "pat({}: {})", self.id,
535 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
540 // FIXME(#19596) this is a workaround, but there should be a better way
541 fn walk_<G>(&self, it: &mut G) -> bool
542 where G: FnMut(&Pat) -> bool
549 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
550 PatKind::Struct(_, ref fields, _) => {
551 fields.iter().all(|field| field.node.pat.walk_(it))
553 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
554 s.iter().all(|p| p.walk_(it))
556 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
559 PatKind::Slice(ref before, ref slice, ref after) => {
560 before.iter().all(|p| p.walk_(it)) &&
561 slice.iter().all(|p| p.walk_(it)) &&
562 after.iter().all(|p| p.walk_(it))
567 PatKind::Binding(..) |
568 PatKind::Path(_) => {
574 pub fn walk<F>(&self, mut it: F) -> bool
575 where F: FnMut(&Pat) -> bool
581 /// A single field in a struct pattern
583 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
584 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
585 /// except is_shorthand is true
586 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
587 pub struct FieldPat {
588 /// The identifier for the field
590 /// The pattern the field is destructured to
592 pub is_shorthand: bool,
595 /// Explicit binding annotations given in the HIR for a binding. Note
596 /// that this is not the final binding *mode* that we infer after type
598 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
599 pub enum BindingAnnotation {
600 /// No binding annotation given: this means that the final binding mode
601 /// will depend on whether we have skipped through a `&` reference
602 /// when matching. For example, the `x` in `Some(x)` will have binding
603 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
604 /// ultimately be inferred to be by-reference.
606 /// Note that implicit reference skipping is not implemented yet (#42640).
609 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
612 /// Annotated as `ref`, like `ref x`
615 /// Annotated as `ref mut x`.
619 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
627 /// Represents a wildcard pattern (`_`)
630 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
631 /// The `NodeId` is the canonical ID for the variable being bound,
632 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
633 /// which is the pattern ID of the first `x`.
634 Binding(BindingAnnotation, NodeId, Spanned<Name>, Option<P<Pat>>),
636 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
637 /// The `bool` is `true` in the presence of a `..`.
638 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
640 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
641 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
642 /// 0 <= position <= subpats.len()
643 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
645 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
648 /// A tuple pattern `(a, b)`.
649 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
650 /// 0 <= position <= subpats.len()
651 Tuple(HirVec<P<Pat>>, Option<usize>),
654 /// A reference pattern, e.g. `&mut (a, b)`
655 Ref(P<Pat>, Mutability),
658 /// A range pattern, e.g. `1...2` or `1..2`
659 Range(P<Expr>, P<Expr>, RangeEnd),
660 /// `[a, b, ..i, y, z]` is represented as:
661 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
662 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
665 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
666 pub enum Mutability {
672 /// Return MutMutable only if both arguments are mutable.
673 pub fn and(self, other: Self) -> Self {
676 MutImmutable => MutImmutable,
681 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
683 /// The `+` operator (addition)
685 /// The `-` operator (subtraction)
687 /// The `*` operator (multiplication)
689 /// The `/` operator (division)
691 /// The `%` operator (modulus)
693 /// The `&&` operator (logical and)
695 /// The `||` operator (logical or)
697 /// The `^` operator (bitwise xor)
699 /// The `&` operator (bitwise and)
701 /// The `|` operator (bitwise or)
703 /// The `<<` operator (shift left)
705 /// The `>>` operator (shift right)
707 /// The `==` operator (equality)
709 /// The `<` operator (less than)
711 /// The `<=` operator (less than or equal to)
713 /// The `!=` operator (not equal to)
715 /// The `>=` operator (greater than or equal to)
717 /// The `>` operator (greater than)
722 pub fn as_str(self) -> &'static str {
745 pub fn is_lazy(self) -> bool {
747 BiAnd | BiOr => true,
752 pub fn is_shift(self) -> bool {
754 BiShl | BiShr => true,
759 pub fn is_comparison(self) -> bool {
761 BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
777 /// Returns `true` if the binary operator takes its arguments by value
778 pub fn is_by_value(self) -> bool {
779 !self.is_comparison()
783 pub type BinOp = Spanned<BinOp_>;
785 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
787 /// The `*` operator for dereferencing
789 /// The `!` operator for logical inversion
791 /// The `-` operator for negation
796 pub fn as_str(self) -> &'static str {
804 /// Returns `true` if the unary operator takes its argument by value
805 pub fn is_by_value(self) -> bool {
807 UnNeg | UnNot => true,
814 pub type Stmt = Spanned<Stmt_>;
816 impl fmt::Debug for Stmt_ {
817 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
819 let spanned = codemap::dummy_spanned(self.clone());
823 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
827 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
829 /// Could be an item or a local (let) binding:
830 StmtDecl(P<Decl>, NodeId),
832 /// Expr without trailing semi-colon (must have unit type):
833 StmtExpr(P<Expr>, NodeId),
835 /// Expr with trailing semi-colon (may have any type):
836 StmtSemi(P<Expr>, NodeId),
840 pub fn attrs(&self) -> &[Attribute] {
842 StmtDecl(ref d, _) => d.node.attrs(),
844 StmtSemi(ref e, _) => &e.attrs,
848 pub fn id(&self) -> NodeId {
850 StmtDecl(_, id) => id,
851 StmtExpr(_, id) => id,
852 StmtSemi(_, id) => id,
857 // FIXME (pending discussion of #1697, #2178...): local should really be
858 // a refinement on pat.
859 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
860 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
863 pub ty: Option<P<Ty>>,
864 /// Initializer expression to set the value, if any
865 pub init: Option<P<Expr>>,
869 pub attrs: ThinVec<Attribute>,
870 pub source: LocalSource,
873 pub type Decl = Spanned<Decl_>;
875 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
877 /// A local (let) binding:
884 pub fn attrs(&self) -> &[Attribute] {
886 DeclLocal(ref l) => &l.attrs,
891 pub fn is_local(&self) -> bool {
893 Decl_::DeclLocal(_) => true,
899 /// represents one arm of a 'match'
900 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
902 pub attrs: HirVec<Attribute>,
903 pub pats: HirVec<P<Pat>>,
904 pub guard: Option<P<Expr>>,
908 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
910 pub name: Spanned<Name>,
913 pub is_shorthand: bool,
916 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
917 pub enum BlockCheckMode {
919 UnsafeBlock(UnsafeSource),
920 PushUnsafeBlock(UnsafeSource),
921 PopUnsafeBlock(UnsafeSource),
924 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
925 pub enum UnsafeSource {
930 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
935 /// The body of a function, closure, or constant value. In the case of
936 /// a function, the body contains not only the function body itself
937 /// (which is an expression), but also the argument patterns, since
938 /// those are something that the caller doesn't really care about.
943 /// fn foo((x, y): (u32, u32)) -> u32 {
948 /// Here, the `Body` associated with `foo()` would contain:
950 /// - an `arguments` array containing the `(x, y)` pattern
951 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
952 /// - `is_generator` would be false
954 /// All bodies have an **owner**, which can be accessed via the HIR
955 /// map using `body_owner_def_id()`.
956 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
958 pub arguments: HirVec<Arg>,
960 pub is_generator: bool,
964 pub fn id(&self) -> BodyId {
966 node_id: self.value.id
972 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
977 pub attrs: ThinVec<Attribute>,
981 impl fmt::Debug for Expr {
982 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
983 write!(f, "expr({}: {})", self.id,
984 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
988 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
990 /// A `box x` expression.
992 /// An array (`[a, b, c, d]`)
993 ExprArray(HirVec<Expr>),
996 /// The first field resolves to the function itself (usually an `ExprPath`),
997 /// and the second field is the list of arguments
998 ExprCall(P<Expr>, HirVec<Expr>),
999 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1001 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1002 /// (within the angle brackets).
1003 /// The first element of the vector of `Expr`s is the expression that evaluates
1004 /// to the object on which the method is being called on (the receiver),
1005 /// and the remaining elements are the rest of the arguments.
1006 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1007 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1008 ExprMethodCall(PathSegment, Span, HirVec<Expr>),
1009 /// A tuple (`(a, b, c ,d)`)
1010 ExprTup(HirVec<Expr>),
1011 /// A binary operation (For example: `a + b`, `a * b`)
1012 ExprBinary(BinOp, P<Expr>, P<Expr>),
1013 /// A unary operation (For example: `!x`, `*x`)
1014 ExprUnary(UnOp, P<Expr>),
1015 /// A literal (For example: `1`, `"foo"`)
1017 /// A cast (`foo as f64`)
1018 ExprCast(P<Expr>, P<Ty>),
1019 ExprType(P<Expr>, P<Ty>),
1020 /// An `if` block, with an optional else block
1022 /// `if expr { expr } else { expr }`
1023 ExprIf(P<Expr>, P<Expr>, Option<P<Expr>>),
1024 /// A while loop, with an optional label
1026 /// `'label: while expr { block }`
1027 ExprWhile(P<Expr>, P<Block>, Option<Spanned<Name>>),
1028 /// Conditionless loop (can be exited with break, continue, or return)
1030 /// `'label: loop { block }`
1031 ExprLoop(P<Block>, Option<Spanned<Name>>, LoopSource),
1032 /// A `match` block, with a source that indicates whether or not it is
1033 /// the result of a desugaring, and if so, which kind.
1034 ExprMatch(P<Expr>, HirVec<Arm>, MatchSource),
1035 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1037 /// The final span is the span of the argument block `|...|`
1039 /// This may also be a generator literal, indicated by the final boolean,
1040 /// in that case there is an GeneratorClause.
1041 ExprClosure(CaptureClause, P<FnDecl>, BodyId, Span, bool),
1042 /// A block (`{ ... }`)
1043 ExprBlock(P<Block>),
1045 /// An assignment (`a = foo()`)
1046 ExprAssign(P<Expr>, P<Expr>),
1047 /// An assignment with an operator
1049 /// For example, `a += 1`.
1050 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
1051 /// Access of a named struct field (`obj.foo`)
1052 ExprField(P<Expr>, Spanned<Name>),
1053 /// Access of an unnamed field of a struct or tuple-struct
1055 /// For example, `foo.0`.
1056 ExprTupField(P<Expr>, Spanned<usize>),
1057 /// An indexing operation (`foo[2]`)
1058 ExprIndex(P<Expr>, P<Expr>),
1060 /// Path to a definition, possibly containing lifetime or type parameters.
1063 /// A referencing operation (`&a` or `&mut a`)
1064 ExprAddrOf(Mutability, P<Expr>),
1065 /// A `break`, with an optional label to break
1066 ExprBreak(Destination, Option<P<Expr>>),
1067 /// A `continue`, with an optional label
1068 ExprAgain(Destination),
1069 /// A `return`, with an optional value to be returned
1070 ExprRet(Option<P<Expr>>),
1072 /// Inline assembly (from `asm!`), with its outputs and inputs.
1073 ExprInlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1075 /// A struct or struct-like variant literal expression.
1077 /// For example, `Foo {x: 1, y: 2}`, or
1078 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1079 ExprStruct(QPath, HirVec<Field>, Option<P<Expr>>),
1081 /// An array literal constructed from one repeated element.
1083 /// For example, `[1; 5]`. The first expression is the element
1084 /// to be repeated; the second is the number of times to repeat it.
1085 ExprRepeat(P<Expr>, BodyId),
1087 /// A suspension point for generators. This is `yield <expr>` in Rust.
1091 /// Optionally `Self`-qualified value/type path or associated extension.
1092 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1094 /// Path to a definition, optionally "fully-qualified" with a `Self`
1095 /// type, if the path points to an associated item in a trait.
1097 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1098 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1099 /// even though they both have the same two-segment `Clone::clone` `Path`.
1100 Resolved(Option<P<Ty>>, P<Path>),
1102 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1103 /// Will be resolved by type-checking to an associated item.
1105 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1106 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1107 /// the `X` and `Y` nodes each being a `TyPath(QPath::TypeRelative(..))`.
1108 TypeRelative(P<Ty>, P<PathSegment>)
1111 /// Hints at the original code for a let statement
1112 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1113 pub enum LocalSource {
1114 /// A `match _ { .. }`
1116 /// A desugared `for _ in _ { .. }` loop
1120 /// Hints at the original code for a `match _ { .. }`
1121 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1122 pub enum MatchSource {
1123 /// A `match _ { .. }`
1125 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1127 contains_else_clause: bool,
1129 /// A `while let _ = _ { .. }` (which was desugared to a
1130 /// `loop { match _ { .. } }`)
1132 /// A desugared `for _ in _ { .. }` loop
1134 /// A desugared `?` operator
1138 /// The loop type that yielded an ExprLoop
1139 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1140 pub enum LoopSource {
1141 /// A `loop { .. }` loop
1143 /// A `while let _ = _ { .. }` loop
1145 /// A `for _ in _ { .. }` loop
1149 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1150 pub enum LoopIdError {
1152 UnlabeledCfInWhileCondition,
1156 impl fmt::Display for LoopIdError {
1157 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1158 fmt::Display::fmt(match *self {
1159 LoopIdError::OutsideLoopScope => "not inside loop scope",
1160 LoopIdError::UnlabeledCfInWhileCondition =>
1161 "unlabeled control flow (break or continue) in while condition",
1162 LoopIdError::UnresolvedLabel => "label not found",
1167 // FIXME(cramertj) this should use `Result` once master compiles w/ a vesion of Rust where
1168 // `Result` implements `Encodable`/`Decodable`
1169 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1170 pub enum LoopIdResult {
1174 impl Into<Result<NodeId, LoopIdError>> for LoopIdResult {
1175 fn into(self) -> Result<NodeId, LoopIdError> {
1177 LoopIdResult::Ok(ok) => Ok(ok),
1178 LoopIdResult::Err(err) => Err(err),
1182 impl From<Result<NodeId, LoopIdError>> for LoopIdResult {
1183 fn from(res: Result<NodeId, LoopIdError>) -> Self {
1185 Ok(ok) => LoopIdResult::Ok(ok),
1186 Err(err) => LoopIdResult::Err(err),
1191 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1192 pub enum ScopeTarget {
1198 pub fn opt_id(self) -> Option<NodeId> {
1200 ScopeTarget::Block(node_id) |
1201 ScopeTarget::Loop(LoopIdResult::Ok(node_id)) => Some(node_id),
1202 ScopeTarget::Loop(LoopIdResult::Err(_)) => None,
1207 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1208 pub struct Destination {
1209 // This is `Some(_)` iff there is an explicit user-specified `label
1210 pub ident: Option<Spanned<Ident>>,
1212 // These errors are caught and then reported during the diagnostics pass in
1213 // librustc_passes/loops.rs
1214 pub target_id: ScopeTarget,
1217 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1218 pub enum CaptureClause {
1223 // NB: If you change this, you'll probably want to change the corresponding
1224 // type structure in middle/ty.rs as well.
1225 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1228 pub mutbl: Mutability,
1231 /// Represents a method's signature in a trait declaration or implementation.
1232 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1233 pub struct MethodSig {
1234 pub unsafety: Unsafety,
1235 pub constness: Constness,
1237 pub decl: P<FnDecl>,
1238 pub generics: Generics,
1241 // The bodies for items are stored "out of line", in a separate
1242 // hashmap in the `Crate`. Here we just record the node-id of the item
1243 // so it can fetched later.
1244 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1245 pub struct TraitItemId {
1246 pub node_id: NodeId,
1249 /// Represents an item declaration within a trait declaration,
1250 /// possibly including a default implementation. A trait item is
1251 /// either required (meaning it doesn't have an implementation, just a
1252 /// signature) or provided (meaning it has a default implementation).
1253 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1254 pub struct TraitItem {
1258 pub attrs: HirVec<Attribute>,
1259 pub node: TraitItemKind,
1263 /// A trait method's body (or just argument names).
1264 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1265 pub enum TraitMethod {
1266 /// No default body in the trait, just a signature.
1267 Required(HirVec<Spanned<Name>>),
1269 /// Both signature and body are provided in the trait.
1273 /// Represents a trait method or associated constant or type
1274 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1275 pub enum TraitItemKind {
1276 /// An associated constant with an optional value (otherwise `impl`s
1277 /// must contain a value)
1278 Const(P<Ty>, Option<BodyId>),
1279 /// A method with an optional body
1280 Method(MethodSig, TraitMethod),
1281 /// An associated type with (possibly empty) bounds and optional concrete
1283 Type(TyParamBounds, Option<P<Ty>>),
1286 // The bodies for items are stored "out of line", in a separate
1287 // hashmap in the `Crate`. Here we just record the node-id of the item
1288 // so it can fetched later.
1289 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1290 pub struct ImplItemId {
1291 pub node_id: NodeId,
1294 /// Represents anything within an `impl` block
1295 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1296 pub struct ImplItem {
1300 pub vis: Visibility,
1301 pub defaultness: Defaultness,
1302 pub attrs: HirVec<Attribute>,
1303 pub node: ImplItemKind,
1307 /// Represents different contents within `impl`s
1308 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1309 pub enum ImplItemKind {
1310 /// An associated constant of the given type, set to the constant result
1311 /// of the expression
1312 Const(P<Ty>, BodyId),
1313 /// A method implementation with the given signature and body
1314 Method(MethodSig, BodyId),
1315 /// An associated type
1319 // Bind a type to an associated type: `A=Foo`.
1320 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1321 pub struct TypeBinding {
1329 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1336 impl fmt::Debug for Ty {
1337 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1338 write!(f, "type({})",
1339 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1343 /// Not represented directly in the AST, referred to by name through a ty_path.
1344 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1354 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1355 pub struct BareFnTy {
1356 pub unsafety: Unsafety,
1358 pub lifetimes: HirVec<LifetimeDef>,
1359 pub decl: P<FnDecl>,
1362 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1363 /// The different kinds of types recognized by the compiler
1365 /// A variable length slice (`[T]`)
1367 /// A fixed length array (`[T; n]`)
1368 TyArray(P<Ty>, BodyId),
1369 /// A raw pointer (`*const T` or `*mut T`)
1371 /// A reference (`&'a T` or `&'a mut T`)
1372 TyRptr(Lifetime, MutTy),
1373 /// A bare function (e.g. `fn(usize) -> bool`)
1374 TyBareFn(P<BareFnTy>),
1375 /// The never type (`!`)
1377 /// A tuple (`(A, B, C, D,...)`)
1378 TyTup(HirVec<P<Ty>>),
1379 /// A path to a type definition (`module::module::...::Type`), or an
1380 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1382 /// Type parameters may be stored in each `PathSegment`.
1384 /// A trait object type `Bound1 + Bound2 + Bound3`
1385 /// where `Bound` is a trait or a lifetime.
1386 TyTraitObject(HirVec<PolyTraitRef>, Lifetime),
1387 /// An `impl Bound1 + Bound2 + Bound3` type
1388 /// where `Bound` is a trait or a lifetime.
1389 TyImplTrait(TyParamBounds),
1392 /// TyInfer means the type should be inferred instead of it having been
1393 /// specified. This can appear anywhere in a type.
1395 /// Placeholder for a type that has failed to be defined.
1399 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1400 pub struct InlineAsmOutput {
1401 pub constraint: Symbol,
1403 pub is_indirect: bool,
1406 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1407 pub struct InlineAsm {
1409 pub asm_str_style: StrStyle,
1410 pub outputs: HirVec<InlineAsmOutput>,
1411 pub inputs: HirVec<Symbol>,
1412 pub clobbers: HirVec<Symbol>,
1414 pub alignstack: bool,
1415 pub dialect: AsmDialect,
1416 pub ctxt: SyntaxContext,
1419 /// represents an argument in a function header
1420 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1427 /// Represents the header (not the body) of a function declaration
1428 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1430 pub inputs: HirVec<P<Ty>>,
1431 pub output: FunctionRetTy,
1433 /// True if this function has an `self`, `&self` or `&mut self` receiver
1434 /// (but not a `self: Xxx` one).
1435 pub has_implicit_self: bool,
1438 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1444 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1445 pub enum Constness {
1450 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1451 pub enum Defaultness {
1452 Default { has_value: bool },
1457 pub fn has_value(&self) -> bool {
1459 Defaultness::Default { has_value, .. } => has_value,
1460 Defaultness::Final => true,
1464 pub fn is_final(&self) -> bool {
1465 *self == Defaultness::Final
1468 pub fn is_default(&self) -> bool {
1470 Defaultness::Default { .. } => true,
1476 impl fmt::Display for Unsafety {
1477 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1478 fmt::Display::fmt(match *self {
1479 Unsafety::Normal => "normal",
1480 Unsafety::Unsafe => "unsafe",
1486 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1487 pub enum ImplPolarity {
1488 /// `impl Trait for Type`
1490 /// `impl !Trait for Type`
1494 impl fmt::Debug for ImplPolarity {
1495 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1497 ImplPolarity::Positive => "positive".fmt(f),
1498 ImplPolarity::Negative => "negative".fmt(f),
1504 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1505 pub enum FunctionRetTy {
1506 /// Return type is not specified.
1508 /// Functions default to `()` and
1509 /// closures default to inference. Span points to where return
1510 /// type would be inserted.
1511 DefaultReturn(Span),
1516 impl FunctionRetTy {
1517 pub fn span(&self) -> Span {
1519 DefaultReturn(span) => span,
1520 Return(ref ty) => ty.span,
1525 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1527 /// A span from the first token past `{` to the last token until `}`.
1528 /// For `mod foo;`, the inner span ranges from the first token
1529 /// to the last token in the external file.
1531 pub item_ids: HirVec<ItemId>,
1534 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1535 pub struct ForeignMod {
1537 pub items: HirVec<ForeignItem>,
1540 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1541 pub struct GlobalAsm {
1543 pub ctxt: SyntaxContext,
1546 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1547 pub struct EnumDef {
1548 pub variants: HirVec<Variant>,
1551 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1552 pub struct Variant_ {
1554 pub attrs: HirVec<Attribute>,
1555 pub data: VariantData,
1556 /// Explicit discriminant, eg `Foo = 1`
1557 pub disr_expr: Option<BodyId>,
1560 pub type Variant = Spanned<Variant_>;
1562 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1564 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1565 /// Also produced for each element of a list `use`, e.g.
1566 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1569 /// Glob import, e.g. `use foo::*`.
1572 /// Degenerate list import, e.g. `use foo::{a, b}` produces
1573 /// an additional `use foo::{}` for performing checks such as
1574 /// unstable feature gating. May be removed in the future.
1578 /// TraitRef's appear in impls.
1580 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1581 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1582 /// trait being referred to but just a unique NodeId that serves as a key
1583 /// within the DefMap.
1584 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1585 pub struct TraitRef {
1590 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1591 pub struct PolyTraitRef {
1592 /// The `'a` in `<'a> Foo<&'a T>`
1593 pub bound_lifetimes: HirVec<LifetimeDef>,
1595 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1596 pub trait_ref: TraitRef,
1601 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1602 pub enum Visibility {
1605 Restricted { path: P<Path>, id: NodeId },
1610 pub fn is_pub_restricted(&self) -> bool {
1611 use self::Visibility::*;
1614 &Inherited => false,
1616 &Restricted { .. } => true,
1621 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1622 pub struct StructField {
1625 pub vis: Visibility,
1628 pub attrs: HirVec<Attribute>,
1632 // Still necessary in couple of places
1633 pub fn is_positional(&self) -> bool {
1634 let first = self.name.as_str().as_bytes()[0];
1635 first >= b'0' && first <= b'9'
1639 /// Fields and Ids of enum variants and structs
1641 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1642 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1643 /// One shared Id can be successfully used for these two purposes.
1644 /// Id of the whole enum lives in `Item`.
1646 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1647 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1648 /// the variant itself" from enum variants.
1649 /// Id of the whole struct lives in `Item`.
1650 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1651 pub enum VariantData {
1652 Struct(HirVec<StructField>, NodeId),
1653 Tuple(HirVec<StructField>, NodeId),
1658 pub fn fields(&self) -> &[StructField] {
1660 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1664 pub fn id(&self) -> NodeId {
1666 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
1669 pub fn is_struct(&self) -> bool {
1670 if let VariantData::Struct(..) = *self {
1676 pub fn is_tuple(&self) -> bool {
1677 if let VariantData::Tuple(..) = *self {
1683 pub fn is_unit(&self) -> bool {
1684 if let VariantData::Unit(..) = *self {
1692 // The bodies for items are stored "out of line", in a separate
1693 // hashmap in the `Crate`. Here we just record the node-id of the item
1694 // so it can fetched later.
1695 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1702 /// The name might be a dummy name in case of anonymous items
1703 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1708 pub attrs: HirVec<Attribute>,
1710 pub vis: Visibility,
1714 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1716 /// An `extern crate` item, with optional original crate name,
1718 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1719 ItemExternCrate(Option<Name>),
1721 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
1725 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
1726 ItemUse(P<Path>, UseKind),
1729 ItemStatic(P<Ty>, Mutability, BodyId),
1731 ItemConst(P<Ty>, BodyId),
1732 /// A function declaration
1733 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, BodyId),
1736 /// An external module
1737 ItemForeignMod(ForeignMod),
1738 /// Module-level inline assembly (from global_asm!)
1739 ItemGlobalAsm(P<GlobalAsm>),
1740 /// A type alias, e.g. `type Foo = Bar<u8>`
1741 ItemTy(P<Ty>, Generics),
1742 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1743 ItemEnum(EnumDef, Generics),
1744 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1745 ItemStruct(VariantData, Generics),
1746 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
1747 ItemUnion(VariantData, Generics),
1748 /// Represents a Trait Declaration
1749 ItemTrait(Unsafety, Generics, TyParamBounds, HirVec<TraitItemRef>),
1751 // Default trait implementations
1753 /// `impl Trait for .. {}`
1754 ItemDefaultImpl(Unsafety, TraitRef),
1755 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1760 Option<TraitRef>, // (optional) trait this impl implements
1762 HirVec<ImplItemRef>),
1766 pub fn descriptive_variant(&self) -> &str {
1768 ItemExternCrate(..) => "extern crate",
1769 ItemUse(..) => "use",
1770 ItemStatic(..) => "static item",
1771 ItemConst(..) => "constant item",
1772 ItemFn(..) => "function",
1773 ItemMod(..) => "module",
1774 ItemForeignMod(..) => "foreign module",
1775 ItemGlobalAsm(..) => "global asm",
1776 ItemTy(..) => "type alias",
1777 ItemEnum(..) => "enum",
1778 ItemStruct(..) => "struct",
1779 ItemUnion(..) => "union",
1780 ItemTrait(..) => "trait",
1782 ItemDefaultImpl(..) => "item",
1786 pub fn adt_kind(&self) -> Option<AdtKind> {
1788 ItemStruct(..) => Some(AdtKind::Struct),
1789 ItemUnion(..) => Some(AdtKind::Union),
1790 ItemEnum(..) => Some(AdtKind::Enum),
1796 /// A reference from an trait to one of its associated items. This
1797 /// contains the item's id, naturally, but also the item's name and
1798 /// some other high-level details (like whether it is an associated
1799 /// type or method, and whether it is public). This allows other
1800 /// passes to find the impl they want without loading the id (which
1801 /// means fewer edges in the incremental compilation graph).
1802 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1803 pub struct TraitItemRef {
1804 pub id: TraitItemId,
1806 pub kind: AssociatedItemKind,
1808 pub defaultness: Defaultness,
1811 /// A reference from an impl to one of its associated items. This
1812 /// contains the item's id, naturally, but also the item's name and
1813 /// some other high-level details (like whether it is an associated
1814 /// type or method, and whether it is public). This allows other
1815 /// passes to find the impl they want without loading the id (which
1816 /// means fewer edges in the incremental compilation graph).
1817 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1818 pub struct ImplItemRef {
1821 pub kind: AssociatedItemKind,
1823 pub vis: Visibility,
1824 pub defaultness: Defaultness,
1827 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1828 pub enum AssociatedItemKind {
1830 Method { has_self: bool },
1834 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1835 pub struct ForeignItem {
1837 pub attrs: HirVec<Attribute>,
1838 pub node: ForeignItem_,
1841 pub vis: Visibility,
1844 /// An item within an `extern` block
1845 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1846 pub enum ForeignItem_ {
1847 /// A foreign function
1848 ForeignItemFn(P<FnDecl>, HirVec<Spanned<Name>>, Generics),
1849 /// A foreign static item (`static ext: u8`), with optional mutability
1850 /// (the boolean is true when mutable)
1851 ForeignItemStatic(P<Ty>, bool),
1855 pub fn descriptive_variant(&self) -> &str {
1857 ForeignItemFn(..) => "foreign function",
1858 ForeignItemStatic(..) => "foreign static item",
1863 /// A free variable referred to in a function.
1864 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
1865 pub struct Freevar {
1866 /// The variable being accessed free.
1869 // First span where it is accessed (there can be multiple).
1874 pub fn var_id(&self) -> NodeId {
1876 Def::Local(id) | Def::Upvar(id, ..) => id,
1877 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
1882 pub type FreevarMap = NodeMap<Vec<Freevar>>;
1884 pub type CaptureModeMap = NodeMap<CaptureClause>;
1886 #[derive(Clone, Debug)]
1887 pub struct TraitCandidate {
1889 pub import_id: Option<NodeId>,
1892 // Trait method resolution
1893 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
1895 // Map from the NodeId of a glob import to a list of items which are actually
1897 pub type GlobMap = NodeMap<FxHashSet<Name>>;