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, LocalDefId, CRATE_DEF_INDEX};
32 use util::nodemap::{NodeMap, FxHashSet};
33 use mir::mono::Linkage;
35 use syntax_pos::{Span, DUMMY_SP};
36 use syntax::codemap::{self, Spanned};
37 use rustc_target::spec::abi::Abi;
38 use syntax::ast::{self, Name, NodeId, DUMMY_NODE_ID, AsmDialect};
39 use syntax::ast::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy, MetaItem};
40 use syntax::attr::InlineAttr;
41 use syntax::ext::hygiene::SyntaxContext;
43 use syntax::symbol::{Symbol, keywords};
44 use syntax::tokenstream::TokenStream;
45 use syntax::util::ThinVec;
46 use syntax::util::parser::ExprPrecedence;
48 use ty::maps::Providers;
50 use rustc_data_structures::indexed_vec;
51 use rustc_data_structures::sync::{ParallelIterator, par_iter, Send, Sync, scope};
53 use serialize::{self, Encoder, Encodable, Decoder, Decodable};
54 use std::collections::BTreeMap;
59 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
60 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
61 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
62 /// of `Vec` to avoid keeping extra capacity.
63 pub type HirVec<T> = P<[T]>;
65 macro_rules! hir_vec {
66 ($elem:expr; $n:expr) => (
67 $crate::hir::HirVec::from(vec![$elem; $n])
70 $crate::hir::HirVec::from(vec![$($x),*])
72 ($($x:expr,)*) => (hir_vec![$($x),*])
79 pub mod itemlikevisit;
86 /// A HirId uniquely identifies a node in the HIR of the current crate. It is
87 /// composed of the `owner`, which is the DefIndex of the directly enclosing
88 /// hir::Item, hir::TraitItem, or hir::ImplItem (i.e. the closest "item-like"),
89 /// and the `local_id` which is unique within the given owner.
91 /// This two-level structure makes for more stable values: One can move an item
92 /// around within the source code, or add or remove stuff before it, without
93 /// the local_id part of the HirId changing, which is a very useful property in
94 /// incremental compilation where we have to persist things through changes to
96 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
99 pub local_id: ItemLocalId,
103 pub fn owner_def_id(self) -> DefId {
104 DefId::local(self.owner)
107 pub fn owner_local_def_id(self) -> LocalDefId {
108 LocalDefId::from_def_id(DefId::local(self.owner))
112 impl serialize::UseSpecializedEncodable for HirId {
113 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
124 impl serialize::UseSpecializedDecodable for HirId {
125 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
126 let owner = DefIndex::decode(d)?;
127 let local_id = ItemLocalId::decode(d)?;
137 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
138 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
139 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
140 /// the node's position within the owning item in any way, but there is a
141 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
142 /// integers starting at zero, so a mapping that maps all or most nodes within
143 /// an "item-like" to something else can be implement by a `Vec` instead of a
144 /// tree or hash map.
145 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug,
146 RustcEncodable, RustcDecodable)]
147 pub struct ItemLocalId(pub u32);
150 pub fn as_usize(&self) -> usize {
155 impl indexed_vec::Idx for ItemLocalId {
156 fn new(idx: usize) -> Self {
157 debug_assert!((idx as u32) as usize == idx);
158 ItemLocalId(idx as u32)
161 fn index(self) -> usize {
166 /// The `HirId` corresponding to CRATE_NODE_ID and CRATE_DEF_INDEX
167 pub const CRATE_HIR_ID: HirId = HirId {
168 owner: CRATE_DEF_INDEX,
169 local_id: ItemLocalId(0)
172 pub const DUMMY_HIR_ID: HirId = HirId {
173 owner: CRATE_DEF_INDEX,
174 local_id: DUMMY_ITEM_LOCAL_ID,
177 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId(!0);
179 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
185 impl fmt::Debug for Label {
186 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
187 write!(f, "label({:?})", self.name)
191 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
192 pub struct Lifetime {
196 /// Either "'a", referring to a named lifetime definition,
197 /// or "" (aka keywords::Invalid), for elision placeholders.
199 /// HIR lowering inserts these placeholders in type paths that
200 /// refer to type definitions needing lifetime parameters,
201 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
202 pub name: LifetimeName,
205 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
206 pub enum LifetimeName {
207 /// User typed nothing. e.g. the lifetime in `&u32`.
213 /// Synthetic name generated when user elided a lifetime in an impl header,
214 /// e.g. the lifetimes in cases like these:
216 /// impl Foo for &u32
217 /// impl Foo<'_> for u32
219 /// in that case, we rewrite to
221 /// impl<'f> Foo for &'f u32
222 /// impl<'f> Foo<'f> for u32
224 /// where `'f` is something like `Fresh(0)`. The indices are
225 /// unique per impl, but not necessarily continuous.
228 /// User wrote `'static`
231 /// Some user-given name like `'x`
236 pub fn name(&self) -> Name {
237 use self::LifetimeName::*;
239 Implicit => keywords::Invalid.name(),
240 Fresh(_) | Underscore => keywords::UnderscoreLifetime.name(),
241 Static => keywords::StaticLifetime.name(),
247 impl fmt::Debug for Lifetime {
248 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
252 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
257 pub fn is_elided(&self) -> bool {
258 use self::LifetimeName::*;
260 Implicit | Underscore => true,
262 // It might seem surprising that `Fresh(_)` counts as
263 // *not* elided -- but this is because, as far as the code
264 // in the compiler is concerned -- `Fresh(_)` variants act
265 // equivalently to "some fresh name". They correspond to
266 // early-bound regions on an impl, in other words.
267 Fresh(_) | Static | Name(_) => false,
271 pub fn is_static(&self) -> bool {
272 self.name == LifetimeName::Static
276 /// A lifetime definition, eg `'a: 'b+'c+'d`
277 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
278 pub struct LifetimeDef {
279 pub lifetime: Lifetime,
280 pub bounds: HirVec<Lifetime>,
281 pub pure_wrt_drop: bool,
282 // Indicates that the lifetime definition was synthetically added
283 // as a result of an in-band lifetime usage like
284 // `fn foo(x: &'a u8) -> &'a u8 { x }`
288 /// A "Path" is essentially Rust's notion of a name; for instance:
289 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
290 /// along with a bunch of supporting information.
291 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
294 /// The definition that the path resolved to.
296 /// The segments in the path: the things separated by `::`.
297 pub segments: HirVec<PathSegment>,
301 pub fn is_global(&self) -> bool {
302 !self.segments.is_empty() && self.segments[0].name == keywords::CrateRoot.name()
306 impl fmt::Debug for Path {
307 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
308 write!(f, "path({})", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
312 impl fmt::Display for Path {
313 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
314 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
318 /// A segment of a path: an identifier, an optional lifetime, and a set of
320 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
321 pub struct PathSegment {
322 /// The identifier portion of this path segment.
325 /// Type/lifetime parameters attached to this path. They come in
326 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
327 /// this is more than just simple syntactic sugar; the use of
328 /// parens affects the region binding rules, so we preserve the
330 pub parameters: Option<P<PathParameters>>,
332 /// Whether to infer remaining type parameters, if any.
333 /// This only applies to expression and pattern paths, and
334 /// out of those only the segments with no type parameters
335 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
336 pub infer_types: bool,
340 /// Convert an identifier to the corresponding segment.
341 pub fn from_name(name: Name) -> PathSegment {
349 pub fn new(name: Name, parameters: PathParameters, infer_types: bool) -> Self {
353 parameters: if parameters.is_empty() {
361 // FIXME: hack required because you can't create a static
362 // PathParameters, so you can't just return a &PathParameters.
363 pub fn with_parameters<F, R>(&self, f: F) -> R
364 where F: FnOnce(&PathParameters) -> R
366 let dummy = PathParameters::none();
367 f(if let Some(ref params) = self.parameters {
375 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
376 pub struct PathParameters {
377 /// The lifetime parameters for this path segment.
378 pub lifetimes: HirVec<Lifetime>,
379 /// The type parameters for this path segment, if present.
380 pub types: HirVec<P<Ty>>,
381 /// Bindings (equality constraints) on associated types, if present.
382 /// E.g., `Foo<A=Bar>`.
383 pub bindings: HirVec<TypeBinding>,
384 /// Were parameters written in parenthesized form `Fn(T) -> U`?
385 /// This is required mostly for pretty-printing and diagnostics,
386 /// but also for changing lifetime elision rules to be "function-like".
387 pub parenthesized: bool,
390 impl PathParameters {
391 pub fn none() -> Self {
393 lifetimes: HirVec::new(),
394 types: HirVec::new(),
395 bindings: HirVec::new(),
396 parenthesized: false,
400 pub fn is_empty(&self) -> bool {
401 self.lifetimes.is_empty() && self.types.is_empty() &&
402 self.bindings.is_empty() && !self.parenthesized
405 pub fn inputs(&self) -> &[P<Ty>] {
406 if self.parenthesized {
407 if let Some(ref ty) = self.types.get(0) {
408 if let TyTup(ref tys) = ty.node {
413 bug!("PathParameters::inputs: not a `Fn(T) -> U`");
417 /// The AST represents all type param bounds as types.
418 /// typeck::collect::compute_bounds matches these against
419 /// the "special" built-in traits (see middle::lang_items) and
420 /// detects Copy, Send and Sync.
421 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
422 pub enum TyParamBound {
423 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
424 RegionTyParamBound(Lifetime),
428 pub fn span(&self) -> Span {
430 &TraitTyParamBound(ref t, ..) => t.span,
431 &RegionTyParamBound(ref l) => l.span,
436 /// A modifier on a bound, currently this is only used for `?Sized`, where the
437 /// modifier is `Maybe`. Negative bounds should also be handled here.
438 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
439 pub enum TraitBoundModifier {
444 pub type TyParamBounds = HirVec<TyParamBound>;
446 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
450 pub bounds: TyParamBounds,
451 pub default: Option<P<Ty>>,
453 pub pure_wrt_drop: bool,
454 pub synthetic: Option<SyntheticTyParamKind>,
455 pub attrs: HirVec<Attribute>,
458 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
459 pub enum GenericParam {
460 Lifetime(LifetimeDef),
465 pub fn is_lifetime_param(&self) -> bool {
467 GenericParam::Lifetime(_) => true,
472 pub fn is_type_param(&self) -> bool {
474 GenericParam::Type(_) => true,
480 pub trait GenericParamsExt {
481 fn lifetimes<'a>(&'a self) -> iter::FilterMap<
482 slice::Iter<GenericParam>,
483 fn(&GenericParam) -> Option<&LifetimeDef>,
486 fn ty_params<'a>(&'a self) -> iter::FilterMap<
487 slice::Iter<GenericParam>,
488 fn(&GenericParam) -> Option<&TyParam>,
492 impl GenericParamsExt for [GenericParam] {
493 fn lifetimes<'a>(&'a self) -> iter::FilterMap<
494 slice::Iter<GenericParam>,
495 fn(&GenericParam) -> Option<&LifetimeDef>,
497 self.iter().filter_map(|param| match *param {
498 GenericParam::Lifetime(ref l) => Some(l),
503 fn ty_params<'a>(&'a self) -> iter::FilterMap<
504 slice::Iter<GenericParam>,
505 fn(&GenericParam) -> Option<&TyParam>,
507 self.iter().filter_map(|param| match *param {
508 GenericParam::Type(ref t) => Some(t),
514 /// Represents lifetimes and type parameters attached to a declaration
515 /// of a function, enum, trait, etc.
516 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
517 pub struct Generics {
518 pub params: HirVec<GenericParam>,
519 pub where_clause: WhereClause,
524 pub fn empty() -> Generics {
526 params: HirVec::new(),
527 where_clause: WhereClause {
529 predicates: HirVec::new(),
535 pub fn is_lt_parameterized(&self) -> bool {
536 self.params.iter().any(|param| param.is_lifetime_param())
539 pub fn is_type_parameterized(&self) -> bool {
540 self.params.iter().any(|param| param.is_type_param())
543 pub fn lifetimes<'a>(&'a self) -> impl Iterator<Item = &'a LifetimeDef> {
544 self.params.lifetimes()
547 pub fn ty_params<'a>(&'a self) -> impl Iterator<Item = &'a TyParam> {
548 self.params.ty_params()
552 pub enum UnsafeGeneric {
553 Region(LifetimeDef, &'static str),
554 Type(TyParam, &'static str),
558 pub fn attr_name(&self) -> &'static str {
560 UnsafeGeneric::Region(_, s) => s,
561 UnsafeGeneric::Type(_, s) => s,
567 pub fn carries_unsafe_attr(&self) -> Option<UnsafeGeneric> {
568 for param in &self.params {
570 GenericParam::Lifetime(ref l) => {
572 return Some(UnsafeGeneric::Region(l.clone(), "may_dangle"));
575 GenericParam::Type(ref t) => {
577 return Some(UnsafeGeneric::Type(t.clone(), "may_dangle"));
587 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
588 /// to track the original form they had. Useful for error messages.
589 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
590 pub enum SyntheticTyParamKind {
594 /// A `where` clause in a definition
595 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
596 pub struct WhereClause {
598 pub predicates: HirVec<WherePredicate>,
601 /// A single predicate in a `where` clause
602 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
603 pub enum WherePredicate {
604 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
605 BoundPredicate(WhereBoundPredicate),
606 /// A lifetime predicate, e.g. `'a: 'b+'c`
607 RegionPredicate(WhereRegionPredicate),
608 /// An equality predicate (unsupported)
609 EqPredicate(WhereEqPredicate),
612 impl WherePredicate {
613 pub fn span(&self) -> Span {
615 &WherePredicate::BoundPredicate(ref p) => p.span,
616 &WherePredicate::RegionPredicate(ref p) => p.span,
617 &WherePredicate::EqPredicate(ref p) => p.span,
622 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
623 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
624 pub struct WhereBoundPredicate {
626 /// Any generics from a `for` binding
627 pub bound_generic_params: HirVec<GenericParam>,
628 /// The type being bounded
629 pub bounded_ty: P<Ty>,
630 /// Trait and lifetime bounds (`Clone+Send+'static`)
631 pub bounds: TyParamBounds,
634 /// A lifetime predicate, e.g. `'a: 'b+'c`
635 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
636 pub struct WhereRegionPredicate {
638 pub lifetime: Lifetime,
639 pub bounds: HirVec<Lifetime>,
642 /// An equality predicate (unsupported), e.g. `T=int`
643 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
644 pub struct WhereEqPredicate {
651 pub type CrateConfig = HirVec<P<MetaItem>>;
653 /// The top-level data structure that stores the entire contents of
654 /// the crate currently being compiled.
656 /// For more details, see the [rustc guide].
658 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/hir.html
659 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
662 pub attrs: HirVec<Attribute>,
664 pub exported_macros: HirVec<MacroDef>,
666 // NB: We use a BTreeMap here so that `visit_all_items` iterates
667 // over the ids in increasing order. In principle it should not
668 // matter what order we visit things in, but in *practice* it
669 // does, because it can affect the order in which errors are
670 // detected, which in turn can make compile-fail tests yield
671 // slightly different results.
672 pub items: BTreeMap<NodeId, Item>,
674 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
675 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
676 pub bodies: BTreeMap<BodyId, Body>,
677 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
678 pub trait_auto_impl: BTreeMap<DefId, NodeId>,
680 /// A list of the body ids written out in the order in which they
681 /// appear in the crate. If you're going to process all the bodies
682 /// in the crate, you should iterate over this list rather than the keys
684 pub body_ids: Vec<BodyId>,
688 pub fn item(&self, id: NodeId) -> &Item {
692 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
693 &self.trait_items[&id]
696 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
697 &self.impl_items[&id]
700 /// Visits all items in the crate in some deterministic (but
701 /// unspecified) order. If you just need to process every item,
702 /// but don't care about nesting, this method is the best choice.
704 /// If you do care about nesting -- usually because your algorithm
705 /// follows lexical scoping rules -- then you want a different
706 /// approach. You should override `visit_nested_item` in your
707 /// visitor and then call `intravisit::walk_crate` instead.
708 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
709 where V: itemlikevisit::ItemLikeVisitor<'hir>
711 for (_, item) in &self.items {
712 visitor.visit_item(item);
715 for (_, trait_item) in &self.trait_items {
716 visitor.visit_trait_item(trait_item);
719 for (_, impl_item) in &self.impl_items {
720 visitor.visit_impl_item(impl_item);
724 /// A parallel version of visit_all_item_likes
725 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
726 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
730 par_iter(&self.items).for_each(|(_, item)| {
731 visitor.visit_item(item);
736 par_iter(&self.trait_items).for_each(|(_, trait_item)| {
737 visitor.visit_trait_item(trait_item);
742 par_iter(&self.impl_items).for_each(|(_, impl_item)| {
743 visitor.visit_impl_item(impl_item);
749 pub fn body(&self, id: BodyId) -> &Body {
754 /// A macro definition, in this crate or imported from another.
756 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
757 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
758 pub struct MacroDef {
761 pub attrs: HirVec<Attribute>,
764 pub body: TokenStream,
768 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
770 /// Statements in a block
771 pub stmts: HirVec<Stmt>,
772 /// An expression at the end of the block
773 /// without a semicolon, if any
774 pub expr: Option<P<Expr>>,
777 /// Distinguishes between `unsafe { ... }` and `{ ... }`
778 pub rules: BlockCheckMode,
780 /// If true, then there may exist `break 'a` values that aim to
781 /// break out of this block early. As of this writing, this is not
782 /// currently permitted in Rust itself, but it is generated as
783 /// part of `catch` statements.
784 pub targeted_by_break: bool,
785 /// If true, don't emit return value type errors as the parser had
786 /// to recover from a parse error so this block will not have an
787 /// appropriate type. A parse error will have been emitted so the
788 /// compilation will never succeed if this is true.
792 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
800 impl fmt::Debug for Pat {
801 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
802 write!(f, "pat({}: {})", self.id,
803 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
808 // FIXME(#19596) this is a workaround, but there should be a better way
809 fn walk_<G>(&self, it: &mut G) -> bool
810 where G: FnMut(&Pat) -> bool
817 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
818 PatKind::Struct(_, ref fields, _) => {
819 fields.iter().all(|field| field.node.pat.walk_(it))
821 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
822 s.iter().all(|p| p.walk_(it))
824 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
827 PatKind::Slice(ref before, ref slice, ref after) => {
828 before.iter().all(|p| p.walk_(it)) &&
829 slice.iter().all(|p| p.walk_(it)) &&
830 after.iter().all(|p| p.walk_(it))
835 PatKind::Binding(..) |
836 PatKind::Path(_) => {
842 pub fn walk<F>(&self, mut it: F) -> bool
843 where F: FnMut(&Pat) -> bool
849 /// A single field in a struct pattern
851 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
852 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
853 /// except is_shorthand is true
854 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
855 pub struct FieldPat {
857 /// The identifier for the field
859 /// The pattern the field is destructured to
861 pub is_shorthand: bool,
864 /// Explicit binding annotations given in the HIR for a binding. Note
865 /// that this is not the final binding *mode* that we infer after type
867 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
868 pub enum BindingAnnotation {
869 /// No binding annotation given: this means that the final binding mode
870 /// will depend on whether we have skipped through a `&` reference
871 /// when matching. For example, the `x` in `Some(x)` will have binding
872 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
873 /// ultimately be inferred to be by-reference.
875 /// Note that implicit reference skipping is not implemented yet (#42640).
878 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
881 /// Annotated as `ref`, like `ref x`
884 /// Annotated as `ref mut x`.
888 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
894 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
896 /// Represents a wildcard pattern (`_`)
899 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
900 /// The `NodeId` is the canonical ID for the variable being bound,
901 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
902 /// which is the pattern ID of the first `x`.
903 Binding(BindingAnnotation, NodeId, Spanned<Name>, Option<P<Pat>>),
905 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
906 /// The `bool` is `true` in the presence of a `..`.
907 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
909 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
910 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
911 /// 0 <= position <= subpats.len()
912 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
914 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
917 /// A tuple pattern `(a, b)`.
918 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
919 /// 0 <= position <= subpats.len()
920 Tuple(HirVec<P<Pat>>, Option<usize>),
923 /// A reference pattern, e.g. `&mut (a, b)`
924 Ref(P<Pat>, Mutability),
927 /// A range pattern, e.g. `1...2` or `1..2`
928 Range(P<Expr>, P<Expr>, RangeEnd),
929 /// `[a, b, ..i, y, z]` is represented as:
930 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
931 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
934 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
935 pub enum Mutability {
941 /// Return MutMutable only if both arguments are mutable.
942 pub fn and(self, other: Self) -> Self {
945 MutImmutable => MutImmutable,
950 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
952 /// The `+` operator (addition)
954 /// The `-` operator (subtraction)
956 /// The `*` operator (multiplication)
958 /// The `/` operator (division)
960 /// The `%` operator (modulus)
962 /// The `&&` operator (logical and)
964 /// The `||` operator (logical or)
966 /// The `^` operator (bitwise xor)
968 /// The `&` operator (bitwise and)
970 /// The `|` operator (bitwise or)
972 /// The `<<` operator (shift left)
974 /// The `>>` operator (shift right)
976 /// The `==` operator (equality)
978 /// The `<` operator (less than)
980 /// The `<=` operator (less than or equal to)
982 /// The `!=` operator (not equal to)
984 /// The `>=` operator (greater than or equal to)
986 /// The `>` operator (greater than)
991 pub fn as_str(self) -> &'static str {
1014 pub fn is_lazy(self) -> bool {
1016 BiAnd | BiOr => true,
1021 pub fn is_shift(self) -> bool {
1023 BiShl | BiShr => true,
1028 pub fn is_comparison(self) -> bool {
1030 BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
1046 /// Returns `true` if the binary operator takes its arguments by value
1047 pub fn is_by_value(self) -> bool {
1048 !self.is_comparison()
1052 impl Into<ast::BinOpKind> for BinOp_ {
1053 fn into(self) -> ast::BinOpKind {
1055 BiAdd => ast::BinOpKind::Add,
1056 BiSub => ast::BinOpKind::Sub,
1057 BiMul => ast::BinOpKind::Mul,
1058 BiDiv => ast::BinOpKind::Div,
1059 BiRem => ast::BinOpKind::Rem,
1060 BiAnd => ast::BinOpKind::And,
1061 BiOr => ast::BinOpKind::Or,
1062 BiBitXor => ast::BinOpKind::BitXor,
1063 BiBitAnd => ast::BinOpKind::BitAnd,
1064 BiBitOr => ast::BinOpKind::BitOr,
1065 BiShl => ast::BinOpKind::Shl,
1066 BiShr => ast::BinOpKind::Shr,
1067 BiEq => ast::BinOpKind::Eq,
1068 BiLt => ast::BinOpKind::Lt,
1069 BiLe => ast::BinOpKind::Le,
1070 BiNe => ast::BinOpKind::Ne,
1071 BiGe => ast::BinOpKind::Ge,
1072 BiGt => ast::BinOpKind::Gt,
1077 pub type BinOp = Spanned<BinOp_>;
1079 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1081 /// The `*` operator for dereferencing
1083 /// The `!` operator for logical inversion
1085 /// The `-` operator for negation
1090 pub fn as_str(self) -> &'static str {
1098 /// Returns `true` if the unary operator takes its argument by value
1099 pub fn is_by_value(self) -> bool {
1101 UnNeg | UnNot => true,
1108 pub type Stmt = Spanned<Stmt_>;
1110 impl fmt::Debug for Stmt_ {
1111 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1113 let spanned = codemap::dummy_spanned(self.clone());
1117 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
1121 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1123 /// Could be an item or a local (let) binding:
1124 StmtDecl(P<Decl>, NodeId),
1126 /// Expr without trailing semi-colon (must have unit type):
1127 StmtExpr(P<Expr>, NodeId),
1129 /// Expr with trailing semi-colon (may have any type):
1130 StmtSemi(P<Expr>, NodeId),
1134 pub fn attrs(&self) -> &[Attribute] {
1136 StmtDecl(ref d, _) => d.node.attrs(),
1137 StmtExpr(ref e, _) |
1138 StmtSemi(ref e, _) => &e.attrs,
1142 pub fn id(&self) -> NodeId {
1144 StmtDecl(_, id) => id,
1145 StmtExpr(_, id) => id,
1146 StmtSemi(_, id) => id,
1151 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
1152 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1155 pub ty: Option<P<Ty>>,
1156 /// Initializer expression to set the value, if any
1157 pub init: Option<P<Expr>>,
1161 pub attrs: ThinVec<Attribute>,
1162 pub source: LocalSource,
1165 pub type Decl = Spanned<Decl_>;
1167 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1169 /// A local (let) binding:
1170 DeclLocal(P<Local>),
1171 /// An item binding:
1176 pub fn attrs(&self) -> &[Attribute] {
1178 DeclLocal(ref l) => &l.attrs,
1183 pub fn is_local(&self) -> bool {
1185 Decl_::DeclLocal(_) => true,
1191 /// represents one arm of a 'match'
1192 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1194 pub attrs: HirVec<Attribute>,
1195 pub pats: HirVec<P<Pat>>,
1196 pub guard: Option<P<Expr>>,
1200 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1203 pub name: Spanned<Name>,
1206 pub is_shorthand: bool,
1209 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1210 pub enum BlockCheckMode {
1212 UnsafeBlock(UnsafeSource),
1213 PushUnsafeBlock(UnsafeSource),
1214 PopUnsafeBlock(UnsafeSource),
1217 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1218 pub enum UnsafeSource {
1223 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1225 pub node_id: NodeId,
1228 /// The body of a function, closure, or constant value. In the case of
1229 /// a function, the body contains not only the function body itself
1230 /// (which is an expression), but also the argument patterns, since
1231 /// those are something that the caller doesn't really care about.
1236 /// fn foo((x, y): (u32, u32)) -> u32 {
1241 /// Here, the `Body` associated with `foo()` would contain:
1243 /// - an `arguments` array containing the `(x, y)` pattern
1244 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1245 /// - `is_generator` would be false
1247 /// All bodies have an **owner**, which can be accessed via the HIR
1248 /// map using `body_owner_def_id()`.
1249 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1251 pub arguments: HirVec<Arg>,
1253 pub is_generator: bool,
1257 pub fn id(&self) -> BodyId {
1259 node_id: self.value.id
1264 #[derive(Copy, Clone, Debug)]
1265 pub enum BodyOwnerKind {
1266 /// Functions and methods.
1269 /// Constants and associated constants.
1272 /// Initializer of a `static` item.
1277 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1282 pub attrs: ThinVec<Attribute>,
1287 pub fn precedence(&self) -> ExprPrecedence {
1289 ExprBox(_) => ExprPrecedence::Box,
1290 ExprArray(_) => ExprPrecedence::Array,
1291 ExprCall(..) => ExprPrecedence::Call,
1292 ExprMethodCall(..) => ExprPrecedence::MethodCall,
1293 ExprTup(_) => ExprPrecedence::Tup,
1294 ExprBinary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1295 ExprUnary(..) => ExprPrecedence::Unary,
1296 ExprLit(_) => ExprPrecedence::Lit,
1297 ExprType(..) | ExprCast(..) => ExprPrecedence::Cast,
1298 ExprIf(..) => ExprPrecedence::If,
1299 ExprWhile(..) => ExprPrecedence::While,
1300 ExprLoop(..) => ExprPrecedence::Loop,
1301 ExprMatch(..) => ExprPrecedence::Match,
1302 ExprClosure(..) => ExprPrecedence::Closure,
1303 ExprBlock(..) => ExprPrecedence::Block,
1304 ExprAssign(..) => ExprPrecedence::Assign,
1305 ExprAssignOp(..) => ExprPrecedence::AssignOp,
1306 ExprField(..) => ExprPrecedence::Field,
1307 ExprIndex(..) => ExprPrecedence::Index,
1308 ExprPath(..) => ExprPrecedence::Path,
1309 ExprAddrOf(..) => ExprPrecedence::AddrOf,
1310 ExprBreak(..) => ExprPrecedence::Break,
1311 ExprAgain(..) => ExprPrecedence::Continue,
1312 ExprRet(..) => ExprPrecedence::Ret,
1313 ExprInlineAsm(..) => ExprPrecedence::InlineAsm,
1314 ExprStruct(..) => ExprPrecedence::Struct,
1315 ExprRepeat(..) => ExprPrecedence::Repeat,
1316 ExprYield(..) => ExprPrecedence::Yield,
1321 impl fmt::Debug for Expr {
1322 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1323 write!(f, "expr({}: {})", self.id,
1324 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1328 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1330 /// A `box x` expression.
1332 /// An array (`[a, b, c, d]`)
1333 ExprArray(HirVec<Expr>),
1336 /// The first field resolves to the function itself (usually an `ExprPath`),
1337 /// and the second field is the list of arguments.
1338 /// This also represents calling the constructor of
1339 /// tuple-like ADTs such as tuple structs and enum variants.
1340 ExprCall(P<Expr>, HirVec<Expr>),
1341 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1343 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1344 /// (within the angle brackets).
1345 /// The first element of the vector of `Expr`s is the expression that evaluates
1346 /// to the object on which the method is being called on (the receiver),
1347 /// and the remaining elements are the rest of the arguments.
1348 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1349 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1350 ExprMethodCall(PathSegment, Span, HirVec<Expr>),
1351 /// A tuple (`(a, b, c ,d)`)
1352 ExprTup(HirVec<Expr>),
1353 /// A binary operation (For example: `a + b`, `a * b`)
1354 ExprBinary(BinOp, P<Expr>, P<Expr>),
1355 /// A unary operation (For example: `!x`, `*x`)
1356 ExprUnary(UnOp, P<Expr>),
1357 /// A literal (For example: `1`, `"foo"`)
1359 /// A cast (`foo as f64`)
1360 ExprCast(P<Expr>, P<Ty>),
1361 ExprType(P<Expr>, P<Ty>),
1362 /// An `if` block, with an optional else block
1364 /// `if expr { expr } else { expr }`
1365 ExprIf(P<Expr>, P<Expr>, Option<P<Expr>>),
1366 /// A while loop, with an optional label
1368 /// `'label: while expr { block }`
1369 ExprWhile(P<Expr>, P<Block>, Option<Label>),
1370 /// Conditionless loop (can be exited with break, continue, or return)
1372 /// `'label: loop { block }`
1373 ExprLoop(P<Block>, Option<Label>, LoopSource),
1374 /// A `match` block, with a source that indicates whether or not it is
1375 /// the result of a desugaring, and if so, which kind.
1376 ExprMatch(P<Expr>, HirVec<Arm>, MatchSource),
1377 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1379 /// The final span is the span of the argument block `|...|`
1381 /// This may also be a generator literal, indicated by the final boolean,
1382 /// in that case there is an GeneratorClause.
1383 ExprClosure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1384 /// A block (`'label: { ... }`)
1385 ExprBlock(P<Block>, Option<Label>),
1387 /// An assignment (`a = foo()`)
1388 ExprAssign(P<Expr>, P<Expr>),
1389 /// An assignment with an operator
1391 /// For example, `a += 1`.
1392 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
1393 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct or tuple field
1394 ExprField(P<Expr>, Spanned<Name>),
1395 /// An indexing operation (`foo[2]`)
1396 ExprIndex(P<Expr>, P<Expr>),
1398 /// Path to a definition, possibly containing lifetime or type parameters.
1401 /// A referencing operation (`&a` or `&mut a`)
1402 ExprAddrOf(Mutability, P<Expr>),
1403 /// A `break`, with an optional label to break
1404 ExprBreak(Destination, Option<P<Expr>>),
1405 /// A `continue`, with an optional label
1406 ExprAgain(Destination),
1407 /// A `return`, with an optional value to be returned
1408 ExprRet(Option<P<Expr>>),
1410 /// Inline assembly (from `asm!`), with its outputs and inputs.
1411 ExprInlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1413 /// A struct or struct-like variant literal expression.
1415 /// For example, `Foo {x: 1, y: 2}`, or
1416 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1417 ExprStruct(QPath, HirVec<Field>, Option<P<Expr>>),
1419 /// An array literal constructed from one repeated element.
1421 /// For example, `[1; 5]`. The first expression is the element
1422 /// to be repeated; the second is the number of times to repeat it.
1423 ExprRepeat(P<Expr>, BodyId),
1425 /// A suspension point for generators. This is `yield <expr>` in Rust.
1429 /// Optionally `Self`-qualified value/type path or associated extension.
1430 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1432 /// Path to a definition, optionally "fully-qualified" with a `Self`
1433 /// type, if the path points to an associated item in a trait.
1435 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1436 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1437 /// even though they both have the same two-segment `Clone::clone` `Path`.
1438 Resolved(Option<P<Ty>>, P<Path>),
1440 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1441 /// Will be resolved by type-checking to an associated item.
1443 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1444 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1445 /// the `X` and `Y` nodes each being a `TyPath(QPath::TypeRelative(..))`.
1446 TypeRelative(P<Ty>, P<PathSegment>)
1449 /// Hints at the original code for a let statement
1450 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1451 pub enum LocalSource {
1452 /// A `match _ { .. }`
1454 /// A desugared `for _ in _ { .. }` loop
1458 /// Hints at the original code for a `match _ { .. }`
1459 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1460 pub enum MatchSource {
1461 /// A `match _ { .. }`
1463 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1465 contains_else_clause: bool,
1467 /// A `while let _ = _ { .. }` (which was desugared to a
1468 /// `loop { match _ { .. } }`)
1470 /// A desugared `for _ in _ { .. }` loop
1472 /// A desugared `?` operator
1476 /// The loop type that yielded an ExprLoop
1477 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1478 pub enum LoopSource {
1479 /// A `loop { .. }` loop
1481 /// A `while let _ = _ { .. }` loop
1483 /// A `for _ in _ { .. }` loop
1487 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1488 pub enum LoopIdError {
1490 UnlabeledCfInWhileCondition,
1494 impl fmt::Display for LoopIdError {
1495 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1496 fmt::Display::fmt(match *self {
1497 LoopIdError::OutsideLoopScope => "not inside loop scope",
1498 LoopIdError::UnlabeledCfInWhileCondition =>
1499 "unlabeled control flow (break or continue) in while condition",
1500 LoopIdError::UnresolvedLabel => "label not found",
1505 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1506 pub struct Destination {
1507 // This is `Some(_)` iff there is an explicit user-specified `label
1508 pub label: Option<Label>,
1510 // These errors are caught and then reported during the diagnostics pass in
1511 // librustc_passes/loops.rs
1512 pub target_id: Result<NodeId, LoopIdError>,
1515 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1516 pub enum GeneratorMovability {
1521 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1522 pub enum CaptureClause {
1527 // NB: If you change this, you'll probably want to change the corresponding
1528 // type structure in middle/ty.rs as well.
1529 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1532 pub mutbl: Mutability,
1535 /// Represents a method's signature in a trait declaration or implementation.
1536 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1537 pub struct MethodSig {
1538 pub unsafety: Unsafety,
1539 pub constness: Constness,
1541 pub decl: P<FnDecl>,
1544 // The bodies for items are stored "out of line", in a separate
1545 // hashmap in the `Crate`. Here we just record the node-id of the item
1546 // so it can fetched later.
1547 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1548 pub struct TraitItemId {
1549 pub node_id: NodeId,
1552 /// Represents an item declaration within a trait declaration,
1553 /// possibly including a default implementation. A trait item is
1554 /// either required (meaning it doesn't have an implementation, just a
1555 /// signature) or provided (meaning it has a default implementation).
1556 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1557 pub struct TraitItem {
1561 pub attrs: HirVec<Attribute>,
1562 pub generics: Generics,
1563 pub node: TraitItemKind,
1567 /// A trait method's body (or just argument names).
1568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1569 pub enum TraitMethod {
1570 /// No default body in the trait, just a signature.
1571 Required(HirVec<Spanned<Name>>),
1573 /// Both signature and body are provided in the trait.
1577 /// Represents a trait method or associated constant or type
1578 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1579 pub enum TraitItemKind {
1580 /// An associated constant with an optional value (otherwise `impl`s
1581 /// must contain a value)
1582 Const(P<Ty>, Option<BodyId>),
1583 /// A method with an optional body
1584 Method(MethodSig, TraitMethod),
1585 /// An associated type with (possibly empty) bounds and optional concrete
1587 Type(TyParamBounds, Option<P<Ty>>),
1590 // The bodies for items are stored "out of line", in a separate
1591 // hashmap in the `Crate`. Here we just record the node-id of the item
1592 // so it can fetched later.
1593 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1594 pub struct ImplItemId {
1595 pub node_id: NodeId,
1598 /// Represents anything within an `impl` block
1599 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1600 pub struct ImplItem {
1604 pub vis: Visibility,
1605 pub defaultness: Defaultness,
1606 pub attrs: HirVec<Attribute>,
1607 pub generics: Generics,
1608 pub node: ImplItemKind,
1612 /// Represents different contents within `impl`s
1613 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1614 pub enum ImplItemKind {
1615 /// An associated constant of the given type, set to the constant result
1616 /// of the expression
1617 Const(P<Ty>, BodyId),
1618 /// A method implementation with the given signature and body
1619 Method(MethodSig, BodyId),
1620 /// An associated type
1624 // Bind a type to an associated type: `A=Foo`.
1625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1626 pub struct TypeBinding {
1634 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1642 impl fmt::Debug for Ty {
1643 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1644 write!(f, "type({})",
1645 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1649 /// Not represented directly in the AST, referred to by name through a ty_path.
1650 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1660 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1661 pub struct BareFnTy {
1662 pub unsafety: Unsafety,
1664 pub generic_params: HirVec<GenericParam>,
1665 pub decl: P<FnDecl>,
1666 pub arg_names: HirVec<Spanned<Name>>,
1669 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1670 pub struct ExistTy {
1671 pub generics: Generics,
1672 pub bounds: TyParamBounds,
1675 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1676 /// The different kinds of types recognized by the compiler
1678 /// A variable length slice (`[T]`)
1680 /// A fixed length array (`[T; n]`)
1681 TyArray(P<Ty>, BodyId),
1682 /// A raw pointer (`*const T` or `*mut T`)
1684 /// A reference (`&'a T` or `&'a mut T`)
1685 TyRptr(Lifetime, MutTy),
1686 /// A bare function (e.g. `fn(usize) -> bool`)
1687 TyBareFn(P<BareFnTy>),
1688 /// The never type (`!`)
1690 /// A tuple (`(A, B, C, D,...)`)
1691 TyTup(HirVec<P<Ty>>),
1692 /// A path to a type definition (`module::module::...::Type`), or an
1693 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1695 /// Type parameters may be stored in each `PathSegment`.
1697 /// A trait object type `Bound1 + Bound2 + Bound3`
1698 /// where `Bound` is a trait or a lifetime.
1699 TyTraitObject(HirVec<PolyTraitRef>, Lifetime),
1700 /// An existentially quantified (there exists a type satisfying) `impl
1701 /// Bound1 + Bound2 + Bound3` type where `Bound` is a trait or a lifetime.
1703 /// The `ExistTy` structure emulates an
1704 /// `abstract type Foo<'a, 'b>: MyTrait<'a, 'b>;`.
1706 /// The `HirVec<Lifetime>` is the list of lifetimes applied as parameters
1707 /// to the `abstract type`, e.g. the `'c` and `'d` in `-> Foo<'c, 'd>`.
1708 /// This list is only a list of lifetimes and not type parameters
1709 /// because all in-scope type parameters are captured by `impl Trait`,
1710 /// so they are resolved directly through the parent `Generics`.
1711 TyImplTraitExistential(ExistTy, HirVec<Lifetime>),
1714 /// TyInfer means the type should be inferred instead of it having been
1715 /// specified. This can appear anywhere in a type.
1717 /// Placeholder for a type that has failed to be defined.
1721 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1722 pub struct InlineAsmOutput {
1723 pub constraint: Symbol,
1725 pub is_indirect: bool,
1728 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1729 pub struct InlineAsm {
1731 pub asm_str_style: StrStyle,
1732 pub outputs: HirVec<InlineAsmOutput>,
1733 pub inputs: HirVec<Symbol>,
1734 pub clobbers: HirVec<Symbol>,
1736 pub alignstack: bool,
1737 pub dialect: AsmDialect,
1738 pub ctxt: SyntaxContext,
1741 /// represents an argument in a function header
1742 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1749 /// Represents the header (not the body) of a function declaration
1750 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1752 pub inputs: HirVec<P<Ty>>,
1753 pub output: FunctionRetTy,
1755 /// True if this function has an `self`, `&self` or `&mut self` receiver
1756 /// (but not a `self: Xxx` one).
1757 pub has_implicit_self: bool,
1760 /// Is the trait definition an auto trait?
1761 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1767 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1773 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1774 pub enum Constness {
1779 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1780 pub enum Defaultness {
1781 Default { has_value: bool },
1786 pub fn has_value(&self) -> bool {
1788 Defaultness::Default { has_value, .. } => has_value,
1789 Defaultness::Final => true,
1793 pub fn is_final(&self) -> bool {
1794 *self == Defaultness::Final
1797 pub fn is_default(&self) -> bool {
1799 Defaultness::Default { .. } => true,
1805 impl fmt::Display for Unsafety {
1806 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1807 fmt::Display::fmt(match *self {
1808 Unsafety::Normal => "normal",
1809 Unsafety::Unsafe => "unsafe",
1815 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1816 pub enum ImplPolarity {
1817 /// `impl Trait for Type`
1819 /// `impl !Trait for Type`
1823 impl fmt::Debug for ImplPolarity {
1824 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1826 ImplPolarity::Positive => "positive".fmt(f),
1827 ImplPolarity::Negative => "negative".fmt(f),
1833 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1834 pub enum FunctionRetTy {
1835 /// Return type is not specified.
1837 /// Functions default to `()` and
1838 /// closures default to inference. Span points to where return
1839 /// type would be inserted.
1840 DefaultReturn(Span),
1845 impl FunctionRetTy {
1846 pub fn span(&self) -> Span {
1848 DefaultReturn(span) => span,
1849 Return(ref ty) => ty.span,
1854 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1856 /// A span from the first token past `{` to the last token until `}`.
1857 /// For `mod foo;`, the inner span ranges from the first token
1858 /// to the last token in the external file.
1860 pub item_ids: HirVec<ItemId>,
1863 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1864 pub struct ForeignMod {
1866 pub items: HirVec<ForeignItem>,
1869 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1870 pub struct GlobalAsm {
1872 pub ctxt: SyntaxContext,
1875 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1876 pub struct EnumDef {
1877 pub variants: HirVec<Variant>,
1880 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1881 pub struct Variant_ {
1883 pub attrs: HirVec<Attribute>,
1884 pub data: VariantData,
1885 /// Explicit discriminant, eg `Foo = 1`
1886 pub disr_expr: Option<BodyId>,
1889 pub type Variant = Spanned<Variant_>;
1891 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1893 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1894 /// Also produced for each element of a list `use`, e.g.
1895 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1898 /// Glob import, e.g. `use foo::*`.
1901 /// Degenerate list import, e.g. `use foo::{a, b}` produces
1902 /// an additional `use foo::{}` for performing checks such as
1903 /// unstable feature gating. May be removed in the future.
1907 /// TraitRef's appear in impls.
1909 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1910 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1911 /// trait being referred to but just a unique NodeId that serves as a key
1912 /// within the DefMap.
1913 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1914 pub struct TraitRef {
1919 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1920 pub struct PolyTraitRef {
1921 /// The `'a` in `<'a> Foo<&'a T>`
1922 pub bound_generic_params: HirVec<GenericParam>,
1924 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1925 pub trait_ref: TraitRef,
1930 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1931 pub enum Visibility {
1934 Restricted { path: P<Path>, id: NodeId },
1939 pub fn is_pub_restricted(&self) -> bool {
1940 use self::Visibility::*;
1943 &Inherited => false,
1945 &Restricted { .. } => true,
1950 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1951 pub struct StructField {
1954 pub vis: Visibility,
1957 pub attrs: HirVec<Attribute>,
1961 // Still necessary in couple of places
1962 pub fn is_positional(&self) -> bool {
1963 let first = self.name.as_str().as_bytes()[0];
1964 first >= b'0' && first <= b'9'
1968 /// Fields and Ids of enum variants and structs
1970 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1971 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1972 /// One shared Id can be successfully used for these two purposes.
1973 /// Id of the whole enum lives in `Item`.
1975 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1976 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1977 /// the variant itself" from enum variants.
1978 /// Id of the whole struct lives in `Item`.
1979 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1980 pub enum VariantData {
1981 Struct(HirVec<StructField>, NodeId),
1982 Tuple(HirVec<StructField>, NodeId),
1987 pub fn fields(&self) -> &[StructField] {
1989 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1993 pub fn id(&self) -> NodeId {
1995 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
1998 pub fn is_struct(&self) -> bool {
1999 if let VariantData::Struct(..) = *self {
2005 pub fn is_tuple(&self) -> bool {
2006 if let VariantData::Tuple(..) = *self {
2012 pub fn is_unit(&self) -> bool {
2013 if let VariantData::Unit(..) = *self {
2021 // The bodies for items are stored "out of line", in a separate
2022 // hashmap in the `Crate`. Here we just record the node-id of the item
2023 // so it can fetched later.
2024 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2031 /// The name might be a dummy name in case of anonymous items
2032 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2037 pub attrs: HirVec<Attribute>,
2039 pub vis: Visibility,
2043 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2045 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2047 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2048 ItemExternCrate(Option<Name>),
2050 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2054 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2055 ItemUse(P<Path>, UseKind),
2058 ItemStatic(P<Ty>, Mutability, BodyId),
2060 ItemConst(P<Ty>, BodyId),
2061 /// A function declaration
2062 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, BodyId),
2065 /// An external module
2066 ItemForeignMod(ForeignMod),
2067 /// Module-level inline assembly (from global_asm!)
2068 ItemGlobalAsm(P<GlobalAsm>),
2069 /// A type alias, e.g. `type Foo = Bar<u8>`
2070 ItemTy(P<Ty>, Generics),
2071 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
2072 ItemEnum(EnumDef, Generics),
2073 /// A struct definition, e.g. `struct Foo<A> {x: A}`
2074 ItemStruct(VariantData, Generics),
2075 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
2076 ItemUnion(VariantData, Generics),
2077 /// Represents a Trait Declaration
2078 ItemTrait(IsAuto, Unsafety, Generics, TyParamBounds, HirVec<TraitItemRef>),
2079 /// Represents a Trait Alias Declaration
2080 ItemTraitAlias(Generics, TyParamBounds),
2082 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2087 Option<TraitRef>, // (optional) trait this impl implements
2089 HirVec<ImplItemRef>),
2093 pub fn descriptive_variant(&self) -> &str {
2095 ItemExternCrate(..) => "extern crate",
2096 ItemUse(..) => "use",
2097 ItemStatic(..) => "static item",
2098 ItemConst(..) => "constant item",
2099 ItemFn(..) => "function",
2100 ItemMod(..) => "module",
2101 ItemForeignMod(..) => "foreign module",
2102 ItemGlobalAsm(..) => "global asm",
2103 ItemTy(..) => "type alias",
2104 ItemEnum(..) => "enum",
2105 ItemStruct(..) => "struct",
2106 ItemUnion(..) => "union",
2107 ItemTrait(..) => "trait",
2108 ItemTraitAlias(..) => "trait alias",
2109 ItemImpl(..) => "item",
2113 pub fn adt_kind(&self) -> Option<AdtKind> {
2115 ItemStruct(..) => Some(AdtKind::Struct),
2116 ItemUnion(..) => Some(AdtKind::Union),
2117 ItemEnum(..) => Some(AdtKind::Enum),
2122 pub fn generics(&self) -> Option<&Generics> {
2124 ItemFn(_, _, _, _, ref generics, _) |
2125 ItemTy(_, ref generics) |
2126 ItemEnum(_, ref generics) |
2127 ItemStruct(_, ref generics) |
2128 ItemUnion(_, ref generics) |
2129 ItemTrait(_, _, ref generics, _, _) |
2130 ItemImpl(_, _, _, ref generics, _, _, _)=> generics,
2136 /// A reference from an trait to one of its associated items. This
2137 /// contains the item's id, naturally, but also the item's name and
2138 /// some other high-level details (like whether it is an associated
2139 /// type or method, and whether it is public). This allows other
2140 /// passes to find the impl they want without loading the id (which
2141 /// means fewer edges in the incremental compilation graph).
2142 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2143 pub struct TraitItemRef {
2144 pub id: TraitItemId,
2146 pub kind: AssociatedItemKind,
2148 pub defaultness: Defaultness,
2151 /// A reference from an impl to one of its associated items. This
2152 /// contains the item's id, naturally, but also the item's name and
2153 /// some other high-level details (like whether it is an associated
2154 /// type or method, and whether it is public). This allows other
2155 /// passes to find the impl they want without loading the id (which
2156 /// means fewer edges in the incremental compilation graph).
2157 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2158 pub struct ImplItemRef {
2161 pub kind: AssociatedItemKind,
2163 pub vis: Visibility,
2164 pub defaultness: Defaultness,
2167 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2168 pub enum AssociatedItemKind {
2170 Method { has_self: bool },
2174 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2175 pub struct ForeignItem {
2177 pub attrs: HirVec<Attribute>,
2178 pub node: ForeignItem_,
2181 pub vis: Visibility,
2184 /// An item within an `extern` block
2185 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
2186 pub enum ForeignItem_ {
2187 /// A foreign function
2188 ForeignItemFn(P<FnDecl>, HirVec<Spanned<Name>>, Generics),
2189 /// A foreign static item (`static ext: u8`), with optional mutability
2190 /// (the boolean is true when mutable)
2191 ForeignItemStatic(P<Ty>, bool),
2197 pub fn descriptive_variant(&self) -> &str {
2199 ForeignItemFn(..) => "foreign function",
2200 ForeignItemStatic(..) => "foreign static item",
2201 ForeignItemType => "foreign type",
2206 /// A free variable referred to in a function.
2207 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2208 pub struct Freevar {
2209 /// The variable being accessed free.
2212 // First span where it is accessed (there can be multiple).
2217 pub fn var_id(&self) -> NodeId {
2219 Def::Local(id) | Def::Upvar(id, ..) => id,
2220 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2225 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2227 pub type CaptureModeMap = NodeMap<CaptureClause>;
2229 #[derive(Clone, Debug)]
2230 pub struct TraitCandidate {
2232 pub import_id: Option<NodeId>,
2235 // Trait method resolution
2236 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2238 // Map from the NodeId of a glob import to a list of items which are actually
2240 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2243 pub fn provide(providers: &mut Providers) {
2244 providers.describe_def = map::describe_def;
2247 #[derive(Clone, RustcEncodable, RustcDecodable, Hash)]
2248 pub struct TransFnAttrs {
2249 pub flags: TransFnAttrFlags,
2250 pub inline: InlineAttr,
2251 pub export_name: Option<Symbol>,
2252 pub target_features: Vec<Symbol>,
2253 pub linkage: Option<Linkage>,
2257 #[derive(RustcEncodable, RustcDecodable)]
2258 pub struct TransFnAttrFlags: u8 {
2259 const COLD = 0b0000_0001;
2260 const ALLOCATOR = 0b0000_0010;
2261 const UNWIND = 0b0000_0100;
2262 const RUSTC_ALLOCATOR_NOUNWIND = 0b0000_1000;
2263 const NAKED = 0b0001_0000;
2264 const NO_MANGLE = 0b0010_0000;
2265 const RUSTC_STD_INTERNAL_SYMBOL = 0b0100_0000;
2266 const NO_DEBUG = 0b1000_0000;
2271 pub fn new() -> TransFnAttrs {
2273 flags: TransFnAttrFlags::empty(),
2274 inline: InlineAttr::None,
2276 target_features: vec![],
2281 /// True if `#[inline]` or `#[inline(always)]` is present.
2282 pub fn requests_inline(&self) -> bool {
2284 InlineAttr::Hint | InlineAttr::Always => true,
2285 InlineAttr::None | InlineAttr::Never => false,
2289 /// True if `#[no_mangle]` or `#[export_name(...)]` is present.
2290 pub fn contains_extern_indicator(&self) -> bool {
2291 self.flags.contains(TransFnAttrFlags::NO_MANGLE) || self.export_name.is_some()