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::source_map::{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::parser::ExprPrecedence;
38 use ty::query::Providers;
40 use rustc_data_structures::indexed_vec;
41 use rustc_data_structures::sync::{ParallelIterator, par_iter, Send, Sync, scope};
42 use rustc_data_structures::thin_vec::ThinVec;
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;
74 /// A HirId uniquely identifies a node in the HIR of the current crate. It is
75 /// composed of the `owner`, which is the DefIndex of the directly enclosing
76 /// hir::Item, hir::TraitItem, or hir::ImplItem (i.e. the closest "item-like"),
77 /// and the `local_id` which is unique within the given owner.
79 /// This two-level structure makes for more stable values: One can move an item
80 /// around within the source code, or add or remove stuff before it, without
81 /// the local_id part of the HirId changing, which is a very useful property in
82 /// incremental compilation where we have to persist things through changes to
84 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
87 pub local_id: ItemLocalId,
91 pub fn owner_def_id(self) -> DefId {
92 DefId::local(self.owner)
95 pub fn owner_local_def_id(self) -> LocalDefId {
96 LocalDefId::from_def_id(DefId::local(self.owner))
100 impl serialize::UseSpecializedEncodable for HirId {
101 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
112 impl serialize::UseSpecializedDecodable for HirId {
113 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
114 let owner = DefIndex::decode(d)?;
115 let local_id = ItemLocalId::decode(d)?;
125 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
126 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
127 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
128 /// the node's position within the owning item in any way, but there is a
129 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
130 /// integers starting at zero, so a mapping that maps all or most nodes within
131 /// an "item-like" to something else can be implement by a `Vec` instead of a
132 /// tree or hash map.
133 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug,
134 RustcEncodable, RustcDecodable)]
135 pub struct ItemLocalId(pub u32);
138 pub fn as_usize(&self) -> usize {
143 impl indexed_vec::Idx for ItemLocalId {
144 fn new(idx: usize) -> Self {
145 debug_assert!((idx as u32) as usize == idx);
146 ItemLocalId(idx as u32)
149 fn index(self) -> usize {
154 /// The `HirId` corresponding to CRATE_NODE_ID and CRATE_DEF_INDEX
155 pub const CRATE_HIR_ID: HirId = HirId {
156 owner: CRATE_DEF_INDEX,
157 local_id: ItemLocalId(0)
160 pub const DUMMY_HIR_ID: HirId = HirId {
161 owner: CRATE_DEF_INDEX,
162 local_id: DUMMY_ITEM_LOCAL_ID,
165 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId(!0);
167 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
172 impl fmt::Debug for Label {
173 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
174 write!(f, "label({:?})", self.ident)
178 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
179 pub struct Lifetime {
183 /// Either "'a", referring to a named lifetime definition,
184 /// or "" (aka keywords::Invalid), for elision placeholders.
186 /// HIR lowering inserts these placeholders in type paths that
187 /// refer to type definitions needing lifetime parameters,
188 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
189 pub name: LifetimeName,
192 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
194 /// Some user-given name like `T` or `'x`.
197 /// Synthetic name generated when user elided a lifetime in an impl header,
198 /// e.g. the lifetimes in cases like these:
200 /// impl Foo for &u32
201 /// impl Foo<'_> for u32
203 /// in that case, we rewrite to
205 /// impl<'f> Foo for &'f u32
206 /// impl<'f> Foo<'f> for u32
208 /// where `'f` is something like `Fresh(0)`. The indices are
209 /// unique per impl, but not necessarily continuous.
214 pub fn ident(&self) -> Ident {
216 ParamName::Plain(ident) => ident,
217 ParamName::Fresh(_) => keywords::UnderscoreLifetime.ident(),
221 pub fn modern(&self) -> ParamName {
223 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
224 param_name => param_name,
229 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
230 pub enum LifetimeName {
231 /// User-given names or fresh (synthetic) names.
234 /// User typed nothing. e.g. the lifetime in `&u32`.
240 /// User wrote `'static`
245 pub fn ident(&self) -> Ident {
247 LifetimeName::Implicit => keywords::Invalid.ident(),
248 LifetimeName::Underscore => keywords::UnderscoreLifetime.ident(),
249 LifetimeName::Static => keywords::StaticLifetime.ident(),
250 LifetimeName::Param(param_name) => param_name.ident(),
254 pub fn is_elided(&self) -> bool {
256 LifetimeName::Implicit | LifetimeName::Underscore => true,
258 // It might seem surprising that `Fresh(_)` counts as
259 // *not* elided -- but this is because, as far as the code
260 // in the compiler is concerned -- `Fresh(_)` variants act
261 // equivalently to "some fresh name". They correspond to
262 // early-bound regions on an impl, in other words.
263 LifetimeName::Param(_) | LifetimeName::Static => false,
267 fn is_static(&self) -> bool {
268 self == &LifetimeName::Static
271 pub fn modern(&self) -> LifetimeName {
273 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
274 lifetime_name => lifetime_name,
279 impl fmt::Display for Lifetime {
280 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
281 self.name.ident().fmt(f)
285 impl fmt::Debug for Lifetime {
286 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
290 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
295 pub fn is_elided(&self) -> bool {
296 self.name.is_elided()
299 pub fn is_static(&self) -> bool {
300 self.name.is_static()
304 /// A "Path" is essentially Rust's notion of a name; for instance:
305 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
306 /// along with a bunch of supporting information.
307 #[derive(Clone, RustcEncodable, RustcDecodable)]
310 /// The definition that the path resolved to.
312 /// The segments in the path: the things separated by `::`.
313 pub segments: HirVec<PathSegment>,
317 pub fn is_global(&self) -> bool {
318 !self.segments.is_empty() && self.segments[0].ident.name == keywords::CrateRoot.name()
322 impl fmt::Debug for Path {
323 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
324 write!(f, "path({})", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
328 impl fmt::Display for Path {
329 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
330 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
334 /// A segment of a path: an identifier, an optional lifetime, and a set of
336 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
337 pub struct PathSegment {
338 /// The identifier portion of this path segment.
341 /// Type/lifetime parameters attached to this path. They come in
342 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
343 /// this is more than just simple syntactic sugar; the use of
344 /// parens affects the region binding rules, so we preserve the
346 pub args: Option<P<GenericArgs>>,
348 /// Whether to infer remaining type parameters, if any.
349 /// This only applies to expression and pattern paths, and
350 /// out of those only the segments with no type parameters
351 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
352 pub infer_types: bool,
356 /// Convert an identifier to the corresponding segment.
357 pub fn from_ident(ident: Ident) -> PathSegment {
365 pub fn new(ident: Ident, args: GenericArgs, infer_types: bool) -> Self {
369 args: if args.is_empty() {
377 // FIXME: hack required because you can't create a static
378 // GenericArgs, so you can't just return a &GenericArgs.
379 pub fn with_generic_args<F, R>(&self, f: F) -> R
380 where F: FnOnce(&GenericArgs) -> R
382 let dummy = GenericArgs::none();
383 f(if let Some(ref args) = self.args {
391 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
392 pub enum GenericArg {
398 pub fn span(&self) -> Span {
400 GenericArg::Lifetime(l) => l.span,
401 GenericArg::Type(t) => t.span,
406 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
407 pub struct GenericArgs {
408 /// The generic arguments for this path segment.
409 pub args: HirVec<GenericArg>,
410 /// Bindings (equality constraints) on associated types, if present.
411 /// E.g., `Foo<A=Bar>`.
412 pub bindings: HirVec<TypeBinding>,
413 /// Were arguments written in parenthesized form `Fn(T) -> U`?
414 /// This is required mostly for pretty-printing and diagnostics,
415 /// but also for changing lifetime elision rules to be "function-like".
416 pub parenthesized: bool,
420 pub fn none() -> Self {
423 bindings: HirVec::new(),
424 parenthesized: false,
428 pub fn is_empty(&self) -> bool {
429 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
432 pub fn inputs(&self) -> &[Ty] {
433 if self.parenthesized {
434 for arg in &self.args {
436 GenericArg::Lifetime(_) => {}
437 GenericArg::Type(ref ty) => {
438 if let TyKind::Tup(ref tys) = ty.node {
446 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
450 /// A modifier on a bound, currently this is only used for `?Sized`, where the
451 /// modifier is `Maybe`. Negative bounds should also be handled here.
452 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
453 pub enum TraitBoundModifier {
458 /// The AST represents all type param bounds as types.
459 /// typeck::collect::compute_bounds matches these against
460 /// the "special" built-in traits (see middle::lang_items) and
461 /// detects Copy, Send and Sync.
462 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
463 pub enum GenericBound {
464 Trait(PolyTraitRef, TraitBoundModifier),
469 pub fn span(&self) -> Span {
471 &GenericBound::Trait(ref t, ..) => t.span,
472 &GenericBound::Outlives(ref l) => l.span,
477 pub type GenericBounds = HirVec<GenericBound>;
479 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
480 pub enum GenericParamKind {
481 /// A lifetime definition, eg `'a: 'b + 'c + 'd`.
483 // Indicates that the lifetime definition was synthetically added
484 // as a result of an in-band lifetime usage like:
485 // `fn foo(x: &'a u8) -> &'a u8 { x }`
489 default: Option<P<Ty>>,
490 synthetic: Option<SyntheticTyParamKind>,
494 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
495 pub struct GenericParam {
498 pub attrs: HirVec<Attribute>,
499 pub bounds: GenericBounds,
501 pub pure_wrt_drop: bool,
503 pub kind: GenericParamKind,
506 pub struct GenericParamCount {
507 pub lifetimes: usize,
511 /// Represents lifetimes and type parameters attached to a declaration
512 /// of a function, enum, trait, etc.
513 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
514 pub struct Generics {
515 pub params: HirVec<GenericParam>,
516 pub where_clause: WhereClause,
521 pub fn empty() -> Generics {
523 params: HirVec::new(),
524 where_clause: WhereClause {
526 predicates: HirVec::new(),
532 pub fn own_counts(&self) -> GenericParamCount {
533 // We could cache this as a property of `GenericParamCount`, but
534 // the aim is to refactor this away entirely eventually and the
535 // presence of this method will be a constant reminder.
536 let mut own_counts = GenericParamCount {
541 for param in &self.params {
543 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
544 GenericParamKind::Type { .. } => own_counts.types += 1,
551 pub fn get_named(&self, name: &InternedString) -> Option<&GenericParam> {
552 for param in &self.params {
553 if *name == param.name.ident().as_interned_str() {
561 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
562 /// to track the original form they had. Useful for error messages.
563 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
564 pub enum SyntheticTyParamKind {
568 /// A `where` clause in a definition
569 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
570 pub struct WhereClause {
572 pub predicates: HirVec<WherePredicate>,
576 pub fn span(&self) -> Option<Span> {
577 self.predicates.iter().map(|predicate| predicate.span())
578 .fold(None, |acc, i| match (acc, i) {
579 (None, i) => Some(i),
587 /// A single predicate in a `where` clause
588 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
589 pub enum WherePredicate {
590 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
591 BoundPredicate(WhereBoundPredicate),
592 /// A lifetime predicate, e.g. `'a: 'b+'c`
593 RegionPredicate(WhereRegionPredicate),
594 /// An equality predicate (unsupported)
595 EqPredicate(WhereEqPredicate),
598 impl WherePredicate {
599 pub fn span(&self) -> Span {
601 &WherePredicate::BoundPredicate(ref p) => p.span,
602 &WherePredicate::RegionPredicate(ref p) => p.span,
603 &WherePredicate::EqPredicate(ref p) => p.span,
608 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
609 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
610 pub struct WhereBoundPredicate {
612 /// Any generics from a `for` binding
613 pub bound_generic_params: HirVec<GenericParam>,
614 /// The type being bounded
615 pub bounded_ty: P<Ty>,
616 /// Trait and lifetime bounds (`Clone+Send+'static`)
617 pub bounds: GenericBounds,
620 /// A lifetime predicate, e.g. `'a: 'b+'c`
621 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
622 pub struct WhereRegionPredicate {
624 pub lifetime: Lifetime,
625 pub bounds: GenericBounds,
628 /// An equality predicate (unsupported), e.g. `T=int`
629 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
630 pub struct WhereEqPredicate {
637 pub type CrateConfig = HirVec<P<MetaItem>>;
639 /// The top-level data structure that stores the entire contents of
640 /// the crate currently being compiled.
642 /// For more details, see the [rustc guide].
644 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/hir.html
645 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
648 pub attrs: HirVec<Attribute>,
650 pub exported_macros: HirVec<MacroDef>,
652 // NB: We use a BTreeMap here so that `visit_all_items` iterates
653 // over the ids in increasing order. In principle it should not
654 // matter what order we visit things in, but in *practice* it
655 // does, because it can affect the order in which errors are
656 // detected, which in turn can make compile-fail tests yield
657 // slightly different results.
658 pub items: BTreeMap<NodeId, Item>,
660 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
661 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
662 pub bodies: BTreeMap<BodyId, Body>,
663 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
664 pub trait_auto_impl: BTreeMap<DefId, NodeId>,
666 /// A list of the body ids written out in the order in which they
667 /// appear in the crate. If you're going to process all the bodies
668 /// in the crate, you should iterate over this list rather than the keys
670 pub body_ids: Vec<BodyId>,
674 pub fn item(&self, id: NodeId) -> &Item {
678 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
679 &self.trait_items[&id]
682 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
683 &self.impl_items[&id]
686 /// Visits all items in the crate in some deterministic (but
687 /// unspecified) order. If you just need to process every item,
688 /// but don't care about nesting, this method is the best choice.
690 /// If you do care about nesting -- usually because your algorithm
691 /// follows lexical scoping rules -- then you want a different
692 /// approach. You should override `visit_nested_item` in your
693 /// visitor and then call `intravisit::walk_crate` instead.
694 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
695 where V: itemlikevisit::ItemLikeVisitor<'hir>
697 for (_, item) in &self.items {
698 visitor.visit_item(item);
701 for (_, trait_item) in &self.trait_items {
702 visitor.visit_trait_item(trait_item);
705 for (_, impl_item) in &self.impl_items {
706 visitor.visit_impl_item(impl_item);
710 /// A parallel version of visit_all_item_likes
711 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
712 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
716 par_iter(&self.items).for_each(|(_, item)| {
717 visitor.visit_item(item);
722 par_iter(&self.trait_items).for_each(|(_, trait_item)| {
723 visitor.visit_trait_item(trait_item);
728 par_iter(&self.impl_items).for_each(|(_, impl_item)| {
729 visitor.visit_impl_item(impl_item);
735 pub fn body(&self, id: BodyId) -> &Body {
740 /// A macro definition, in this crate or imported from another.
742 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
743 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
744 pub struct MacroDef {
747 pub attrs: HirVec<Attribute>,
750 pub body: TokenStream,
754 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
756 /// Statements in a block
757 pub stmts: HirVec<Stmt>,
758 /// An expression at the end of the block
759 /// without a semicolon, if any
760 pub expr: Option<P<Expr>>,
763 /// Distinguishes between `unsafe { ... }` and `{ ... }`
764 pub rules: BlockCheckMode,
766 /// If true, then there may exist `break 'a` values that aim to
767 /// break out of this block early.
768 /// Used by `'label: {}` blocks and by `catch` statements.
769 pub targeted_by_break: bool,
770 /// If true, don't emit return value type errors as the parser had
771 /// to recover from a parse error so this block will not have an
772 /// appropriate type. A parse error will have been emitted so the
773 /// compilation will never succeed if this is true.
777 #[derive(Clone, RustcEncodable, RustcDecodable)]
785 impl fmt::Debug for Pat {
786 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
787 write!(f, "pat({}: {})", self.id,
788 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
793 // FIXME(#19596) this is a workaround, but there should be a better way
794 fn walk_<G>(&self, it: &mut G) -> bool
795 where G: FnMut(&Pat) -> bool
802 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
803 PatKind::Struct(_, ref fields, _) => {
804 fields.iter().all(|field| field.node.pat.walk_(it))
806 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
807 s.iter().all(|p| p.walk_(it))
809 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
812 PatKind::Slice(ref before, ref slice, ref after) => {
813 before.iter().all(|p| p.walk_(it)) &&
814 slice.iter().all(|p| p.walk_(it)) &&
815 after.iter().all(|p| p.walk_(it))
820 PatKind::Binding(..) |
821 PatKind::Path(_) => {
827 pub fn walk<F>(&self, mut it: F) -> bool
828 where F: FnMut(&Pat) -> bool
834 /// A single field in a struct pattern
836 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
837 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
838 /// except is_shorthand is true
839 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
840 pub struct FieldPat {
842 /// The identifier for the field
844 /// The pattern the field is destructured to
846 pub is_shorthand: bool,
849 /// Explicit binding annotations given in the HIR for a binding. Note
850 /// that this is not the final binding *mode* that we infer after type
852 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
853 pub enum BindingAnnotation {
854 /// No binding annotation given: this means that the final binding mode
855 /// will depend on whether we have skipped through a `&` reference
856 /// when matching. For example, the `x` in `Some(x)` will have binding
857 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
858 /// ultimately be inferred to be by-reference.
860 /// Note that implicit reference skipping is not implemented yet (#42640).
863 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
866 /// Annotated as `ref`, like `ref x`
869 /// Annotated as `ref mut x`.
873 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
879 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
881 /// Represents a wildcard pattern (`_`)
884 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
885 /// The `NodeId` is the canonical ID for the variable being bound,
886 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
887 /// which is the pattern ID of the first `x`.
888 Binding(BindingAnnotation, NodeId, Ident, Option<P<Pat>>),
890 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
891 /// The `bool` is `true` in the presence of a `..`.
892 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
894 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
895 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
896 /// 0 <= position <= subpats.len()
897 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
899 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
902 /// A tuple pattern `(a, b)`.
903 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
904 /// 0 <= position <= subpats.len()
905 Tuple(HirVec<P<Pat>>, Option<usize>),
908 /// A reference pattern, e.g. `&mut (a, b)`
909 Ref(P<Pat>, Mutability),
912 /// A range pattern, e.g. `1...2` or `1..2`
913 Range(P<Expr>, P<Expr>, RangeEnd),
914 /// `[a, b, ..i, y, z]` is represented as:
915 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
916 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
919 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
920 pub enum Mutability {
926 /// Return MutMutable only if both arguments are mutable.
927 pub fn and(self, other: Self) -> Self {
930 MutImmutable => MutImmutable,
935 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
937 /// The `+` operator (addition)
939 /// The `-` operator (subtraction)
941 /// The `*` operator (multiplication)
943 /// The `/` operator (division)
945 /// The `%` operator (modulus)
947 /// The `&&` operator (logical and)
949 /// The `||` operator (logical or)
951 /// The `^` operator (bitwise xor)
953 /// The `&` operator (bitwise and)
955 /// The `|` operator (bitwise or)
957 /// The `<<` operator (shift left)
959 /// The `>>` operator (shift right)
961 /// The `==` operator (equality)
963 /// The `<` operator (less than)
965 /// The `<=` operator (less than or equal to)
967 /// The `!=` operator (not equal to)
969 /// The `>=` operator (greater than or equal to)
971 /// The `>` operator (greater than)
976 pub fn as_str(self) -> &'static str {
978 BinOpKind::Add => "+",
979 BinOpKind::Sub => "-",
980 BinOpKind::Mul => "*",
981 BinOpKind::Div => "/",
982 BinOpKind::Rem => "%",
983 BinOpKind::And => "&&",
984 BinOpKind::Or => "||",
985 BinOpKind::BitXor => "^",
986 BinOpKind::BitAnd => "&",
987 BinOpKind::BitOr => "|",
988 BinOpKind::Shl => "<<",
989 BinOpKind::Shr => ">>",
990 BinOpKind::Eq => "==",
991 BinOpKind::Lt => "<",
992 BinOpKind::Le => "<=",
993 BinOpKind::Ne => "!=",
994 BinOpKind::Ge => ">=",
995 BinOpKind::Gt => ">",
999 pub fn is_lazy(self) -> bool {
1001 BinOpKind::And | BinOpKind::Or => true,
1006 pub fn is_shift(self) -> bool {
1008 BinOpKind::Shl | BinOpKind::Shr => true,
1013 pub fn is_comparison(self) -> bool {
1020 BinOpKind::Ge => true,
1032 BinOpKind::Shr => false,
1036 /// Returns `true` if the binary operator takes its arguments by value
1037 pub fn is_by_value(self) -> bool {
1038 !self.is_comparison()
1042 impl Into<ast::BinOpKind> for BinOpKind {
1043 fn into(self) -> ast::BinOpKind {
1045 BinOpKind::Add => ast::BinOpKind::Add,
1046 BinOpKind::Sub => ast::BinOpKind::Sub,
1047 BinOpKind::Mul => ast::BinOpKind::Mul,
1048 BinOpKind::Div => ast::BinOpKind::Div,
1049 BinOpKind::Rem => ast::BinOpKind::Rem,
1050 BinOpKind::And => ast::BinOpKind::And,
1051 BinOpKind::Or => ast::BinOpKind::Or,
1052 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1053 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1054 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1055 BinOpKind::Shl => ast::BinOpKind::Shl,
1056 BinOpKind::Shr => ast::BinOpKind::Shr,
1057 BinOpKind::Eq => ast::BinOpKind::Eq,
1058 BinOpKind::Lt => ast::BinOpKind::Lt,
1059 BinOpKind::Le => ast::BinOpKind::Le,
1060 BinOpKind::Ne => ast::BinOpKind::Ne,
1061 BinOpKind::Ge => ast::BinOpKind::Ge,
1062 BinOpKind::Gt => ast::BinOpKind::Gt,
1067 pub type BinOp = Spanned<BinOpKind>;
1069 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, Hash)]
1071 /// The `*` operator for dereferencing
1073 /// The `!` operator for logical inversion
1075 /// The `-` operator for negation
1080 pub fn as_str(self) -> &'static str {
1088 /// Returns `true` if the unary operator takes its argument by value
1089 pub fn is_by_value(self) -> bool {
1091 UnNeg | UnNot => true,
1098 pub type Stmt = Spanned<StmtKind>;
1100 impl fmt::Debug for StmtKind {
1101 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1103 let spanned = source_map::dummy_spanned(self.clone());
1107 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
1111 #[derive(Clone, RustcEncodable, RustcDecodable)]
1113 /// Could be an item or a local (let) binding:
1114 Decl(P<Decl>, NodeId),
1116 /// Expr without trailing semi-colon (must have unit type):
1117 Expr(P<Expr>, NodeId),
1119 /// Expr with trailing semi-colon (may have any type):
1120 Semi(P<Expr>, NodeId),
1124 pub fn attrs(&self) -> &[Attribute] {
1126 StmtKind::Decl(ref d, _) => d.node.attrs(),
1127 StmtKind::Expr(ref e, _) |
1128 StmtKind::Semi(ref e, _) => &e.attrs,
1132 pub fn id(&self) -> NodeId {
1134 StmtKind::Decl(_, id) => id,
1135 StmtKind::Expr(_, id) => id,
1136 StmtKind::Semi(_, id) => id,
1141 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
1142 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1145 pub ty: Option<P<Ty>>,
1146 /// Initializer expression to set the value, if any
1147 pub init: Option<P<Expr>>,
1151 pub attrs: ThinVec<Attribute>,
1152 pub source: LocalSource,
1155 pub type Decl = Spanned<DeclKind>;
1157 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1159 /// A local (let) binding:
1161 /// An item binding:
1166 pub fn attrs(&self) -> &[Attribute] {
1168 DeclKind::Local(ref l) => &l.attrs,
1169 DeclKind::Item(_) => &[]
1173 pub fn is_local(&self) -> bool {
1175 DeclKind::Local(_) => true,
1181 /// represents one arm of a 'match'
1182 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1184 pub attrs: HirVec<Attribute>,
1185 pub pats: HirVec<P<Pat>>,
1186 pub guard: Option<P<Expr>>,
1190 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1196 pub is_shorthand: bool,
1199 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1200 pub enum BlockCheckMode {
1202 UnsafeBlock(UnsafeSource),
1203 PushUnsafeBlock(UnsafeSource),
1204 PopUnsafeBlock(UnsafeSource),
1207 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1208 pub enum UnsafeSource {
1213 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1215 pub node_id: NodeId,
1218 /// The body of a function, closure, or constant value. In the case of
1219 /// a function, the body contains not only the function body itself
1220 /// (which is an expression), but also the argument patterns, since
1221 /// those are something that the caller doesn't really care about.
1226 /// fn foo((x, y): (u32, u32)) -> u32 {
1231 /// Here, the `Body` associated with `foo()` would contain:
1233 /// - an `arguments` array containing the `(x, y)` pattern
1234 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1235 /// - `is_generator` would be false
1237 /// All bodies have an **owner**, which can be accessed via the HIR
1238 /// map using `body_owner_def_id()`.
1239 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1241 pub arguments: HirVec<Arg>,
1243 pub is_generator: bool,
1247 pub fn id(&self) -> BodyId {
1249 node_id: self.value.id
1254 #[derive(Copy, Clone, Debug)]
1255 pub enum BodyOwnerKind {
1256 /// Functions and methods.
1259 /// Constants and associated constants.
1262 /// Initializer of a `static` item.
1266 /// A constant (expression) that's not an item or associated item,
1267 /// but needs its own `DefId` for type-checking, const-eval, etc.
1268 /// These are usually found nested inside types (e.g. array lengths)
1269 /// or expressions (e.g. repeat counts), and also used to define
1270 /// explicit discriminant values for enum variants.
1271 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1272 pub struct AnonConst {
1279 #[derive(Clone, RustcEncodable, RustcDecodable)]
1284 pub attrs: ThinVec<Attribute>,
1289 pub fn precedence(&self) -> ExprPrecedence {
1291 ExprKind::Box(_) => ExprPrecedence::Box,
1292 ExprKind::Array(_) => ExprPrecedence::Array,
1293 ExprKind::Call(..) => ExprPrecedence::Call,
1294 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1295 ExprKind::Tup(_) => ExprPrecedence::Tup,
1296 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1297 ExprKind::Unary(..) => ExprPrecedence::Unary,
1298 ExprKind::Lit(_) => ExprPrecedence::Lit,
1299 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1300 ExprKind::If(..) => ExprPrecedence::If,
1301 ExprKind::While(..) => ExprPrecedence::While,
1302 ExprKind::Loop(..) => ExprPrecedence::Loop,
1303 ExprKind::Match(..) => ExprPrecedence::Match,
1304 ExprKind::Closure(..) => ExprPrecedence::Closure,
1305 ExprKind::Block(..) => ExprPrecedence::Block,
1306 ExprKind::Assign(..) => ExprPrecedence::Assign,
1307 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1308 ExprKind::Field(..) => ExprPrecedence::Field,
1309 ExprKind::Index(..) => ExprPrecedence::Index,
1310 ExprKind::Path(..) => ExprPrecedence::Path,
1311 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1312 ExprKind::Break(..) => ExprPrecedence::Break,
1313 ExprKind::Continue(..) => ExprPrecedence::Continue,
1314 ExprKind::Ret(..) => ExprPrecedence::Ret,
1315 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1316 ExprKind::Struct(..) => ExprPrecedence::Struct,
1317 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1318 ExprKind::Yield(..) => ExprPrecedence::Yield,
1323 impl fmt::Debug for Expr {
1324 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1325 write!(f, "expr({}: {})", self.id,
1326 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1330 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1332 /// A `box x` expression.
1334 /// An array (`[a, b, c, d]`)
1335 Array(HirVec<Expr>),
1338 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1339 /// and the second field is the list of arguments.
1340 /// This also represents calling the constructor of
1341 /// tuple-like ADTs such as tuple structs and enum variants.
1342 Call(P<Expr>, HirVec<Expr>),
1343 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1345 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1346 /// (within the angle brackets).
1347 /// The first element of the vector of `Expr`s is the expression that evaluates
1348 /// to the object on which the method is being called on (the receiver),
1349 /// and the remaining elements are the rest of the arguments.
1350 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1351 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1352 MethodCall(PathSegment, Span, HirVec<Expr>),
1353 /// A tuple (`(a, b, c ,d)`)
1355 /// A binary operation (For example: `a + b`, `a * b`)
1356 Binary(BinOp, P<Expr>, P<Expr>),
1357 /// A unary operation (For example: `!x`, `*x`)
1358 Unary(UnOp, P<Expr>),
1359 /// A literal (For example: `1`, `"foo"`)
1361 /// A cast (`foo as f64`)
1362 Cast(P<Expr>, P<Ty>),
1363 Type(P<Expr>, P<Ty>),
1364 /// An `if` block, with an optional else block
1366 /// `if expr { expr } else { expr }`
1367 If(P<Expr>, P<Expr>, Option<P<Expr>>),
1368 /// A while loop, with an optional label
1370 /// `'label: while expr { block }`
1371 While(P<Expr>, P<Block>, Option<Label>),
1372 /// Conditionless loop (can be exited with break, continue, or return)
1374 /// `'label: loop { block }`
1375 Loop(P<Block>, Option<Label>, LoopSource),
1376 /// A `match` block, with a source that indicates whether or not it is
1377 /// the result of a desugaring, and if so, which kind.
1378 Match(P<Expr>, HirVec<Arm>, MatchSource),
1379 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1381 /// The final span is the span of the argument block `|...|`
1383 /// This may also be a generator literal, indicated by the final boolean,
1384 /// in that case there is an GeneratorClause.
1385 Closure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1386 /// A block (`'label: { ... }`)
1387 Block(P<Block>, Option<Label>),
1389 /// An assignment (`a = foo()`)
1390 Assign(P<Expr>, P<Expr>),
1391 /// An assignment with an operator
1393 /// For example, `a += 1`.
1394 AssignOp(BinOp, P<Expr>, P<Expr>),
1395 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct or tuple field
1396 Field(P<Expr>, Ident),
1397 /// An indexing operation (`foo[2]`)
1398 Index(P<Expr>, P<Expr>),
1400 /// Path to a definition, possibly containing lifetime or type parameters.
1403 /// A referencing operation (`&a` or `&mut a`)
1404 AddrOf(Mutability, P<Expr>),
1405 /// A `break`, with an optional label to break
1406 Break(Destination, Option<P<Expr>>),
1407 /// A `continue`, with an optional label
1408 Continue(Destination),
1409 /// A `return`, with an optional value to be returned
1410 Ret(Option<P<Expr>>),
1412 /// Inline assembly (from `asm!`), with its outputs and inputs.
1413 InlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1415 /// A struct or struct-like variant literal expression.
1417 /// For example, `Foo {x: 1, y: 2}`, or
1418 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1419 Struct(QPath, HirVec<Field>, Option<P<Expr>>),
1421 /// An array literal constructed from one repeated element.
1423 /// For example, `[1; 5]`. The first expression is the element
1424 /// to be repeated; the second is the number of times to repeat it.
1425 Repeat(P<Expr>, AnonConst),
1427 /// A suspension point for generators. This is `yield <expr>` in Rust.
1431 /// Optionally `Self`-qualified value/type path or associated extension.
1432 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1434 /// Path to a definition, optionally "fully-qualified" with a `Self`
1435 /// type, if the path points to an associated item in a trait.
1437 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1438 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1439 /// even though they both have the same two-segment `Clone::clone` `Path`.
1440 Resolved(Option<P<Ty>>, P<Path>),
1442 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1443 /// Will be resolved by type-checking to an associated item.
1445 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1446 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1447 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1448 TypeRelative(P<Ty>, P<PathSegment>)
1451 /// Hints at the original code for a let statement
1452 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1453 pub enum LocalSource {
1454 /// A `match _ { .. }`
1456 /// A desugared `for _ in _ { .. }` loop
1460 /// Hints at the original code for a `match _ { .. }`
1461 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1462 pub enum MatchSource {
1463 /// A `match _ { .. }`
1465 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1467 contains_else_clause: bool,
1469 /// A `while let _ = _ { .. }` (which was desugared to a
1470 /// `loop { match _ { .. } }`)
1472 /// A desugared `for _ in _ { .. }` loop
1474 /// A desugared `?` operator
1478 /// The loop type that yielded an ExprKind::Loop
1479 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1480 pub enum LoopSource {
1481 /// A `loop { .. }` loop
1483 /// A `while let _ = _ { .. }` loop
1485 /// A `for _ in _ { .. }` loop
1489 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1490 pub enum LoopIdError {
1492 UnlabeledCfInWhileCondition,
1496 impl fmt::Display for LoopIdError {
1497 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1498 fmt::Display::fmt(match *self {
1499 LoopIdError::OutsideLoopScope => "not inside loop scope",
1500 LoopIdError::UnlabeledCfInWhileCondition =>
1501 "unlabeled control flow (break or continue) in while condition",
1502 LoopIdError::UnresolvedLabel => "label not found",
1507 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1508 pub struct Destination {
1509 // This is `Some(_)` iff there is an explicit user-specified `label
1510 pub label: Option<Label>,
1512 // These errors are caught and then reported during the diagnostics pass in
1513 // librustc_passes/loops.rs
1514 pub target_id: Result<NodeId, LoopIdError>,
1517 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1518 pub enum GeneratorMovability {
1523 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1524 pub enum CaptureClause {
1529 // NB: If you change this, you'll probably want to change the corresponding
1530 // type structure in middle/ty.rs as well.
1531 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1534 pub mutbl: Mutability,
1537 /// Represents a method's signature in a trait declaration or implementation.
1538 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1539 pub struct MethodSig {
1540 pub header: FnHeader,
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, 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, RustcEncodable, RustcDecodable, 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, RustcEncodable, RustcDecodable, Debug)]
1569 pub enum TraitMethod {
1570 /// No default body in the trait, just a signature.
1571 Required(HirVec<Ident>),
1573 /// Both signature and body are provided in the trait.
1577 /// Represents a trait method or associated constant or type
1578 #[derive(Clone, RustcEncodable, RustcDecodable, 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(GenericBounds, 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, Debug)]
1594 pub struct ImplItemId {
1595 pub node_id: NodeId,
1598 /// Represents anything within an `impl` block
1599 #[derive(Clone, RustcEncodable, RustcDecodable, 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, RustcEncodable, RustcDecodable, 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
1622 /// An associated existential type
1623 Existential(GenericBounds),
1626 // Bind a type to an associated type: `A=Foo`.
1627 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1628 pub struct TypeBinding {
1636 #[derive(Clone, RustcEncodable, RustcDecodable)]
1644 impl fmt::Debug for Ty {
1645 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1646 write!(f, "type({})",
1647 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1651 /// Not represented directly in the AST, referred to by name through a ty_path.
1652 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1662 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1663 pub struct BareFnTy {
1664 pub unsafety: Unsafety,
1666 pub generic_params: HirVec<GenericParam>,
1667 pub decl: P<FnDecl>,
1668 pub arg_names: HirVec<Ident>,
1671 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1672 pub struct ExistTy {
1673 pub generics: Generics,
1674 pub bounds: GenericBounds,
1675 pub impl_trait_fn: Option<DefId>,
1678 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1679 /// The different kinds of types recognized by the compiler
1681 /// A variable length slice (`[T]`)
1683 /// A fixed length array (`[T; n]`)
1684 Array(P<Ty>, AnonConst),
1685 /// A raw pointer (`*const T` or `*mut T`)
1687 /// A reference (`&'a T` or `&'a mut T`)
1688 Rptr(Lifetime, MutTy),
1689 /// A bare function (e.g. `fn(usize) -> bool`)
1690 BareFn(P<BareFnTy>),
1691 /// The never type (`!`)
1693 /// A tuple (`(A, B, C, D,...)`)
1695 /// A path to a type definition (`module::module::...::Type`), or an
1696 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1698 /// Type parameters may be stored in each `PathSegment`.
1700 /// A trait object type `Bound1 + Bound2 + Bound3`
1701 /// where `Bound` is a trait or a lifetime.
1702 TraitObject(HirVec<PolyTraitRef>, Lifetime),
1705 /// TyKind::Infer means the type should be inferred instead of it having been
1706 /// specified. This can appear anywhere in a type.
1708 /// Placeholder for a type that has failed to be defined.
1712 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1713 pub struct InlineAsmOutput {
1714 pub constraint: Symbol,
1716 pub is_indirect: bool,
1719 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1720 pub struct InlineAsm {
1722 pub asm_str_style: StrStyle,
1723 pub outputs: HirVec<InlineAsmOutput>,
1724 pub inputs: HirVec<Symbol>,
1725 pub clobbers: HirVec<Symbol>,
1727 pub alignstack: bool,
1728 pub dialect: AsmDialect,
1729 pub ctxt: SyntaxContext,
1732 /// represents an argument in a function header
1733 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1740 /// Represents the header (not the body) of a function declaration
1741 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1743 pub inputs: HirVec<Ty>,
1744 pub output: FunctionRetTy,
1746 /// True if this function has an `self`, `&self` or `&mut self` receiver
1747 /// (but not a `self: Xxx` one).
1748 pub has_implicit_self: bool,
1751 /// Is the trait definition an auto trait?
1752 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1758 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1764 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1770 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1771 pub enum Constness {
1776 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1777 pub enum Defaultness {
1778 Default { has_value: bool },
1783 pub fn has_value(&self) -> bool {
1785 Defaultness::Default { has_value, .. } => has_value,
1786 Defaultness::Final => true,
1790 pub fn is_final(&self) -> bool {
1791 *self == Defaultness::Final
1794 pub fn is_default(&self) -> bool {
1796 Defaultness::Default { .. } => true,
1802 impl fmt::Display for Unsafety {
1803 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1804 fmt::Display::fmt(match *self {
1805 Unsafety::Normal => "normal",
1806 Unsafety::Unsafe => "unsafe",
1812 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1813 pub enum ImplPolarity {
1814 /// `impl Trait for Type`
1816 /// `impl !Trait for Type`
1820 impl fmt::Debug for ImplPolarity {
1821 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1823 ImplPolarity::Positive => "positive".fmt(f),
1824 ImplPolarity::Negative => "negative".fmt(f),
1830 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1831 pub enum FunctionRetTy {
1832 /// Return type is not specified.
1834 /// Functions default to `()` and
1835 /// closures default to inference. Span points to where return
1836 /// type would be inserted.
1837 DefaultReturn(Span),
1842 impl FunctionRetTy {
1843 pub fn span(&self) -> Span {
1845 DefaultReturn(span) => span,
1846 Return(ref ty) => ty.span,
1851 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1853 /// A span from the first token past `{` to the last token until `}`.
1854 /// For `mod foo;`, the inner span ranges from the first token
1855 /// to the last token in the external file.
1857 pub item_ids: HirVec<ItemId>,
1860 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1861 pub struct ForeignMod {
1863 pub items: HirVec<ForeignItem>,
1866 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1867 pub struct GlobalAsm {
1869 pub ctxt: SyntaxContext,
1872 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1873 pub struct EnumDef {
1874 pub variants: HirVec<Variant>,
1877 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1878 pub struct VariantKind {
1880 pub attrs: HirVec<Attribute>,
1881 pub data: VariantData,
1882 /// Explicit discriminant, eg `Foo = 1`
1883 pub disr_expr: Option<AnonConst>,
1886 pub type Variant = Spanned<VariantKind>;
1888 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1890 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1891 /// Also produced for each element of a list `use`, e.g.
1892 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1895 /// Glob import, e.g. `use foo::*`.
1898 /// Degenerate list import, e.g. `use foo::{a, b}` produces
1899 /// an additional `use foo::{}` for performing checks such as
1900 /// unstable feature gating. May be removed in the future.
1904 /// TraitRef's appear in impls.
1906 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1907 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1908 /// trait being referred to but just a unique NodeId that serves as a key
1909 /// within the DefMap.
1910 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1911 pub struct TraitRef {
1914 pub hir_ref_id: HirId,
1917 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1918 pub struct PolyTraitRef {
1919 /// The `'a` in `<'a> Foo<&'a T>`
1920 pub bound_generic_params: HirVec<GenericParam>,
1922 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1923 pub trait_ref: TraitRef,
1928 pub type Visibility = Spanned<VisibilityKind>;
1930 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1931 pub enum VisibilityKind {
1934 Restricted { path: P<Path>, id: NodeId, hir_id: HirId },
1938 impl VisibilityKind {
1939 pub fn is_pub(&self) -> bool {
1941 VisibilityKind::Public => true,
1946 pub fn is_pub_restricted(&self) -> bool {
1948 VisibilityKind::Public |
1949 VisibilityKind::Inherited => false,
1950 VisibilityKind::Crate(..) |
1951 VisibilityKind::Restricted { .. } => true,
1956 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1957 pub struct StructField {
1960 pub vis: Visibility,
1963 pub attrs: HirVec<Attribute>,
1967 // Still necessary in couple of places
1968 pub fn is_positional(&self) -> bool {
1969 let first = self.ident.as_str().as_bytes()[0];
1970 first >= b'0' && first <= b'9'
1974 /// Fields and Ids of enum variants and structs
1976 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1977 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1978 /// One shared Id can be successfully used for these two purposes.
1979 /// Id of the whole enum lives in `Item`.
1981 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1982 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1983 /// the variant itself" from enum variants.
1984 /// Id of the whole struct lives in `Item`.
1985 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1986 pub enum VariantData {
1987 Struct(HirVec<StructField>, NodeId),
1988 Tuple(HirVec<StructField>, NodeId),
1993 pub fn fields(&self) -> &[StructField] {
1995 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1999 pub fn id(&self) -> NodeId {
2001 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
2004 pub fn is_struct(&self) -> bool {
2005 if let VariantData::Struct(..) = *self {
2011 pub fn is_tuple(&self) -> bool {
2012 if let VariantData::Tuple(..) = *self {
2018 pub fn is_unit(&self) -> bool {
2019 if let VariantData::Unit(..) = *self {
2027 // The bodies for items are stored "out of line", in a separate
2028 // hashmap in the `Crate`. Here we just record the node-id of the item
2029 // so it can fetched later.
2030 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2037 /// The name might be a dummy name in case of anonymous items
2038 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2043 pub attrs: HirVec<Attribute>,
2045 pub vis: Visibility,
2049 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2050 pub struct FnHeader {
2051 pub unsafety: Unsafety,
2052 pub constness: Constness,
2053 pub asyncness: IsAsync,
2057 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2059 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2061 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
2062 ExternCrate(Option<Name>),
2064 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2068 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
2069 Use(P<Path>, UseKind),
2072 Static(P<Ty>, Mutability, BodyId),
2074 Const(P<Ty>, BodyId),
2075 /// A function declaration
2076 Fn(P<FnDecl>, FnHeader, Generics, BodyId),
2079 /// An external module
2080 ForeignMod(ForeignMod),
2081 /// Module-level inline assembly (from global_asm!)
2082 GlobalAsm(P<GlobalAsm>),
2083 /// A type alias, e.g. `type Foo = Bar<u8>`
2084 Ty(P<Ty>, Generics),
2085 /// An existential type definition, e.g. `existential type Foo: Bar;`
2086 Existential(ExistTy),
2087 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
2088 Enum(EnumDef, Generics),
2089 /// A struct definition, e.g. `struct Foo<A> {x: A}`
2090 Struct(VariantData, Generics),
2091 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
2092 Union(VariantData, Generics),
2093 /// Represents a Trait Declaration
2094 Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2095 /// Represents a Trait Alias Declaration
2096 TraitAlias(Generics, GenericBounds),
2098 /// An implementation, eg `impl<A> Trait for Foo { .. }`
2103 Option<TraitRef>, // (optional) trait this impl implements
2105 HirVec<ImplItemRef>),
2109 pub fn descriptive_variant(&self) -> &str {
2111 ItemKind::ExternCrate(..) => "extern crate",
2112 ItemKind::Use(..) => "use",
2113 ItemKind::Static(..) => "static item",
2114 ItemKind::Const(..) => "constant item",
2115 ItemKind::Fn(..) => "function",
2116 ItemKind::Mod(..) => "module",
2117 ItemKind::ForeignMod(..) => "foreign module",
2118 ItemKind::GlobalAsm(..) => "global asm",
2119 ItemKind::Ty(..) => "type alias",
2120 ItemKind::Existential(..) => "existential type",
2121 ItemKind::Enum(..) => "enum",
2122 ItemKind::Struct(..) => "struct",
2123 ItemKind::Union(..) => "union",
2124 ItemKind::Trait(..) => "trait",
2125 ItemKind::TraitAlias(..) => "trait alias",
2126 ItemKind::Impl(..) => "item",
2130 pub fn adt_kind(&self) -> Option<AdtKind> {
2132 ItemKind::Struct(..) => Some(AdtKind::Struct),
2133 ItemKind::Union(..) => Some(AdtKind::Union),
2134 ItemKind::Enum(..) => Some(AdtKind::Enum),
2139 pub fn generics(&self) -> Option<&Generics> {
2141 ItemKind::Fn(_, _, ref generics, _) |
2142 ItemKind::Ty(_, ref generics) |
2143 ItemKind::Existential(ExistTy { ref generics, impl_trait_fn: None, .. }) |
2144 ItemKind::Enum(_, ref generics) |
2145 ItemKind::Struct(_, ref generics) |
2146 ItemKind::Union(_, ref generics) |
2147 ItemKind::Trait(_, _, ref generics, _, _) |
2148 ItemKind::Impl(_, _, _, ref generics, _, _, _)=> generics,
2154 /// A reference from an trait to one of its associated items. This
2155 /// contains the item's id, naturally, but also the item's name and
2156 /// some other high-level details (like whether it is an associated
2157 /// type or method, and whether it is public). This allows other
2158 /// passes to find the impl they want without loading the id (which
2159 /// means fewer edges in the incremental compilation graph).
2160 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2161 pub struct TraitItemRef {
2162 pub id: TraitItemId,
2164 pub kind: AssociatedItemKind,
2166 pub defaultness: Defaultness,
2169 /// A reference from an impl to one of its associated items. This
2170 /// contains the item's id, naturally, but also the item's name and
2171 /// some other high-level details (like whether it is an associated
2172 /// type or method, and whether it is public). This allows other
2173 /// passes to find the impl they want without loading the id (which
2174 /// means fewer edges in the incremental compilation graph).
2175 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2176 pub struct ImplItemRef {
2179 pub kind: AssociatedItemKind,
2181 pub vis: Visibility,
2182 pub defaultness: Defaultness,
2185 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2186 pub enum AssociatedItemKind {
2188 Method { has_self: bool },
2193 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2194 pub struct ForeignItem {
2196 pub attrs: HirVec<Attribute>,
2197 pub node: ForeignItemKind,
2200 pub vis: Visibility,
2203 /// An item within an `extern` block
2204 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2205 pub enum ForeignItemKind {
2206 /// A foreign function
2207 Fn(P<FnDecl>, HirVec<Ident>, Generics),
2208 /// A foreign static item (`static ext: u8`), with optional mutability
2209 /// (the boolean is true when mutable)
2210 Static(P<Ty>, bool),
2215 impl ForeignItemKind {
2216 pub fn descriptive_variant(&self) -> &str {
2218 ForeignItemKind::Fn(..) => "foreign function",
2219 ForeignItemKind::Static(..) => "foreign static item",
2220 ForeignItemKind::Type => "foreign type",
2225 /// A free variable referred to in a function.
2226 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2227 pub struct Freevar {
2228 /// The variable being accessed free.
2231 // First span where it is accessed (there can be multiple).
2236 pub fn var_id(&self) -> NodeId {
2238 Def::Local(id) | Def::Upvar(id, ..) => id,
2239 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2244 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2246 pub type CaptureModeMap = NodeMap<CaptureClause>;
2248 #[derive(Clone, Debug)]
2249 pub struct TraitCandidate {
2251 pub import_id: Option<NodeId>,
2254 // Trait method resolution
2255 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2257 // Map from the NodeId of a glob import to a list of items which are actually
2259 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2262 pub fn provide(providers: &mut Providers) {
2263 providers.describe_def = map::describe_def;
2266 #[derive(Clone, RustcEncodable, RustcDecodable)]
2267 pub struct CodegenFnAttrs {
2268 pub flags: CodegenFnAttrFlags,
2269 pub inline: InlineAttr,
2270 pub export_name: Option<Symbol>,
2271 pub target_features: Vec<Symbol>,
2272 pub linkage: Option<Linkage>,
2273 pub link_section: Option<Symbol>,
2277 #[derive(RustcEncodable, RustcDecodable)]
2278 pub struct CodegenFnAttrFlags: u32 {
2279 const COLD = 1 << 0;
2280 const ALLOCATOR = 1 << 1;
2281 const UNWIND = 1 << 2;
2282 const RUSTC_ALLOCATOR_NOUNWIND = 1 << 3;
2283 const NAKED = 1 << 4;
2284 const NO_MANGLE = 1 << 5;
2285 const RUSTC_STD_INTERNAL_SYMBOL = 1 << 6;
2286 const NO_DEBUG = 1 << 7;
2287 const THREAD_LOCAL = 1 << 8;
2288 const USED = 1 << 9;
2292 impl CodegenFnAttrs {
2293 pub fn new() -> CodegenFnAttrs {
2295 flags: CodegenFnAttrFlags::empty(),
2296 inline: InlineAttr::None,
2298 target_features: vec![],
2304 /// True if `#[inline]` or `#[inline(always)]` is present.
2305 pub fn requests_inline(&self) -> bool {
2307 InlineAttr::Hint | InlineAttr::Always => true,
2308 InlineAttr::None | InlineAttr::Never => false,
2312 /// True if `#[no_mangle]` or `#[export_name(...)]` is present.
2313 pub fn contains_extern_indicator(&self) -> bool {
2314 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) || self.export_name.is_some()