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_auto_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
1031 #[derive(Copy, Clone, Debug)]
1032 pub enum BodyOwnerKind {
1033 /// Functions and methods.
1036 /// Constants and associated constants.
1039 /// Initializer of a `static` item.
1044 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1049 pub attrs: ThinVec<Attribute>,
1053 impl fmt::Debug for Expr {
1054 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1055 write!(f, "expr({}: {})", self.id,
1056 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1060 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1062 /// A `box x` expression.
1064 /// An array (`[a, b, c, d]`)
1065 ExprArray(HirVec<Expr>),
1068 /// The first field resolves to the function itself (usually an `ExprPath`),
1069 /// and the second field is the list of arguments.
1070 /// This also represents calling the constructor of
1071 /// tuple-like ADTs such as tuple structs and enum variants.
1072 ExprCall(P<Expr>, HirVec<Expr>),
1073 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1075 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1076 /// (within the angle brackets).
1077 /// The first element of the vector of `Expr`s is the expression that evaluates
1078 /// to the object on which the method is being called on (the receiver),
1079 /// and the remaining elements are the rest of the arguments.
1080 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1081 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1082 ExprMethodCall(PathSegment, Span, HirVec<Expr>),
1083 /// A tuple (`(a, b, c ,d)`)
1084 ExprTup(HirVec<Expr>),
1085 /// A binary operation (For example: `a + b`, `a * b`)
1086 ExprBinary(BinOp, P<Expr>, P<Expr>),
1087 /// A unary operation (For example: `!x`, `*x`)
1088 ExprUnary(UnOp, P<Expr>),
1089 /// A literal (For example: `1`, `"foo"`)
1091 /// A cast (`foo as f64`)
1092 ExprCast(P<Expr>, P<Ty>),
1093 ExprType(P<Expr>, P<Ty>),
1094 /// An `if` block, with an optional else block
1096 /// `if expr { expr } else { expr }`
1097 ExprIf(P<Expr>, P<Expr>, Option<P<Expr>>),
1098 /// A while loop, with an optional label
1100 /// `'label: while expr { block }`
1101 ExprWhile(P<Expr>, P<Block>, Option<Spanned<Name>>),
1102 /// Conditionless loop (can be exited with break, continue, or return)
1104 /// `'label: loop { block }`
1105 ExprLoop(P<Block>, Option<Spanned<Name>>, LoopSource),
1106 /// A `match` block, with a source that indicates whether or not it is
1107 /// the result of a desugaring, and if so, which kind.
1108 ExprMatch(P<Expr>, HirVec<Arm>, MatchSource),
1109 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1111 /// The final span is the span of the argument block `|...|`
1113 /// This may also be a generator literal, indicated by the final boolean,
1114 /// in that case there is an GeneratorClause.
1115 ExprClosure(CaptureClause, P<FnDecl>, BodyId, Span, bool),
1116 /// A block (`{ ... }`)
1117 ExprBlock(P<Block>),
1119 /// An assignment (`a = foo()`)
1120 ExprAssign(P<Expr>, P<Expr>),
1121 /// An assignment with an operator
1123 /// For example, `a += 1`.
1124 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
1125 /// Access of a named struct field (`obj.foo`)
1126 ExprField(P<Expr>, Spanned<Name>),
1127 /// Access of an unnamed field of a struct or tuple-struct
1129 /// For example, `foo.0`.
1130 ExprTupField(P<Expr>, Spanned<usize>),
1131 /// An indexing operation (`foo[2]`)
1132 ExprIndex(P<Expr>, P<Expr>),
1134 /// Path to a definition, possibly containing lifetime or type parameters.
1137 /// A referencing operation (`&a` or `&mut a`)
1138 ExprAddrOf(Mutability, P<Expr>),
1139 /// A `break`, with an optional label to break
1140 ExprBreak(Destination, Option<P<Expr>>),
1141 /// A `continue`, with an optional label
1142 ExprAgain(Destination),
1143 /// A `return`, with an optional value to be returned
1144 ExprRet(Option<P<Expr>>),
1146 /// Inline assembly (from `asm!`), with its outputs and inputs.
1147 ExprInlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1149 /// A struct or struct-like variant literal expression.
1151 /// For example, `Foo {x: 1, y: 2}`, or
1152 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1153 ExprStruct(QPath, HirVec<Field>, Option<P<Expr>>),
1155 /// An array literal constructed from one repeated element.
1157 /// For example, `[1; 5]`. The first expression is the element
1158 /// to be repeated; the second is the number of times to repeat it.
1159 ExprRepeat(P<Expr>, BodyId),
1161 /// A suspension point for generators. This is `yield <expr>` in Rust.
1165 /// Optionally `Self`-qualified value/type path or associated extension.
1166 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1168 /// Path to a definition, optionally "fully-qualified" with a `Self`
1169 /// type, if the path points to an associated item in a trait.
1171 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1172 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1173 /// even though they both have the same two-segment `Clone::clone` `Path`.
1174 Resolved(Option<P<Ty>>, P<Path>),
1176 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1177 /// Will be resolved by type-checking to an associated item.
1179 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1180 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1181 /// the `X` and `Y` nodes each being a `TyPath(QPath::TypeRelative(..))`.
1182 TypeRelative(P<Ty>, P<PathSegment>)
1185 /// Hints at the original code for a let statement
1186 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1187 pub enum LocalSource {
1188 /// A `match _ { .. }`
1190 /// A desugared `for _ in _ { .. }` loop
1194 /// Hints at the original code for a `match _ { .. }`
1195 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1196 pub enum MatchSource {
1197 /// A `match _ { .. }`
1199 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1201 contains_else_clause: bool,
1203 /// A `while let _ = _ { .. }` (which was desugared to a
1204 /// `loop { match _ { .. } }`)
1206 /// A desugared `for _ in _ { .. }` loop
1208 /// A desugared `?` operator
1212 /// The loop type that yielded an ExprLoop
1213 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1214 pub enum LoopSource {
1215 /// A `loop { .. }` loop
1217 /// A `while let _ = _ { .. }` loop
1219 /// A `for _ in _ { .. }` loop
1223 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1224 pub enum LoopIdError {
1226 UnlabeledCfInWhileCondition,
1230 impl fmt::Display for LoopIdError {
1231 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1232 fmt::Display::fmt(match *self {
1233 LoopIdError::OutsideLoopScope => "not inside loop scope",
1234 LoopIdError::UnlabeledCfInWhileCondition =>
1235 "unlabeled control flow (break or continue) in while condition",
1236 LoopIdError::UnresolvedLabel => "label not found",
1241 // FIXME(cramertj) this should use `Result` once master compiles w/ a vesion of Rust where
1242 // `Result` implements `Encodable`/`Decodable`
1243 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1244 pub enum LoopIdResult {
1248 impl Into<Result<NodeId, LoopIdError>> for LoopIdResult {
1249 fn into(self) -> Result<NodeId, LoopIdError> {
1251 LoopIdResult::Ok(ok) => Ok(ok),
1252 LoopIdResult::Err(err) => Err(err),
1256 impl From<Result<NodeId, LoopIdError>> for LoopIdResult {
1257 fn from(res: Result<NodeId, LoopIdError>) -> Self {
1259 Ok(ok) => LoopIdResult::Ok(ok),
1260 Err(err) => LoopIdResult::Err(err),
1265 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1266 pub enum ScopeTarget {
1272 pub fn opt_id(self) -> Option<NodeId> {
1274 ScopeTarget::Block(node_id) |
1275 ScopeTarget::Loop(LoopIdResult::Ok(node_id)) => Some(node_id),
1276 ScopeTarget::Loop(LoopIdResult::Err(_)) => None,
1281 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1282 pub struct Destination {
1283 // This is `Some(_)` iff there is an explicit user-specified `label
1284 pub ident: Option<Spanned<Ident>>,
1286 // These errors are caught and then reported during the diagnostics pass in
1287 // librustc_passes/loops.rs
1288 pub target_id: ScopeTarget,
1291 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1292 pub enum CaptureClause {
1297 // NB: If you change this, you'll probably want to change the corresponding
1298 // type structure in middle/ty.rs as well.
1299 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1302 pub mutbl: Mutability,
1305 /// Represents a method's signature in a trait declaration or implementation.
1306 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1307 pub struct MethodSig {
1308 pub unsafety: Unsafety,
1309 pub constness: Constness,
1311 pub decl: P<FnDecl>,
1314 // The bodies for items are stored "out of line", in a separate
1315 // hashmap in the `Crate`. Here we just record the node-id of the item
1316 // so it can fetched later.
1317 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1318 pub struct TraitItemId {
1319 pub node_id: NodeId,
1322 /// Represents an item declaration within a trait declaration,
1323 /// possibly including a default implementation. A trait item is
1324 /// either required (meaning it doesn't have an implementation, just a
1325 /// signature) or provided (meaning it has a default implementation).
1326 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1327 pub struct TraitItem {
1331 pub attrs: HirVec<Attribute>,
1332 pub generics: Generics,
1333 pub node: TraitItemKind,
1337 /// A trait method's body (or just argument names).
1338 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1339 pub enum TraitMethod {
1340 /// No default body in the trait, just a signature.
1341 Required(HirVec<Spanned<Name>>),
1343 /// Both signature and body are provided in the trait.
1347 /// Represents a trait method or associated constant or type
1348 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1349 pub enum TraitItemKind {
1350 /// An associated constant with an optional value (otherwise `impl`s
1351 /// must contain a value)
1352 Const(P<Ty>, Option<BodyId>),
1353 /// A method with an optional body
1354 Method(MethodSig, TraitMethod),
1355 /// An associated type with (possibly empty) bounds and optional concrete
1357 Type(TyParamBounds, Option<P<Ty>>),
1360 // The bodies for items are stored "out of line", in a separate
1361 // hashmap in the `Crate`. Here we just record the node-id of the item
1362 // so it can fetched later.
1363 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1364 pub struct ImplItemId {
1365 pub node_id: NodeId,
1368 /// Represents anything within an `impl` block
1369 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1370 pub struct ImplItem {
1374 pub vis: Visibility,
1375 pub defaultness: Defaultness,
1376 pub attrs: HirVec<Attribute>,
1377 pub generics: Generics,
1378 pub node: ImplItemKind,
1382 /// Represents different contents within `impl`s
1383 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1384 pub enum ImplItemKind {
1385 /// An associated constant of the given type, set to the constant result
1386 /// of the expression
1387 Const(P<Ty>, BodyId),
1388 /// A method implementation with the given signature and body
1389 Method(MethodSig, BodyId),
1390 /// An associated type
1394 // Bind a type to an associated type: `A=Foo`.
1395 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1396 pub struct TypeBinding {
1404 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1412 impl fmt::Debug for Ty {
1413 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1414 write!(f, "type({})",
1415 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1419 /// Not represented directly in the AST, referred to by name through a ty_path.
1420 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1430 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1431 pub struct BareFnTy {
1432 pub unsafety: Unsafety,
1434 pub lifetimes: HirVec<LifetimeDef>,
1435 pub decl: P<FnDecl>,
1436 pub arg_names: HirVec<Spanned<Name>>,
1439 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1440 /// The different kinds of types recognized by the compiler
1442 /// A variable length slice (`[T]`)
1444 /// A fixed length array (`[T; n]`)
1445 TyArray(P<Ty>, BodyId),
1446 /// A raw pointer (`*const T` or `*mut T`)
1448 /// A reference (`&'a T` or `&'a mut T`)
1449 TyRptr(Lifetime, MutTy),
1450 /// A bare function (e.g. `fn(usize) -> bool`)
1451 TyBareFn(P<BareFnTy>),
1452 /// The never type (`!`)
1454 /// A tuple (`(A, B, C, D,...)`)
1455 TyTup(HirVec<P<Ty>>),
1456 /// A path to a type definition (`module::module::...::Type`), or an
1457 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1459 /// Type parameters may be stored in each `PathSegment`.
1461 /// A trait object type `Bound1 + Bound2 + Bound3`
1462 /// where `Bound` is a trait or a lifetime.
1463 TyTraitObject(HirVec<PolyTraitRef>, Lifetime),
1464 /// An `impl Bound1 + Bound2 + Bound3` type
1465 /// where `Bound` is a trait or a lifetime.
1466 TyImplTrait(TyParamBounds),
1469 /// TyInfer means the type should be inferred instead of it having been
1470 /// specified. This can appear anywhere in a type.
1472 /// Placeholder for a type that has failed to be defined.
1476 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1477 pub struct InlineAsmOutput {
1478 pub constraint: Symbol,
1480 pub is_indirect: bool,
1483 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1484 pub struct InlineAsm {
1486 pub asm_str_style: StrStyle,
1487 pub outputs: HirVec<InlineAsmOutput>,
1488 pub inputs: HirVec<Symbol>,
1489 pub clobbers: HirVec<Symbol>,
1491 pub alignstack: bool,
1492 pub dialect: AsmDialect,
1493 pub ctxt: SyntaxContext,
1496 /// represents an argument in a function header
1497 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1504 /// Represents the header (not the body) of a function declaration
1505 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1507 pub inputs: HirVec<P<Ty>>,
1508 pub output: FunctionRetTy,
1510 /// True if this function has an `self`, `&self` or `&mut self` receiver
1511 /// (but not a `self: Xxx` one).
1512 pub has_implicit_self: bool,
1515 /// Is the trait definition an auto trait?
1516 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1522 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1528 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1529 pub enum Constness {
1534 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1535 pub enum Defaultness {
1536 Default { has_value: bool },
1541 pub fn has_value(&self) -> bool {
1543 Defaultness::Default { has_value, .. } => has_value,
1544 Defaultness::Final => true,
1548 pub fn is_final(&self) -> bool {
1549 *self == Defaultness::Final
1552 pub fn is_default(&self) -> bool {
1554 Defaultness::Default { .. } => true,
1560 impl fmt::Display for Unsafety {
1561 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1562 fmt::Display::fmt(match *self {
1563 Unsafety::Normal => "normal",
1564 Unsafety::Unsafe => "unsafe",
1570 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1571 pub enum ImplPolarity {
1572 /// `impl Trait for Type`
1574 /// `impl !Trait for Type`
1578 impl fmt::Debug for ImplPolarity {
1579 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1581 ImplPolarity::Positive => "positive".fmt(f),
1582 ImplPolarity::Negative => "negative".fmt(f),
1588 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1589 pub enum FunctionRetTy {
1590 /// Return type is not specified.
1592 /// Functions default to `()` and
1593 /// closures default to inference. Span points to where return
1594 /// type would be inserted.
1595 DefaultReturn(Span),
1600 impl FunctionRetTy {
1601 pub fn span(&self) -> Span {
1603 DefaultReturn(span) => span,
1604 Return(ref ty) => ty.span,
1609 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1611 /// A span from the first token past `{` to the last token until `}`.
1612 /// For `mod foo;`, the inner span ranges from the first token
1613 /// to the last token in the external file.
1615 pub item_ids: HirVec<ItemId>,
1618 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1619 pub struct ForeignMod {
1621 pub items: HirVec<ForeignItem>,
1624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1625 pub struct GlobalAsm {
1627 pub ctxt: SyntaxContext,
1630 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1631 pub struct EnumDef {
1632 pub variants: HirVec<Variant>,
1635 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1636 pub struct Variant_ {
1638 pub attrs: HirVec<Attribute>,
1639 pub data: VariantData,
1640 /// Explicit discriminant, eg `Foo = 1`
1641 pub disr_expr: Option<BodyId>,
1644 pub type Variant = Spanned<Variant_>;
1646 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1648 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1649 /// Also produced for each element of a list `use`, e.g.
1650 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1653 /// Glob import, e.g. `use foo::*`.
1656 /// Degenerate list import, e.g. `use foo::{a, b}` produces
1657 /// an additional `use foo::{}` for performing checks such as
1658 /// unstable feature gating. May be removed in the future.
1662 /// TraitRef's appear in impls.
1664 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1665 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1666 /// trait being referred to but just a unique NodeId that serves as a key
1667 /// within the DefMap.
1668 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1669 pub struct TraitRef {
1674 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1675 pub struct PolyTraitRef {
1676 /// The `'a` in `<'a> Foo<&'a T>`
1677 pub bound_lifetimes: HirVec<LifetimeDef>,
1679 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1680 pub trait_ref: TraitRef,
1685 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1686 pub enum Visibility {
1689 Restricted { path: P<Path>, id: NodeId },
1694 pub fn is_pub_restricted(&self) -> bool {
1695 use self::Visibility::*;
1698 &Inherited => false,
1700 &Restricted { .. } => true,
1705 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1706 pub struct StructField {
1709 pub vis: Visibility,
1712 pub attrs: HirVec<Attribute>,
1716 // Still necessary in couple of places
1717 pub fn is_positional(&self) -> bool {
1718 let first = self.name.as_str().as_bytes()[0];
1719 first >= b'0' && first <= b'9'
1723 /// Fields and Ids of enum variants and structs
1725 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1726 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1727 /// One shared Id can be successfully used for these two purposes.
1728 /// Id of the whole enum lives in `Item`.
1730 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1731 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1732 /// the variant itself" from enum variants.
1733 /// Id of the whole struct lives in `Item`.
1734 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1735 pub enum VariantData {
1736 Struct(HirVec<StructField>, NodeId),
1737 Tuple(HirVec<StructField>, NodeId),
1742 pub fn fields(&self) -> &[StructField] {
1744 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1748 pub fn id(&self) -> NodeId {
1750 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
1753 pub fn is_struct(&self) -> bool {
1754 if let VariantData::Struct(..) = *self {
1760 pub fn is_tuple(&self) -> bool {
1761 if let VariantData::Tuple(..) = *self {
1767 pub fn is_unit(&self) -> bool {
1768 if let VariantData::Unit(..) = *self {
1776 // The bodies for items are stored "out of line", in a separate
1777 // hashmap in the `Crate`. Here we just record the node-id of the item
1778 // so it can fetched later.
1779 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1786 /// The name might be a dummy name in case of anonymous items
1787 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1792 pub attrs: HirVec<Attribute>,
1794 pub vis: Visibility,
1798 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1800 /// An `extern crate` item, with optional original crate name,
1802 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1803 ItemExternCrate(Option<Name>),
1805 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
1809 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
1810 ItemUse(P<Path>, UseKind),
1813 ItemStatic(P<Ty>, Mutability, BodyId),
1815 ItemConst(P<Ty>, BodyId),
1816 /// A function declaration
1817 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, BodyId),
1820 /// An external module
1821 ItemForeignMod(ForeignMod),
1822 /// Module-level inline assembly (from global_asm!)
1823 ItemGlobalAsm(P<GlobalAsm>),
1824 /// A type alias, e.g. `type Foo = Bar<u8>`
1825 ItemTy(P<Ty>, Generics),
1826 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1827 ItemEnum(EnumDef, Generics),
1828 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1829 ItemStruct(VariantData, Generics),
1830 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
1831 ItemUnion(VariantData, Generics),
1832 /// Represents a Trait Declaration
1833 ItemTrait(IsAuto, Unsafety, Generics, TyParamBounds, HirVec<TraitItemRef>),
1835 /// Auto trait implementations
1837 /// `impl Trait for .. {}`
1838 ItemAutoImpl(Unsafety, TraitRef),
1839 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1844 Option<TraitRef>, // (optional) trait this impl implements
1846 HirVec<ImplItemRef>),
1850 pub fn descriptive_variant(&self) -> &str {
1852 ItemExternCrate(..) => "extern crate",
1853 ItemUse(..) => "use",
1854 ItemStatic(..) => "static item",
1855 ItemConst(..) => "constant item",
1856 ItemFn(..) => "function",
1857 ItemMod(..) => "module",
1858 ItemForeignMod(..) => "foreign module",
1859 ItemGlobalAsm(..) => "global asm",
1860 ItemTy(..) => "type alias",
1861 ItemEnum(..) => "enum",
1862 ItemStruct(..) => "struct",
1863 ItemUnion(..) => "union",
1864 ItemTrait(..) => "trait",
1866 ItemAutoImpl(..) => "item",
1870 pub fn adt_kind(&self) -> Option<AdtKind> {
1872 ItemStruct(..) => Some(AdtKind::Struct),
1873 ItemUnion(..) => Some(AdtKind::Union),
1874 ItemEnum(..) => Some(AdtKind::Enum),
1879 pub fn generics(&self) -> Option<&Generics> {
1881 ItemFn(_, _, _, _, ref generics, _) |
1882 ItemTy(_, ref generics) |
1883 ItemEnum(_, ref generics) |
1884 ItemStruct(_, ref generics) |
1885 ItemUnion(_, ref generics) |
1886 ItemTrait(_, _, ref generics, _, _) |
1887 ItemImpl(_, _, _, ref generics, _, _, _)=> generics,
1893 /// A reference from an trait to one of its associated items. This
1894 /// contains the item's id, naturally, but also the item's name and
1895 /// some other high-level details (like whether it is an associated
1896 /// type or method, and whether it is public). This allows other
1897 /// passes to find the impl they want without loading the id (which
1898 /// means fewer edges in the incremental compilation graph).
1899 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1900 pub struct TraitItemRef {
1901 pub id: TraitItemId,
1903 pub kind: AssociatedItemKind,
1905 pub defaultness: Defaultness,
1908 /// A reference from an impl to one of its associated items. This
1909 /// contains the item's id, naturally, but also the item's name and
1910 /// some other high-level details (like whether it is an associated
1911 /// type or method, and whether it is public). This allows other
1912 /// passes to find the impl they want without loading the id (which
1913 /// means fewer edges in the incremental compilation graph).
1914 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1915 pub struct ImplItemRef {
1918 pub kind: AssociatedItemKind,
1920 pub vis: Visibility,
1921 pub defaultness: Defaultness,
1924 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1925 pub enum AssociatedItemKind {
1927 Method { has_self: bool },
1931 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1932 pub struct ForeignItem {
1934 pub attrs: HirVec<Attribute>,
1935 pub node: ForeignItem_,
1938 pub vis: Visibility,
1941 /// An item within an `extern` block
1942 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1943 pub enum ForeignItem_ {
1944 /// A foreign function
1945 ForeignItemFn(P<FnDecl>, HirVec<Spanned<Name>>, Generics),
1946 /// A foreign static item (`static ext: u8`), with optional mutability
1947 /// (the boolean is true when mutable)
1948 ForeignItemStatic(P<Ty>, bool),
1954 pub fn descriptive_variant(&self) -> &str {
1956 ForeignItemFn(..) => "foreign function",
1957 ForeignItemStatic(..) => "foreign static item",
1958 ForeignItemType => "foreign type",
1963 /// A free variable referred to in a function.
1964 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
1965 pub struct Freevar {
1966 /// The variable being accessed free.
1969 // First span where it is accessed (there can be multiple).
1974 pub fn var_id(&self) -> NodeId {
1976 Def::Local(id) | Def::Upvar(id, ..) => id,
1977 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
1982 pub type FreevarMap = NodeMap<Vec<Freevar>>;
1984 pub type CaptureModeMap = NodeMap<CaptureClause>;
1986 #[derive(Clone, Debug)]
1987 pub struct TraitCandidate {
1989 pub import_id: Option<NodeId>,
1992 // Trait method resolution
1993 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
1995 // Map from the NodeId of a glob import to a list of items which are actually
1997 pub type GlobMap = NodeMap<FxHashSet<Name>>;