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 serialize::{self, Encoder, Encodable, Decoder, Decodable};
49 use std::collections::BTreeMap;
52 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
53 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
54 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
55 /// of `Vec` to avoid keeping extra capacity.
56 pub type HirVec<T> = P<[T]>;
58 macro_rules! hir_vec {
59 ($elem:expr; $n:expr) => (
60 $crate::hir::HirVec::from(vec![$elem; $n])
63 $crate::hir::HirVec::from(vec![$($x),*])
65 ($($x:expr,)*) => (hir_vec![$($x),*])
72 pub mod itemlikevisit;
79 /// A HirId uniquely identifies a node in the HIR of the current crate. It is
80 /// composed of the `owner`, which is the DefIndex of the directly enclosing
81 /// hir::Item, hir::TraitItem, or hir::ImplItem (i.e. the closest "item-like"),
82 /// and the `local_id` which is unique within the given owner.
84 /// This two-level structure makes for more stable values: One can move an item
85 /// around within the source code, or add or remove stuff before it, without
86 /// the local_id part of the HirId changing, which is a very useful property in
87 /// incremental compilation where we have to persist things through changes to
89 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
92 pub local_id: ItemLocalId,
95 impl serialize::UseSpecializedEncodable for HirId {
96 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
107 impl serialize::UseSpecializedDecodable for HirId {
108 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
109 let owner = DefIndex::decode(d)?;
110 let local_id = ItemLocalId::decode(d)?;
120 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
121 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
122 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
123 /// the node's position within the owning item in any way, but there is a
124 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
125 /// integers starting at zero, so a mapping that maps all or most nodes within
126 /// an "item-like" to something else can be implement by a `Vec` instead of a
127 /// tree or hash map.
128 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug,
129 RustcEncodable, RustcDecodable)]
130 pub struct ItemLocalId(pub u32);
133 pub fn as_usize(&self) -> usize {
138 impl indexed_vec::Idx for ItemLocalId {
139 fn new(idx: usize) -> Self {
140 debug_assert!((idx as u32) as usize == idx);
141 ItemLocalId(idx as u32)
144 fn index(self) -> usize {
149 /// The `HirId` corresponding to CRATE_NODE_ID and CRATE_DEF_INDEX
150 pub const CRATE_HIR_ID: HirId = HirId {
151 owner: CRATE_DEF_INDEX,
152 local_id: ItemLocalId(0)
155 pub const DUMMY_HIR_ID: HirId = HirId {
156 owner: CRATE_DEF_INDEX,
157 local_id: DUMMY_ITEM_LOCAL_ID,
160 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId(!0);
162 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
163 pub struct Lifetime {
167 /// Either "'a", referring to a named lifetime definition,
168 /// or "" (aka keywords::Invalid), for elision placeholders.
170 /// HIR lowering inserts these placeholders in type paths that
171 /// refer to type definitions needing lifetime parameters,
172 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
173 pub name: LifetimeName,
176 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
177 pub enum LifetimeName {
185 pub fn name(&self) -> Name {
186 use self::LifetimeName::*;
188 Implicit => keywords::Invalid.name(),
189 Underscore => Symbol::intern("'_"),
190 Static => keywords::StaticLifetime.name(),
196 impl fmt::Debug for Lifetime {
197 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
201 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
206 pub fn is_elided(&self) -> bool {
207 use self::LifetimeName::*;
209 Implicit | Underscore => true,
210 Static | Name(_) => false,
214 pub fn is_static(&self) -> bool {
215 self.name == LifetimeName::Static
219 /// A lifetime definition, eg `'a: 'b+'c+'d`
220 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
221 pub struct LifetimeDef {
222 pub lifetime: Lifetime,
223 pub bounds: HirVec<Lifetime>,
224 pub pure_wrt_drop: bool,
225 // Indicates that the lifetime definition was synthetically added
226 // as a result of an in-band lifetime usage like
227 // `fn foo(x: &'a u8) -> &'a u8 { x }`
231 /// A "Path" is essentially Rust's notion of a name; for instance:
232 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
233 /// along with a bunch of supporting information.
234 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
237 /// The definition that the path resolved to.
239 /// The segments in the path: the things separated by `::`.
240 pub segments: HirVec<PathSegment>,
244 pub fn is_global(&self) -> bool {
245 !self.segments.is_empty() && self.segments[0].name == keywords::CrateRoot.name()
249 impl fmt::Debug for Path {
250 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
251 write!(f, "path({})",
252 print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
256 /// A segment of a path: an identifier, an optional lifetime, and a set of
258 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
259 pub struct PathSegment {
260 /// The identifier portion of this path segment.
263 /// Type/lifetime parameters attached to this path. They come in
264 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
265 /// this is more than just simple syntactic sugar; the use of
266 /// parens affects the region binding rules, so we preserve the
268 pub parameters: Option<P<PathParameters>>,
270 /// Whether to infer remaining type parameters, if any.
271 /// This only applies to expression and pattern paths, and
272 /// out of those only the segments with no type parameters
273 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
274 pub infer_types: bool,
278 /// Convert an identifier to the corresponding segment.
279 pub fn from_name(name: Name) -> PathSegment {
287 pub fn new(name: Name, parameters: PathParameters, infer_types: bool) -> Self {
291 parameters: if parameters.is_empty() {
299 // FIXME: hack required because you can't create a static
300 // PathParameters, so you can't just return a &PathParameters.
301 pub fn with_parameters<F, R>(&self, f: F) -> R
302 where F: FnOnce(&PathParameters) -> R
304 let dummy = PathParameters::none();
305 f(if let Some(ref params) = self.parameters {
313 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
314 pub struct PathParameters {
315 /// The lifetime parameters for this path segment.
316 pub lifetimes: HirVec<Lifetime>,
317 /// The type parameters for this path segment, if present.
318 pub types: HirVec<P<Ty>>,
319 /// Bindings (equality constraints) on associated types, if present.
320 /// E.g., `Foo<A=Bar>`.
321 pub bindings: HirVec<TypeBinding>,
322 /// Were parameters written in parenthesized form `Fn(T) -> U`?
323 /// This is required mostly for pretty-printing and diagnostics,
324 /// but also for changing lifetime elision rules to be "function-like".
325 pub parenthesized: bool,
328 impl PathParameters {
329 pub fn none() -> Self {
331 lifetimes: HirVec::new(),
332 types: HirVec::new(),
333 bindings: HirVec::new(),
334 parenthesized: false,
338 pub fn is_empty(&self) -> bool {
339 self.lifetimes.is_empty() && self.types.is_empty() &&
340 self.bindings.is_empty() && !self.parenthesized
343 pub fn inputs(&self) -> &[P<Ty>] {
344 if self.parenthesized {
345 if let Some(ref ty) = self.types.get(0) {
346 if let TyTup(ref tys) = ty.node {
351 bug!("PathParameters::inputs: not a `Fn(T) -> U`");
355 /// The AST represents all type param bounds as types.
356 /// typeck::collect::compute_bounds matches these against
357 /// the "special" built-in traits (see middle::lang_items) and
358 /// detects Copy, Send and Sync.
359 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
360 pub enum TyParamBound {
361 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
362 RegionTyParamBound(Lifetime),
365 /// A modifier on a bound, currently this is only used for `?Sized`, where the
366 /// modifier is `Maybe`. Negative bounds should also be handled here.
367 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
368 pub enum TraitBoundModifier {
373 pub type TyParamBounds = HirVec<TyParamBound>;
375 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
379 pub bounds: TyParamBounds,
380 pub default: Option<P<Ty>>,
382 pub pure_wrt_drop: bool,
383 pub synthetic: Option<SyntheticTyParamKind>,
386 /// Represents lifetimes and type parameters attached to a declaration
387 /// of a function, enum, trait, etc.
388 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
389 pub struct Generics {
390 pub lifetimes: HirVec<LifetimeDef>,
391 pub ty_params: HirVec<TyParam>,
392 pub where_clause: WhereClause,
397 pub fn empty() -> Generics {
399 lifetimes: HirVec::new(),
400 ty_params: HirVec::new(),
401 where_clause: WhereClause {
403 predicates: HirVec::new(),
409 pub fn is_lt_parameterized(&self) -> bool {
410 !self.lifetimes.is_empty()
413 pub fn is_type_parameterized(&self) -> bool {
414 !self.ty_params.is_empty()
417 pub fn is_parameterized(&self) -> bool {
418 self.is_lt_parameterized() || self.is_type_parameterized()
422 pub enum UnsafeGeneric {
423 Region(LifetimeDef, &'static str),
424 Type(TyParam, &'static str),
428 pub fn attr_name(&self) -> &'static str {
430 UnsafeGeneric::Region(_, s) => s,
431 UnsafeGeneric::Type(_, s) => s,
437 pub fn carries_unsafe_attr(&self) -> Option<UnsafeGeneric> {
438 for r in &self.lifetimes {
440 return Some(UnsafeGeneric::Region(r.clone(), "may_dangle"));
443 for t in &self.ty_params {
445 return Some(UnsafeGeneric::Type(t.clone(), "may_dangle"));
452 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
453 /// to track the original form they had. Usefull for error messages.
454 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
455 pub enum SyntheticTyParamKind {
459 /// A `where` clause in a definition
460 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
461 pub struct WhereClause {
463 pub predicates: HirVec<WherePredicate>,
466 /// A single predicate in a `where` clause
467 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
468 pub enum WherePredicate {
469 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
470 BoundPredicate(WhereBoundPredicate),
471 /// A lifetime predicate, e.g. `'a: 'b+'c`
472 RegionPredicate(WhereRegionPredicate),
473 /// An equality predicate (unsupported)
474 EqPredicate(WhereEqPredicate),
477 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
478 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
479 pub struct WhereBoundPredicate {
481 /// Any lifetimes from a `for` binding
482 pub bound_lifetimes: HirVec<LifetimeDef>,
483 /// The type being bounded
484 pub bounded_ty: P<Ty>,
485 /// Trait and lifetime bounds (`Clone+Send+'static`)
486 pub bounds: TyParamBounds,
489 /// A lifetime predicate, e.g. `'a: 'b+'c`
490 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
491 pub struct WhereRegionPredicate {
493 pub lifetime: Lifetime,
494 pub bounds: HirVec<Lifetime>,
497 /// An equality predicate (unsupported), e.g. `T=int`
498 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
499 pub struct WhereEqPredicate {
506 pub type CrateConfig = HirVec<P<MetaItem>>;
508 /// The top-level data structure that stores the entire contents of
509 /// the crate currently being compiled.
511 /// For more details, see [the module-level README](README.md).
512 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
515 pub attrs: HirVec<Attribute>,
517 pub exported_macros: HirVec<MacroDef>,
519 // NB: We use a BTreeMap here so that `visit_all_items` iterates
520 // over the ids in increasing order. In principle it should not
521 // matter what order we visit things in, but in *practice* it
522 // does, because it can affect the order in which errors are
523 // detected, which in turn can make compile-fail tests yield
524 // slightly different results.
525 pub items: BTreeMap<NodeId, Item>,
527 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
528 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
529 pub bodies: BTreeMap<BodyId, Body>,
530 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
531 pub trait_auto_impl: BTreeMap<DefId, NodeId>,
533 /// A list of the body ids written out in the order in which they
534 /// appear in the crate. If you're going to process all the bodies
535 /// in the crate, you should iterate over this list rather than the keys
537 pub body_ids: Vec<BodyId>,
541 pub fn item(&self, id: NodeId) -> &Item {
545 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
546 &self.trait_items[&id]
549 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
550 &self.impl_items[&id]
553 /// Visits all items in the crate in some deterministic (but
554 /// unspecified) order. If you just need to process every item,
555 /// but don't care about nesting, this method is the best choice.
557 /// If you do care about nesting -- usually because your algorithm
558 /// follows lexical scoping rules -- then you want a different
559 /// approach. You should override `visit_nested_item` in your
560 /// visitor and then call `intravisit::walk_crate` instead.
561 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
562 where V: itemlikevisit::ItemLikeVisitor<'hir>
564 for (_, item) in &self.items {
565 visitor.visit_item(item);
568 for (_, trait_item) in &self.trait_items {
569 visitor.visit_trait_item(trait_item);
572 for (_, impl_item) in &self.impl_items {
573 visitor.visit_impl_item(impl_item);
577 pub fn body(&self, id: BodyId) -> &Body {
582 /// A macro definition, in this crate or imported from another.
584 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
585 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
586 pub struct MacroDef {
589 pub attrs: HirVec<Attribute>,
592 pub body: TokenStream,
596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
598 /// Statements in a block
599 pub stmts: HirVec<Stmt>,
600 /// An expression at the end of the block
601 /// without a semicolon, if any
602 pub expr: Option<P<Expr>>,
605 /// Distinguishes between `unsafe { ... }` and `{ ... }`
606 pub rules: BlockCheckMode,
608 /// If true, then there may exist `break 'a` values that aim to
609 /// break out of this block early. As of this writing, this is not
610 /// currently permitted in Rust itself, but it is generated as
611 /// part of `catch` statements.
612 pub targeted_by_break: bool,
615 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
623 impl fmt::Debug for Pat {
624 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
625 write!(f, "pat({}: {})", self.id,
626 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
631 // FIXME(#19596) this is a workaround, but there should be a better way
632 fn walk_<G>(&self, it: &mut G) -> bool
633 where G: FnMut(&Pat) -> bool
640 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
641 PatKind::Struct(_, ref fields, _) => {
642 fields.iter().all(|field| field.node.pat.walk_(it))
644 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
645 s.iter().all(|p| p.walk_(it))
647 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
650 PatKind::Slice(ref before, ref slice, ref after) => {
651 before.iter().all(|p| p.walk_(it)) &&
652 slice.iter().all(|p| p.walk_(it)) &&
653 after.iter().all(|p| p.walk_(it))
658 PatKind::Binding(..) |
659 PatKind::Path(_) => {
665 pub fn walk<F>(&self, mut it: F) -> bool
666 where F: FnMut(&Pat) -> bool
672 /// A single field in a struct pattern
674 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
675 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
676 /// except is_shorthand is true
677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
678 pub struct FieldPat {
679 /// The identifier for the field
681 /// The pattern the field is destructured to
683 pub is_shorthand: bool,
686 /// Explicit binding annotations given in the HIR for a binding. Note
687 /// that this is not the final binding *mode* that we infer after type
689 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
690 pub enum BindingAnnotation {
691 /// No binding annotation given: this means that the final binding mode
692 /// will depend on whether we have skipped through a `&` reference
693 /// when matching. For example, the `x` in `Some(x)` will have binding
694 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
695 /// ultimately be inferred to be by-reference.
697 /// Note that implicit reference skipping is not implemented yet (#42640).
700 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
703 /// Annotated as `ref`, like `ref x`
706 /// Annotated as `ref mut x`.
710 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
716 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
718 /// Represents a wildcard pattern (`_`)
721 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
722 /// The `NodeId` is the canonical ID for the variable being bound,
723 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
724 /// which is the pattern ID of the first `x`.
725 Binding(BindingAnnotation, NodeId, Spanned<Name>, Option<P<Pat>>),
727 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
728 /// The `bool` is `true` in the presence of a `..`.
729 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
731 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
732 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
733 /// 0 <= position <= subpats.len()
734 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
736 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
739 /// A tuple pattern `(a, b)`.
740 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
741 /// 0 <= position <= subpats.len()
742 Tuple(HirVec<P<Pat>>, Option<usize>),
745 /// A reference pattern, e.g. `&mut (a, b)`
746 Ref(P<Pat>, Mutability),
749 /// A range pattern, e.g. `1...2` or `1..2`
750 Range(P<Expr>, P<Expr>, RangeEnd),
751 /// `[a, b, ..i, y, z]` is represented as:
752 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
753 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
756 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
757 pub enum Mutability {
763 /// Return MutMutable only if both arguments are mutable.
764 pub fn and(self, other: Self) -> Self {
767 MutImmutable => MutImmutable,
772 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
774 /// The `+` operator (addition)
776 /// The `-` operator (subtraction)
778 /// The `*` operator (multiplication)
780 /// The `/` operator (division)
782 /// The `%` operator (modulus)
784 /// The `&&` operator (logical and)
786 /// The `||` operator (logical or)
788 /// The `^` operator (bitwise xor)
790 /// The `&` operator (bitwise and)
792 /// The `|` operator (bitwise or)
794 /// The `<<` operator (shift left)
796 /// The `>>` operator (shift right)
798 /// The `==` operator (equality)
800 /// The `<` operator (less than)
802 /// The `<=` operator (less than or equal to)
804 /// The `!=` operator (not equal to)
806 /// The `>=` operator (greater than or equal to)
808 /// The `>` operator (greater than)
813 pub fn as_str(self) -> &'static str {
836 pub fn is_lazy(self) -> bool {
838 BiAnd | BiOr => true,
843 pub fn is_shift(self) -> bool {
845 BiShl | BiShr => true,
850 pub fn is_comparison(self) -> bool {
852 BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
868 /// Returns `true` if the binary operator takes its arguments by value
869 pub fn is_by_value(self) -> bool {
870 !self.is_comparison()
874 pub type BinOp = Spanned<BinOp_>;
876 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
878 /// The `*` operator for dereferencing
880 /// The `!` operator for logical inversion
882 /// The `-` operator for negation
887 pub fn as_str(self) -> &'static str {
895 /// Returns `true` if the unary operator takes its argument by value
896 pub fn is_by_value(self) -> bool {
898 UnNeg | UnNot => true,
905 pub type Stmt = Spanned<Stmt_>;
907 impl fmt::Debug for Stmt_ {
908 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
910 let spanned = codemap::dummy_spanned(self.clone());
914 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
918 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
920 /// Could be an item or a local (let) binding:
921 StmtDecl(P<Decl>, NodeId),
923 /// Expr without trailing semi-colon (must have unit type):
924 StmtExpr(P<Expr>, NodeId),
926 /// Expr with trailing semi-colon (may have any type):
927 StmtSemi(P<Expr>, NodeId),
931 pub fn attrs(&self) -> &[Attribute] {
933 StmtDecl(ref d, _) => d.node.attrs(),
935 StmtSemi(ref e, _) => &e.attrs,
939 pub fn id(&self) -> NodeId {
941 StmtDecl(_, id) => id,
942 StmtExpr(_, id) => id,
943 StmtSemi(_, id) => id,
948 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
949 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
952 pub ty: Option<P<Ty>>,
953 /// Initializer expression to set the value, if any
954 pub init: Option<P<Expr>>,
958 pub attrs: ThinVec<Attribute>,
959 pub source: LocalSource,
962 pub type Decl = Spanned<Decl_>;
964 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
966 /// A local (let) binding:
973 pub fn attrs(&self) -> &[Attribute] {
975 DeclLocal(ref l) => &l.attrs,
980 pub fn is_local(&self) -> bool {
982 Decl_::DeclLocal(_) => true,
988 /// represents one arm of a 'match'
989 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
991 pub attrs: HirVec<Attribute>,
992 pub pats: HirVec<P<Pat>>,
993 pub guard: Option<P<Expr>>,
997 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
999 pub name: Spanned<Name>,
1002 pub is_shorthand: bool,
1005 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1006 pub enum BlockCheckMode {
1008 UnsafeBlock(UnsafeSource),
1009 PushUnsafeBlock(UnsafeSource),
1010 PopUnsafeBlock(UnsafeSource),
1013 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1014 pub enum UnsafeSource {
1019 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1021 pub node_id: NodeId,
1024 /// The body of a function, closure, or constant value. In the case of
1025 /// a function, the body contains not only the function body itself
1026 /// (which is an expression), but also the argument patterns, since
1027 /// those are something that the caller doesn't really care about.
1032 /// fn foo((x, y): (u32, u32)) -> u32 {
1037 /// Here, the `Body` associated with `foo()` would contain:
1039 /// - an `arguments` array containing the `(x, y)` pattern
1040 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1041 /// - `is_generator` would be false
1043 /// All bodies have an **owner**, which can be accessed via the HIR
1044 /// map using `body_owner_def_id()`.
1045 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1047 pub arguments: HirVec<Arg>,
1049 pub is_generator: bool,
1053 pub fn id(&self) -> BodyId {
1055 node_id: self.value.id
1060 #[derive(Copy, Clone, Debug)]
1061 pub enum BodyOwnerKind {
1062 /// Functions and methods.
1065 /// Constants and associated constants.
1068 /// Initializer of a `static` item.
1073 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1078 pub attrs: ThinVec<Attribute>,
1082 impl fmt::Debug for Expr {
1083 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1084 write!(f, "expr({}: {})", self.id,
1085 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1089 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1091 /// A `box x` expression.
1093 /// An array (`[a, b, c, d]`)
1094 ExprArray(HirVec<Expr>),
1097 /// The first field resolves to the function itself (usually an `ExprPath`),
1098 /// and the second field is the list of arguments.
1099 /// This also represents calling the constructor of
1100 /// tuple-like ADTs such as tuple structs and enum variants.
1101 ExprCall(P<Expr>, HirVec<Expr>),
1102 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1104 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1105 /// (within the angle brackets).
1106 /// The first element of the vector of `Expr`s is the expression that evaluates
1107 /// to the object on which the method is being called on (the receiver),
1108 /// and the remaining elements are the rest of the arguments.
1109 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1110 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1111 ExprMethodCall(PathSegment, Span, HirVec<Expr>),
1112 /// A tuple (`(a, b, c ,d)`)
1113 ExprTup(HirVec<Expr>),
1114 /// A binary operation (For example: `a + b`, `a * b`)
1115 ExprBinary(BinOp, P<Expr>, P<Expr>),
1116 /// A unary operation (For example: `!x`, `*x`)
1117 ExprUnary(UnOp, P<Expr>),
1118 /// A literal (For example: `1`, `"foo"`)
1120 /// A cast (`foo as f64`)
1121 ExprCast(P<Expr>, P<Ty>),
1122 ExprType(P<Expr>, P<Ty>),
1123 /// An `if` block, with an optional else block
1125 /// `if expr { expr } else { expr }`
1126 ExprIf(P<Expr>, P<Expr>, Option<P<Expr>>),
1127 /// A while loop, with an optional label
1129 /// `'label: while expr { block }`
1130 ExprWhile(P<Expr>, P<Block>, Option<Spanned<Name>>),
1131 /// Conditionless loop (can be exited with break, continue, or return)
1133 /// `'label: loop { block }`
1134 ExprLoop(P<Block>, Option<Spanned<Name>>, LoopSource),
1135 /// A `match` block, with a source that indicates whether or not it is
1136 /// the result of a desugaring, and if so, which kind.
1137 ExprMatch(P<Expr>, HirVec<Arm>, MatchSource),
1138 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1140 /// The final span is the span of the argument block `|...|`
1142 /// This may also be a generator literal, indicated by the final boolean,
1143 /// in that case there is an GeneratorClause.
1144 ExprClosure(CaptureClause, P<FnDecl>, BodyId, Span, bool),
1145 /// A block (`{ ... }`)
1146 ExprBlock(P<Block>),
1148 /// An assignment (`a = foo()`)
1149 ExprAssign(P<Expr>, P<Expr>),
1150 /// An assignment with an operator
1152 /// For example, `a += 1`.
1153 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
1154 /// Access of a named struct field (`obj.foo`)
1155 ExprField(P<Expr>, Spanned<Name>),
1156 /// Access of an unnamed field of a struct or tuple-struct
1158 /// For example, `foo.0`.
1159 ExprTupField(P<Expr>, Spanned<usize>),
1160 /// An indexing operation (`foo[2]`)
1161 ExprIndex(P<Expr>, P<Expr>),
1163 /// Path to a definition, possibly containing lifetime or type parameters.
1166 /// A referencing operation (`&a` or `&mut a`)
1167 ExprAddrOf(Mutability, P<Expr>),
1168 /// A `break`, with an optional label to break
1169 ExprBreak(Destination, Option<P<Expr>>),
1170 /// A `continue`, with an optional label
1171 ExprAgain(Destination),
1172 /// A `return`, with an optional value to be returned
1173 ExprRet(Option<P<Expr>>),
1175 /// Inline assembly (from `asm!`), with its outputs and inputs.
1176 ExprInlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1178 /// A struct or struct-like variant literal expression.
1180 /// For example, `Foo {x: 1, y: 2}`, or
1181 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1182 ExprStruct(QPath, HirVec<Field>, Option<P<Expr>>),
1184 /// An array literal constructed from one repeated element.
1186 /// For example, `[1; 5]`. The first expression is the element
1187 /// to be repeated; the second is the number of times to repeat it.
1188 ExprRepeat(P<Expr>, BodyId),
1190 /// A suspension point for generators. This is `yield <expr>` in Rust.
1194 /// Optionally `Self`-qualified value/type path or associated extension.
1195 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1197 /// Path to a definition, optionally "fully-qualified" with a `Self`
1198 /// type, if the path points to an associated item in a trait.
1200 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1201 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1202 /// even though they both have the same two-segment `Clone::clone` `Path`.
1203 Resolved(Option<P<Ty>>, P<Path>),
1205 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1206 /// Will be resolved by type-checking to an associated item.
1208 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1209 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1210 /// the `X` and `Y` nodes each being a `TyPath(QPath::TypeRelative(..))`.
1211 TypeRelative(P<Ty>, P<PathSegment>)
1214 /// Hints at the original code for a let statement
1215 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1216 pub enum LocalSource {
1217 /// A `match _ { .. }`
1219 /// A desugared `for _ in _ { .. }` loop
1223 /// Hints at the original code for a `match _ { .. }`
1224 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1225 pub enum MatchSource {
1226 /// A `match _ { .. }`
1228 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1230 contains_else_clause: bool,
1232 /// A `while let _ = _ { .. }` (which was desugared to a
1233 /// `loop { match _ { .. } }`)
1235 /// A desugared `for _ in _ { .. }` loop
1237 /// A desugared `?` operator
1241 /// The loop type that yielded an ExprLoop
1242 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1243 pub enum LoopSource {
1244 /// A `loop { .. }` loop
1246 /// A `while let _ = _ { .. }` loop
1248 /// A `for _ in _ { .. }` loop
1252 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1253 pub enum LoopIdError {
1255 UnlabeledCfInWhileCondition,
1259 impl fmt::Display for LoopIdError {
1260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1261 fmt::Display::fmt(match *self {
1262 LoopIdError::OutsideLoopScope => "not inside loop scope",
1263 LoopIdError::UnlabeledCfInWhileCondition =>
1264 "unlabeled control flow (break or continue) in while condition",
1265 LoopIdError::UnresolvedLabel => "label not found",
1270 // FIXME(cramertj) this should use `Result` once master compiles w/ a vesion of Rust where
1271 // `Result` implements `Encodable`/`Decodable`
1272 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1273 pub enum LoopIdResult {
1277 impl Into<Result<NodeId, LoopIdError>> for LoopIdResult {
1278 fn into(self) -> Result<NodeId, LoopIdError> {
1280 LoopIdResult::Ok(ok) => Ok(ok),
1281 LoopIdResult::Err(err) => Err(err),
1285 impl From<Result<NodeId, LoopIdError>> for LoopIdResult {
1286 fn from(res: Result<NodeId, LoopIdError>) -> Self {
1288 Ok(ok) => LoopIdResult::Ok(ok),
1289 Err(err) => LoopIdResult::Err(err),
1294 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1295 pub enum ScopeTarget {
1301 pub fn opt_id(self) -> Option<NodeId> {
1303 ScopeTarget::Block(node_id) |
1304 ScopeTarget::Loop(LoopIdResult::Ok(node_id)) => Some(node_id),
1305 ScopeTarget::Loop(LoopIdResult::Err(_)) => None,
1310 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1311 pub struct Destination {
1312 // This is `Some(_)` iff there is an explicit user-specified `label
1313 pub ident: Option<Spanned<Ident>>,
1315 // These errors are caught and then reported during the diagnostics pass in
1316 // librustc_passes/loops.rs
1317 pub target_id: ScopeTarget,
1320 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1321 pub enum CaptureClause {
1326 // NB: If you change this, you'll probably want to change the corresponding
1327 // type structure in middle/ty.rs as well.
1328 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1331 pub mutbl: Mutability,
1334 /// Represents a method's signature in a trait declaration or implementation.
1335 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1336 pub struct MethodSig {
1337 pub unsafety: Unsafety,
1338 pub constness: Constness,
1340 pub decl: P<FnDecl>,
1343 // The bodies for items are stored "out of line", in a separate
1344 // hashmap in the `Crate`. Here we just record the node-id of the item
1345 // so it can fetched later.
1346 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1347 pub struct TraitItemId {
1348 pub node_id: NodeId,
1351 /// Represents an item declaration within a trait declaration,
1352 /// possibly including a default implementation. A trait item is
1353 /// either required (meaning it doesn't have an implementation, just a
1354 /// signature) or provided (meaning it has a default implementation).
1355 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1356 pub struct TraitItem {
1360 pub attrs: HirVec<Attribute>,
1361 pub generics: Generics,
1362 pub node: TraitItemKind,
1366 /// A trait method's body (or just argument names).
1367 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1368 pub enum TraitMethod {
1369 /// No default body in the trait, just a signature.
1370 Required(HirVec<Spanned<Name>>),
1372 /// Both signature and body are provided in the trait.
1376 /// Represents a trait method or associated constant or type
1377 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1378 pub enum TraitItemKind {
1379 /// An associated constant with an optional value (otherwise `impl`s
1380 /// must contain a value)
1381 Const(P<Ty>, Option<BodyId>),
1382 /// A method with an optional body
1383 Method(MethodSig, TraitMethod),
1384 /// An associated type with (possibly empty) bounds and optional concrete
1386 Type(TyParamBounds, Option<P<Ty>>),
1389 // The bodies for items are stored "out of line", in a separate
1390 // hashmap in the `Crate`. Here we just record the node-id of the item
1391 // so it can fetched later.
1392 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1393 pub struct ImplItemId {
1394 pub node_id: NodeId,
1397 /// Represents anything within an `impl` block
1398 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1399 pub struct ImplItem {
1403 pub vis: Visibility,
1404 pub defaultness: Defaultness,
1405 pub attrs: HirVec<Attribute>,
1406 pub generics: Generics,
1407 pub node: ImplItemKind,
1411 /// Represents different contents within `impl`s
1412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1413 pub enum ImplItemKind {
1414 /// An associated constant of the given type, set to the constant result
1415 /// of the expression
1416 Const(P<Ty>, BodyId),
1417 /// A method implementation with the given signature and body
1418 Method(MethodSig, BodyId),
1419 /// An associated type
1423 // Bind a type to an associated type: `A=Foo`.
1424 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1425 pub struct TypeBinding {
1433 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1441 impl fmt::Debug for Ty {
1442 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1443 write!(f, "type({})",
1444 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1448 /// Not represented directly in the AST, referred to by name through a ty_path.
1449 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1459 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1460 pub struct BareFnTy {
1461 pub unsafety: Unsafety,
1463 pub lifetimes: HirVec<LifetimeDef>,
1464 pub decl: P<FnDecl>,
1465 pub arg_names: HirVec<Spanned<Name>>,
1468 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1469 pub struct ExistTy {
1470 pub generics: Generics,
1471 pub bounds: TyParamBounds,
1474 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1475 /// The different kinds of types recognized by the compiler
1477 /// A variable length slice (`[T]`)
1479 /// A fixed length array (`[T; n]`)
1480 TyArray(P<Ty>, BodyId),
1481 /// A raw pointer (`*const T` or `*mut T`)
1483 /// A reference (`&'a T` or `&'a mut T`)
1484 TyRptr(Lifetime, MutTy),
1485 /// A bare function (e.g. `fn(usize) -> bool`)
1486 TyBareFn(P<BareFnTy>),
1487 /// The never type (`!`)
1489 /// A tuple (`(A, B, C, D,...)`)
1490 TyTup(HirVec<P<Ty>>),
1491 /// A path to a type definition (`module::module::...::Type`), or an
1492 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1494 /// Type parameters may be stored in each `PathSegment`.
1496 /// A trait object type `Bound1 + Bound2 + Bound3`
1497 /// where `Bound` is a trait or a lifetime.
1498 TyTraitObject(HirVec<PolyTraitRef>, Lifetime),
1499 /// An exsitentially quantified (there exists a type satisfying) `impl
1500 /// Bound1 + Bound2 + Bound3` type where `Bound` is a trait or a lifetime.
1502 /// The `ExistTy` structure emulates an
1503 /// `abstract type Foo<'a, 'b>: MyTrait<'a, 'b>;`.
1505 /// The `HirVec<Lifetime>` is the list of lifetimes applied as parameters
1506 /// to the `abstract type`, e.g. the `'c` and `'d` in `-> Foo<'c, 'd>`.
1507 /// This list is only a list of lifetimes and not type parameters
1508 /// because all in-scope type parameters are captured by `impl Trait`,
1509 /// so they are resolved directly through the parent `Generics`.
1510 TyImplTraitExistential(ExistTy, HirVec<Lifetime>),
1511 /// An universally quantified (for all types satisfying) `impl
1512 /// Bound1 + Bound2 + Bound3` type where `Bound` is a trait or a lifetime.
1513 TyImplTraitUniversal(DefId, TyParamBounds),
1516 /// TyInfer means the type should be inferred instead of it having been
1517 /// specified. This can appear anywhere in a type.
1519 /// Placeholder for a type that has failed to be defined.
1523 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1524 pub struct InlineAsmOutput {
1525 pub constraint: Symbol,
1527 pub is_indirect: bool,
1530 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1531 pub struct InlineAsm {
1533 pub asm_str_style: StrStyle,
1534 pub outputs: HirVec<InlineAsmOutput>,
1535 pub inputs: HirVec<Symbol>,
1536 pub clobbers: HirVec<Symbol>,
1538 pub alignstack: bool,
1539 pub dialect: AsmDialect,
1540 pub ctxt: SyntaxContext,
1543 /// represents an argument in a function header
1544 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1551 /// Represents the header (not the body) of a function declaration
1552 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1554 pub inputs: HirVec<P<Ty>>,
1555 pub output: FunctionRetTy,
1557 /// True if this function has an `self`, `&self` or `&mut self` receiver
1558 /// (but not a `self: Xxx` one).
1559 pub has_implicit_self: bool,
1562 /// Is the trait definition an auto trait?
1563 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1569 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1575 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1576 pub enum Constness {
1581 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1582 pub enum Defaultness {
1583 Default { has_value: bool },
1588 pub fn has_value(&self) -> bool {
1590 Defaultness::Default { has_value, .. } => has_value,
1591 Defaultness::Final => true,
1595 pub fn is_final(&self) -> bool {
1596 *self == Defaultness::Final
1599 pub fn is_default(&self) -> bool {
1601 Defaultness::Default { .. } => true,
1607 impl fmt::Display for Unsafety {
1608 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1609 fmt::Display::fmt(match *self {
1610 Unsafety::Normal => "normal",
1611 Unsafety::Unsafe => "unsafe",
1617 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1618 pub enum ImplPolarity {
1619 /// `impl Trait for Type`
1621 /// `impl !Trait for Type`
1625 impl fmt::Debug for ImplPolarity {
1626 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1628 ImplPolarity::Positive => "positive".fmt(f),
1629 ImplPolarity::Negative => "negative".fmt(f),
1635 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1636 pub enum FunctionRetTy {
1637 /// Return type is not specified.
1639 /// Functions default to `()` and
1640 /// closures default to inference. Span points to where return
1641 /// type would be inserted.
1642 DefaultReturn(Span),
1647 impl FunctionRetTy {
1648 pub fn span(&self) -> Span {
1650 DefaultReturn(span) => span,
1651 Return(ref ty) => ty.span,
1656 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1658 /// A span from the first token past `{` to the last token until `}`.
1659 /// For `mod foo;`, the inner span ranges from the first token
1660 /// to the last token in the external file.
1662 pub item_ids: HirVec<ItemId>,
1665 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1666 pub struct ForeignMod {
1668 pub items: HirVec<ForeignItem>,
1671 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1672 pub struct GlobalAsm {
1674 pub ctxt: SyntaxContext,
1677 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1678 pub struct EnumDef {
1679 pub variants: HirVec<Variant>,
1682 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1683 pub struct Variant_ {
1685 pub attrs: HirVec<Attribute>,
1686 pub data: VariantData,
1687 /// Explicit discriminant, eg `Foo = 1`
1688 pub disr_expr: Option<BodyId>,
1691 pub type Variant = Spanned<Variant_>;
1693 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1695 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1696 /// Also produced for each element of a list `use`, e.g.
1697 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1700 /// Glob import, e.g. `use foo::*`.
1703 /// Degenerate list import, e.g. `use foo::{a, b}` produces
1704 /// an additional `use foo::{}` for performing checks such as
1705 /// unstable feature gating. May be removed in the future.
1709 /// TraitRef's appear in impls.
1711 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1712 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1713 /// trait being referred to but just a unique NodeId that serves as a key
1714 /// within the DefMap.
1715 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1716 pub struct TraitRef {
1721 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1722 pub struct PolyTraitRef {
1723 /// The `'a` in `<'a> Foo<&'a T>`
1724 pub bound_lifetimes: HirVec<LifetimeDef>,
1726 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1727 pub trait_ref: TraitRef,
1732 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1733 pub enum Visibility {
1736 Restricted { path: P<Path>, id: NodeId },
1741 pub fn is_pub_restricted(&self) -> bool {
1742 use self::Visibility::*;
1745 &Inherited => false,
1747 &Restricted { .. } => true,
1752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1753 pub struct StructField {
1756 pub vis: Visibility,
1759 pub attrs: HirVec<Attribute>,
1763 // Still necessary in couple of places
1764 pub fn is_positional(&self) -> bool {
1765 let first = self.name.as_str().as_bytes()[0];
1766 first >= b'0' && first <= b'9'
1770 /// Fields and Ids of enum variants and structs
1772 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1773 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1774 /// One shared Id can be successfully used for these two purposes.
1775 /// Id of the whole enum lives in `Item`.
1777 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1778 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1779 /// the variant itself" from enum variants.
1780 /// Id of the whole struct lives in `Item`.
1781 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1782 pub enum VariantData {
1783 Struct(HirVec<StructField>, NodeId),
1784 Tuple(HirVec<StructField>, NodeId),
1789 pub fn fields(&self) -> &[StructField] {
1791 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1795 pub fn id(&self) -> NodeId {
1797 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
1800 pub fn is_struct(&self) -> bool {
1801 if let VariantData::Struct(..) = *self {
1807 pub fn is_tuple(&self) -> bool {
1808 if let VariantData::Tuple(..) = *self {
1814 pub fn is_unit(&self) -> bool {
1815 if let VariantData::Unit(..) = *self {
1823 // The bodies for items are stored "out of line", in a separate
1824 // hashmap in the `Crate`. Here we just record the node-id of the item
1825 // so it can fetched later.
1826 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1833 /// The name might be a dummy name in case of anonymous items
1834 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1839 pub attrs: HirVec<Attribute>,
1841 pub vis: Visibility,
1845 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1847 /// An `extern crate` item, with optional original crate name,
1849 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1850 ItemExternCrate(Option<Name>),
1852 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
1856 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
1857 ItemUse(P<Path>, UseKind),
1860 ItemStatic(P<Ty>, Mutability, BodyId),
1862 ItemConst(P<Ty>, BodyId),
1863 /// A function declaration
1864 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, BodyId),
1867 /// An external module
1868 ItemForeignMod(ForeignMod),
1869 /// Module-level inline assembly (from global_asm!)
1870 ItemGlobalAsm(P<GlobalAsm>),
1871 /// A type alias, e.g. `type Foo = Bar<u8>`
1872 ItemTy(P<Ty>, Generics),
1873 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1874 ItemEnum(EnumDef, Generics),
1875 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1876 ItemStruct(VariantData, Generics),
1877 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
1878 ItemUnion(VariantData, Generics),
1879 /// Represents a Trait Declaration
1880 ItemTrait(IsAuto, Unsafety, Generics, TyParamBounds, HirVec<TraitItemRef>),
1882 /// Auto trait implementations
1884 /// `impl Trait for .. {}`
1885 ItemAutoImpl(Unsafety, TraitRef),
1886 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1891 Option<TraitRef>, // (optional) trait this impl implements
1893 HirVec<ImplItemRef>),
1897 pub fn descriptive_variant(&self) -> &str {
1899 ItemExternCrate(..) => "extern crate",
1900 ItemUse(..) => "use",
1901 ItemStatic(..) => "static item",
1902 ItemConst(..) => "constant item",
1903 ItemFn(..) => "function",
1904 ItemMod(..) => "module",
1905 ItemForeignMod(..) => "foreign module",
1906 ItemGlobalAsm(..) => "global asm",
1907 ItemTy(..) => "type alias",
1908 ItemEnum(..) => "enum",
1909 ItemStruct(..) => "struct",
1910 ItemUnion(..) => "union",
1911 ItemTrait(..) => "trait",
1913 ItemAutoImpl(..) => "item",
1917 pub fn adt_kind(&self) -> Option<AdtKind> {
1919 ItemStruct(..) => Some(AdtKind::Struct),
1920 ItemUnion(..) => Some(AdtKind::Union),
1921 ItemEnum(..) => Some(AdtKind::Enum),
1926 pub fn generics(&self) -> Option<&Generics> {
1928 ItemFn(_, _, _, _, ref generics, _) |
1929 ItemTy(_, ref generics) |
1930 ItemEnum(_, ref generics) |
1931 ItemStruct(_, ref generics) |
1932 ItemUnion(_, ref generics) |
1933 ItemTrait(_, _, ref generics, _, _) |
1934 ItemImpl(_, _, _, ref generics, _, _, _)=> generics,
1940 /// A reference from an trait to one of its associated items. This
1941 /// contains the item's id, naturally, but also the item's name and
1942 /// some other high-level details (like whether it is an associated
1943 /// type or method, and whether it is public). This allows other
1944 /// passes to find the impl they want without loading the id (which
1945 /// means fewer edges in the incremental compilation graph).
1946 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1947 pub struct TraitItemRef {
1948 pub id: TraitItemId,
1950 pub kind: AssociatedItemKind,
1952 pub defaultness: Defaultness,
1955 /// A reference from an impl to one of its associated items. This
1956 /// contains the item's id, naturally, but also the item's name and
1957 /// some other high-level details (like whether it is an associated
1958 /// type or method, and whether it is public). This allows other
1959 /// passes to find the impl they want without loading the id (which
1960 /// means fewer edges in the incremental compilation graph).
1961 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1962 pub struct ImplItemRef {
1965 pub kind: AssociatedItemKind,
1967 pub vis: Visibility,
1968 pub defaultness: Defaultness,
1971 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1972 pub enum AssociatedItemKind {
1974 Method { has_self: bool },
1978 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1979 pub struct ForeignItem {
1981 pub attrs: HirVec<Attribute>,
1982 pub node: ForeignItem_,
1985 pub vis: Visibility,
1988 /// An item within an `extern` block
1989 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1990 pub enum ForeignItem_ {
1991 /// A foreign function
1992 ForeignItemFn(P<FnDecl>, HirVec<Spanned<Name>>, Generics),
1993 /// A foreign static item (`static ext: u8`), with optional mutability
1994 /// (the boolean is true when mutable)
1995 ForeignItemStatic(P<Ty>, bool),
2001 pub fn descriptive_variant(&self) -> &str {
2003 ForeignItemFn(..) => "foreign function",
2004 ForeignItemStatic(..) => "foreign static item",
2005 ForeignItemType => "foreign type",
2010 /// A free variable referred to in a function.
2011 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2012 pub struct Freevar {
2013 /// The variable being accessed free.
2016 // First span where it is accessed (there can be multiple).
2021 pub fn var_id(&self) -> NodeId {
2023 Def::Local(id) | Def::Upvar(id, ..) => id,
2024 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2029 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2031 pub type CaptureModeMap = NodeMap<CaptureClause>;
2033 #[derive(Clone, Debug)]
2034 pub struct TraitCandidate {
2036 pub import_id: Option<NodeId>,
2039 // Trait method resolution
2040 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2042 // Map from the NodeId of a glob import to a list of items which are actually
2044 pub type GlobMap = NodeMap<FxHashSet<Name>>;