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()
165 pub fn is_static(&self) -> bool {
166 self.name == "'static"
170 /// A lifetime definition, eg `'a: 'b+'c+'d`
171 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
172 pub struct LifetimeDef {
173 pub lifetime: Lifetime,
174 pub bounds: HirVec<Lifetime>,
175 pub pure_wrt_drop: bool,
178 /// A "Path" is essentially Rust's notion of a name; for instance:
179 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
180 /// along with a bunch of supporting information.
181 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
184 /// The definition that the path resolved to.
186 /// The segments in the path: the things separated by `::`.
187 pub segments: HirVec<PathSegment>,
191 pub fn is_global(&self) -> bool {
192 !self.segments.is_empty() && self.segments[0].name == keywords::CrateRoot.name()
196 impl fmt::Debug for Path {
197 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
198 write!(f, "path({})",
199 print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
203 /// A segment of a path: an identifier, an optional lifetime, and a set of
205 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
206 pub struct PathSegment {
207 /// The identifier portion of this path segment.
210 /// Type/lifetime parameters attached to this path. They come in
211 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
212 /// this is more than just simple syntactic sugar; the use of
213 /// parens affects the region binding rules, so we preserve the
215 pub parameters: PathParameters,
219 /// Convert an identifier to the corresponding segment.
220 pub fn from_name(name: Name) -> PathSegment {
223 parameters: PathParameters::none()
228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
229 pub struct PathParameters {
230 /// The lifetime parameters for this path segment.
231 pub lifetimes: HirVec<Lifetime>,
232 /// The type parameters for this path segment, if present.
233 pub types: HirVec<P<Ty>>,
234 /// Whether to infer remaining type parameters, if any.
235 /// This only applies to expression and pattern paths, and
236 /// out of those only the segments with no type parameters
237 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
238 pub infer_types: bool,
239 /// Bindings (equality constraints) on associated types, if present.
240 /// E.g., `Foo<A=Bar>`.
241 pub bindings: HirVec<TypeBinding>,
242 /// Were parameters written in parenthesized form `Fn(T) -> U`?
243 /// This is required mostly for pretty-printing and diagnostics,
244 /// but also for changing lifetime elision rules to be "function-like".
245 pub parenthesized: bool,
248 impl PathParameters {
249 pub fn none() -> Self {
251 lifetimes: HirVec::new(),
252 types: HirVec::new(),
254 bindings: HirVec::new(),
255 parenthesized: false,
259 pub fn inputs(&self) -> &[P<Ty>] {
260 if self.parenthesized {
261 if let Some(ref ty) = self.types.get(0) {
262 if let TyTup(ref tys) = ty.node {
267 bug!("PathParameters::inputs: not a `Fn(T) -> U`");
271 /// The AST represents all type param bounds as types.
272 /// typeck::collect::compute_bounds matches these against
273 /// the "special" built-in traits (see middle::lang_items) and
274 /// detects Copy, Send and Sync.
275 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
276 pub enum TyParamBound {
277 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
278 RegionTyParamBound(Lifetime),
281 /// A modifier on a bound, currently this is only used for `?Sized`, where the
282 /// modifier is `Maybe`. Negative bounds should also be handled here.
283 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
284 pub enum TraitBoundModifier {
289 pub type TyParamBounds = HirVec<TyParamBound>;
291 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
295 pub bounds: TyParamBounds,
296 pub default: Option<P<Ty>>,
298 pub pure_wrt_drop: bool,
301 /// Represents lifetimes and type parameters attached to a declaration
302 /// of a function, enum, trait, etc.
303 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
304 pub struct Generics {
305 pub lifetimes: HirVec<LifetimeDef>,
306 pub ty_params: HirVec<TyParam>,
307 pub where_clause: WhereClause,
312 pub fn empty() -> Generics {
314 lifetimes: HirVec::new(),
315 ty_params: HirVec::new(),
316 where_clause: WhereClause {
318 predicates: HirVec::new(),
324 pub fn is_lt_parameterized(&self) -> bool {
325 !self.lifetimes.is_empty()
328 pub fn is_type_parameterized(&self) -> bool {
329 !self.ty_params.is_empty()
332 pub fn is_parameterized(&self) -> bool {
333 self.is_lt_parameterized() || self.is_type_parameterized()
337 pub enum UnsafeGeneric {
338 Region(LifetimeDef, &'static str),
339 Type(TyParam, &'static str),
343 pub fn attr_name(&self) -> &'static str {
345 UnsafeGeneric::Region(_, s) => s,
346 UnsafeGeneric::Type(_, s) => s,
352 pub fn carries_unsafe_attr(&self) -> Option<UnsafeGeneric> {
353 for r in &self.lifetimes {
355 return Some(UnsafeGeneric::Region(r.clone(), "may_dangle"));
358 for t in &self.ty_params {
360 return Some(UnsafeGeneric::Type(t.clone(), "may_dangle"));
367 /// A `where` clause in a definition
368 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
369 pub struct WhereClause {
371 pub predicates: HirVec<WherePredicate>,
374 /// A single predicate in a `where` clause
375 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
376 pub enum WherePredicate {
377 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
378 BoundPredicate(WhereBoundPredicate),
379 /// A lifetime predicate, e.g. `'a: 'b+'c`
380 RegionPredicate(WhereRegionPredicate),
381 /// An equality predicate (unsupported)
382 EqPredicate(WhereEqPredicate),
385 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
386 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
387 pub struct WhereBoundPredicate {
389 /// Any lifetimes from a `for` binding
390 pub bound_lifetimes: HirVec<LifetimeDef>,
391 /// The type being bounded
392 pub bounded_ty: P<Ty>,
393 /// Trait and lifetime bounds (`Clone+Send+'static`)
394 pub bounds: TyParamBounds,
397 /// A lifetime predicate, e.g. `'a: 'b+'c`
398 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
399 pub struct WhereRegionPredicate {
401 pub lifetime: Lifetime,
402 pub bounds: HirVec<Lifetime>,
405 /// An equality predicate (unsupported), e.g. `T=int`
406 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
407 pub struct WhereEqPredicate {
414 pub type CrateConfig = HirVec<P<MetaItem>>;
416 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
419 pub attrs: HirVec<Attribute>,
421 pub exported_macros: HirVec<MacroDef>,
423 // NB: We use a BTreeMap here so that `visit_all_items` iterates
424 // over the ids in increasing order. In principle it should not
425 // matter what order we visit things in, but in *practice* it
426 // does, because it can affect the order in which errors are
427 // detected, which in turn can make compile-fail tests yield
428 // slightly different results.
429 pub items: BTreeMap<NodeId, Item>,
431 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
432 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
433 pub bodies: BTreeMap<BodyId, Body>,
434 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
435 pub trait_default_impl: BTreeMap<DefId, NodeId>,
437 /// A list of the body ids written out in the order in which they
438 /// appear in the crate. If you're going to process all the bodies
439 /// in the crate, you should iterate over this list rather than the keys
441 pub body_ids: Vec<BodyId>,
445 pub fn item(&self, id: NodeId) -> &Item {
449 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
450 &self.trait_items[&id]
453 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
454 &self.impl_items[&id]
457 /// Visits all items in the crate in some deterministic (but
458 /// unspecified) order. If you just need to process every item,
459 /// but don't care about nesting, this method is the best choice.
461 /// If you do care about nesting -- usually because your algorithm
462 /// follows lexical scoping rules -- then you want a different
463 /// approach. You should override `visit_nested_item` in your
464 /// visitor and then call `intravisit::walk_crate` instead.
465 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
466 where V: itemlikevisit::ItemLikeVisitor<'hir>
468 for (_, item) in &self.items {
469 visitor.visit_item(item);
472 for (_, trait_item) in &self.trait_items {
473 visitor.visit_trait_item(trait_item);
476 for (_, impl_item) in &self.impl_items {
477 visitor.visit_impl_item(impl_item);
481 pub fn body(&self, id: BodyId) -> &Body {
486 /// A macro definition, in this crate or imported from another.
488 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
489 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
490 pub struct MacroDef {
493 pub attrs: HirVec<Attribute>,
496 pub body: TokenStream,
500 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
502 /// Statements in a block
503 pub stmts: HirVec<Stmt>,
504 /// An expression at the end of the block
505 /// without a semicolon, if any
506 pub expr: Option<P<Expr>>,
509 /// Distinguishes between `unsafe { ... }` and `{ ... }`
510 pub rules: BlockCheckMode,
512 /// If true, then there may exist `break 'a` values that aim to
513 /// break out of this block early. As of this writing, this is not
514 /// currently permitted in Rust itself, but it is generated as
515 /// part of `catch` statements.
516 pub targeted_by_break: bool,
519 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
527 impl fmt::Debug for Pat {
528 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
529 write!(f, "pat({}: {})", self.id,
530 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
535 // FIXME(#19596) this is a workaround, but there should be a better way
536 fn walk_<G>(&self, it: &mut G) -> bool
537 where G: FnMut(&Pat) -> bool
544 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
545 PatKind::Struct(_, ref fields, _) => {
546 fields.iter().all(|field| field.node.pat.walk_(it))
548 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
549 s.iter().all(|p| p.walk_(it))
551 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
554 PatKind::Slice(ref before, ref slice, ref after) => {
555 before.iter().all(|p| p.walk_(it)) &&
556 slice.iter().all(|p| p.walk_(it)) &&
557 after.iter().all(|p| p.walk_(it))
562 PatKind::Binding(..) |
563 PatKind::Path(_) => {
569 pub fn walk<F>(&self, mut it: F) -> bool
570 where F: FnMut(&Pat) -> bool
576 /// A single field in a struct pattern
578 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
579 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
580 /// except is_shorthand is true
581 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
582 pub struct FieldPat {
583 /// The identifier for the field
585 /// The pattern the field is destructured to
587 pub is_shorthand: bool,
590 /// Explicit binding annotations given in the HIR for a binding. Note
591 /// that this is not the final binding *mode* that we infer after type
593 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
594 pub enum BindingAnnotation {
595 /// No binding annotation given: this means that the final binding mode
596 /// will depend on whether we have skipped through a `&` reference
597 /// when matching. For example, the `x` in `Some(x)` will have binding
598 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
599 /// ultimately be inferred to be by-reference.
601 /// Note that implicit reference skipping is not implemented yet (#42640).
604 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
607 /// Annotated as `ref`, like `ref x`
610 /// Annotated as `ref mut x`.
614 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
620 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
622 /// Represents a wildcard pattern (`_`)
625 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
626 /// The `NodeId` is the canonical ID for the variable being bound,
627 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
628 /// which is the pattern ID of the first `x`.
629 Binding(BindingAnnotation, NodeId, Spanned<Name>, Option<P<Pat>>),
631 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
632 /// The `bool` is `true` in the presence of a `..`.
633 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
635 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
636 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
637 /// 0 <= position <= subpats.len()
638 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
640 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
643 /// A tuple pattern `(a, b)`.
644 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
645 /// 0 <= position <= subpats.len()
646 Tuple(HirVec<P<Pat>>, Option<usize>),
649 /// A reference pattern, e.g. `&mut (a, b)`
650 Ref(P<Pat>, Mutability),
653 /// A range pattern, e.g. `1...2` or `1..2`
654 Range(P<Expr>, P<Expr>, RangeEnd),
655 /// `[a, b, ..i, y, z]` is represented as:
656 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
657 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
660 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
661 pub enum Mutability {
667 /// Return MutMutable only if both arguments are mutable.
668 pub fn and(self, other: Self) -> Self {
671 MutImmutable => MutImmutable,
676 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
678 /// The `+` operator (addition)
680 /// The `-` operator (subtraction)
682 /// The `*` operator (multiplication)
684 /// The `/` operator (division)
686 /// The `%` operator (modulus)
688 /// The `&&` operator (logical and)
690 /// The `||` operator (logical or)
692 /// The `^` operator (bitwise xor)
694 /// The `&` operator (bitwise and)
696 /// The `|` operator (bitwise or)
698 /// The `<<` operator (shift left)
700 /// The `>>` operator (shift right)
702 /// The `==` operator (equality)
704 /// The `<` operator (less than)
706 /// The `<=` operator (less than or equal to)
708 /// The `!=` operator (not equal to)
710 /// The `>=` operator (greater than or equal to)
712 /// The `>` operator (greater than)
717 pub fn as_str(self) -> &'static str {
740 pub fn is_lazy(self) -> bool {
742 BiAnd | BiOr => true,
747 pub fn is_shift(self) -> bool {
749 BiShl | BiShr => true,
754 pub fn is_comparison(self) -> bool {
756 BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
772 /// Returns `true` if the binary operator takes its arguments by value
773 pub fn is_by_value(self) -> bool {
774 !self.is_comparison()
778 pub type BinOp = Spanned<BinOp_>;
780 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
782 /// The `*` operator for dereferencing
784 /// The `!` operator for logical inversion
786 /// The `-` operator for negation
791 pub fn as_str(self) -> &'static str {
799 /// Returns `true` if the unary operator takes its argument by value
800 pub fn is_by_value(self) -> bool {
802 UnNeg | UnNot => true,
809 pub type Stmt = Spanned<Stmt_>;
811 impl fmt::Debug for Stmt_ {
812 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
814 let spanned = codemap::dummy_spanned(self.clone());
818 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
822 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
824 /// Could be an item or a local (let) binding:
825 StmtDecl(P<Decl>, NodeId),
827 /// Expr without trailing semi-colon (must have unit type):
828 StmtExpr(P<Expr>, NodeId),
830 /// Expr with trailing semi-colon (may have any type):
831 StmtSemi(P<Expr>, NodeId),
835 pub fn attrs(&self) -> &[Attribute] {
837 StmtDecl(ref d, _) => d.node.attrs(),
839 StmtSemi(ref e, _) => &e.attrs,
843 pub fn id(&self) -> NodeId {
845 StmtDecl(_, id) => id,
846 StmtExpr(_, id) => id,
847 StmtSemi(_, id) => id,
852 // FIXME (pending discussion of #1697, #2178...): local should really be
853 // a refinement on pat.
854 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
855 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
858 pub ty: Option<P<Ty>>,
859 /// Initializer expression to set the value, if any
860 pub init: Option<P<Expr>>,
864 pub attrs: ThinVec<Attribute>,
865 pub source: LocalSource,
868 pub type Decl = Spanned<Decl_>;
870 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
872 /// A local (let) binding:
879 pub fn attrs(&self) -> &[Attribute] {
881 DeclLocal(ref l) => &l.attrs,
886 pub fn is_local(&self) -> bool {
888 Decl_::DeclLocal(_) => true,
894 /// represents one arm of a 'match'
895 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
897 pub attrs: HirVec<Attribute>,
898 pub pats: HirVec<P<Pat>>,
899 pub guard: Option<P<Expr>>,
903 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
905 pub name: Spanned<Name>,
908 pub is_shorthand: bool,
911 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
912 pub enum BlockCheckMode {
914 UnsafeBlock(UnsafeSource),
915 PushUnsafeBlock(UnsafeSource),
916 PopUnsafeBlock(UnsafeSource),
919 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
920 pub enum UnsafeSource {
925 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
930 /// The body of a function or constant value.
931 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
933 pub arguments: HirVec<Arg>,
935 pub is_generator: bool,
939 pub fn id(&self) -> BodyId {
941 node_id: self.value.id
947 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
952 pub attrs: ThinVec<Attribute>,
956 impl fmt::Debug for Expr {
957 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
958 write!(f, "expr({}: {})", self.id,
959 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
963 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
965 /// A `box x` expression.
967 /// An array (`[a, b, c, d]`)
968 ExprArray(HirVec<Expr>),
971 /// The first field resolves to the function itself (usually an `ExprPath`),
972 /// and the second field is the list of arguments
973 ExprCall(P<Expr>, HirVec<Expr>),
974 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
976 /// The `PathSegment`/`Span` represent the method name and its generic arguments
977 /// (within the angle brackets).
978 /// The first element of the vector of `Expr`s is the expression that evaluates
979 /// to the object on which the method is being called on (the receiver),
980 /// and the remaining elements are the rest of the arguments.
981 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
982 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
983 ExprMethodCall(PathSegment, Span, HirVec<Expr>),
984 /// A tuple (`(a, b, c ,d)`)
985 ExprTup(HirVec<Expr>),
986 /// A binary operation (For example: `a + b`, `a * b`)
987 ExprBinary(BinOp, P<Expr>, P<Expr>),
988 /// A unary operation (For example: `!x`, `*x`)
989 ExprUnary(UnOp, P<Expr>),
990 /// A literal (For example: `1`, `"foo"`)
992 /// A cast (`foo as f64`)
993 ExprCast(P<Expr>, P<Ty>),
994 ExprType(P<Expr>, P<Ty>),
995 /// An `if` block, with an optional else block
997 /// `if expr { expr } else { expr }`
998 ExprIf(P<Expr>, P<Expr>, Option<P<Expr>>),
999 /// A while loop, with an optional label
1001 /// `'label: while expr { block }`
1002 ExprWhile(P<Expr>, P<Block>, Option<Spanned<Name>>),
1003 /// Conditionless loop (can be exited with break, continue, or return)
1005 /// `'label: loop { block }`
1006 ExprLoop(P<Block>, Option<Spanned<Name>>, LoopSource),
1007 /// A `match` block, with a source that indicates whether or not it is
1008 /// the result of a desugaring, and if so, which kind.
1009 ExprMatch(P<Expr>, HirVec<Arm>, MatchSource),
1010 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1012 /// The final span is the span of the argument block `|...|`
1014 /// This may also be a generator literal, indicated by the final boolean,
1015 /// in that case there is an GeneratorClause.
1016 ExprClosure(CaptureClause, P<FnDecl>, BodyId, Span, bool),
1017 /// A block (`{ ... }`)
1018 ExprBlock(P<Block>),
1020 /// An assignment (`a = foo()`)
1021 ExprAssign(P<Expr>, P<Expr>),
1022 /// An assignment with an operator
1024 /// For example, `a += 1`.
1025 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
1026 /// Access of a named struct field (`obj.foo`)
1027 ExprField(P<Expr>, Spanned<Name>),
1028 /// Access of an unnamed field of a struct or tuple-struct
1030 /// For example, `foo.0`.
1031 ExprTupField(P<Expr>, Spanned<usize>),
1032 /// An indexing operation (`foo[2]`)
1033 ExprIndex(P<Expr>, P<Expr>),
1035 /// Path to a definition, possibly containing lifetime or type parameters.
1038 /// A referencing operation (`&a` or `&mut a`)
1039 ExprAddrOf(Mutability, P<Expr>),
1040 /// A `break`, with an optional label to break
1041 ExprBreak(Destination, Option<P<Expr>>),
1042 /// A `continue`, with an optional label
1043 ExprAgain(Destination),
1044 /// A `return`, with an optional value to be returned
1045 ExprRet(Option<P<Expr>>),
1047 /// Inline assembly (from `asm!`), with its outputs and inputs.
1048 ExprInlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1050 /// A struct or struct-like variant literal expression.
1052 /// For example, `Foo {x: 1, y: 2}`, or
1053 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1054 ExprStruct(QPath, HirVec<Field>, Option<P<Expr>>),
1056 /// An array literal constructed from one repeated element.
1058 /// For example, `[1; 5]`. The first expression is the element
1059 /// to be repeated; the second is the number of times to repeat it.
1060 ExprRepeat(P<Expr>, BodyId),
1062 /// A suspension point for generators. This is `yield <expr>` in Rust.
1066 /// Optionally `Self`-qualified value/type path or associated extension.
1067 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1069 /// Path to a definition, optionally "fully-qualified" with a `Self`
1070 /// type, if the path points to an associated item in a trait.
1072 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1073 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1074 /// even though they both have the same two-segment `Clone::clone` `Path`.
1075 Resolved(Option<P<Ty>>, P<Path>),
1077 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1078 /// Will be resolved by type-checking to an associated item.
1080 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1081 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1082 /// the `X` and `Y` nodes each being a `TyPath(QPath::TypeRelative(..))`.
1083 TypeRelative(P<Ty>, P<PathSegment>)
1086 /// Hints at the original code for a let statement
1087 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1088 pub enum LocalSource {
1089 /// A `match _ { .. }`
1091 /// A desugared `for _ in _ { .. }` loop
1095 /// Hints at the original code for a `match _ { .. }`
1096 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1097 pub enum MatchSource {
1098 /// A `match _ { .. }`
1100 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1102 contains_else_clause: bool,
1104 /// A `while let _ = _ { .. }` (which was desugared to a
1105 /// `loop { match _ { .. } }`)
1107 /// A desugared `for _ in _ { .. }` loop
1109 /// A desugared `?` operator
1113 /// The loop type that yielded an ExprLoop
1114 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1115 pub enum LoopSource {
1116 /// A `loop { .. }` loop
1118 /// A `while let _ = _ { .. }` loop
1120 /// A `for _ in _ { .. }` loop
1124 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1125 pub enum LoopIdError {
1127 UnlabeledCfInWhileCondition,
1131 impl fmt::Display for LoopIdError {
1132 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1133 fmt::Display::fmt(match *self {
1134 LoopIdError::OutsideLoopScope => "not inside loop scope",
1135 LoopIdError::UnlabeledCfInWhileCondition =>
1136 "unlabeled control flow (break or continue) in while condition",
1137 LoopIdError::UnresolvedLabel => "label not found",
1142 // FIXME(cramertj) this should use `Result` once master compiles w/ a vesion of Rust where
1143 // `Result` implements `Encodable`/`Decodable`
1144 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1145 pub enum LoopIdResult {
1149 impl Into<Result<NodeId, LoopIdError>> for LoopIdResult {
1150 fn into(self) -> Result<NodeId, LoopIdError> {
1152 LoopIdResult::Ok(ok) => Ok(ok),
1153 LoopIdResult::Err(err) => Err(err),
1157 impl From<Result<NodeId, LoopIdError>> for LoopIdResult {
1158 fn from(res: Result<NodeId, LoopIdError>) -> Self {
1160 Ok(ok) => LoopIdResult::Ok(ok),
1161 Err(err) => LoopIdResult::Err(err),
1166 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1167 pub enum ScopeTarget {
1173 pub fn opt_id(self) -> Option<NodeId> {
1175 ScopeTarget::Block(node_id) |
1176 ScopeTarget::Loop(LoopIdResult::Ok(node_id)) => Some(node_id),
1177 ScopeTarget::Loop(LoopIdResult::Err(_)) => None,
1182 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1183 pub struct Destination {
1184 // This is `Some(_)` iff there is an explicit user-specified `label
1185 pub ident: Option<Spanned<Ident>>,
1187 // These errors are caught and then reported during the diagnostics pass in
1188 // librustc_passes/loops.rs
1189 pub target_id: ScopeTarget,
1192 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1193 pub enum CaptureClause {
1198 // NB: If you change this, you'll probably want to change the corresponding
1199 // type structure in middle/ty.rs as well.
1200 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1203 pub mutbl: Mutability,
1206 /// Represents a method's signature in a trait declaration or implementation.
1207 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1208 pub struct MethodSig {
1209 pub unsafety: Unsafety,
1210 pub constness: Constness,
1212 pub decl: P<FnDecl>,
1213 pub generics: Generics,
1216 // The bodies for items are stored "out of line", in a separate
1217 // hashmap in the `Crate`. Here we just record the node-id of the item
1218 // so it can fetched later.
1219 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1220 pub struct TraitItemId {
1221 pub node_id: NodeId,
1224 /// Represents an item declaration within a trait declaration,
1225 /// possibly including a default implementation. A trait item is
1226 /// either required (meaning it doesn't have an implementation, just a
1227 /// signature) or provided (meaning it has a default implementation).
1228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1229 pub struct TraitItem {
1233 pub attrs: HirVec<Attribute>,
1234 pub node: TraitItemKind,
1238 /// A trait method's body (or just argument names).
1239 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1240 pub enum TraitMethod {
1241 /// No default body in the trait, just a signature.
1242 Required(HirVec<Spanned<Name>>),
1244 /// Both signature and body are provided in the trait.
1248 /// Represents a trait method or associated constant or type
1249 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1250 pub enum TraitItemKind {
1251 /// An associated constant with an optional value (otherwise `impl`s
1252 /// must contain a value)
1253 Const(P<Ty>, Option<BodyId>),
1254 /// A method with an optional body
1255 Method(MethodSig, TraitMethod),
1256 /// An associated type with (possibly empty) bounds and optional concrete
1258 Type(TyParamBounds, Option<P<Ty>>),
1261 // The bodies for items are stored "out of line", in a separate
1262 // hashmap in the `Crate`. Here we just record the node-id of the item
1263 // so it can fetched later.
1264 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1265 pub struct ImplItemId {
1266 pub node_id: NodeId,
1269 /// Represents anything within an `impl` block
1270 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1271 pub struct ImplItem {
1275 pub vis: Visibility,
1276 pub defaultness: Defaultness,
1277 pub attrs: HirVec<Attribute>,
1278 pub node: ImplItemKind,
1282 /// Represents different contents within `impl`s
1283 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1284 pub enum ImplItemKind {
1285 /// An associated constant of the given type, set to the constant result
1286 /// of the expression
1287 Const(P<Ty>, BodyId),
1288 /// A method implementation with the given signature and body
1289 Method(MethodSig, BodyId),
1290 /// An associated type
1294 // Bind a type to an associated type: `A=Foo`.
1295 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1296 pub struct TypeBinding {
1304 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1311 impl fmt::Debug for Ty {
1312 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1313 write!(f, "type({})",
1314 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1318 /// Not represented directly in the AST, referred to by name through a ty_path.
1319 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1329 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1330 pub struct BareFnTy {
1331 pub unsafety: Unsafety,
1333 pub lifetimes: HirVec<LifetimeDef>,
1334 pub decl: P<FnDecl>,
1337 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1338 /// The different kinds of types recognized by the compiler
1340 /// A variable length slice (`[T]`)
1342 /// A fixed length array (`[T; n]`)
1343 TyArray(P<Ty>, BodyId),
1344 /// A raw pointer (`*const T` or `*mut T`)
1346 /// A reference (`&'a T` or `&'a mut T`)
1347 TyRptr(Lifetime, MutTy),
1348 /// A bare function (e.g. `fn(usize) -> bool`)
1349 TyBareFn(P<BareFnTy>),
1350 /// The never type (`!`)
1352 /// A tuple (`(A, B, C, D,...)`)
1353 TyTup(HirVec<P<Ty>>),
1354 /// A path to a type definition (`module::module::...::Type`), or an
1355 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1357 /// Type parameters may be stored in each `PathSegment`.
1359 /// A trait object type `Bound1 + Bound2 + Bound3`
1360 /// where `Bound` is a trait or a lifetime.
1361 TyTraitObject(HirVec<PolyTraitRef>, Lifetime),
1362 /// An `impl Bound1 + Bound2 + Bound3` type
1363 /// where `Bound` is a trait or a lifetime.
1364 TyImplTrait(TyParamBounds),
1367 /// TyInfer means the type should be inferred instead of it having been
1368 /// specified. This can appear anywhere in a type.
1370 /// Placeholder for a type that has failed to be defined.
1374 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1375 pub struct InlineAsmOutput {
1376 pub constraint: Symbol,
1378 pub is_indirect: bool,
1381 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1382 pub struct InlineAsm {
1384 pub asm_str_style: StrStyle,
1385 pub outputs: HirVec<InlineAsmOutput>,
1386 pub inputs: HirVec<Symbol>,
1387 pub clobbers: HirVec<Symbol>,
1389 pub alignstack: bool,
1390 pub dialect: AsmDialect,
1391 pub ctxt: SyntaxContext,
1394 /// represents an argument in a function header
1395 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1402 /// Represents the header (not the body) of a function declaration
1403 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1405 pub inputs: HirVec<P<Ty>>,
1406 pub output: FunctionRetTy,
1408 /// True if this function has an `self`, `&self` or `&mut self` receiver
1409 /// (but not a `self: Xxx` one).
1410 pub has_implicit_self: bool,
1413 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1419 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1420 pub enum Constness {
1425 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1426 pub enum Defaultness {
1427 Default { has_value: bool },
1432 pub fn has_value(&self) -> bool {
1434 Defaultness::Default { has_value, .. } => has_value,
1435 Defaultness::Final => true,
1439 pub fn is_final(&self) -> bool {
1440 *self == Defaultness::Final
1443 pub fn is_default(&self) -> bool {
1445 Defaultness::Default { .. } => true,
1451 impl fmt::Display for Unsafety {
1452 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1453 fmt::Display::fmt(match *self {
1454 Unsafety::Normal => "normal",
1455 Unsafety::Unsafe => "unsafe",
1461 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1462 pub enum ImplPolarity {
1463 /// `impl Trait for Type`
1465 /// `impl !Trait for Type`
1469 impl fmt::Debug for ImplPolarity {
1470 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1472 ImplPolarity::Positive => "positive".fmt(f),
1473 ImplPolarity::Negative => "negative".fmt(f),
1479 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1480 pub enum FunctionRetTy {
1481 /// Return type is not specified.
1483 /// Functions default to `()` and
1484 /// closures default to inference. Span points to where return
1485 /// type would be inserted.
1486 DefaultReturn(Span),
1491 impl FunctionRetTy {
1492 pub fn span(&self) -> Span {
1494 DefaultReturn(span) => span,
1495 Return(ref ty) => ty.span,
1500 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1502 /// A span from the first token past `{` to the last token until `}`.
1503 /// For `mod foo;`, the inner span ranges from the first token
1504 /// to the last token in the external file.
1506 pub item_ids: HirVec<ItemId>,
1509 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1510 pub struct ForeignMod {
1512 pub items: HirVec<ForeignItem>,
1515 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1516 pub struct GlobalAsm {
1518 pub ctxt: SyntaxContext,
1521 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1522 pub struct EnumDef {
1523 pub variants: HirVec<Variant>,
1526 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1527 pub struct Variant_ {
1529 pub attrs: HirVec<Attribute>,
1530 pub data: VariantData,
1531 /// Explicit discriminant, eg `Foo = 1`
1532 pub disr_expr: Option<BodyId>,
1535 pub type Variant = Spanned<Variant_>;
1537 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1539 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1540 /// Also produced for each element of a list `use`, e.g.
1541 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1544 /// Glob import, e.g. `use foo::*`.
1547 /// Degenerate list import, e.g. `use foo::{a, b}` produces
1548 /// an additional `use foo::{}` for performing checks such as
1549 /// unstable feature gating. May be removed in the future.
1553 /// TraitRef's appear in impls.
1555 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1556 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1557 /// trait being referred to but just a unique NodeId that serves as a key
1558 /// within the DefMap.
1559 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1560 pub struct TraitRef {
1565 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1566 pub struct PolyTraitRef {
1567 /// The `'a` in `<'a> Foo<&'a T>`
1568 pub bound_lifetimes: HirVec<LifetimeDef>,
1570 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1571 pub trait_ref: TraitRef,
1576 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1577 pub enum Visibility {
1580 Restricted { path: P<Path>, id: NodeId },
1585 pub fn is_pub_restricted(&self) -> bool {
1586 use self::Visibility::*;
1589 &Inherited => false,
1591 &Restricted { .. } => true,
1596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1597 pub struct StructField {
1600 pub vis: Visibility,
1603 pub attrs: HirVec<Attribute>,
1607 // Still necessary in couple of places
1608 pub fn is_positional(&self) -> bool {
1609 let first = self.name.as_str().as_bytes()[0];
1610 first >= b'0' && first <= b'9'
1614 /// Fields and Ids of enum variants and structs
1616 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1617 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1618 /// One shared Id can be successfully used for these two purposes.
1619 /// Id of the whole enum lives in `Item`.
1621 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1622 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1623 /// the variant itself" from enum variants.
1624 /// Id of the whole struct lives in `Item`.
1625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1626 pub enum VariantData {
1627 Struct(HirVec<StructField>, NodeId),
1628 Tuple(HirVec<StructField>, NodeId),
1633 pub fn fields(&self) -> &[StructField] {
1635 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1639 pub fn id(&self) -> NodeId {
1641 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
1644 pub fn is_struct(&self) -> bool {
1645 if let VariantData::Struct(..) = *self {
1651 pub fn is_tuple(&self) -> bool {
1652 if let VariantData::Tuple(..) = *self {
1658 pub fn is_unit(&self) -> bool {
1659 if let VariantData::Unit(..) = *self {
1667 // The bodies for items are stored "out of line", in a separate
1668 // hashmap in the `Crate`. Here we just record the node-id of the item
1669 // so it can fetched later.
1670 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1677 /// The name might be a dummy name in case of anonymous items
1678 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1683 pub attrs: HirVec<Attribute>,
1685 pub vis: Visibility,
1689 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1691 /// An `extern crate` item, with optional original crate name,
1693 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1694 ItemExternCrate(Option<Name>),
1696 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
1700 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
1701 ItemUse(P<Path>, UseKind),
1704 ItemStatic(P<Ty>, Mutability, BodyId),
1706 ItemConst(P<Ty>, BodyId),
1707 /// A function declaration
1708 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, BodyId),
1711 /// An external module
1712 ItemForeignMod(ForeignMod),
1713 /// Module-level inline assembly (from global_asm!)
1714 ItemGlobalAsm(P<GlobalAsm>),
1715 /// A type alias, e.g. `type Foo = Bar<u8>`
1716 ItemTy(P<Ty>, Generics),
1717 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1718 ItemEnum(EnumDef, Generics),
1719 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1720 ItemStruct(VariantData, Generics),
1721 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
1722 ItemUnion(VariantData, Generics),
1723 /// Represents a Trait Declaration
1724 ItemTrait(Unsafety, Generics, TyParamBounds, HirVec<TraitItemRef>),
1726 // Default trait implementations
1728 /// `impl Trait for .. {}`
1729 ItemDefaultImpl(Unsafety, TraitRef),
1730 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1735 Option<TraitRef>, // (optional) trait this impl implements
1737 HirVec<ImplItemRef>),
1741 pub fn descriptive_variant(&self) -> &str {
1743 ItemExternCrate(..) => "extern crate",
1744 ItemUse(..) => "use",
1745 ItemStatic(..) => "static item",
1746 ItemConst(..) => "constant item",
1747 ItemFn(..) => "function",
1748 ItemMod(..) => "module",
1749 ItemForeignMod(..) => "foreign module",
1750 ItemGlobalAsm(..) => "global asm",
1751 ItemTy(..) => "type alias",
1752 ItemEnum(..) => "enum",
1753 ItemStruct(..) => "struct",
1754 ItemUnion(..) => "union",
1755 ItemTrait(..) => "trait",
1757 ItemDefaultImpl(..) => "item",
1761 pub fn adt_kind(&self) -> Option<AdtKind> {
1763 ItemStruct(..) => Some(AdtKind::Struct),
1764 ItemUnion(..) => Some(AdtKind::Union),
1765 ItemEnum(..) => Some(AdtKind::Enum),
1771 /// A reference from an trait to one of its associated items. This
1772 /// contains the item's id, naturally, but also the item's name and
1773 /// some other high-level details (like whether it is an associated
1774 /// type or method, and whether it is public). This allows other
1775 /// passes to find the impl they want without loading the id (which
1776 /// means fewer edges in the incremental compilation graph).
1777 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1778 pub struct TraitItemRef {
1779 pub id: TraitItemId,
1781 pub kind: AssociatedItemKind,
1783 pub defaultness: Defaultness,
1786 /// A reference from an impl to one of its associated items. This
1787 /// contains the item's id, naturally, but also the item's name and
1788 /// some other high-level details (like whether it is an associated
1789 /// type or method, and whether it is public). This allows other
1790 /// passes to find the impl they want without loading the id (which
1791 /// means fewer edges in the incremental compilation graph).
1792 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1793 pub struct ImplItemRef {
1796 pub kind: AssociatedItemKind,
1798 pub vis: Visibility,
1799 pub defaultness: Defaultness,
1802 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1803 pub enum AssociatedItemKind {
1805 Method { has_self: bool },
1809 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1810 pub struct ForeignItem {
1812 pub attrs: HirVec<Attribute>,
1813 pub node: ForeignItem_,
1816 pub vis: Visibility,
1819 /// An item within an `extern` block
1820 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1821 pub enum ForeignItem_ {
1822 /// A foreign function
1823 ForeignItemFn(P<FnDecl>, HirVec<Spanned<Name>>, Generics),
1824 /// A foreign static item (`static ext: u8`), with optional mutability
1825 /// (the boolean is true when mutable)
1826 ForeignItemStatic(P<Ty>, bool),
1830 pub fn descriptive_variant(&self) -> &str {
1832 ForeignItemFn(..) => "foreign function",
1833 ForeignItemStatic(..) => "foreign static item",
1838 /// A free variable referred to in a function.
1839 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
1840 pub struct Freevar {
1841 /// The variable being accessed free.
1844 // First span where it is accessed (there can be multiple).
1849 pub fn var_id(&self) -> NodeId {
1851 Def::Local(id) | Def::Upvar(id, ..) => id,
1852 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
1857 pub type FreevarMap = NodeMap<Vec<Freevar>>;
1859 pub type CaptureModeMap = NodeMap<CaptureClause>;
1861 #[derive(Clone, Debug)]
1862 pub struct TraitCandidate {
1864 pub import_id: Option<NodeId>,
1867 // Trait method resolution
1868 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
1870 // Map from the NodeId of a glob import to a list of items which are actually
1872 pub type GlobMap = NodeMap<FxHashSet<Name>>;