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::BlockCheckMode::*;
14 pub use self::CaptureClause::*;
15 pub use self::FunctionRetTy::*;
16 pub use self::Mutability::*;
17 pub use self::PrimTy::*;
18 pub use self::UnOp::*;
19 pub use self::UnsafeSource::*;
22 use hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
23 use util::nodemap::{NodeMap, FxHashSet};
24 use mir::mono::Linkage;
26 use syntax_pos::{Span, DUMMY_SP, symbol::InternedString};
27 use syntax::codemap::{self, Spanned};
28 use rustc_target::spec::abi::Abi;
29 use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, DUMMY_NODE_ID, AsmDialect};
30 use syntax::ast::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy, MetaItem};
31 use syntax::attr::InlineAttr;
32 use syntax::ext::hygiene::SyntaxContext;
34 use syntax::symbol::{Symbol, keywords};
35 use syntax::tokenstream::TokenStream;
36 use syntax::util::ThinVec;
37 use syntax::util::parser::ExprPrecedence;
39 use ty::query::Providers;
41 use rustc_data_structures::indexed_vec;
42 use rustc_data_structures::sync::{ParallelIterator, par_iter, Send, Sync, scope};
44 use serialize::{self, Encoder, Encodable, Decoder, Decodable};
45 use std::collections::BTreeMap;
48 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
49 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
50 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
51 /// of `Vec` to avoid keeping extra capacity.
52 pub type HirVec<T> = P<[T]>;
54 macro_rules! hir_vec {
55 ($elem:expr; $n:expr) => (
56 $crate::hir::HirVec::from(vec![$elem; $n])
59 $crate::hir::HirVec::from(vec![$($x),*])
61 ($($x:expr,)*) => (hir_vec![$($x),*])
68 pub mod itemlikevisit;
75 /// A HirId uniquely identifies a node in the HIR of the current crate. It is
76 /// composed of the `owner`, which is the DefIndex of the directly enclosing
77 /// hir::Item, hir::TraitItem, or hir::ImplItem (i.e. the closest "item-like"),
78 /// and the `local_id` which is unique within the given owner.
80 /// This two-level structure makes for more stable values: One can move an item
81 /// around within the source code, or add or remove stuff before it, without
82 /// the local_id part of the HirId changing, which is a very useful property in
83 /// incremental compilation where we have to persist things through changes to
85 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
88 pub local_id: ItemLocalId,
92 pub fn owner_def_id(self) -> DefId {
93 DefId::local(self.owner)
96 pub fn owner_local_def_id(self) -> LocalDefId {
97 LocalDefId::from_def_id(DefId::local(self.owner))
101 impl serialize::UseSpecializedEncodable for HirId {
102 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
113 impl serialize::UseSpecializedDecodable for HirId {
114 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
115 let owner = DefIndex::decode(d)?;
116 let local_id = ItemLocalId::decode(d)?;
126 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
127 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
128 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
129 /// the node's position within the owning item in any way, but there is a
130 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
131 /// integers starting at zero, so a mapping that maps all or most nodes within
132 /// an "item-like" to something else can be implement by a `Vec` instead of a
133 /// tree or hash map.
134 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug,
135 RustcEncodable, RustcDecodable)]
136 pub struct ItemLocalId(pub u32);
139 pub fn as_usize(&self) -> usize {
144 impl indexed_vec::Idx for ItemLocalId {
145 fn new(idx: usize) -> Self {
146 debug_assert!((idx as u32) as usize == idx);
147 ItemLocalId(idx as u32)
150 fn index(self) -> usize {
155 /// The `HirId` corresponding to CRATE_NODE_ID and CRATE_DEF_INDEX
156 pub const CRATE_HIR_ID: HirId = HirId {
157 owner: CRATE_DEF_INDEX,
158 local_id: ItemLocalId(0)
161 pub const DUMMY_HIR_ID: HirId = HirId {
162 owner: CRATE_DEF_INDEX,
163 local_id: DUMMY_ITEM_LOCAL_ID,
166 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId(!0);
168 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
173 impl fmt::Debug for Label {
174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
175 write!(f, "label({:?})", self.ident)
179 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
180 pub struct Lifetime {
184 /// Either "'a", referring to a named lifetime definition,
185 /// or "" (aka keywords::Invalid), for elision placeholders.
187 /// HIR lowering inserts these placeholders in type paths that
188 /// refer to type definitions needing lifetime parameters,
189 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
190 pub name: LifetimeName,
193 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
195 /// Some user-given name like `T` or `'x`.
198 /// Synthetic name generated when user elided a lifetime in an impl header,
199 /// e.g. the lifetimes in cases like these:
201 /// impl Foo for &u32
202 /// impl Foo<'_> for u32
204 /// in that case, we rewrite to
206 /// impl<'f> Foo for &'f u32
207 /// impl<'f> Foo<'f> for u32
209 /// where `'f` is something like `Fresh(0)`. The indices are
210 /// unique per impl, but not necessarily continuous.
215 pub fn ident(&self) -> Ident {
217 ParamName::Plain(ident) => ident,
218 ParamName::Fresh(_) => keywords::UnderscoreLifetime.ident(),
222 pub fn modern(&self) -> ParamName {
224 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
225 param_name => param_name,
230 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
231 pub enum LifetimeName {
232 /// User-given names or fresh (synthetic) names.
235 /// User typed nothing. e.g. the lifetime in `&u32`.
241 /// User wrote `'static`
246 pub fn ident(&self) -> Ident {
248 LifetimeName::Implicit => keywords::Invalid.ident(),
249 LifetimeName::Underscore => keywords::UnderscoreLifetime.ident(),
250 LifetimeName::Static => keywords::StaticLifetime.ident(),
251 LifetimeName::Param(param_name) => param_name.ident(),
255 pub fn is_elided(&self) -> bool {
257 LifetimeName::Implicit | LifetimeName::Underscore => true,
259 // It might seem surprising that `Fresh(_)` counts as
260 // *not* elided -- but this is because, as far as the code
261 // in the compiler is concerned -- `Fresh(_)` variants act
262 // equivalently to "some fresh name". They correspond to
263 // early-bound regions on an impl, in other words.
264 LifetimeName::Param(_) | LifetimeName::Static => false,
268 fn is_static(&self) -> bool {
269 self == &LifetimeName::Static
272 pub fn modern(&self) -> LifetimeName {
274 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
275 lifetime_name => lifetime_name,
280 impl fmt::Display for Lifetime {
281 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
282 self.name.ident().fmt(f)
286 impl fmt::Debug for Lifetime {
287 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
291 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
296 pub fn is_elided(&self) -> bool {
297 self.name.is_elided()
300 pub fn is_static(&self) -> bool {
301 self.name.is_static()
305 /// A "Path" is essentially Rust's notion of a name; for instance:
306 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
307 /// along with a bunch of supporting information.
308 #[derive(Clone, RustcEncodable, RustcDecodable)]
311 /// The definition that the path resolved to.
313 /// The segments in the path: the things separated by `::`.
314 pub segments: HirVec<PathSegment>,
318 pub fn is_global(&self) -> bool {
319 !self.segments.is_empty() && self.segments[0].ident.name == keywords::CrateRoot.name()
323 impl fmt::Debug for Path {
324 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
325 write!(f, "path({})", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
329 impl fmt::Display for Path {
330 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
331 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
335 /// A segment of a path: an identifier, an optional lifetime, and a set of
337 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
338 pub struct PathSegment {
339 /// The identifier portion of this path segment.
342 /// Type/lifetime parameters attached to this path. They come in
343 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
344 /// this is more than just simple syntactic sugar; the use of
345 /// parens affects the region binding rules, so we preserve the
347 pub args: Option<P<GenericArgs>>,
349 /// Whether to infer remaining type parameters, if any.
350 /// This only applies to expression and pattern paths, and
351 /// out of those only the segments with no type parameters
352 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
353 pub infer_types: bool,
357 /// Convert an identifier to the corresponding segment.
358 pub fn from_ident(ident: Ident) -> PathSegment {
366 pub fn new(ident: Ident, args: GenericArgs, infer_types: bool) -> Self {
370 args: if args.is_empty() {
378 // FIXME: hack required because you can't create a static
379 // GenericArgs, so you can't just return a &GenericArgs.
380 pub fn with_generic_args<F, R>(&self, f: F) -> R
381 where F: FnOnce(&GenericArgs) -> R
383 let dummy = GenericArgs::none();
384 f(if let Some(ref args) = self.args {
392 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
393 pub enum GenericArg {
399 pub fn span(&self) -> Span {
401 GenericArg::Lifetime(l) => l.span,
402 GenericArg::Type(t) => t.span,
407 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
408 pub struct GenericArgs {
409 /// The generic arguments for this path segment.
410 pub args: HirVec<GenericArg>,
411 /// Bindings (equality constraints) on associated types, if present.
412 /// E.g., `Foo<A=Bar>`.
413 pub bindings: HirVec<TypeBinding>,
414 /// Were arguments written in parenthesized form `Fn(T) -> U`?
415 /// This is required mostly for pretty-printing and diagnostics,
416 /// but also for changing lifetime elision rules to be "function-like".
417 pub parenthesized: bool,
421 pub fn none() -> Self {
424 bindings: HirVec::new(),
425 parenthesized: false,
429 pub fn is_empty(&self) -> bool {
430 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
433 pub fn inputs(&self) -> &[Ty] {
434 if self.parenthesized {
435 for arg in &self.args {
437 GenericArg::Lifetime(_) => {}
438 GenericArg::Type(ref ty) => {
439 if let TyKind::Tup(ref tys) = ty.node {
447 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
451 /// A modifier on a bound, currently this is only used for `?Sized`, where the
452 /// modifier is `Maybe`. Negative bounds should also be handled here.
453 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
454 pub enum TraitBoundModifier {
459 /// The AST represents all type param bounds as types.
460 /// typeck::collect::compute_bounds matches these against
461 /// the "special" built-in traits (see middle::lang_items) and
462 /// detects Copy, Send and Sync.
463 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
464 pub enum GenericBound {
465 Trait(PolyTraitRef, TraitBoundModifier),
470 pub fn span(&self) -> Span {
472 &GenericBound::Trait(ref t, ..) => t.span,
473 &GenericBound::Outlives(ref l) => l.span,
478 pub type GenericBounds = HirVec<GenericBound>;
480 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
481 pub enum GenericParamKind {
482 /// A lifetime definition, eg `'a: 'b + 'c + 'd`.
484 // Indicates that the lifetime definition was synthetically added
485 // as a result of an in-band lifetime usage like:
486 // `fn foo(x: &'a u8) -> &'a u8 { x }`
490 default: Option<P<Ty>>,
491 synthetic: Option<SyntheticTyParamKind>,
495 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
496 pub struct GenericParam {
499 pub attrs: HirVec<Attribute>,
500 pub bounds: GenericBounds,
502 pub pure_wrt_drop: bool,
504 pub kind: GenericParamKind,
507 pub struct GenericParamCount {
508 pub lifetimes: usize,
512 /// Represents lifetimes and type parameters attached to a declaration
513 /// of a function, enum, trait, etc.
514 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
515 pub struct Generics {
516 pub params: HirVec<GenericParam>,
517 pub where_clause: WhereClause,
522 pub fn empty() -> Generics {
524 params: HirVec::new(),
525 where_clause: WhereClause {
527 predicates: HirVec::new(),
533 pub fn own_counts(&self) -> GenericParamCount {
534 // We could cache this as a property of `GenericParamCount`, but
535 // the aim is to refactor this away entirely eventually and the
536 // presence of this method will be a constant reminder.
537 let mut own_counts = GenericParamCount {
542 for param in &self.params {
544 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
545 GenericParamKind::Type { .. } => own_counts.types += 1,
552 pub fn get_named(&self, name: &InternedString) -> Option<&GenericParam> {
553 for param in &self.params {
554 if *name == param.name.ident().as_interned_str() {
562 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
563 /// to track the original form they had. Useful for error messages.
564 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
565 pub enum SyntheticTyParamKind {
569 /// A `where` clause in a definition
570 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
571 pub struct WhereClause {
573 pub predicates: HirVec<WherePredicate>,
577 pub fn span(&self) -> Option<Span> {
578 self.predicates.iter().map(|predicate| predicate.span())
579 .fold(None, |acc, i| match (acc, i) {
580 (None, i) => Some(i),
588 /// A single predicate in a `where` clause
589 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
590 pub enum WherePredicate {
591 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
592 BoundPredicate(WhereBoundPredicate),
593 /// A lifetime predicate, e.g. `'a: 'b+'c`
594 RegionPredicate(WhereRegionPredicate),
595 /// An equality predicate (unsupported)
596 EqPredicate(WhereEqPredicate),
599 impl WherePredicate {
600 pub fn span(&self) -> Span {
602 &WherePredicate::BoundPredicate(ref p) => p.span,
603 &WherePredicate::RegionPredicate(ref p) => p.span,
604 &WherePredicate::EqPredicate(ref p) => p.span,
609 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
610 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
611 pub struct WhereBoundPredicate {
613 /// Any generics from a `for` binding
614 pub bound_generic_params: HirVec<GenericParam>,
615 /// The type being bounded
616 pub bounded_ty: P<Ty>,
617 /// Trait and lifetime bounds (`Clone+Send+'static`)
618 pub bounds: GenericBounds,
621 /// A lifetime predicate, e.g. `'a: 'b+'c`
622 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
623 pub struct WhereRegionPredicate {
625 pub lifetime: Lifetime,
626 pub bounds: GenericBounds,
629 /// An equality predicate (unsupported), e.g. `T=int`
630 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
631 pub struct WhereEqPredicate {
638 pub type CrateConfig = HirVec<P<MetaItem>>;
640 /// The top-level data structure that stores the entire contents of
641 /// the crate currently being compiled.
643 /// For more details, see the [rustc guide].
645 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/hir.html
646 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
649 pub attrs: HirVec<Attribute>,
651 pub exported_macros: HirVec<MacroDef>,
653 // NB: We use a BTreeMap here so that `visit_all_items` iterates
654 // over the ids in increasing order. In principle it should not
655 // matter what order we visit things in, but in *practice* it
656 // does, because it can affect the order in which errors are
657 // detected, which in turn can make compile-fail tests yield
658 // slightly different results.
659 pub items: BTreeMap<NodeId, Item>,
661 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
662 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
663 pub bodies: BTreeMap<BodyId, Body>,
664 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
665 pub trait_auto_impl: BTreeMap<DefId, NodeId>,
667 /// A list of the body ids written out in the order in which they
668 /// appear in the crate. If you're going to process all the bodies
669 /// in the crate, you should iterate over this list rather than the keys
671 pub body_ids: Vec<BodyId>,
675 pub fn item(&self, id: NodeId) -> &Item {
679 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
680 &self.trait_items[&id]
683 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
684 &self.impl_items[&id]
687 /// Visits all items in the crate in some deterministic (but
688 /// unspecified) order. If you just need to process every item,
689 /// but don't care about nesting, this method is the best choice.
691 /// If you do care about nesting -- usually because your algorithm
692 /// follows lexical scoping rules -- then you want a different
693 /// approach. You should override `visit_nested_item` in your
694 /// visitor and then call `intravisit::walk_crate` instead.
695 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
696 where V: itemlikevisit::ItemLikeVisitor<'hir>
698 for (_, item) in &self.items {
699 visitor.visit_item(item);
702 for (_, trait_item) in &self.trait_items {
703 visitor.visit_trait_item(trait_item);
706 for (_, impl_item) in &self.impl_items {
707 visitor.visit_impl_item(impl_item);
711 /// A parallel version of visit_all_item_likes
712 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
713 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
717 par_iter(&self.items).for_each(|(_, item)| {
718 visitor.visit_item(item);
723 par_iter(&self.trait_items).for_each(|(_, trait_item)| {
724 visitor.visit_trait_item(trait_item);
729 par_iter(&self.impl_items).for_each(|(_, impl_item)| {
730 visitor.visit_impl_item(impl_item);
736 pub fn body(&self, id: BodyId) -> &Body {
741 /// A macro definition, in this crate or imported from another.
743 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
744 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
745 pub struct MacroDef {
748 pub attrs: HirVec<Attribute>,
751 pub body: TokenStream,
755 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
757 /// Statements in a block
758 pub stmts: HirVec<Stmt>,
759 /// An expression at the end of the block
760 /// without a semicolon, if any
761 pub expr: Option<P<Expr>>,
764 /// Distinguishes between `unsafe { ... }` and `{ ... }`
765 pub rules: BlockCheckMode,
767 /// If true, then there may exist `break 'a` values that aim to
768 /// break out of this block early.
769 /// Used by `'label: {}` blocks and by `catch` statements.
770 pub targeted_by_break: bool,
771 /// If true, don't emit return value type errors as the parser had
772 /// to recover from a parse error so this block will not have an
773 /// appropriate type. A parse error will have been emitted so the
774 /// compilation will never succeed if this is true.
778 #[derive(Clone, RustcEncodable, RustcDecodable)]
786 impl fmt::Debug for Pat {
787 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
788 write!(f, "pat({}: {})", self.id,
789 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
794 // FIXME(#19596) this is a workaround, but there should be a better way
795 fn walk_<G>(&self, it: &mut G) -> bool
796 where G: FnMut(&Pat) -> bool
803 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
804 PatKind::Struct(_, ref fields, _) => {
805 fields.iter().all(|field| field.node.pat.walk_(it))
807 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
808 s.iter().all(|p| p.walk_(it))
810 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
813 PatKind::Slice(ref before, ref slice, ref after) => {
814 before.iter().all(|p| p.walk_(it)) &&
815 slice.iter().all(|p| p.walk_(it)) &&
816 after.iter().all(|p| p.walk_(it))
821 PatKind::Binding(..) |
822 PatKind::Path(_) => {
828 pub fn walk<F>(&self, mut it: F) -> bool
829 where F: FnMut(&Pat) -> bool
835 /// A single field in a struct pattern
837 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
838 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
839 /// except is_shorthand is true
840 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
841 pub struct FieldPat {
843 /// The identifier for the field
845 /// The pattern the field is destructured to
847 pub is_shorthand: bool,
850 /// Explicit binding annotations given in the HIR for a binding. Note
851 /// that this is not the final binding *mode* that we infer after type
853 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
854 pub enum BindingAnnotation {
855 /// No binding annotation given: this means that the final binding mode
856 /// will depend on whether we have skipped through a `&` reference
857 /// when matching. For example, the `x` in `Some(x)` will have binding
858 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
859 /// ultimately be inferred to be by-reference.
861 /// Note that implicit reference skipping is not implemented yet (#42640).
864 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
867 /// Annotated as `ref`, like `ref x`
870 /// Annotated as `ref mut x`.
874 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
880 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
882 /// Represents a wildcard pattern (`_`)
885 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
886 /// The `NodeId` is the canonical ID for the variable being bound,
887 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
888 /// which is the pattern ID of the first `x`.
889 Binding(BindingAnnotation, NodeId, Ident, Option<P<Pat>>),
891 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
892 /// The `bool` is `true` in the presence of a `..`.
893 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
895 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
896 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
897 /// 0 <= position <= subpats.len()
898 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
900 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
903 /// A tuple pattern `(a, b)`.
904 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
905 /// 0 <= position <= subpats.len()
906 Tuple(HirVec<P<Pat>>, Option<usize>),
909 /// A reference pattern, e.g. `&mut (a, b)`
910 Ref(P<Pat>, Mutability),
913 /// A range pattern, e.g. `1...2` or `1..2`
914 Range(P<Expr>, P<Expr>, RangeEnd),
915 /// `[a, b, ..i, y, z]` is represented as:
916 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
917 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
920 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
921 pub enum Mutability {
927 /// Return MutMutable only if both arguments are mutable.
928 pub fn and(self, other: Self) -> Self {
931 MutImmutable => MutImmutable,
936 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
938 /// The `+` operator (addition)
940 /// The `-` operator (subtraction)
942 /// The `*` operator (multiplication)
944 /// The `/` operator (division)
946 /// The `%` operator (modulus)
948 /// The `&&` operator (logical and)
950 /// The `||` operator (logical or)
952 /// The `^` operator (bitwise xor)
954 /// The `&` operator (bitwise and)
956 /// The `|` operator (bitwise or)
958 /// The `<<` operator (shift left)
960 /// The `>>` operator (shift right)
962 /// The `==` operator (equality)
964 /// The `<` operator (less than)
966 /// The `<=` operator (less than or equal to)
968 /// The `!=` operator (not equal to)
970 /// The `>=` operator (greater than or equal to)
972 /// The `>` operator (greater than)
977 pub fn as_str(self) -> &'static str {
979 BinOpKind::Add => "+",
980 BinOpKind::Sub => "-",
981 BinOpKind::Mul => "*",
982 BinOpKind::Div => "/",
983 BinOpKind::Rem => "%",
984 BinOpKind::And => "&&",
985 BinOpKind::Or => "||",
986 BinOpKind::BitXor => "^",
987 BinOpKind::BitAnd => "&",
988 BinOpKind::BitOr => "|",
989 BinOpKind::Shl => "<<",
990 BinOpKind::Shr => ">>",
991 BinOpKind::Eq => "==",
992 BinOpKind::Lt => "<",
993 BinOpKind::Le => "<=",
994 BinOpKind::Ne => "!=",
995 BinOpKind::Ge => ">=",
996 BinOpKind::Gt => ">",
1000 pub fn is_lazy(self) -> bool {
1002 BinOpKind::And | BinOpKind::Or => true,
1007 pub fn is_shift(self) -> bool {
1009 BinOpKind::Shl | BinOpKind::Shr => true,
1014 pub fn is_comparison(self) -> bool {
1021 BinOpKind::Ge => true,
1033 BinOpKind::Shr => false,
1037 /// Returns `true` if the binary operator takes its arguments by value
1038 pub fn is_by_value(self) -> bool {
1039 !self.is_comparison()
1043 impl Into<ast::BinOpKind> for BinOpKind {
1044 fn into(self) -> ast::BinOpKind {
1046 BinOpKind::Add => ast::BinOpKind::Add,
1047 BinOpKind::Sub => ast::BinOpKind::Sub,
1048 BinOpKind::Mul => ast::BinOpKind::Mul,
1049 BinOpKind::Div => ast::BinOpKind::Div,
1050 BinOpKind::Rem => ast::BinOpKind::Rem,
1051 BinOpKind::And => ast::BinOpKind::And,
1052 BinOpKind::Or => ast::BinOpKind::Or,
1053 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1054 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1055 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1056 BinOpKind::Shl => ast::BinOpKind::Shl,
1057 BinOpKind::Shr => ast::BinOpKind::Shr,
1058 BinOpKind::Eq => ast::BinOpKind::Eq,
1059 BinOpKind::Lt => ast::BinOpKind::Lt,
1060 BinOpKind::Le => ast::BinOpKind::Le,
1061 BinOpKind::Ne => ast::BinOpKind::Ne,
1062 BinOpKind::Ge => ast::BinOpKind::Ge,
1063 BinOpKind::Gt => ast::BinOpKind::Gt,
1068 pub type BinOp = Spanned<BinOpKind>;
1070 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
1072 /// The `*` operator for dereferencing
1074 /// The `!` operator for logical inversion
1076 /// The `-` operator for negation
1081 pub fn as_str(self) -> &'static str {
1089 /// Returns `true` if the unary operator takes its argument by value
1090 pub fn is_by_value(self) -> bool {
1092 UnNeg | UnNot => true,
1099 pub type Stmt = Spanned<StmtKind>;
1101 impl fmt::Debug for StmtKind {
1102 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1104 let spanned = codemap::dummy_spanned(self.clone());
1108 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
1112 #[derive(Clone, RustcEncodable, RustcDecodable)]
1114 /// Could be an item or a local (let) binding:
1115 Decl(P<Decl>, NodeId),
1117 /// Expr without trailing semi-colon (must have unit type):
1118 Expr(P<Expr>, NodeId),
1120 /// Expr with trailing semi-colon (may have any type):
1121 Semi(P<Expr>, NodeId),
1125 pub fn attrs(&self) -> &[Attribute] {
1127 StmtKind::Decl(ref d, _) => d.node.attrs(),
1128 StmtKind::Expr(ref e, _) |
1129 StmtKind::Semi(ref e, _) => &e.attrs,
1133 pub fn id(&self) -> NodeId {
1135 StmtKind::Decl(_, id) => id,
1136 StmtKind::Expr(_, id) => id,
1137 StmtKind::Semi(_, id) => id,
1142 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
1143 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1146 pub ty: Option<P<Ty>>,
1147 /// Initializer expression to set the value, if any
1148 pub init: Option<P<Expr>>,
1152 pub attrs: ThinVec<Attribute>,
1153 pub source: LocalSource,
1156 pub type Decl = Spanned<DeclKind>;
1158 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1160 /// A local (let) binding:
1162 /// An item binding:
1167 pub fn attrs(&self) -> &[Attribute] {
1169 DeclKind::Local(ref l) => &l.attrs,
1170 DeclKind::Item(_) => &[]
1174 pub fn is_local(&self) -> bool {
1176 DeclKind::Local(_) => true,
1182 /// represents one arm of a 'match'
1183 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1185 pub attrs: HirVec<Attribute>,
1186 pub pats: HirVec<P<Pat>>,
1187 pub guard: Option<P<Expr>>,
1191 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1197 pub is_shorthand: bool,
1200 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1201 pub enum BlockCheckMode {
1203 UnsafeBlock(UnsafeSource),
1204 PushUnsafeBlock(UnsafeSource),
1205 PopUnsafeBlock(UnsafeSource),
1208 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1209 pub enum UnsafeSource {
1214 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1216 pub node_id: NodeId,
1219 /// The body of a function, closure, or constant value. In the case of
1220 /// a function, the body contains not only the function body itself
1221 /// (which is an expression), but also the argument patterns, since
1222 /// those are something that the caller doesn't really care about.
1227 /// fn foo((x, y): (u32, u32)) -> u32 {
1232 /// Here, the `Body` associated with `foo()` would contain:
1234 /// - an `arguments` array containing the `(x, y)` pattern
1235 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1236 /// - `is_generator` would be false
1238 /// All bodies have an **owner**, which can be accessed via the HIR
1239 /// map using `body_owner_def_id()`.
1240 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1242 pub arguments: HirVec<Arg>,
1244 pub is_generator: bool,
1248 pub fn id(&self) -> BodyId {
1250 node_id: self.value.id
1255 #[derive(Copy, Clone, Debug)]
1256 pub enum BodyOwnerKind {
1257 /// Functions and methods.
1260 /// Constants and associated constants.
1263 /// Initializer of a `static` item.
1267 /// A constant (expression) that's not an item or associated item,
1268 /// but needs its own `DefId` for type-checking, const-eval, etc.
1269 /// These are usually found nested inside types (e.g. array lengths)
1270 /// or expressions (e.g. repeat counts), and also used to define
1271 /// explicit discriminant values for enum variants.
1272 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1273 pub struct AnonConst {
1280 #[derive(Clone, RustcEncodable, RustcDecodable)]
1285 pub attrs: ThinVec<Attribute>,
1290 pub fn precedence(&self) -> ExprPrecedence {
1292 ExprKind::Box(_) => ExprPrecedence::Box,
1293 ExprKind::Array(_) => ExprPrecedence::Array,
1294 ExprKind::Call(..) => ExprPrecedence::Call,
1295 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1296 ExprKind::Tup(_) => ExprPrecedence::Tup,
1297 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1298 ExprKind::Unary(..) => ExprPrecedence::Unary,
1299 ExprKind::Lit(_) => ExprPrecedence::Lit,
1300 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1301 ExprKind::If(..) => ExprPrecedence::If,
1302 ExprKind::While(..) => ExprPrecedence::While,
1303 ExprKind::Loop(..) => ExprPrecedence::Loop,
1304 ExprKind::Match(..) => ExprPrecedence::Match,
1305 ExprKind::Closure(..) => ExprPrecedence::Closure,
1306 ExprKind::Block(..) => ExprPrecedence::Block,
1307 ExprKind::Assign(..) => ExprPrecedence::Assign,
1308 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1309 ExprKind::Field(..) => ExprPrecedence::Field,
1310 ExprKind::Index(..) => ExprPrecedence::Index,
1311 ExprKind::Path(..) => ExprPrecedence::Path,
1312 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1313 ExprKind::Break(..) => ExprPrecedence::Break,
1314 ExprKind::Continue(..) => ExprPrecedence::Continue,
1315 ExprKind::Ret(..) => ExprPrecedence::Ret,
1316 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1317 ExprKind::Struct(..) => ExprPrecedence::Struct,
1318 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1319 ExprKind::Yield(..) => ExprPrecedence::Yield,
1324 impl fmt::Debug for Expr {
1325 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1326 write!(f, "expr({}: {})", self.id,
1327 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1331 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1333 /// A `box x` expression.
1335 /// An array (`[a, b, c, d]`)
1336 Array(HirVec<Expr>),
1339 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1340 /// and the second field is the list of arguments.
1341 /// This also represents calling the constructor of
1342 /// tuple-like ADTs such as tuple structs and enum variants.
1343 Call(P<Expr>, HirVec<Expr>),
1344 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1346 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1347 /// (within the angle brackets).
1348 /// The first element of the vector of `Expr`s is the expression that evaluates
1349 /// to the object on which the method is being called on (the receiver),
1350 /// and the remaining elements are the rest of the arguments.
1351 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1352 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1353 MethodCall(PathSegment, Span, HirVec<Expr>),
1354 /// A tuple (`(a, b, c ,d)`)
1356 /// A binary operation (For example: `a + b`, `a * b`)
1357 Binary(BinOp, P<Expr>, P<Expr>),
1358 /// A unary operation (For example: `!x`, `*x`)
1359 Unary(UnOp, P<Expr>),
1360 /// A literal (For example: `1`, `"foo"`)
1362 /// A cast (`foo as f64`)
1363 Cast(P<Expr>, P<Ty>),
1364 Type(P<Expr>, P<Ty>),
1365 /// An `if` block, with an optional else block
1367 /// `if expr { expr } else { expr }`
1368 If(P<Expr>, P<Expr>, Option<P<Expr>>),
1369 /// A while loop, with an optional label
1371 /// `'label: while expr { block }`
1372 While(P<Expr>, P<Block>, Option<Label>),
1373 /// Conditionless loop (can be exited with break, continue, or return)
1375 /// `'label: loop { block }`
1376 Loop(P<Block>, Option<Label>, LoopSource),
1377 /// A `match` block, with a source that indicates whether or not it is
1378 /// the result of a desugaring, and if so, which kind.
1379 Match(P<Expr>, HirVec<Arm>, MatchSource),
1380 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1382 /// The final span is the span of the argument block `|...|`
1384 /// This may also be a generator literal, indicated by the final boolean,
1385 /// in that case there is an GeneratorClause.
1386 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1387 /// A block (`'label: { ... }`)
1388 Block(P<Block>, Option<Label>),
1390 /// An assignment (`a = foo()`)
1391 Assign(P<Expr>, P<Expr>),
1392 /// An assignment with an operator
1394 /// For example, `a += 1`.
1395 AssignOp(BinOp, P<Expr>, P<Expr>),
1396 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct or tuple field
1397 Field(P<Expr>, Ident),
1398 /// An indexing operation (`foo[2]`)
1399 Index(P<Expr>, P<Expr>),
1401 /// Path to a definition, possibly containing lifetime or type parameters.
1404 /// A referencing operation (`&a` or `&mut a`)
1405 AddrOf(Mutability, P<Expr>),
1406 /// A `break`, with an optional label to break
1407 Break(Destination, Option<P<Expr>>),
1408 /// A `continue`, with an optional label
1409 Continue(Destination),
1410 /// A `return`, with an optional value to be returned
1411 Ret(Option<P<Expr>>),
1413 /// Inline assembly (from `asm!`), with its outputs and inputs.
1414 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1416 /// A struct or struct-like variant literal expression.
1418 /// For example, `Foo {x: 1, y: 2}`, or
1419 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1420 Struct(QPath, HirVec<Field>, Option<P<Expr>>),
1422 /// An array literal constructed from one repeated element.
1424 /// For example, `[1; 5]`. The first expression is the element
1425 /// to be repeated; the second is the number of times to repeat it.
1426 Repeat(P<Expr>, AnonConst),
1428 /// A suspension point for generators. This is `yield <expr>` in Rust.
1432 /// Optionally `Self`-qualified value/type path or associated extension.
1433 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1435 /// Path to a definition, optionally "fully-qualified" with a `Self`
1436 /// type, if the path points to an associated item in a trait.
1438 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1439 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1440 /// even though they both have the same two-segment `Clone::clone` `Path`.
1441 Resolved(Option<P<Ty>>, P<Path>),
1443 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1444 /// Will be resolved by type-checking to an associated item.
1446 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1447 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1448 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1449 TypeRelative(P<Ty>, P<PathSegment>)
1452 /// Hints at the original code for a let statement
1453 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1454 pub enum LocalSource {
1455 /// A `match _ { .. }`
1457 /// A desugared `for _ in _ { .. }` loop
1461 /// Hints at the original code for a `match _ { .. }`
1462 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1463 pub enum MatchSource {
1464 /// A `match _ { .. }`
1466 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1468 contains_else_clause: bool,
1470 /// A `while let _ = _ { .. }` (which was desugared to a
1471 /// `loop { match _ { .. } }`)
1473 /// A desugared `for _ in _ { .. }` loop
1475 /// A desugared `?` operator
1479 /// The loop type that yielded an ExprKind::Loop
1480 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1481 pub enum LoopSource {
1482 /// A `loop { .. }` loop
1484 /// A `while let _ = _ { .. }` loop
1486 /// A `for _ in _ { .. }` loop
1490 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1491 pub enum LoopIdError {
1493 UnlabeledCfInWhileCondition,
1497 impl fmt::Display for LoopIdError {
1498 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1499 fmt::Display::fmt(match *self {
1500 LoopIdError::OutsideLoopScope => "not inside loop scope",
1501 LoopIdError::UnlabeledCfInWhileCondition =>
1502 "unlabeled control flow (break or continue) in while condition",
1503 LoopIdError::UnresolvedLabel => "label not found",
1508 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1509 pub struct Destination {
1510 // This is `Some(_)` iff there is an explicit user-specified `label
1511 pub label: Option<Label>,
1513 // These errors are caught and then reported during the diagnostics pass in
1514 // librustc_passes/loops.rs
1515 pub target_id: Result<NodeId, LoopIdError>,
1518 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1519 pub enum GeneratorMovability {
1524 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1525 pub enum CaptureClause {
1530 // NB: If you change this, you'll probably want to change the corresponding
1531 // type structure in middle/ty.rs as well.
1532 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1535 pub mutbl: Mutability,
1538 /// Represents a method's signature in a trait declaration or implementation.
1539 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1540 pub struct MethodSig {
1541 pub header: FnHeader,
1542 pub decl: P<FnDecl>,
1545 // The bodies for items are stored "out of line", in a separate
1546 // hashmap in the `Crate`. Here we just record the node-id of the item
1547 // so it can fetched later.
1548 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1549 pub struct TraitItemId {
1550 pub node_id: NodeId,
1553 /// Represents an item declaration within a trait declaration,
1554 /// possibly including a default implementation. A trait item is
1555 /// either required (meaning it doesn't have an implementation, just a
1556 /// signature) or provided (meaning it has a default implementation).
1557 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1558 pub struct TraitItem {
1562 pub attrs: HirVec<Attribute>,
1563 pub generics: Generics,
1564 pub node: TraitItemKind,
1568 /// A trait method's body (or just argument names).
1569 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1570 pub enum TraitMethod {
1571 /// No default body in the trait, just a signature.
1572 Required(HirVec<Ident>),
1574 /// Both signature and body are provided in the trait.
1578 /// Represents a trait method or associated constant or type
1579 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1580 pub enum TraitItemKind {
1581 /// An associated constant with an optional value (otherwise `impl`s
1582 /// must contain a value)
1583 Const(P<Ty>, Option<BodyId>),
1584 /// A method with an optional body
1585 Method(MethodSig, TraitMethod),
1586 /// An associated type with (possibly empty) bounds and optional concrete
1588 Type(GenericBounds, Option<P<Ty>>),
1591 // The bodies for items are stored "out of line", in a separate
1592 // hashmap in the `Crate`. Here we just record the node-id of the item
1593 // so it can fetched later.
1594 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1595 pub struct ImplItemId {
1596 pub node_id: NodeId,
1599 /// Represents anything within an `impl` block
1600 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1601 pub struct ImplItem {
1605 pub vis: Visibility,
1606 pub defaultness: Defaultness,
1607 pub attrs: HirVec<Attribute>,
1608 pub generics: Generics,
1609 pub node: ImplItemKind,
1613 /// Represents different contents within `impl`s
1614 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1615 pub enum ImplItemKind {
1616 /// An associated constant of the given type, set to the constant result
1617 /// of the expression
1618 Const(P<Ty>, BodyId),
1619 /// A method implementation with the given signature and body
1620 Method(MethodSig, BodyId),
1621 /// An associated type
1625 // Bind a type to an associated type: `A=Foo`.
1626 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1627 pub struct TypeBinding {
1635 #[derive(Clone, RustcEncodable, RustcDecodable)]
1643 impl fmt::Debug for Ty {
1644 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1645 write!(f, "type({})",
1646 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1650 /// Not represented directly in the AST, referred to by name through a ty_path.
1651 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1661 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1662 pub struct BareFnTy {
1663 pub unsafety: Unsafety,
1665 pub generic_params: HirVec<GenericParam>,
1666 pub decl: P<FnDecl>,
1667 pub arg_names: HirVec<Ident>,
1670 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1671 pub struct ExistTy {
1672 pub generics: Generics,
1673 pub bounds: GenericBounds,
1674 pub impl_trait_fn: Option<DefId>,
1677 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1678 /// The different kinds of types recognized by the compiler
1680 /// A variable length slice (`[T]`)
1682 /// A fixed length array (`[T; n]`)
1683 Array(P<Ty>, AnonConst),
1684 /// A raw pointer (`*const T` or `*mut T`)
1686 /// A reference (`&'a T` or `&'a mut T`)
1687 Rptr(Lifetime, MutTy),
1688 /// A bare function (e.g. `fn(usize) -> bool`)
1689 BareFn(P<BareFnTy>),
1690 /// The never type (`!`)
1692 /// A tuple (`(A, B, C, D,...)`)
1694 /// A path to a type definition (`module::module::...::Type`), or an
1695 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1697 /// Type parameters may be stored in each `PathSegment`.
1699 /// A trait object type `Bound1 + Bound2 + Bound3`
1700 /// where `Bound` is a trait or a lifetime.
1701 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1704 /// TyKind::Infer means the type should be inferred instead of it having been
1705 /// specified. This can appear anywhere in a type.
1707 /// Placeholder for a type that has failed to be defined.
1711 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1712 pub struct InlineAsmOutput {
1713 pub constraint: Symbol,
1715 pub is_indirect: bool,
1718 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1719 pub struct InlineAsm {
1721 pub asm_str_style: StrStyle,
1722 pub outputs: HirVec<InlineAsmOutput>,
1723 pub inputs: HirVec<Symbol>,
1724 pub clobbers: HirVec<Symbol>,
1726 pub alignstack: bool,
1727 pub dialect: AsmDialect,
1728 pub ctxt: SyntaxContext,
1731 /// represents an argument in a function header
1732 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1739 /// Represents the header (not the body) of a function declaration
1740 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1742 pub inputs: HirVec<Ty>,
1743 pub output: FunctionRetTy,
1745 /// True if this function has an `self`, `&self` or `&mut self` receiver
1746 /// (but not a `self: Xxx` one).
1747 pub has_implicit_self: bool,
1750 /// Is the trait definition an auto trait?
1751 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1757 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1763 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1769 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1770 pub enum Constness {
1775 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1776 pub enum Defaultness {
1777 Default { has_value: bool },
1782 pub fn has_value(&self) -> bool {
1784 Defaultness::Default { has_value, .. } => has_value,
1785 Defaultness::Final => true,
1789 pub fn is_final(&self) -> bool {
1790 *self == Defaultness::Final
1793 pub fn is_default(&self) -> bool {
1795 Defaultness::Default { .. } => true,
1801 impl fmt::Display for Unsafety {
1802 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1803 fmt::Display::fmt(match *self {
1804 Unsafety::Normal => "normal",
1805 Unsafety::Unsafe => "unsafe",
1811 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1812 pub enum ImplPolarity {
1813 /// `impl Trait for Type`
1815 /// `impl !Trait for Type`
1819 impl fmt::Debug for ImplPolarity {
1820 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1822 ImplPolarity::Positive => "positive".fmt(f),
1823 ImplPolarity::Negative => "negative".fmt(f),
1829 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1830 pub enum FunctionRetTy {
1831 /// Return type is not specified.
1833 /// Functions default to `()` and
1834 /// closures default to inference. Span points to where return
1835 /// type would be inserted.
1836 DefaultReturn(Span),
1841 impl FunctionRetTy {
1842 pub fn span(&self) -> Span {
1844 DefaultReturn(span) => span,
1845 Return(ref ty) => ty.span,
1850 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1852 /// A span from the first token past `{` to the last token until `}`.
1853 /// For `mod foo;`, the inner span ranges from the first token
1854 /// to the last token in the external file.
1856 pub item_ids: HirVec<ItemId>,
1859 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1860 pub struct ForeignMod {
1862 pub items: HirVec<ForeignItem>,
1865 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1866 pub struct GlobalAsm {
1868 pub ctxt: SyntaxContext,
1871 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1872 pub struct EnumDef {
1873 pub variants: HirVec<Variant>,
1876 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1877 pub struct VariantKind {
1879 pub attrs: HirVec<Attribute>,
1880 pub data: VariantData,
1881 /// Explicit discriminant, eg `Foo = 1`
1882 pub disr_expr: Option<AnonConst>,
1885 pub type Variant = Spanned<VariantKind>;
1887 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1889 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1890 /// Also produced for each element of a list `use`, e.g.
1891 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1894 /// Glob import, e.g. `use foo::*`.
1897 /// Degenerate list import, e.g. `use foo::{a, b}` produces
1898 /// an additional `use foo::{}` for performing checks such as
1899 /// unstable feature gating. May be removed in the future.
1903 /// TraitRef's appear in impls.
1905 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1906 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1907 /// trait being referred to but just a unique NodeId that serves as a key
1908 /// within the DefMap.
1909 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1910 pub struct TraitRef {
1915 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1916 pub struct PolyTraitRef {
1917 /// The `'a` in `<'a> Foo<&'a T>`
1918 pub bound_generic_params: HirVec<GenericParam>,
1920 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1921 pub trait_ref: TraitRef,
1926 pub type Visibility = Spanned<VisibilityKind>;
1928 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1929 pub enum VisibilityKind {
1932 Restricted { path: P<Path>, id: NodeId },
1936 impl VisibilityKind {
1937 pub fn is_pub(&self) -> bool {
1939 VisibilityKind::Public => true,
1944 pub fn is_pub_restricted(&self) -> bool {
1946 VisibilityKind::Public |
1947 VisibilityKind::Inherited => false,
1948 VisibilityKind::Crate(..) |
1949 VisibilityKind::Restricted { .. } => true,
1954 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1955 pub struct StructField {
1958 pub vis: Visibility,
1961 pub attrs: HirVec<Attribute>,
1965 // Still necessary in couple of places
1966 pub fn is_positional(&self) -> bool {
1967 let first = self.ident.as_str().as_bytes()[0];
1968 first >= b'0' && first <= b'9'
1972 /// Fields and Ids of enum variants and structs
1974 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1975 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1976 /// One shared Id can be successfully used for these two purposes.
1977 /// Id of the whole enum lives in `Item`.
1979 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1980 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1981 /// the variant itself" from enum variants.
1982 /// Id of the whole struct lives in `Item`.
1983 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1984 pub enum VariantData {
1985 Struct(HirVec<StructField>, NodeId),
1986 Tuple(HirVec<StructField>, NodeId),
1991 pub fn fields(&self) -> &[StructField] {
1993 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1997 pub fn id(&self) -> NodeId {
1999 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2002 pub fn is_struct(&self) -> bool {
2003 if let VariantData::Struct(..) = *self {
2009 pub fn is_tuple(&self) -> bool {
2010 if let VariantData::Tuple(..) = *self {
2016 pub fn is_unit(&self) -> bool {
2017 if let VariantData::Unit(..) = *self {
2025 // The bodies for items are stored "out of line", in a separate
2026 // hashmap in the `Crate`. Here we just record the node-id of the item
2027 // so it can fetched later.
2028 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2035 /// The name might be a dummy name in case of anonymous items
2036 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2041 pub attrs: HirVec<Attribute>,
2043 pub vis: Visibility,
2047 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2048 pub struct FnHeader {
2049 pub unsafety: Unsafety,
2050 pub constness: Constness,
2051 pub asyncness: IsAsync,
2055 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2057 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2059 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2060 ExternCrate(Option<Name>),
2062 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2066 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2067 Use(P<Path>, UseKind),
2070 Static(P<Ty>, Mutability, BodyId),
2072 Const(P<Ty>, BodyId),
2073 /// A function declaration
2074 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2077 /// An external module
2078 ForeignMod(ForeignMod),
2079 /// Module-level inline assembly (from global_asm!)
2080 GlobalAsm(P<GlobalAsm>),
2081 /// A type alias, e.g. `type Foo = Bar<u8>`
2082 Ty(P<Ty>, Generics),
2083 /// A type alias, e.g. `type Foo = Bar<u8>`
2084 Existential(ExistTy),
2085 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
2086 Enum(EnumDef, Generics),
2087 /// A struct definition, e.g. `struct Foo<A> {x: A}`
2088 Struct(VariantData, Generics),
2089 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
2090 Union(VariantData, Generics),
2091 /// Represents a Trait Declaration
2092 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2093 /// Represents a Trait Alias Declaration
2094 TraitAlias(Generics, GenericBounds),
2096 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2101 Option<TraitRef>, // (optional) trait this impl implements
2103 HirVec<ImplItemRef>),
2107 pub fn descriptive_variant(&self) -> &str {
2109 ItemKind::ExternCrate(..) => "extern crate",
2110 ItemKind::Use(..) => "use",
2111 ItemKind::Static(..) => "static item",
2112 ItemKind::Const(..) => "constant item",
2113 ItemKind::Fn(..) => "function",
2114 ItemKind::Mod(..) => "module",
2115 ItemKind::ForeignMod(..) => "foreign module",
2116 ItemKind::GlobalAsm(..) => "global asm",
2117 ItemKind::Ty(..) => "type alias",
2118 ItemKind::Existential(..) => "existential type",
2119 ItemKind::Enum(..) => "enum",
2120 ItemKind::Struct(..) => "struct",
2121 ItemKind::Union(..) => "union",
2122 ItemKind::Trait(..) => "trait",
2123 ItemKind::TraitAlias(..) => "trait alias",
2124 ItemKind::Impl(..) => "item",
2128 pub fn adt_kind(&self) -> Option<AdtKind> {
2130 ItemKind::Struct(..) => Some(AdtKind::Struct),
2131 ItemKind::Union(..) => Some(AdtKind::Union),
2132 ItemKind::Enum(..) => Some(AdtKind::Enum),
2137 pub fn generics(&self) -> Option<&Generics> {
2139 ItemKind::Fn(_, _, ref generics, _) |
2140 ItemKind::Ty(_, ref generics) |
2141 ItemKind::Enum(_, ref generics) |
2142 ItemKind::Struct(_, ref generics) |
2143 ItemKind::Union(_, ref generics) |
2144 ItemKind::Trait(_, _, ref generics, _, _) |
2145 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2151 /// A reference from an trait 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, RustcEncodable, RustcDecodable, Debug)]
2158 pub struct TraitItemRef {
2159 pub id: TraitItemId,
2161 pub kind: AssociatedItemKind,
2163 pub defaultness: Defaultness,
2166 /// A reference from an impl to one of its associated items. This
2167 /// contains the item's id, naturally, but also the item's name and
2168 /// some other high-level details (like whether it is an associated
2169 /// type or method, and whether it is public). This allows other
2170 /// passes to find the impl they want without loading the id (which
2171 /// means fewer edges in the incremental compilation graph).
2172 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2173 pub struct ImplItemRef {
2176 pub kind: AssociatedItemKind,
2178 pub vis: Visibility,
2179 pub defaultness: Defaultness,
2182 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2183 pub enum AssociatedItemKind {
2185 Method { has_self: bool },
2189 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2190 pub struct ForeignItem {
2192 pub attrs: HirVec<Attribute>,
2193 pub node: ForeignItemKind,
2196 pub vis: Visibility,
2199 /// An item within an `extern` block
2200 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2201 pub enum ForeignItemKind {
2202 /// A foreign function
2203 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2204 /// A foreign static item (`static ext: u8`), with optional mutability
2205 /// (the boolean is true when mutable)
2206 Static(P<Ty>, bool),
2211 impl ForeignItemKind {
2212 pub fn descriptive_variant(&self) -> &str {
2214 ForeignItemKind::Fn(..) => "foreign function",
2215 ForeignItemKind::Static(..) => "foreign static item",
2216 ForeignItemKind::Type => "foreign type",
2221 /// A free variable referred to in a function.
2222 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2223 pub struct Freevar {
2224 /// The variable being accessed free.
2227 // First span where it is accessed (there can be multiple).
2232 pub fn var_id(&self) -> NodeId {
2234 Def::Local(id) | Def::Upvar(id, ..) => id,
2235 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2240 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2242 pub type CaptureModeMap = NodeMap<CaptureClause>;
2244 #[derive(Clone, Debug)]
2245 pub struct TraitCandidate {
2247 pub import_id: Option<NodeId>,
2250 // Trait method resolution
2251 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2253 // Map from the NodeId of a glob import to a list of items which are actually
2255 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2258 pub fn provide(providers: &mut Providers) {
2259 providers.describe_def = map::describe_def;
2262 #[derive(Clone, RustcEncodable, RustcDecodable)]
2263 pub struct CodegenFnAttrs {
2264 pub flags: CodegenFnAttrFlags,
2265 pub inline: InlineAttr,
2266 pub export_name: Option<Symbol>,
2267 pub target_features: Vec<Symbol>,
2268 pub linkage: Option<Linkage>,
2269 pub wasm_custom_section: Option<Symbol>,
2273 #[derive(RustcEncodable, RustcDecodable)]
2274 pub struct CodegenFnAttrFlags: u8 {
2275 const COLD = 0b0000_0001;
2276 const ALLOCATOR = 0b0000_0010;
2277 const UNWIND = 0b0000_0100;
2278 const RUSTC_ALLOCATOR_NOUNWIND = 0b0000_1000;
2279 const NAKED = 0b0001_0000;
2280 const NO_MANGLE = 0b0010_0000;
2281 const RUSTC_STD_INTERNAL_SYMBOL = 0b0100_0000;
2282 const NO_DEBUG = 0b1000_0000;
2286 impl CodegenFnAttrs {
2287 pub fn new() -> CodegenFnAttrs {
2289 flags: CodegenFnAttrFlags::empty(),
2290 inline: InlineAttr::None,
2292 target_features: vec![],
2294 wasm_custom_section: None,
2298 /// True if `#[inline]` or `#[inline(always)]` is present.
2299 pub fn requests_inline(&self) -> bool {
2301 InlineAttr::Hint | InlineAttr::Always => true,
2302 InlineAttr::None | InlineAttr::Never => false,
2306 /// True if `#[no_mangle]` or `#[export_name(...)]` is present.
2307 pub fn contains_extern_indicator(&self) -> bool {
2308 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) || self.export_name.is_some()