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: Option<P<PathParameters>>,
241 /// Whether to infer remaining type parameters, if any.
242 /// This only applies to expression and pattern paths, and
243 /// out of those only the segments with no type parameters
244 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
245 pub infer_types: bool,
249 /// Convert an identifier to the corresponding segment.
250 pub fn from_name(name: Name) -> PathSegment {
258 pub fn new(name: Name, parameters: PathParameters, infer_types: bool) -> Self {
262 parameters: if parameters.is_empty() {
270 // FIXME: hack required because you can't create a static
271 // PathParameters, so you can't just return a &PathParameters.
272 pub fn with_parameters<F, R>(&self, f: F) -> R
273 where F: FnOnce(&PathParameters) -> R
275 let dummy = PathParameters::none();
276 f(if let Some(ref params) = self.parameters {
284 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
285 pub struct PathParameters {
286 /// The lifetime parameters for this path segment.
287 pub lifetimes: HirVec<Lifetime>,
288 /// The type parameters for this path segment, if present.
289 pub types: HirVec<P<Ty>>,
290 /// Bindings (equality constraints) on associated types, if present.
291 /// E.g., `Foo<A=Bar>`.
292 pub bindings: HirVec<TypeBinding>,
293 /// Were parameters written in parenthesized form `Fn(T) -> U`?
294 /// This is required mostly for pretty-printing and diagnostics,
295 /// but also for changing lifetime elision rules to be "function-like".
296 pub parenthesized: bool,
299 impl PathParameters {
300 pub fn none() -> Self {
302 lifetimes: HirVec::new(),
303 types: HirVec::new(),
304 bindings: HirVec::new(),
305 parenthesized: false,
309 pub fn is_empty(&self) -> bool {
310 self.lifetimes.is_empty() && self.types.is_empty() &&
311 self.bindings.is_empty() && !self.parenthesized
314 pub fn inputs(&self) -> &[P<Ty>] {
315 if self.parenthesized {
316 if let Some(ref ty) = self.types.get(0) {
317 if let TyTup(ref tys) = ty.node {
322 bug!("PathParameters::inputs: not a `Fn(T) -> U`");
326 /// The AST represents all type param bounds as types.
327 /// typeck::collect::compute_bounds matches these against
328 /// the "special" built-in traits (see middle::lang_items) and
329 /// detects Copy, Send and Sync.
330 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
331 pub enum TyParamBound {
332 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
333 RegionTyParamBound(Lifetime),
336 /// A modifier on a bound, currently this is only used for `?Sized`, where the
337 /// modifier is `Maybe`. Negative bounds should also be handled here.
338 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
339 pub enum TraitBoundModifier {
344 pub type TyParamBounds = HirVec<TyParamBound>;
346 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
350 pub bounds: TyParamBounds,
351 pub default: Option<P<Ty>>,
353 pub pure_wrt_drop: bool,
354 pub synthetic: Option<SyntheticTyParamKind>,
357 /// Represents lifetimes and type parameters attached to a declaration
358 /// of a function, enum, trait, etc.
359 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
360 pub struct Generics {
361 pub lifetimes: HirVec<LifetimeDef>,
362 pub ty_params: HirVec<TyParam>,
363 pub where_clause: WhereClause,
368 pub fn empty() -> Generics {
370 lifetimes: HirVec::new(),
371 ty_params: HirVec::new(),
372 where_clause: WhereClause {
374 predicates: HirVec::new(),
380 pub fn is_lt_parameterized(&self) -> bool {
381 !self.lifetimes.is_empty()
384 pub fn is_type_parameterized(&self) -> bool {
385 !self.ty_params.is_empty()
388 pub fn is_parameterized(&self) -> bool {
389 self.is_lt_parameterized() || self.is_type_parameterized()
393 pub enum UnsafeGeneric {
394 Region(LifetimeDef, &'static str),
395 Type(TyParam, &'static str),
399 pub fn attr_name(&self) -> &'static str {
401 UnsafeGeneric::Region(_, s) => s,
402 UnsafeGeneric::Type(_, s) => s,
408 pub fn carries_unsafe_attr(&self) -> Option<UnsafeGeneric> {
409 for r in &self.lifetimes {
411 return Some(UnsafeGeneric::Region(r.clone(), "may_dangle"));
414 for t in &self.ty_params {
416 return Some(UnsafeGeneric::Type(t.clone(), "may_dangle"));
423 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
424 /// to track the original form they had. Usefull for error messages.
425 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
426 pub enum SyntheticTyParamKind {
430 /// A `where` clause in a definition
431 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
432 pub struct WhereClause {
434 pub predicates: HirVec<WherePredicate>,
437 /// A single predicate in a `where` clause
438 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
439 pub enum WherePredicate {
440 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
441 BoundPredicate(WhereBoundPredicate),
442 /// A lifetime predicate, e.g. `'a: 'b+'c`
443 RegionPredicate(WhereRegionPredicate),
444 /// An equality predicate (unsupported)
445 EqPredicate(WhereEqPredicate),
448 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
449 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
450 pub struct WhereBoundPredicate {
452 /// Any lifetimes from a `for` binding
453 pub bound_lifetimes: HirVec<LifetimeDef>,
454 /// The type being bounded
455 pub bounded_ty: P<Ty>,
456 /// Trait and lifetime bounds (`Clone+Send+'static`)
457 pub bounds: TyParamBounds,
460 /// A lifetime predicate, e.g. `'a: 'b+'c`
461 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
462 pub struct WhereRegionPredicate {
464 pub lifetime: Lifetime,
465 pub bounds: HirVec<Lifetime>,
468 /// An equality predicate (unsupported), e.g. `T=int`
469 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
470 pub struct WhereEqPredicate {
477 pub type CrateConfig = HirVec<P<MetaItem>>;
479 /// The top-level data structure that stores the entire contents of
480 /// the crate currently being compiled.
482 /// For more details, see [the module-level README](README.md).
483 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
486 pub attrs: HirVec<Attribute>,
488 pub exported_macros: HirVec<MacroDef>,
490 // NB: We use a BTreeMap here so that `visit_all_items` iterates
491 // over the ids in increasing order. In principle it should not
492 // matter what order we visit things in, but in *practice* it
493 // does, because it can affect the order in which errors are
494 // detected, which in turn can make compile-fail tests yield
495 // slightly different results.
496 pub items: BTreeMap<NodeId, Item>,
498 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
499 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
500 pub bodies: BTreeMap<BodyId, Body>,
501 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
502 pub trait_default_impl: BTreeMap<DefId, NodeId>,
504 /// A list of the body ids written out in the order in which they
505 /// appear in the crate. If you're going to process all the bodies
506 /// in the crate, you should iterate over this list rather than the keys
508 pub body_ids: Vec<BodyId>,
512 pub fn item(&self, id: NodeId) -> &Item {
516 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
517 &self.trait_items[&id]
520 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
521 &self.impl_items[&id]
524 /// Visits all items in the crate in some deterministic (but
525 /// unspecified) order. If you just need to process every item,
526 /// but don't care about nesting, this method is the best choice.
528 /// If you do care about nesting -- usually because your algorithm
529 /// follows lexical scoping rules -- then you want a different
530 /// approach. You should override `visit_nested_item` in your
531 /// visitor and then call `intravisit::walk_crate` instead.
532 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
533 where V: itemlikevisit::ItemLikeVisitor<'hir>
535 for (_, item) in &self.items {
536 visitor.visit_item(item);
539 for (_, trait_item) in &self.trait_items {
540 visitor.visit_trait_item(trait_item);
543 for (_, impl_item) in &self.impl_items {
544 visitor.visit_impl_item(impl_item);
548 pub fn body(&self, id: BodyId) -> &Body {
553 /// A macro definition, in this crate or imported from another.
555 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
556 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
557 pub struct MacroDef {
560 pub attrs: HirVec<Attribute>,
563 pub body: TokenStream,
567 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
569 /// Statements in a block
570 pub stmts: HirVec<Stmt>,
571 /// An expression at the end of the block
572 /// without a semicolon, if any
573 pub expr: Option<P<Expr>>,
576 /// Distinguishes between `unsafe { ... }` and `{ ... }`
577 pub rules: BlockCheckMode,
579 /// If true, then there may exist `break 'a` values that aim to
580 /// break out of this block early. As of this writing, this is not
581 /// currently permitted in Rust itself, but it is generated as
582 /// part of `catch` statements.
583 pub targeted_by_break: bool,
586 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
594 impl fmt::Debug for Pat {
595 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
596 write!(f, "pat({}: {})", self.id,
597 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
602 // FIXME(#19596) this is a workaround, but there should be a better way
603 fn walk_<G>(&self, it: &mut G) -> bool
604 where G: FnMut(&Pat) -> bool
611 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
612 PatKind::Struct(_, ref fields, _) => {
613 fields.iter().all(|field| field.node.pat.walk_(it))
615 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
616 s.iter().all(|p| p.walk_(it))
618 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
621 PatKind::Slice(ref before, ref slice, ref after) => {
622 before.iter().all(|p| p.walk_(it)) &&
623 slice.iter().all(|p| p.walk_(it)) &&
624 after.iter().all(|p| p.walk_(it))
629 PatKind::Binding(..) |
630 PatKind::Path(_) => {
636 pub fn walk<F>(&self, mut it: F) -> bool
637 where F: FnMut(&Pat) -> bool
643 /// A single field in a struct pattern
645 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
646 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
647 /// except is_shorthand is true
648 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
649 pub struct FieldPat {
650 /// The identifier for the field
652 /// The pattern the field is destructured to
654 pub is_shorthand: bool,
657 /// Explicit binding annotations given in the HIR for a binding. Note
658 /// that this is not the final binding *mode* that we infer after type
660 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
661 pub enum BindingAnnotation {
662 /// No binding annotation given: this means that the final binding mode
663 /// will depend on whether we have skipped through a `&` reference
664 /// when matching. For example, the `x` in `Some(x)` will have binding
665 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
666 /// ultimately be inferred to be by-reference.
668 /// Note that implicit reference skipping is not implemented yet (#42640).
671 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
674 /// Annotated as `ref`, like `ref x`
677 /// Annotated as `ref mut x`.
681 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
687 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
689 /// Represents a wildcard pattern (`_`)
692 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
693 /// The `NodeId` is the canonical ID for the variable being bound,
694 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
695 /// which is the pattern ID of the first `x`.
696 Binding(BindingAnnotation, NodeId, Spanned<Name>, Option<P<Pat>>),
698 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
699 /// The `bool` is `true` in the presence of a `..`.
700 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
702 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
703 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
704 /// 0 <= position <= subpats.len()
705 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
707 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
710 /// A tuple pattern `(a, b)`.
711 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
712 /// 0 <= position <= subpats.len()
713 Tuple(HirVec<P<Pat>>, Option<usize>),
716 /// A reference pattern, e.g. `&mut (a, b)`
717 Ref(P<Pat>, Mutability),
720 /// A range pattern, e.g. `1...2` or `1..2`
721 Range(P<Expr>, P<Expr>, RangeEnd),
722 /// `[a, b, ..i, y, z]` is represented as:
723 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
724 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
727 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
728 pub enum Mutability {
734 /// Return MutMutable only if both arguments are mutable.
735 pub fn and(self, other: Self) -> Self {
738 MutImmutable => MutImmutable,
743 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
745 /// The `+` operator (addition)
747 /// The `-` operator (subtraction)
749 /// The `*` operator (multiplication)
751 /// The `/` operator (division)
753 /// The `%` operator (modulus)
755 /// The `&&` operator (logical and)
757 /// The `||` operator (logical or)
759 /// The `^` operator (bitwise xor)
761 /// The `&` operator (bitwise and)
763 /// The `|` operator (bitwise or)
765 /// The `<<` operator (shift left)
767 /// The `>>` operator (shift right)
769 /// The `==` operator (equality)
771 /// The `<` operator (less than)
773 /// The `<=` operator (less than or equal to)
775 /// The `!=` operator (not equal to)
777 /// The `>=` operator (greater than or equal to)
779 /// The `>` operator (greater than)
784 pub fn as_str(self) -> &'static str {
807 pub fn is_lazy(self) -> bool {
809 BiAnd | BiOr => true,
814 pub fn is_shift(self) -> bool {
816 BiShl | BiShr => true,
821 pub fn is_comparison(self) -> bool {
823 BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
839 /// Returns `true` if the binary operator takes its arguments by value
840 pub fn is_by_value(self) -> bool {
841 !self.is_comparison()
845 pub type BinOp = Spanned<BinOp_>;
847 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
849 /// The `*` operator for dereferencing
851 /// The `!` operator for logical inversion
853 /// The `-` operator for negation
858 pub fn as_str(self) -> &'static str {
866 /// Returns `true` if the unary operator takes its argument by value
867 pub fn is_by_value(self) -> bool {
869 UnNeg | UnNot => true,
876 pub type Stmt = Spanned<Stmt_>;
878 impl fmt::Debug for Stmt_ {
879 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
881 let spanned = codemap::dummy_spanned(self.clone());
885 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
889 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
891 /// Could be an item or a local (let) binding:
892 StmtDecl(P<Decl>, NodeId),
894 /// Expr without trailing semi-colon (must have unit type):
895 StmtExpr(P<Expr>, NodeId),
897 /// Expr with trailing semi-colon (may have any type):
898 StmtSemi(P<Expr>, NodeId),
902 pub fn attrs(&self) -> &[Attribute] {
904 StmtDecl(ref d, _) => d.node.attrs(),
906 StmtSemi(ref e, _) => &e.attrs,
910 pub fn id(&self) -> NodeId {
912 StmtDecl(_, id) => id,
913 StmtExpr(_, id) => id,
914 StmtSemi(_, id) => id,
919 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
920 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
923 pub ty: Option<P<Ty>>,
924 /// Initializer expression to set the value, if any
925 pub init: Option<P<Expr>>,
929 pub attrs: ThinVec<Attribute>,
930 pub source: LocalSource,
933 pub type Decl = Spanned<Decl_>;
935 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
937 /// A local (let) binding:
944 pub fn attrs(&self) -> &[Attribute] {
946 DeclLocal(ref l) => &l.attrs,
951 pub fn is_local(&self) -> bool {
953 Decl_::DeclLocal(_) => true,
959 /// represents one arm of a 'match'
960 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
962 pub attrs: HirVec<Attribute>,
963 pub pats: HirVec<P<Pat>>,
964 pub guard: Option<P<Expr>>,
968 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
970 pub name: Spanned<Name>,
973 pub is_shorthand: bool,
976 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
977 pub enum BlockCheckMode {
979 UnsafeBlock(UnsafeSource),
980 PushUnsafeBlock(UnsafeSource),
981 PopUnsafeBlock(UnsafeSource),
984 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
985 pub enum UnsafeSource {
990 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
995 /// The body of a function, closure, or constant value. In the case of
996 /// a function, the body contains not only the function body itself
997 /// (which is an expression), but also the argument patterns, since
998 /// those are something that the caller doesn't really care about.
1003 /// fn foo((x, y): (u32, u32)) -> u32 {
1008 /// Here, the `Body` associated with `foo()` would contain:
1010 /// - an `arguments` array containing the `(x, y)` pattern
1011 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1012 /// - `is_generator` would be false
1014 /// All bodies have an **owner**, which can be accessed via the HIR
1015 /// map using `body_owner_def_id()`.
1016 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1018 pub arguments: HirVec<Arg>,
1020 pub is_generator: bool,
1024 pub fn id(&self) -> BodyId {
1026 node_id: self.value.id
1032 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1037 pub attrs: ThinVec<Attribute>,
1041 impl fmt::Debug for Expr {
1042 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1043 write!(f, "expr({}: {})", self.id,
1044 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1048 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1050 /// A `box x` expression.
1052 /// An array (`[a, b, c, d]`)
1053 ExprArray(HirVec<Expr>),
1056 /// The first field resolves to the function itself (usually an `ExprPath`),
1057 /// and the second field is the list of arguments.
1058 /// This also represents calling the constructor of
1059 /// tuple-like ADTs such as tuple structs and enum variants.
1060 ExprCall(P<Expr>, HirVec<Expr>),
1061 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1063 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1064 /// (within the angle brackets).
1065 /// The first element of the vector of `Expr`s is the expression that evaluates
1066 /// to the object on which the method is being called on (the receiver),
1067 /// and the remaining elements are the rest of the arguments.
1068 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1069 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1070 ExprMethodCall(PathSegment, Span, HirVec<Expr>),
1071 /// A tuple (`(a, b, c ,d)`)
1072 ExprTup(HirVec<Expr>),
1073 /// A binary operation (For example: `a + b`, `a * b`)
1074 ExprBinary(BinOp, P<Expr>, P<Expr>),
1075 /// A unary operation (For example: `!x`, `*x`)
1076 ExprUnary(UnOp, P<Expr>),
1077 /// A literal (For example: `1`, `"foo"`)
1079 /// A cast (`foo as f64`)
1080 ExprCast(P<Expr>, P<Ty>),
1081 ExprType(P<Expr>, P<Ty>),
1082 /// An `if` block, with an optional else block
1084 /// `if expr { expr } else { expr }`
1085 ExprIf(P<Expr>, P<Expr>, Option<P<Expr>>),
1086 /// A while loop, with an optional label
1088 /// `'label: while expr { block }`
1089 ExprWhile(P<Expr>, P<Block>, Option<Spanned<Name>>),
1090 /// Conditionless loop (can be exited with break, continue, or return)
1092 /// `'label: loop { block }`
1093 ExprLoop(P<Block>, Option<Spanned<Name>>, LoopSource),
1094 /// A `match` block, with a source that indicates whether or not it is
1095 /// the result of a desugaring, and if so, which kind.
1096 ExprMatch(P<Expr>, HirVec<Arm>, MatchSource),
1097 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1099 /// The final span is the span of the argument block `|...|`
1101 /// This may also be a generator literal, indicated by the final boolean,
1102 /// in that case there is an GeneratorClause.
1103 ExprClosure(CaptureClause, P<FnDecl>, BodyId, Span, bool),
1104 /// A block (`{ ... }`)
1105 ExprBlock(P<Block>),
1107 /// An assignment (`a = foo()`)
1108 ExprAssign(P<Expr>, P<Expr>),
1109 /// An assignment with an operator
1111 /// For example, `a += 1`.
1112 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
1113 /// Access of a named struct field (`obj.foo`)
1114 ExprField(P<Expr>, Spanned<Name>),
1115 /// Access of an unnamed field of a struct or tuple-struct
1117 /// For example, `foo.0`.
1118 ExprTupField(P<Expr>, Spanned<usize>),
1119 /// An indexing operation (`foo[2]`)
1120 ExprIndex(P<Expr>, P<Expr>),
1122 /// Path to a definition, possibly containing lifetime or type parameters.
1125 /// A referencing operation (`&a` or `&mut a`)
1126 ExprAddrOf(Mutability, P<Expr>),
1127 /// A `break`, with an optional label to break
1128 ExprBreak(Destination, Option<P<Expr>>),
1129 /// A `continue`, with an optional label
1130 ExprAgain(Destination),
1131 /// A `return`, with an optional value to be returned
1132 ExprRet(Option<P<Expr>>),
1134 /// Inline assembly (from `asm!`), with its outputs and inputs.
1135 ExprInlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1137 /// A struct or struct-like variant literal expression.
1139 /// For example, `Foo {x: 1, y: 2}`, or
1140 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1141 ExprStruct(QPath, HirVec<Field>, Option<P<Expr>>),
1143 /// An array literal constructed from one repeated element.
1145 /// For example, `[1; 5]`. The first expression is the element
1146 /// to be repeated; the second is the number of times to repeat it.
1147 ExprRepeat(P<Expr>, BodyId),
1149 /// A suspension point for generators. This is `yield <expr>` in Rust.
1153 /// Optionally `Self`-qualified value/type path or associated extension.
1154 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1156 /// Path to a definition, optionally "fully-qualified" with a `Self`
1157 /// type, if the path points to an associated item in a trait.
1159 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1160 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1161 /// even though they both have the same two-segment `Clone::clone` `Path`.
1162 Resolved(Option<P<Ty>>, P<Path>),
1164 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1165 /// Will be resolved by type-checking to an associated item.
1167 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1168 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1169 /// the `X` and `Y` nodes each being a `TyPath(QPath::TypeRelative(..))`.
1170 TypeRelative(P<Ty>, P<PathSegment>)
1173 /// Hints at the original code for a let statement
1174 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1175 pub enum LocalSource {
1176 /// A `match _ { .. }`
1178 /// A desugared `for _ in _ { .. }` loop
1182 /// Hints at the original code for a `match _ { .. }`
1183 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1184 pub enum MatchSource {
1185 /// A `match _ { .. }`
1187 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1189 contains_else_clause: bool,
1191 /// A `while let _ = _ { .. }` (which was desugared to a
1192 /// `loop { match _ { .. } }`)
1194 /// A desugared `for _ in _ { .. }` loop
1196 /// A desugared `?` operator
1200 /// The loop type that yielded an ExprLoop
1201 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1202 pub enum LoopSource {
1203 /// A `loop { .. }` loop
1205 /// A `while let _ = _ { .. }` loop
1207 /// A `for _ in _ { .. }` loop
1211 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1212 pub enum LoopIdError {
1214 UnlabeledCfInWhileCondition,
1218 impl fmt::Display for LoopIdError {
1219 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1220 fmt::Display::fmt(match *self {
1221 LoopIdError::OutsideLoopScope => "not inside loop scope",
1222 LoopIdError::UnlabeledCfInWhileCondition =>
1223 "unlabeled control flow (break or continue) in while condition",
1224 LoopIdError::UnresolvedLabel => "label not found",
1229 // FIXME(cramertj) this should use `Result` once master compiles w/ a vesion of Rust where
1230 // `Result` implements `Encodable`/`Decodable`
1231 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1232 pub enum LoopIdResult {
1236 impl Into<Result<NodeId, LoopIdError>> for LoopIdResult {
1237 fn into(self) -> Result<NodeId, LoopIdError> {
1239 LoopIdResult::Ok(ok) => Ok(ok),
1240 LoopIdResult::Err(err) => Err(err),
1244 impl From<Result<NodeId, LoopIdError>> for LoopIdResult {
1245 fn from(res: Result<NodeId, LoopIdError>) -> Self {
1247 Ok(ok) => LoopIdResult::Ok(ok),
1248 Err(err) => LoopIdResult::Err(err),
1253 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1254 pub enum ScopeTarget {
1260 pub fn opt_id(self) -> Option<NodeId> {
1262 ScopeTarget::Block(node_id) |
1263 ScopeTarget::Loop(LoopIdResult::Ok(node_id)) => Some(node_id),
1264 ScopeTarget::Loop(LoopIdResult::Err(_)) => None,
1269 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1270 pub struct Destination {
1271 // This is `Some(_)` iff there is an explicit user-specified `label
1272 pub ident: Option<Spanned<Ident>>,
1274 // These errors are caught and then reported during the diagnostics pass in
1275 // librustc_passes/loops.rs
1276 pub target_id: ScopeTarget,
1279 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1280 pub enum CaptureClause {
1285 // NB: If you change this, you'll probably want to change the corresponding
1286 // type structure in middle/ty.rs as well.
1287 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1290 pub mutbl: Mutability,
1293 /// Represents a method's signature in a trait declaration or implementation.
1294 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1295 pub struct MethodSig {
1296 pub unsafety: Unsafety,
1297 pub constness: Constness,
1299 pub decl: P<FnDecl>,
1302 // The bodies for items are stored "out of line", in a separate
1303 // hashmap in the `Crate`. Here we just record the node-id of the item
1304 // so it can fetched later.
1305 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1306 pub struct TraitItemId {
1307 pub node_id: NodeId,
1310 /// Represents an item declaration within a trait declaration,
1311 /// possibly including a default implementation. A trait item is
1312 /// either required (meaning it doesn't have an implementation, just a
1313 /// signature) or provided (meaning it has a default implementation).
1314 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1315 pub struct TraitItem {
1319 pub attrs: HirVec<Attribute>,
1320 pub generics: Generics,
1321 pub node: TraitItemKind,
1325 /// A trait method's body (or just argument names).
1326 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1327 pub enum TraitMethod {
1328 /// No default body in the trait, just a signature.
1329 Required(HirVec<Spanned<Name>>),
1331 /// Both signature and body are provided in the trait.
1335 /// Represents a trait method or associated constant or type
1336 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1337 pub enum TraitItemKind {
1338 /// An associated constant with an optional value (otherwise `impl`s
1339 /// must contain a value)
1340 Const(P<Ty>, Option<BodyId>),
1341 /// A method with an optional body
1342 Method(MethodSig, TraitMethod),
1343 /// An associated type with (possibly empty) bounds and optional concrete
1345 Type(TyParamBounds, Option<P<Ty>>),
1348 // The bodies for items are stored "out of line", in a separate
1349 // hashmap in the `Crate`. Here we just record the node-id of the item
1350 // so it can fetched later.
1351 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1352 pub struct ImplItemId {
1353 pub node_id: NodeId,
1356 /// Represents anything within an `impl` block
1357 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1358 pub struct ImplItem {
1362 pub vis: Visibility,
1363 pub defaultness: Defaultness,
1364 pub attrs: HirVec<Attribute>,
1365 pub generics: Generics,
1366 pub node: ImplItemKind,
1370 /// Represents different contents within `impl`s
1371 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1372 pub enum ImplItemKind {
1373 /// An associated constant of the given type, set to the constant result
1374 /// of the expression
1375 Const(P<Ty>, BodyId),
1376 /// A method implementation with the given signature and body
1377 Method(MethodSig, BodyId),
1378 /// An associated type
1382 // Bind a type to an associated type: `A=Foo`.
1383 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1384 pub struct TypeBinding {
1392 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1400 impl fmt::Debug for Ty {
1401 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1402 write!(f, "type({})",
1403 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1407 /// Not represented directly in the AST, referred to by name through a ty_path.
1408 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1418 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1419 pub struct BareFnTy {
1420 pub unsafety: Unsafety,
1422 pub lifetimes: HirVec<LifetimeDef>,
1423 pub decl: P<FnDecl>,
1424 pub arg_names: HirVec<Spanned<Name>>,
1427 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1428 /// The different kinds of types recognized by the compiler
1430 /// A variable length slice (`[T]`)
1432 /// A fixed length array (`[T; n]`)
1433 TyArray(P<Ty>, BodyId),
1434 /// A raw pointer (`*const T` or `*mut T`)
1436 /// A reference (`&'a T` or `&'a mut T`)
1437 TyRptr(Lifetime, MutTy),
1438 /// A bare function (e.g. `fn(usize) -> bool`)
1439 TyBareFn(P<BareFnTy>),
1440 /// The never type (`!`)
1442 /// A tuple (`(A, B, C, D,...)`)
1443 TyTup(HirVec<P<Ty>>),
1444 /// A path to a type definition (`module::module::...::Type`), or an
1445 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1447 /// Type parameters may be stored in each `PathSegment`.
1449 /// A trait object type `Bound1 + Bound2 + Bound3`
1450 /// where `Bound` is a trait or a lifetime.
1451 TyTraitObject(HirVec<PolyTraitRef>, Lifetime),
1452 /// An `impl Bound1 + Bound2 + Bound3` type
1453 /// where `Bound` is a trait or a lifetime.
1454 TyImplTrait(TyParamBounds),
1457 /// TyInfer means the type should be inferred instead of it having been
1458 /// specified. This can appear anywhere in a type.
1460 /// Placeholder for a type that has failed to be defined.
1464 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1465 pub struct InlineAsmOutput {
1466 pub constraint: Symbol,
1468 pub is_indirect: bool,
1471 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1472 pub struct InlineAsm {
1474 pub asm_str_style: StrStyle,
1475 pub outputs: HirVec<InlineAsmOutput>,
1476 pub inputs: HirVec<Symbol>,
1477 pub clobbers: HirVec<Symbol>,
1479 pub alignstack: bool,
1480 pub dialect: AsmDialect,
1481 pub ctxt: SyntaxContext,
1484 /// represents an argument in a function header
1485 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1492 /// Represents the header (not the body) of a function declaration
1493 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1495 pub inputs: HirVec<P<Ty>>,
1496 pub output: FunctionRetTy,
1498 /// True if this function has an `self`, `&self` or `&mut self` receiver
1499 /// (but not a `self: Xxx` one).
1500 pub has_implicit_self: bool,
1503 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1509 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1510 pub enum Constness {
1515 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1516 pub enum Defaultness {
1517 Default { has_value: bool },
1522 pub fn has_value(&self) -> bool {
1524 Defaultness::Default { has_value, .. } => has_value,
1525 Defaultness::Final => true,
1529 pub fn is_final(&self) -> bool {
1530 *self == Defaultness::Final
1533 pub fn is_default(&self) -> bool {
1535 Defaultness::Default { .. } => true,
1541 impl fmt::Display for Unsafety {
1542 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1543 fmt::Display::fmt(match *self {
1544 Unsafety::Normal => "normal",
1545 Unsafety::Unsafe => "unsafe",
1551 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1552 pub enum ImplPolarity {
1553 /// `impl Trait for Type`
1555 /// `impl !Trait for Type`
1559 impl fmt::Debug for ImplPolarity {
1560 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1562 ImplPolarity::Positive => "positive".fmt(f),
1563 ImplPolarity::Negative => "negative".fmt(f),
1569 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1570 pub enum FunctionRetTy {
1571 /// Return type is not specified.
1573 /// Functions default to `()` and
1574 /// closures default to inference. Span points to where return
1575 /// type would be inserted.
1576 DefaultReturn(Span),
1581 impl FunctionRetTy {
1582 pub fn span(&self) -> Span {
1584 DefaultReturn(span) => span,
1585 Return(ref ty) => ty.span,
1590 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1592 /// A span from the first token past `{` to the last token until `}`.
1593 /// For `mod foo;`, the inner span ranges from the first token
1594 /// to the last token in the external file.
1596 pub item_ids: HirVec<ItemId>,
1599 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1600 pub struct ForeignMod {
1602 pub items: HirVec<ForeignItem>,
1605 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1606 pub struct GlobalAsm {
1608 pub ctxt: SyntaxContext,
1611 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1612 pub struct EnumDef {
1613 pub variants: HirVec<Variant>,
1616 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1617 pub struct Variant_ {
1619 pub attrs: HirVec<Attribute>,
1620 pub data: VariantData,
1621 /// Explicit discriminant, eg `Foo = 1`
1622 pub disr_expr: Option<BodyId>,
1625 pub type Variant = Spanned<Variant_>;
1627 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1629 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1630 /// Also produced for each element of a list `use`, e.g.
1631 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1634 /// Glob import, e.g. `use foo::*`.
1637 /// Degenerate list import, e.g. `use foo::{a, b}` produces
1638 /// an additional `use foo::{}` for performing checks such as
1639 /// unstable feature gating. May be removed in the future.
1643 /// TraitRef's appear in impls.
1645 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1646 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1647 /// trait being referred to but just a unique NodeId that serves as a key
1648 /// within the DefMap.
1649 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1650 pub struct TraitRef {
1655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1656 pub struct PolyTraitRef {
1657 /// The `'a` in `<'a> Foo<&'a T>`
1658 pub bound_lifetimes: HirVec<LifetimeDef>,
1660 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1661 pub trait_ref: TraitRef,
1666 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1667 pub enum Visibility {
1670 Restricted { path: P<Path>, id: NodeId },
1675 pub fn is_pub_restricted(&self) -> bool {
1676 use self::Visibility::*;
1679 &Inherited => false,
1681 &Restricted { .. } => true,
1686 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1687 pub struct StructField {
1690 pub vis: Visibility,
1693 pub attrs: HirVec<Attribute>,
1697 // Still necessary in couple of places
1698 pub fn is_positional(&self) -> bool {
1699 let first = self.name.as_str().as_bytes()[0];
1700 first >= b'0' && first <= b'9'
1704 /// Fields and Ids of enum variants and structs
1706 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1707 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1708 /// One shared Id can be successfully used for these two purposes.
1709 /// Id of the whole enum lives in `Item`.
1711 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1712 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1713 /// the variant itself" from enum variants.
1714 /// Id of the whole struct lives in `Item`.
1715 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1716 pub enum VariantData {
1717 Struct(HirVec<StructField>, NodeId),
1718 Tuple(HirVec<StructField>, NodeId),
1723 pub fn fields(&self) -> &[StructField] {
1725 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1729 pub fn id(&self) -> NodeId {
1731 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
1734 pub fn is_struct(&self) -> bool {
1735 if let VariantData::Struct(..) = *self {
1741 pub fn is_tuple(&self) -> bool {
1742 if let VariantData::Tuple(..) = *self {
1748 pub fn is_unit(&self) -> bool {
1749 if let VariantData::Unit(..) = *self {
1757 // The bodies for items are stored "out of line", in a separate
1758 // hashmap in the `Crate`. Here we just record the node-id of the item
1759 // so it can fetched later.
1760 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1767 /// The name might be a dummy name in case of anonymous items
1768 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1773 pub attrs: HirVec<Attribute>,
1775 pub vis: Visibility,
1779 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1781 /// An `extern crate` item, with optional original crate name,
1783 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1784 ItemExternCrate(Option<Name>),
1786 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
1790 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
1791 ItemUse(P<Path>, UseKind),
1794 ItemStatic(P<Ty>, Mutability, BodyId),
1796 ItemConst(P<Ty>, BodyId),
1797 /// A function declaration
1798 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, BodyId),
1801 /// An external module
1802 ItemForeignMod(ForeignMod),
1803 /// Module-level inline assembly (from global_asm!)
1804 ItemGlobalAsm(P<GlobalAsm>),
1805 /// A type alias, e.g. `type Foo = Bar<u8>`
1806 ItemTy(P<Ty>, Generics),
1807 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1808 ItemEnum(EnumDef, Generics),
1809 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1810 ItemStruct(VariantData, Generics),
1811 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
1812 ItemUnion(VariantData, Generics),
1813 /// Represents a Trait Declaration
1814 ItemTrait(Unsafety, Generics, TyParamBounds, HirVec<TraitItemRef>),
1816 // Default trait implementations
1818 /// `impl Trait for .. {}`
1819 ItemDefaultImpl(Unsafety, TraitRef),
1820 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1825 Option<TraitRef>, // (optional) trait this impl implements
1827 HirVec<ImplItemRef>),
1831 pub fn descriptive_variant(&self) -> &str {
1833 ItemExternCrate(..) => "extern crate",
1834 ItemUse(..) => "use",
1835 ItemStatic(..) => "static item",
1836 ItemConst(..) => "constant item",
1837 ItemFn(..) => "function",
1838 ItemMod(..) => "module",
1839 ItemForeignMod(..) => "foreign module",
1840 ItemGlobalAsm(..) => "global asm",
1841 ItemTy(..) => "type alias",
1842 ItemEnum(..) => "enum",
1843 ItemStruct(..) => "struct",
1844 ItemUnion(..) => "union",
1845 ItemTrait(..) => "trait",
1847 ItemDefaultImpl(..) => "item",
1851 pub fn adt_kind(&self) -> Option<AdtKind> {
1853 ItemStruct(..) => Some(AdtKind::Struct),
1854 ItemUnion(..) => Some(AdtKind::Union),
1855 ItemEnum(..) => Some(AdtKind::Enum),
1860 pub fn generics(&self) -> Option<&Generics> {
1862 ItemFn(_, _, _, _, ref generics, _) |
1863 ItemTy(_, ref generics) |
1864 ItemEnum(_, ref generics) |
1865 ItemStruct(_, ref generics) |
1866 ItemUnion(_, ref generics) |
1867 ItemTrait(_, ref generics, _, _) |
1868 ItemImpl(_, _, _, ref generics, _, _, _)=> generics,
1874 /// A reference from an trait to one of its associated items. This
1875 /// contains the item's id, naturally, but also the item's name and
1876 /// some other high-level details (like whether it is an associated
1877 /// type or method, and whether it is public). This allows other
1878 /// passes to find the impl they want without loading the id (which
1879 /// means fewer edges in the incremental compilation graph).
1880 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1881 pub struct TraitItemRef {
1882 pub id: TraitItemId,
1884 pub kind: AssociatedItemKind,
1886 pub defaultness: Defaultness,
1889 /// A reference from an impl to one of its associated items. This
1890 /// contains the item's id, naturally, but also the item's name and
1891 /// some other high-level details (like whether it is an associated
1892 /// type or method, and whether it is public). This allows other
1893 /// passes to find the impl they want without loading the id (which
1894 /// means fewer edges in the incremental compilation graph).
1895 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1896 pub struct ImplItemRef {
1899 pub kind: AssociatedItemKind,
1901 pub vis: Visibility,
1902 pub defaultness: Defaultness,
1905 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1906 pub enum AssociatedItemKind {
1908 Method { has_self: bool },
1912 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1913 pub struct ForeignItem {
1915 pub attrs: HirVec<Attribute>,
1916 pub node: ForeignItem_,
1919 pub vis: Visibility,
1922 /// An item within an `extern` block
1923 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1924 pub enum ForeignItem_ {
1925 /// A foreign function
1926 ForeignItemFn(P<FnDecl>, HirVec<Spanned<Name>>, Generics),
1927 /// A foreign static item (`static ext: u8`), with optional mutability
1928 /// (the boolean is true when mutable)
1929 ForeignItemStatic(P<Ty>, bool),
1935 pub fn descriptive_variant(&self) -> &str {
1937 ForeignItemFn(..) => "foreign function",
1938 ForeignItemStatic(..) => "foreign static item",
1939 ForeignItemType => "foreign type",
1944 /// A free variable referred to in a function.
1945 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
1946 pub struct Freevar {
1947 /// The variable being accessed free.
1950 // First span where it is accessed (there can be multiple).
1955 pub fn var_id(&self) -> NodeId {
1957 Def::Local(id) | Def::Upvar(id, ..) => id,
1958 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
1963 pub type FreevarMap = NodeMap<Vec<Freevar>>;
1965 pub type CaptureModeMap = NodeMap<CaptureClause>;
1967 #[derive(Clone, Debug)]
1968 pub struct TraitCandidate {
1970 pub import_id: Option<NodeId>,
1973 // Trait method resolution
1974 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
1976 // Map from the NodeId of a glob import to a list of items which are actually
1978 pub type GlobMap = NodeMap<FxHashSet<Name>>;