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`.
148 pub name: LifetimeName,
151 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
152 pub enum LifetimeName {
160 pub fn name(&self) -> Name {
161 use self::LifetimeName::*;
163 Implicit => keywords::Invalid.name(),
164 Underscore => Symbol::intern("'_"),
165 Static => keywords::StaticLifetime.name(),
171 impl fmt::Debug for Lifetime {
172 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
176 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
181 pub fn is_elided(&self) -> bool {
182 use self::LifetimeName::*;
184 Implicit | Underscore => true,
185 Static | Name(_) => false,
189 pub fn is_static(&self) -> bool {
190 self.name == LifetimeName::Static
194 /// A lifetime definition, eg `'a: 'b+'c+'d`
195 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
196 pub struct LifetimeDef {
197 pub lifetime: Lifetime,
198 pub bounds: HirVec<Lifetime>,
199 pub pure_wrt_drop: bool,
202 /// A "Path" is essentially Rust's notion of a name; for instance:
203 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
204 /// along with a bunch of supporting information.
205 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
208 /// The definition that the path resolved to.
210 /// The segments in the path: the things separated by `::`.
211 pub segments: HirVec<PathSegment>,
215 pub fn is_global(&self) -> bool {
216 !self.segments.is_empty() && self.segments[0].name == keywords::CrateRoot.name()
220 impl fmt::Debug for Path {
221 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
222 write!(f, "path({})",
223 print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
227 /// A segment of a path: an identifier, an optional lifetime, and a set of
229 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
230 pub struct PathSegment {
231 /// The identifier portion of this path segment.
234 /// Type/lifetime parameters attached to this path. They come in
235 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
236 /// this is more than just simple syntactic sugar; the use of
237 /// parens affects the region binding rules, so we preserve the
239 pub parameters: PathParameters,
243 /// Convert an identifier to the corresponding segment.
244 pub fn from_name(name: Name) -> PathSegment {
247 parameters: PathParameters::none()
252 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
253 pub struct PathParameters {
254 /// The lifetime parameters for this path segment.
255 pub lifetimes: HirVec<Lifetime>,
256 /// The type parameters for this path segment, if present.
257 pub types: HirVec<P<Ty>>,
258 /// Whether to infer remaining type parameters, if any.
259 /// This only applies to expression and pattern paths, and
260 /// out of those only the segments with no type parameters
261 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
262 pub infer_types: bool,
263 /// Bindings (equality constraints) on associated types, if present.
264 /// E.g., `Foo<A=Bar>`.
265 pub bindings: HirVec<TypeBinding>,
266 /// Were parameters written in parenthesized form `Fn(T) -> U`?
267 /// This is required mostly for pretty-printing and diagnostics,
268 /// but also for changing lifetime elision rules to be "function-like".
269 pub parenthesized: bool,
272 impl PathParameters {
273 pub fn none() -> Self {
275 lifetimes: HirVec::new(),
276 types: HirVec::new(),
278 bindings: HirVec::new(),
279 parenthesized: false,
283 pub fn inputs(&self) -> &[P<Ty>] {
284 if self.parenthesized {
285 if let Some(ref ty) = self.types.get(0) {
286 if let TyTup(ref tys) = ty.node {
291 bug!("PathParameters::inputs: not a `Fn(T) -> U`");
295 /// The AST represents all type param bounds as types.
296 /// typeck::collect::compute_bounds matches these against
297 /// the "special" built-in traits (see middle::lang_items) and
298 /// detects Copy, Send and Sync.
299 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
300 pub enum TyParamBound {
301 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
302 RegionTyParamBound(Lifetime),
305 /// A modifier on a bound, currently this is only used for `?Sized`, where the
306 /// modifier is `Maybe`. Negative bounds should also be handled here.
307 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
308 pub enum TraitBoundModifier {
313 pub type TyParamBounds = HirVec<TyParamBound>;
315 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
319 pub bounds: TyParamBounds,
320 pub default: Option<P<Ty>>,
322 pub pure_wrt_drop: bool,
325 /// Represents lifetimes and type parameters attached to a declaration
326 /// of a function, enum, trait, etc.
327 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
328 pub struct Generics {
329 pub lifetimes: HirVec<LifetimeDef>,
330 pub ty_params: HirVec<TyParam>,
331 pub where_clause: WhereClause,
336 pub fn empty() -> Generics {
338 lifetimes: HirVec::new(),
339 ty_params: HirVec::new(),
340 where_clause: WhereClause {
342 predicates: HirVec::new(),
348 pub fn is_lt_parameterized(&self) -> bool {
349 !self.lifetimes.is_empty()
352 pub fn is_type_parameterized(&self) -> bool {
353 !self.ty_params.is_empty()
356 pub fn is_parameterized(&self) -> bool {
357 self.is_lt_parameterized() || self.is_type_parameterized()
361 pub enum UnsafeGeneric {
362 Region(LifetimeDef, &'static str),
363 Type(TyParam, &'static str),
367 pub fn attr_name(&self) -> &'static str {
369 UnsafeGeneric::Region(_, s) => s,
370 UnsafeGeneric::Type(_, s) => s,
376 pub fn carries_unsafe_attr(&self) -> Option<UnsafeGeneric> {
377 for r in &self.lifetimes {
379 return Some(UnsafeGeneric::Region(r.clone(), "may_dangle"));
382 for t in &self.ty_params {
384 return Some(UnsafeGeneric::Type(t.clone(), "may_dangle"));
391 /// A `where` clause in a definition
392 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
393 pub struct WhereClause {
395 pub predicates: HirVec<WherePredicate>,
398 /// A single predicate in a `where` clause
399 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
400 pub enum WherePredicate {
401 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
402 BoundPredicate(WhereBoundPredicate),
403 /// A lifetime predicate, e.g. `'a: 'b+'c`
404 RegionPredicate(WhereRegionPredicate),
405 /// An equality predicate (unsupported)
406 EqPredicate(WhereEqPredicate),
409 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
410 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
411 pub struct WhereBoundPredicate {
413 /// Any lifetimes from a `for` binding
414 pub bound_lifetimes: HirVec<LifetimeDef>,
415 /// The type being bounded
416 pub bounded_ty: P<Ty>,
417 /// Trait and lifetime bounds (`Clone+Send+'static`)
418 pub bounds: TyParamBounds,
421 /// A lifetime predicate, e.g. `'a: 'b+'c`
422 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
423 pub struct WhereRegionPredicate {
425 pub lifetime: Lifetime,
426 pub bounds: HirVec<Lifetime>,
429 /// An equality predicate (unsupported), e.g. `T=int`
430 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
431 pub struct WhereEqPredicate {
438 pub type CrateConfig = HirVec<P<MetaItem>>;
440 /// The top-level data structure that stores the entire contents of
441 /// the crate currently being compiled.
443 /// For more details, see [the module-level README](README.md).
444 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
447 pub attrs: HirVec<Attribute>,
449 pub exported_macros: HirVec<MacroDef>,
451 // NB: We use a BTreeMap here so that `visit_all_items` iterates
452 // over the ids in increasing order. In principle it should not
453 // matter what order we visit things in, but in *practice* it
454 // does, because it can affect the order in which errors are
455 // detected, which in turn can make compile-fail tests yield
456 // slightly different results.
457 pub items: BTreeMap<NodeId, Item>,
459 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
460 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
461 pub bodies: BTreeMap<BodyId, Body>,
462 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
463 pub trait_default_impl: BTreeMap<DefId, NodeId>,
465 /// A list of the body ids written out in the order in which they
466 /// appear in the crate. If you're going to process all the bodies
467 /// in the crate, you should iterate over this list rather than the keys
469 pub body_ids: Vec<BodyId>,
473 pub fn item(&self, id: NodeId) -> &Item {
477 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
478 &self.trait_items[&id]
481 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
482 &self.impl_items[&id]
485 /// Visits all items in the crate in some deterministic (but
486 /// unspecified) order. If you just need to process every item,
487 /// but don't care about nesting, this method is the best choice.
489 /// If you do care about nesting -- usually because your algorithm
490 /// follows lexical scoping rules -- then you want a different
491 /// approach. You should override `visit_nested_item` in your
492 /// visitor and then call `intravisit::walk_crate` instead.
493 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
494 where V: itemlikevisit::ItemLikeVisitor<'hir>
496 for (_, item) in &self.items {
497 visitor.visit_item(item);
500 for (_, trait_item) in &self.trait_items {
501 visitor.visit_trait_item(trait_item);
504 for (_, impl_item) in &self.impl_items {
505 visitor.visit_impl_item(impl_item);
509 pub fn body(&self, id: BodyId) -> &Body {
514 /// A macro definition, in this crate or imported from another.
516 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
517 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
518 pub struct MacroDef {
521 pub attrs: HirVec<Attribute>,
524 pub body: TokenStream,
528 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
530 /// Statements in a block
531 pub stmts: HirVec<Stmt>,
532 /// An expression at the end of the block
533 /// without a semicolon, if any
534 pub expr: Option<P<Expr>>,
537 /// Distinguishes between `unsafe { ... }` and `{ ... }`
538 pub rules: BlockCheckMode,
540 /// If true, then there may exist `break 'a` values that aim to
541 /// break out of this block early. As of this writing, this is not
542 /// currently permitted in Rust itself, but it is generated as
543 /// part of `catch` statements.
544 pub targeted_by_break: bool,
547 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
555 impl fmt::Debug for Pat {
556 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
557 write!(f, "pat({}: {})", self.id,
558 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
563 // FIXME(#19596) this is a workaround, but there should be a better way
564 fn walk_<G>(&self, it: &mut G) -> bool
565 where G: FnMut(&Pat) -> bool
572 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
573 PatKind::Struct(_, ref fields, _) => {
574 fields.iter().all(|field| field.node.pat.walk_(it))
576 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
577 s.iter().all(|p| p.walk_(it))
579 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
582 PatKind::Slice(ref before, ref slice, ref after) => {
583 before.iter().all(|p| p.walk_(it)) &&
584 slice.iter().all(|p| p.walk_(it)) &&
585 after.iter().all(|p| p.walk_(it))
590 PatKind::Binding(..) |
591 PatKind::Path(_) => {
597 pub fn walk<F>(&self, mut it: F) -> bool
598 where F: FnMut(&Pat) -> bool
604 /// A single field in a struct pattern
606 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
607 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
608 /// except is_shorthand is true
609 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
610 pub struct FieldPat {
611 /// The identifier for the field
613 /// The pattern the field is destructured to
615 pub is_shorthand: bool,
618 /// Explicit binding annotations given in the HIR for a binding. Note
619 /// that this is not the final binding *mode* that we infer after type
621 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
622 pub enum BindingAnnotation {
623 /// No binding annotation given: this means that the final binding mode
624 /// will depend on whether we have skipped through a `&` reference
625 /// when matching. For example, the `x` in `Some(x)` will have binding
626 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
627 /// ultimately be inferred to be by-reference.
629 /// Note that implicit reference skipping is not implemented yet (#42640).
632 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
635 /// Annotated as `ref`, like `ref x`
638 /// Annotated as `ref mut x`.
642 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
648 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
650 /// Represents a wildcard pattern (`_`)
653 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
654 /// The `NodeId` is the canonical ID for the variable being bound,
655 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
656 /// which is the pattern ID of the first `x`.
657 Binding(BindingAnnotation, NodeId, Spanned<Name>, Option<P<Pat>>),
659 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
660 /// The `bool` is `true` in the presence of a `..`.
661 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
663 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
664 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
665 /// 0 <= position <= subpats.len()
666 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
668 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
671 /// A tuple pattern `(a, b)`.
672 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
673 /// 0 <= position <= subpats.len()
674 Tuple(HirVec<P<Pat>>, Option<usize>),
677 /// A reference pattern, e.g. `&mut (a, b)`
678 Ref(P<Pat>, Mutability),
681 /// A range pattern, e.g. `1...2` or `1..2`
682 Range(P<Expr>, P<Expr>, RangeEnd),
683 /// `[a, b, ..i, y, z]` is represented as:
684 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
685 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
688 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
689 pub enum Mutability {
695 /// Return MutMutable only if both arguments are mutable.
696 pub fn and(self, other: Self) -> Self {
699 MutImmutable => MutImmutable,
704 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
706 /// The `+` operator (addition)
708 /// The `-` operator (subtraction)
710 /// The `*` operator (multiplication)
712 /// The `/` operator (division)
714 /// The `%` operator (modulus)
716 /// The `&&` operator (logical and)
718 /// The `||` operator (logical or)
720 /// The `^` operator (bitwise xor)
722 /// The `&` operator (bitwise and)
724 /// The `|` operator (bitwise or)
726 /// The `<<` operator (shift left)
728 /// The `>>` operator (shift right)
730 /// The `==` operator (equality)
732 /// The `<` operator (less than)
734 /// The `<=` operator (less than or equal to)
736 /// The `!=` operator (not equal to)
738 /// The `>=` operator (greater than or equal to)
740 /// The `>` operator (greater than)
745 pub fn as_str(self) -> &'static str {
768 pub fn is_lazy(self) -> bool {
770 BiAnd | BiOr => true,
775 pub fn is_shift(self) -> bool {
777 BiShl | BiShr => true,
782 pub fn is_comparison(self) -> bool {
784 BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
800 /// Returns `true` if the binary operator takes its arguments by value
801 pub fn is_by_value(self) -> bool {
802 !self.is_comparison()
806 pub type BinOp = Spanned<BinOp_>;
808 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
810 /// The `*` operator for dereferencing
812 /// The `!` operator for logical inversion
814 /// The `-` operator for negation
819 pub fn as_str(self) -> &'static str {
827 /// Returns `true` if the unary operator takes its argument by value
828 pub fn is_by_value(self) -> bool {
830 UnNeg | UnNot => true,
837 pub type Stmt = Spanned<Stmt_>;
839 impl fmt::Debug for Stmt_ {
840 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
842 let spanned = codemap::dummy_spanned(self.clone());
846 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
850 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
852 /// Could be an item or a local (let) binding:
853 StmtDecl(P<Decl>, NodeId),
855 /// Expr without trailing semi-colon (must have unit type):
856 StmtExpr(P<Expr>, NodeId),
858 /// Expr with trailing semi-colon (may have any type):
859 StmtSemi(P<Expr>, NodeId),
863 pub fn attrs(&self) -> &[Attribute] {
865 StmtDecl(ref d, _) => d.node.attrs(),
867 StmtSemi(ref e, _) => &e.attrs,
871 pub fn id(&self) -> NodeId {
873 StmtDecl(_, id) => id,
874 StmtExpr(_, id) => id,
875 StmtSemi(_, id) => id,
880 // FIXME (pending discussion of #1697, #2178...): local should really be
881 // a refinement on pat.
882 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
883 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
886 pub ty: Option<P<Ty>>,
887 /// Initializer expression to set the value, if any
888 pub init: Option<P<Expr>>,
892 pub attrs: ThinVec<Attribute>,
893 pub source: LocalSource,
896 pub type Decl = Spanned<Decl_>;
898 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
900 /// A local (let) binding:
907 pub fn attrs(&self) -> &[Attribute] {
909 DeclLocal(ref l) => &l.attrs,
914 pub fn is_local(&self) -> bool {
916 Decl_::DeclLocal(_) => true,
922 /// represents one arm of a 'match'
923 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
925 pub attrs: HirVec<Attribute>,
926 pub pats: HirVec<P<Pat>>,
927 pub guard: Option<P<Expr>>,
931 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
933 pub name: Spanned<Name>,
936 pub is_shorthand: bool,
939 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
940 pub enum BlockCheckMode {
942 UnsafeBlock(UnsafeSource),
943 PushUnsafeBlock(UnsafeSource),
944 PopUnsafeBlock(UnsafeSource),
947 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
948 pub enum UnsafeSource {
953 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
958 /// The body of a function, closure, or constant value. In the case of
959 /// a function, the body contains not only the function body itself
960 /// (which is an expression), but also the argument patterns, since
961 /// those are something that the caller doesn't really care about.
966 /// fn foo((x, y): (u32, u32)) -> u32 {
971 /// Here, the `Body` associated with `foo()` would contain:
973 /// - an `arguments` array containing the `(x, y)` pattern
974 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
975 /// - `is_generator` would be false
977 /// All bodies have an **owner**, which can be accessed via the HIR
978 /// map using `body_owner_def_id()`.
979 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
981 pub arguments: HirVec<Arg>,
983 pub is_generator: bool,
987 pub fn id(&self) -> BodyId {
989 node_id: self.value.id
995 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1000 pub attrs: ThinVec<Attribute>,
1004 impl fmt::Debug for Expr {
1005 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1006 write!(f, "expr({}: {})", self.id,
1007 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1011 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1013 /// A `box x` expression.
1015 /// An array (`[a, b, c, d]`)
1016 ExprArray(HirVec<Expr>),
1019 /// The first field resolves to the function itself (usually an `ExprPath`),
1020 /// and the second field is the list of arguments
1021 ExprCall(P<Expr>, HirVec<Expr>),
1022 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1024 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1025 /// (within the angle brackets).
1026 /// The first element of the vector of `Expr`s is the expression that evaluates
1027 /// to the object on which the method is being called on (the receiver),
1028 /// and the remaining elements are the rest of the arguments.
1029 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1030 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1031 ExprMethodCall(PathSegment, Span, HirVec<Expr>),
1032 /// A tuple (`(a, b, c ,d)`)
1033 ExprTup(HirVec<Expr>),
1034 /// A binary operation (For example: `a + b`, `a * b`)
1035 ExprBinary(BinOp, P<Expr>, P<Expr>),
1036 /// A unary operation (For example: `!x`, `*x`)
1037 ExprUnary(UnOp, P<Expr>),
1038 /// A literal (For example: `1`, `"foo"`)
1040 /// A cast (`foo as f64`)
1041 ExprCast(P<Expr>, P<Ty>),
1042 ExprType(P<Expr>, P<Ty>),
1043 /// An `if` block, with an optional else block
1045 /// `if expr { expr } else { expr }`
1046 ExprIf(P<Expr>, P<Expr>, Option<P<Expr>>),
1047 /// A while loop, with an optional label
1049 /// `'label: while expr { block }`
1050 ExprWhile(P<Expr>, P<Block>, Option<Spanned<Name>>),
1051 /// Conditionless loop (can be exited with break, continue, or return)
1053 /// `'label: loop { block }`
1054 ExprLoop(P<Block>, Option<Spanned<Name>>, LoopSource),
1055 /// A `match` block, with a source that indicates whether or not it is
1056 /// the result of a desugaring, and if so, which kind.
1057 ExprMatch(P<Expr>, HirVec<Arm>, MatchSource),
1058 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1060 /// The final span is the span of the argument block `|...|`
1062 /// This may also be a generator literal, indicated by the final boolean,
1063 /// in that case there is an GeneratorClause.
1064 ExprClosure(CaptureClause, P<FnDecl>, BodyId, Span, bool),
1065 /// A block (`{ ... }`)
1066 ExprBlock(P<Block>),
1068 /// An assignment (`a = foo()`)
1069 ExprAssign(P<Expr>, P<Expr>),
1070 /// An assignment with an operator
1072 /// For example, `a += 1`.
1073 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
1074 /// Access of a named struct field (`obj.foo`)
1075 ExprField(P<Expr>, Spanned<Name>),
1076 /// Access of an unnamed field of a struct or tuple-struct
1078 /// For example, `foo.0`.
1079 ExprTupField(P<Expr>, Spanned<usize>),
1080 /// An indexing operation (`foo[2]`)
1081 ExprIndex(P<Expr>, P<Expr>),
1083 /// Path to a definition, possibly containing lifetime or type parameters.
1086 /// A referencing operation (`&a` or `&mut a`)
1087 ExprAddrOf(Mutability, P<Expr>),
1088 /// A `break`, with an optional label to break
1089 ExprBreak(Destination, Option<P<Expr>>),
1090 /// A `continue`, with an optional label
1091 ExprAgain(Destination),
1092 /// A `return`, with an optional value to be returned
1093 ExprRet(Option<P<Expr>>),
1095 /// Inline assembly (from `asm!`), with its outputs and inputs.
1096 ExprInlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1098 /// A struct or struct-like variant literal expression.
1100 /// For example, `Foo {x: 1, y: 2}`, or
1101 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1102 ExprStruct(QPath, HirVec<Field>, Option<P<Expr>>),
1104 /// An array literal constructed from one repeated element.
1106 /// For example, `[1; 5]`. The first expression is the element
1107 /// to be repeated; the second is the number of times to repeat it.
1108 ExprRepeat(P<Expr>, BodyId),
1110 /// A suspension point for generators. This is `yield <expr>` in Rust.
1114 /// Optionally `Self`-qualified value/type path or associated extension.
1115 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1117 /// Path to a definition, optionally "fully-qualified" with a `Self`
1118 /// type, if the path points to an associated item in a trait.
1120 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1121 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1122 /// even though they both have the same two-segment `Clone::clone` `Path`.
1123 Resolved(Option<P<Ty>>, P<Path>),
1125 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1126 /// Will be resolved by type-checking to an associated item.
1128 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1129 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1130 /// the `X` and `Y` nodes each being a `TyPath(QPath::TypeRelative(..))`.
1131 TypeRelative(P<Ty>, P<PathSegment>)
1134 /// Hints at the original code for a let statement
1135 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1136 pub enum LocalSource {
1137 /// A `match _ { .. }`
1139 /// A desugared `for _ in _ { .. }` loop
1143 /// Hints at the original code for a `match _ { .. }`
1144 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1145 pub enum MatchSource {
1146 /// A `match _ { .. }`
1148 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1150 contains_else_clause: bool,
1152 /// A `while let _ = _ { .. }` (which was desugared to a
1153 /// `loop { match _ { .. } }`)
1155 /// A desugared `for _ in _ { .. }` loop
1157 /// A desugared `?` operator
1161 /// The loop type that yielded an ExprLoop
1162 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1163 pub enum LoopSource {
1164 /// A `loop { .. }` loop
1166 /// A `while let _ = _ { .. }` loop
1168 /// A `for _ in _ { .. }` loop
1172 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1173 pub enum LoopIdError {
1175 UnlabeledCfInWhileCondition,
1179 impl fmt::Display for LoopIdError {
1180 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1181 fmt::Display::fmt(match *self {
1182 LoopIdError::OutsideLoopScope => "not inside loop scope",
1183 LoopIdError::UnlabeledCfInWhileCondition =>
1184 "unlabeled control flow (break or continue) in while condition",
1185 LoopIdError::UnresolvedLabel => "label not found",
1190 // FIXME(cramertj) this should use `Result` once master compiles w/ a vesion of Rust where
1191 // `Result` implements `Encodable`/`Decodable`
1192 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1193 pub enum LoopIdResult {
1197 impl Into<Result<NodeId, LoopIdError>> for LoopIdResult {
1198 fn into(self) -> Result<NodeId, LoopIdError> {
1200 LoopIdResult::Ok(ok) => Ok(ok),
1201 LoopIdResult::Err(err) => Err(err),
1205 impl From<Result<NodeId, LoopIdError>> for LoopIdResult {
1206 fn from(res: Result<NodeId, LoopIdError>) -> Self {
1208 Ok(ok) => LoopIdResult::Ok(ok),
1209 Err(err) => LoopIdResult::Err(err),
1214 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1215 pub enum ScopeTarget {
1221 pub fn opt_id(self) -> Option<NodeId> {
1223 ScopeTarget::Block(node_id) |
1224 ScopeTarget::Loop(LoopIdResult::Ok(node_id)) => Some(node_id),
1225 ScopeTarget::Loop(LoopIdResult::Err(_)) => None,
1230 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1231 pub struct Destination {
1232 // This is `Some(_)` iff there is an explicit user-specified `label
1233 pub ident: Option<Spanned<Ident>>,
1235 // These errors are caught and then reported during the diagnostics pass in
1236 // librustc_passes/loops.rs
1237 pub target_id: ScopeTarget,
1240 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1241 pub enum CaptureClause {
1246 // NB: If you change this, you'll probably want to change the corresponding
1247 // type structure in middle/ty.rs as well.
1248 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1251 pub mutbl: Mutability,
1254 /// Represents a method's signature in a trait declaration or implementation.
1255 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1256 pub struct MethodSig {
1257 pub unsafety: Unsafety,
1258 pub constness: Constness,
1260 pub decl: P<FnDecl>,
1261 pub generics: Generics,
1264 // The bodies for items are stored "out of line", in a separate
1265 // hashmap in the `Crate`. Here we just record the node-id of the item
1266 // so it can fetched later.
1267 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1268 pub struct TraitItemId {
1269 pub node_id: NodeId,
1272 /// Represents an item declaration within a trait declaration,
1273 /// possibly including a default implementation. A trait item is
1274 /// either required (meaning it doesn't have an implementation, just a
1275 /// signature) or provided (meaning it has a default implementation).
1276 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1277 pub struct TraitItem {
1281 pub attrs: HirVec<Attribute>,
1282 pub node: TraitItemKind,
1286 /// A trait method's body (or just argument names).
1287 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1288 pub enum TraitMethod {
1289 /// No default body in the trait, just a signature.
1290 Required(HirVec<Spanned<Name>>),
1292 /// Both signature and body are provided in the trait.
1296 /// Represents a trait method or associated constant or type
1297 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1298 pub enum TraitItemKind {
1299 /// An associated constant with an optional value (otherwise `impl`s
1300 /// must contain a value)
1301 Const(P<Ty>, Option<BodyId>),
1302 /// A method with an optional body
1303 Method(MethodSig, TraitMethod),
1304 /// An associated type with (possibly empty) bounds and optional concrete
1306 Type(TyParamBounds, Option<P<Ty>>),
1309 // The bodies for items are stored "out of line", in a separate
1310 // hashmap in the `Crate`. Here we just record the node-id of the item
1311 // so it can fetched later.
1312 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1313 pub struct ImplItemId {
1314 pub node_id: NodeId,
1317 /// Represents anything within an `impl` block
1318 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1319 pub struct ImplItem {
1323 pub vis: Visibility,
1324 pub defaultness: Defaultness,
1325 pub attrs: HirVec<Attribute>,
1326 pub node: ImplItemKind,
1330 /// Represents different contents within `impl`s
1331 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1332 pub enum ImplItemKind {
1333 /// An associated constant of the given type, set to the constant result
1334 /// of the expression
1335 Const(P<Ty>, BodyId),
1336 /// A method implementation with the given signature and body
1337 Method(MethodSig, BodyId),
1338 /// An associated type
1342 // Bind a type to an associated type: `A=Foo`.
1343 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1344 pub struct TypeBinding {
1352 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1360 impl fmt::Debug for Ty {
1361 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1362 write!(f, "type({})",
1363 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1367 /// Not represented directly in the AST, referred to by name through a ty_path.
1368 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1378 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1379 pub struct BareFnTy {
1380 pub unsafety: Unsafety,
1382 pub lifetimes: HirVec<LifetimeDef>,
1383 pub decl: P<FnDecl>,
1386 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1387 /// The different kinds of types recognized by the compiler
1389 /// A variable length slice (`[T]`)
1391 /// A fixed length array (`[T; n]`)
1392 TyArray(P<Ty>, BodyId),
1393 /// A raw pointer (`*const T` or `*mut T`)
1395 /// A reference (`&'a T` or `&'a mut T`)
1396 TyRptr(Lifetime, MutTy),
1397 /// A bare function (e.g. `fn(usize) -> bool`)
1398 TyBareFn(P<BareFnTy>),
1399 /// The never type (`!`)
1401 /// A tuple (`(A, B, C, D,...)`)
1402 TyTup(HirVec<P<Ty>>),
1403 /// A path to a type definition (`module::module::...::Type`), or an
1404 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1406 /// Type parameters may be stored in each `PathSegment`.
1408 /// A trait object type `Bound1 + Bound2 + Bound3`
1409 /// where `Bound` is a trait or a lifetime.
1410 TyTraitObject(HirVec<PolyTraitRef>, Lifetime),
1411 /// An `impl Bound1 + Bound2 + Bound3` type
1412 /// where `Bound` is a trait or a lifetime.
1413 TyImplTrait(TyParamBounds),
1416 /// TyInfer means the type should be inferred instead of it having been
1417 /// specified. This can appear anywhere in a type.
1419 /// Placeholder for a type that has failed to be defined.
1423 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1424 pub struct InlineAsmOutput {
1425 pub constraint: Symbol,
1427 pub is_indirect: bool,
1430 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1431 pub struct InlineAsm {
1433 pub asm_str_style: StrStyle,
1434 pub outputs: HirVec<InlineAsmOutput>,
1435 pub inputs: HirVec<Symbol>,
1436 pub clobbers: HirVec<Symbol>,
1438 pub alignstack: bool,
1439 pub dialect: AsmDialect,
1440 pub ctxt: SyntaxContext,
1443 /// represents an argument in a function header
1444 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1451 /// Represents the header (not the body) of a function declaration
1452 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1454 pub inputs: HirVec<P<Ty>>,
1455 pub output: FunctionRetTy,
1457 /// True if this function has an `self`, `&self` or `&mut self` receiver
1458 /// (but not a `self: Xxx` one).
1459 pub has_implicit_self: bool,
1462 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1468 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1469 pub enum Constness {
1474 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1475 pub enum Defaultness {
1476 Default { has_value: bool },
1481 pub fn has_value(&self) -> bool {
1483 Defaultness::Default { has_value, .. } => has_value,
1484 Defaultness::Final => true,
1488 pub fn is_final(&self) -> bool {
1489 *self == Defaultness::Final
1492 pub fn is_default(&self) -> bool {
1494 Defaultness::Default { .. } => true,
1500 impl fmt::Display for Unsafety {
1501 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1502 fmt::Display::fmt(match *self {
1503 Unsafety::Normal => "normal",
1504 Unsafety::Unsafe => "unsafe",
1510 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1511 pub enum ImplPolarity {
1512 /// `impl Trait for Type`
1514 /// `impl !Trait for Type`
1518 impl fmt::Debug for ImplPolarity {
1519 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1521 ImplPolarity::Positive => "positive".fmt(f),
1522 ImplPolarity::Negative => "negative".fmt(f),
1528 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1529 pub enum FunctionRetTy {
1530 /// Return type is not specified.
1532 /// Functions default to `()` and
1533 /// closures default to inference. Span points to where return
1534 /// type would be inserted.
1535 DefaultReturn(Span),
1540 impl FunctionRetTy {
1541 pub fn span(&self) -> Span {
1543 DefaultReturn(span) => span,
1544 Return(ref ty) => ty.span,
1549 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1551 /// A span from the first token past `{` to the last token until `}`.
1552 /// For `mod foo;`, the inner span ranges from the first token
1553 /// to the last token in the external file.
1555 pub item_ids: HirVec<ItemId>,
1558 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1559 pub struct ForeignMod {
1561 pub items: HirVec<ForeignItem>,
1564 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1565 pub struct GlobalAsm {
1567 pub ctxt: SyntaxContext,
1570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1571 pub struct EnumDef {
1572 pub variants: HirVec<Variant>,
1575 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1576 pub struct Variant_ {
1578 pub attrs: HirVec<Attribute>,
1579 pub data: VariantData,
1580 /// Explicit discriminant, eg `Foo = 1`
1581 pub disr_expr: Option<BodyId>,
1584 pub type Variant = Spanned<Variant_>;
1586 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1588 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1589 /// Also produced for each element of a list `use`, e.g.
1590 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1593 /// Glob import, e.g. `use foo::*`.
1596 /// Degenerate list import, e.g. `use foo::{a, b}` produces
1597 /// an additional `use foo::{}` for performing checks such as
1598 /// unstable feature gating. May be removed in the future.
1602 /// TraitRef's appear in impls.
1604 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1605 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1606 /// trait being referred to but just a unique NodeId that serves as a key
1607 /// within the DefMap.
1608 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1609 pub struct TraitRef {
1614 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1615 pub struct PolyTraitRef {
1616 /// The `'a` in `<'a> Foo<&'a T>`
1617 pub bound_lifetimes: HirVec<LifetimeDef>,
1619 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1620 pub trait_ref: TraitRef,
1625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1626 pub enum Visibility {
1629 Restricted { path: P<Path>, id: NodeId },
1634 pub fn is_pub_restricted(&self) -> bool {
1635 use self::Visibility::*;
1638 &Inherited => false,
1640 &Restricted { .. } => true,
1645 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1646 pub struct StructField {
1649 pub vis: Visibility,
1652 pub attrs: HirVec<Attribute>,
1656 // Still necessary in couple of places
1657 pub fn is_positional(&self) -> bool {
1658 let first = self.name.as_str().as_bytes()[0];
1659 first >= b'0' && first <= b'9'
1663 /// Fields and Ids of enum variants and structs
1665 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1666 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1667 /// One shared Id can be successfully used for these two purposes.
1668 /// Id of the whole enum lives in `Item`.
1670 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1671 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1672 /// the variant itself" from enum variants.
1673 /// Id of the whole struct lives in `Item`.
1674 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1675 pub enum VariantData {
1676 Struct(HirVec<StructField>, NodeId),
1677 Tuple(HirVec<StructField>, NodeId),
1682 pub fn fields(&self) -> &[StructField] {
1684 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1688 pub fn id(&self) -> NodeId {
1690 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
1693 pub fn is_struct(&self) -> bool {
1694 if let VariantData::Struct(..) = *self {
1700 pub fn is_tuple(&self) -> bool {
1701 if let VariantData::Tuple(..) = *self {
1707 pub fn is_unit(&self) -> bool {
1708 if let VariantData::Unit(..) = *self {
1716 // The bodies for items are stored "out of line", in a separate
1717 // hashmap in the `Crate`. Here we just record the node-id of the item
1718 // so it can fetched later.
1719 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1726 /// The name might be a dummy name in case of anonymous items
1727 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1732 pub attrs: HirVec<Attribute>,
1734 pub vis: Visibility,
1738 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1740 /// An `extern crate` item, with optional original crate name,
1742 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1743 ItemExternCrate(Option<Name>),
1745 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
1749 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
1750 ItemUse(P<Path>, UseKind),
1753 ItemStatic(P<Ty>, Mutability, BodyId),
1755 ItemConst(P<Ty>, BodyId),
1756 /// A function declaration
1757 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, BodyId),
1760 /// An external module
1761 ItemForeignMod(ForeignMod),
1762 /// Module-level inline assembly (from global_asm!)
1763 ItemGlobalAsm(P<GlobalAsm>),
1764 /// A type alias, e.g. `type Foo = Bar<u8>`
1765 ItemTy(P<Ty>, Generics),
1766 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1767 ItemEnum(EnumDef, Generics),
1768 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1769 ItemStruct(VariantData, Generics),
1770 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
1771 ItemUnion(VariantData, Generics),
1772 /// Represents a Trait Declaration
1773 ItemTrait(Unsafety, Generics, TyParamBounds, HirVec<TraitItemRef>),
1775 // Default trait implementations
1777 /// `impl Trait for .. {}`
1778 ItemDefaultImpl(Unsafety, TraitRef),
1779 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1784 Option<TraitRef>, // (optional) trait this impl implements
1786 HirVec<ImplItemRef>),
1790 pub fn descriptive_variant(&self) -> &str {
1792 ItemExternCrate(..) => "extern crate",
1793 ItemUse(..) => "use",
1794 ItemStatic(..) => "static item",
1795 ItemConst(..) => "constant item",
1796 ItemFn(..) => "function",
1797 ItemMod(..) => "module",
1798 ItemForeignMod(..) => "foreign module",
1799 ItemGlobalAsm(..) => "global asm",
1800 ItemTy(..) => "type alias",
1801 ItemEnum(..) => "enum",
1802 ItemStruct(..) => "struct",
1803 ItemUnion(..) => "union",
1804 ItemTrait(..) => "trait",
1806 ItemDefaultImpl(..) => "item",
1810 pub fn adt_kind(&self) -> Option<AdtKind> {
1812 ItemStruct(..) => Some(AdtKind::Struct),
1813 ItemUnion(..) => Some(AdtKind::Union),
1814 ItemEnum(..) => Some(AdtKind::Enum),
1820 /// A reference from an trait to one of its associated items. This
1821 /// contains the item's id, naturally, but also the item's name and
1822 /// some other high-level details (like whether it is an associated
1823 /// type or method, and whether it is public). This allows other
1824 /// passes to find the impl they want without loading the id (which
1825 /// means fewer edges in the incremental compilation graph).
1826 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1827 pub struct TraitItemRef {
1828 pub id: TraitItemId,
1830 pub kind: AssociatedItemKind,
1832 pub defaultness: Defaultness,
1835 /// A reference from an impl to one of its associated items. This
1836 /// contains the item's id, naturally, but also the item's name and
1837 /// some other high-level details (like whether it is an associated
1838 /// type or method, and whether it is public). This allows other
1839 /// passes to find the impl they want without loading the id (which
1840 /// means fewer edges in the incremental compilation graph).
1841 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1842 pub struct ImplItemRef {
1845 pub kind: AssociatedItemKind,
1847 pub vis: Visibility,
1848 pub defaultness: Defaultness,
1851 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1852 pub enum AssociatedItemKind {
1854 Method { has_self: bool },
1858 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1859 pub struct ForeignItem {
1861 pub attrs: HirVec<Attribute>,
1862 pub node: ForeignItem_,
1865 pub vis: Visibility,
1868 /// An item within an `extern` block
1869 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1870 pub enum ForeignItem_ {
1871 /// A foreign function
1872 ForeignItemFn(P<FnDecl>, HirVec<Spanned<Name>>, Generics),
1873 /// A foreign static item (`static ext: u8`), with optional mutability
1874 /// (the boolean is true when mutable)
1875 ForeignItemStatic(P<Ty>, bool),
1879 pub fn descriptive_variant(&self) -> &str {
1881 ForeignItemFn(..) => "foreign function",
1882 ForeignItemStatic(..) => "foreign static item",
1887 /// A free variable referred to in a function.
1888 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
1889 pub struct Freevar {
1890 /// The variable being accessed free.
1893 // First span where it is accessed (there can be multiple).
1898 pub fn var_id(&self) -> NodeId {
1900 Def::Local(id) | Def::Upvar(id, ..) => id,
1901 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
1906 pub type FreevarMap = NodeMap<Vec<Freevar>>;
1908 pub type CaptureModeMap = NodeMap<CaptureClause>;
1910 #[derive(Clone, Debug)]
1911 pub struct TraitCandidate {
1913 pub import_id: Option<NodeId>,
1916 // Trait method resolution
1917 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
1919 // Map from the NodeId of a glob import to a list of items which are actually
1921 pub type GlobMap = NodeMap<FxHashSet<Name>>;