1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 pub use self::BinOp_::*;
14 pub use self::BlockCheckMode::*;
15 pub use self::CaptureClause::*;
16 pub use self::Decl_::*;
17 pub use self::Expr_::*;
18 pub use self::FunctionRetTy::*;
19 pub use self::ForeignItem_::*;
20 pub use self::Item_::*;
21 pub use self::Mutability::*;
22 pub use self::PrimTy::*;
23 pub use self::Stmt_::*;
25 pub use self::UnOp::*;
26 pub use self::UnsafeSource::*;
29 use hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
30 use util::nodemap::{NodeMap, FxHashSet};
31 use mir::mono::Linkage;
33 use syntax_pos::{Span, DUMMY_SP, symbol::InternedString};
34 use syntax::codemap::{self, Spanned};
35 use rustc_target::spec::abi::Abi;
36 use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, DUMMY_NODE_ID, AsmDialect};
37 use syntax::ast::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy, MetaItem};
38 use syntax::attr::InlineAttr;
39 use syntax::ext::hygiene::SyntaxContext;
41 use syntax::symbol::{Symbol, keywords};
42 use syntax::tokenstream::TokenStream;
43 use syntax::util::ThinVec;
44 use syntax::util::parser::ExprPrecedence;
46 use ty::query::Providers;
48 use rustc_data_structures::indexed_vec;
49 use rustc_data_structures::sync::{ParallelIterator, par_iter, Send, Sync, scope};
51 use serialize::{self, Encoder, Encodable, Decoder, Decodable};
52 use std::collections::BTreeMap;
55 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
56 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
57 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
58 /// of `Vec` to avoid keeping extra capacity.
59 pub type HirVec<T> = P<[T]>;
61 macro_rules! hir_vec {
62 ($elem:expr; $n:expr) => (
63 $crate::hir::HirVec::from(vec![$elem; $n])
66 $crate::hir::HirVec::from(vec![$($x),*])
68 ($($x:expr,)*) => (hir_vec![$($x),*])
75 pub mod itemlikevisit;
82 /// A HirId uniquely identifies a node in the HIR of the current crate. It is
83 /// composed of the `owner`, which is the DefIndex of the directly enclosing
84 /// hir::Item, hir::TraitItem, or hir::ImplItem (i.e. the closest "item-like"),
85 /// and the `local_id` which is unique within the given owner.
87 /// This two-level structure makes for more stable values: One can move an item
88 /// around within the source code, or add or remove stuff before it, without
89 /// the local_id part of the HirId changing, which is a very useful property in
90 /// incremental compilation where we have to persist things through changes to
92 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
95 pub local_id: ItemLocalId,
99 pub fn owner_def_id(self) -> DefId {
100 DefId::local(self.owner)
103 pub fn owner_local_def_id(self) -> LocalDefId {
104 LocalDefId::from_def_id(DefId::local(self.owner))
108 impl serialize::UseSpecializedEncodable for HirId {
109 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
120 impl serialize::UseSpecializedDecodable for HirId {
121 fn default_decode<D: Decoder>(d: &mut D) -> Result<HirId, D::Error> {
122 let owner = DefIndex::decode(d)?;
123 let local_id = ItemLocalId::decode(d)?;
133 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
134 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
135 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
136 /// the node's position within the owning item in any way, but there is a
137 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
138 /// integers starting at zero, so a mapping that maps all or most nodes within
139 /// an "item-like" to something else can be implement by a `Vec` instead of a
140 /// tree or hash map.
141 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug,
142 RustcEncodable, RustcDecodable)]
143 pub struct ItemLocalId(pub u32);
146 pub fn as_usize(&self) -> usize {
151 impl indexed_vec::Idx for ItemLocalId {
152 fn new(idx: usize) -> Self {
153 debug_assert!((idx as u32) as usize == idx);
154 ItemLocalId(idx as u32)
157 fn index(self) -> usize {
162 /// The `HirId` corresponding to CRATE_NODE_ID and CRATE_DEF_INDEX
163 pub const CRATE_HIR_ID: HirId = HirId {
164 owner: CRATE_DEF_INDEX,
165 local_id: ItemLocalId(0)
168 pub const DUMMY_HIR_ID: HirId = HirId {
169 owner: CRATE_DEF_INDEX,
170 local_id: DUMMY_ITEM_LOCAL_ID,
173 pub const DUMMY_ITEM_LOCAL_ID: ItemLocalId = ItemLocalId(!0);
175 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
180 impl fmt::Debug for Label {
181 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
182 write!(f, "label({:?})", self.ident)
186 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
187 pub struct Lifetime {
191 /// Either "'a", referring to a named lifetime definition,
192 /// or "" (aka keywords::Invalid), for elision placeholders.
194 /// HIR lowering inserts these placeholders in type paths that
195 /// refer to type definitions needing lifetime parameters,
196 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
197 pub name: LifetimeName,
200 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
202 /// Some user-given name like `T` or `'x`.
205 /// Synthetic name generated when user elided a lifetime in an impl header,
206 /// e.g. the lifetimes in cases like these:
208 /// impl Foo for &u32
209 /// impl Foo<'_> for u32
211 /// in that case, we rewrite to
213 /// impl<'f> Foo for &'f u32
214 /// impl<'f> Foo<'f> for u32
216 /// where `'f` is something like `Fresh(0)`. The indices are
217 /// unique per impl, but not necessarily continuous.
222 pub fn ident(&self) -> Ident {
224 ParamName::Plain(ident) => ident,
225 ParamName::Fresh(_) => keywords::UnderscoreLifetime.ident(),
229 pub fn modern(&self) -> ParamName {
231 ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
232 param_name => param_name,
237 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
238 pub enum LifetimeName {
239 /// User-given names or fresh (synthetic) names.
242 /// User typed nothing. e.g. the lifetime in `&u32`.
248 /// User wrote `'static`
253 pub fn ident(&self) -> Ident {
255 LifetimeName::Implicit => keywords::Invalid.ident(),
256 LifetimeName::Underscore => keywords::UnderscoreLifetime.ident(),
257 LifetimeName::Static => keywords::StaticLifetime.ident(),
258 LifetimeName::Param(param_name) => param_name.ident(),
262 pub fn is_elided(&self) -> bool {
264 LifetimeName::Implicit | LifetimeName::Underscore => true,
266 // It might seem surprising that `Fresh(_)` counts as
267 // *not* elided -- but this is because, as far as the code
268 // in the compiler is concerned -- `Fresh(_)` variants act
269 // equivalently to "some fresh name". They correspond to
270 // early-bound regions on an impl, in other words.
271 LifetimeName::Param(_) | LifetimeName::Static => false,
275 fn is_static(&self) -> bool {
276 self == &LifetimeName::Static
279 pub fn modern(&self) -> LifetimeName {
281 LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
282 lifetime_name => lifetime_name,
287 impl fmt::Display for Lifetime {
288 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
289 self.name.ident().fmt(f)
293 impl fmt::Debug for Lifetime {
294 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
298 print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
303 pub fn is_elided(&self) -> bool {
304 self.name.is_elided()
307 pub fn is_static(&self) -> bool {
308 self.name.is_static()
312 /// A "Path" is essentially Rust's notion of a name; for instance:
313 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
314 /// along with a bunch of supporting information.
315 #[derive(Clone, RustcEncodable, RustcDecodable)]
318 /// The definition that the path resolved to.
320 /// The segments in the path: the things separated by `::`.
321 pub segments: HirVec<PathSegment>,
325 pub fn is_global(&self) -> bool {
326 !self.segments.is_empty() && self.segments[0].ident.name == keywords::CrateRoot.name()
330 impl fmt::Debug for Path {
331 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
332 write!(f, "path({})", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
336 impl fmt::Display for Path {
337 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
338 write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
342 /// A segment of a path: an identifier, an optional lifetime, and a set of
344 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
345 pub struct PathSegment {
346 /// The identifier portion of this path segment.
349 /// Type/lifetime parameters attached to this path. They come in
350 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
351 /// this is more than just simple syntactic sugar; the use of
352 /// parens affects the region binding rules, so we preserve the
354 pub args: Option<P<GenericArgs>>,
356 /// Whether to infer remaining type parameters, if any.
357 /// This only applies to expression and pattern paths, and
358 /// out of those only the segments with no type parameters
359 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
360 pub infer_types: bool,
364 /// Convert an identifier to the corresponding segment.
365 pub fn from_ident(ident: Ident) -> PathSegment {
373 pub fn new(ident: Ident, args: GenericArgs, infer_types: bool) -> Self {
377 args: if args.is_empty() {
385 // FIXME: hack required because you can't create a static
386 // GenericArgs, so you can't just return a &GenericArgs.
387 pub fn with_generic_args<F, R>(&self, f: F) -> R
388 where F: FnOnce(&GenericArgs) -> R
390 let dummy = GenericArgs::none();
391 f(if let Some(ref args) = self.args {
399 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
400 pub enum GenericArg {
406 pub fn span(&self) -> Span {
408 GenericArg::Lifetime(l) => l.span,
409 GenericArg::Type(t) => t.span,
414 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
415 pub struct GenericArgs {
416 /// The generic arguments for this path segment.
417 pub args: HirVec<GenericArg>,
418 /// Bindings (equality constraints) on associated types, if present.
419 /// E.g., `Foo<A=Bar>`.
420 pub bindings: HirVec<TypeBinding>,
421 /// Were arguments written in parenthesized form `Fn(T) -> U`?
422 /// This is required mostly for pretty-printing and diagnostics,
423 /// but also for changing lifetime elision rules to be "function-like".
424 pub parenthesized: bool,
428 pub fn none() -> Self {
431 bindings: HirVec::new(),
432 parenthesized: false,
436 pub fn is_empty(&self) -> bool {
437 self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
440 pub fn inputs(&self) -> &[Ty] {
441 if self.parenthesized {
442 for arg in &self.args {
444 GenericArg::Lifetime(_) => {}
445 GenericArg::Type(ref ty) => {
446 if let TyTup(ref tys) = ty.node {
454 bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
458 /// A modifier on a bound, currently this is only used for `?Sized`, where the
459 /// modifier is `Maybe`. Negative bounds should also be handled here.
460 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
461 pub enum TraitBoundModifier {
466 /// The AST represents all type param bounds as types.
467 /// typeck::collect::compute_bounds matches these against
468 /// the "special" built-in traits (see middle::lang_items) and
469 /// detects Copy, Send and Sync.
470 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
471 pub enum GenericBound {
472 Trait(PolyTraitRef, TraitBoundModifier),
477 pub fn span(&self) -> Span {
479 &GenericBound::Trait(ref t, ..) => t.span,
480 &GenericBound::Outlives(ref l) => l.span,
485 pub type GenericBounds = HirVec<GenericBound>;
487 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
488 pub enum GenericParamKind {
489 /// A lifetime definition, eg `'a: 'b + 'c + 'd`.
491 // Indicates that the lifetime definition was synthetically added
492 // as a result of an in-band lifetime usage like:
493 // `fn foo(x: &'a u8) -> &'a u8 { x }`
497 default: Option<P<Ty>>,
498 synthetic: Option<SyntheticTyParamKind>,
502 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
503 pub struct GenericParam {
506 pub attrs: HirVec<Attribute>,
507 pub bounds: GenericBounds,
509 pub pure_wrt_drop: bool,
511 pub kind: GenericParamKind,
514 pub struct GenericParamCount {
515 pub lifetimes: usize,
519 /// Represents lifetimes and type parameters attached to a declaration
520 /// of a function, enum, trait, etc.
521 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
522 pub struct Generics {
523 pub params: HirVec<GenericParam>,
524 pub where_clause: WhereClause,
529 pub fn empty() -> Generics {
531 params: HirVec::new(),
532 where_clause: WhereClause {
534 predicates: HirVec::new(),
540 pub fn own_counts(&self) -> GenericParamCount {
541 // We could cache this as a property of `GenericParamCount`, but
542 // the aim is to refactor this away entirely eventually and the
543 // presence of this method will be a constant reminder.
544 let mut own_counts = GenericParamCount {
549 for param in &self.params {
551 GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
552 GenericParamKind::Type { .. } => own_counts.types += 1,
559 pub fn get_named(&self, name: &InternedString) -> Option<&GenericParam> {
560 for param in &self.params {
561 if *name == param.name.ident().as_interned_str() {
569 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
570 /// to track the original form they had. Useful for error messages.
571 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
572 pub enum SyntheticTyParamKind {
576 /// A `where` clause in a definition
577 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
578 pub struct WhereClause {
580 pub predicates: HirVec<WherePredicate>,
584 pub fn span(&self) -> Option<Span> {
585 self.predicates.iter().map(|predicate| predicate.span())
586 .fold(None, |acc, i| match (acc, i) {
587 (None, i) => Some(i),
595 /// A single predicate in a `where` clause
596 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
597 pub enum WherePredicate {
598 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
599 BoundPredicate(WhereBoundPredicate),
600 /// A lifetime predicate, e.g. `'a: 'b+'c`
601 RegionPredicate(WhereRegionPredicate),
602 /// An equality predicate (unsupported)
603 EqPredicate(WhereEqPredicate),
606 impl WherePredicate {
607 pub fn span(&self) -> Span {
609 &WherePredicate::BoundPredicate(ref p) => p.span,
610 &WherePredicate::RegionPredicate(ref p) => p.span,
611 &WherePredicate::EqPredicate(ref p) => p.span,
616 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
617 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
618 pub struct WhereBoundPredicate {
620 /// Any generics from a `for` binding
621 pub bound_generic_params: HirVec<GenericParam>,
622 /// The type being bounded
623 pub bounded_ty: P<Ty>,
624 /// Trait and lifetime bounds (`Clone+Send+'static`)
625 pub bounds: GenericBounds,
628 /// A lifetime predicate, e.g. `'a: 'b+'c`
629 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
630 pub struct WhereRegionPredicate {
632 pub lifetime: Lifetime,
633 pub bounds: GenericBounds,
636 /// An equality predicate (unsupported), e.g. `T=int`
637 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
638 pub struct WhereEqPredicate {
645 pub type CrateConfig = HirVec<P<MetaItem>>;
647 /// The top-level data structure that stores the entire contents of
648 /// the crate currently being compiled.
650 /// For more details, see the [rustc guide].
652 /// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/hir.html
653 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
656 pub attrs: HirVec<Attribute>,
658 pub exported_macros: HirVec<MacroDef>,
660 // NB: We use a BTreeMap here so that `visit_all_items` iterates
661 // over the ids in increasing order. In principle it should not
662 // matter what order we visit things in, but in *practice* it
663 // does, because it can affect the order in which errors are
664 // detected, which in turn can make compile-fail tests yield
665 // slightly different results.
666 pub items: BTreeMap<NodeId, Item>,
668 pub trait_items: BTreeMap<TraitItemId, TraitItem>,
669 pub impl_items: BTreeMap<ImplItemId, ImplItem>,
670 pub bodies: BTreeMap<BodyId, Body>,
671 pub trait_impls: BTreeMap<DefId, Vec<NodeId>>,
672 pub trait_auto_impl: BTreeMap<DefId, NodeId>,
674 /// A list of the body ids written out in the order in which they
675 /// appear in the crate. If you're going to process all the bodies
676 /// in the crate, you should iterate over this list rather than the keys
678 pub body_ids: Vec<BodyId>,
682 pub fn item(&self, id: NodeId) -> &Item {
686 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem {
687 &self.trait_items[&id]
690 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem {
691 &self.impl_items[&id]
694 /// Visits all items in the crate in some deterministic (but
695 /// unspecified) order. If you just need to process every item,
696 /// but don't care about nesting, this method is the best choice.
698 /// If you do care about nesting -- usually because your algorithm
699 /// follows lexical scoping rules -- then you want a different
700 /// approach. You should override `visit_nested_item` in your
701 /// visitor and then call `intravisit::walk_crate` instead.
702 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
703 where V: itemlikevisit::ItemLikeVisitor<'hir>
705 for (_, item) in &self.items {
706 visitor.visit_item(item);
709 for (_, trait_item) in &self.trait_items {
710 visitor.visit_trait_item(trait_item);
713 for (_, impl_item) in &self.impl_items {
714 visitor.visit_impl_item(impl_item);
718 /// A parallel version of visit_all_item_likes
719 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
720 where V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send
724 par_iter(&self.items).for_each(|(_, item)| {
725 visitor.visit_item(item);
730 par_iter(&self.trait_items).for_each(|(_, trait_item)| {
731 visitor.visit_trait_item(trait_item);
736 par_iter(&self.impl_items).for_each(|(_, impl_item)| {
737 visitor.visit_impl_item(impl_item);
743 pub fn body(&self, id: BodyId) -> &Body {
748 /// A macro definition, in this crate or imported from another.
750 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
751 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
752 pub struct MacroDef {
755 pub attrs: HirVec<Attribute>,
758 pub body: TokenStream,
762 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
764 /// Statements in a block
765 pub stmts: HirVec<Stmt>,
766 /// An expression at the end of the block
767 /// without a semicolon, if any
768 pub expr: Option<P<Expr>>,
771 /// Distinguishes between `unsafe { ... }` and `{ ... }`
772 pub rules: BlockCheckMode,
774 /// If true, then there may exist `break 'a` values that aim to
775 /// break out of this block early.
776 /// Used by `'label: {}` blocks and by `catch` statements.
777 pub targeted_by_break: bool,
778 /// If true, don't emit return value type errors as the parser had
779 /// to recover from a parse error so this block will not have an
780 /// appropriate type. A parse error will have been emitted so the
781 /// compilation will never succeed if this is true.
785 #[derive(Clone, RustcEncodable, RustcDecodable)]
793 impl fmt::Debug for Pat {
794 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
795 write!(f, "pat({}: {})", self.id,
796 print::to_string(print::NO_ANN, |s| s.print_pat(self)))
801 // FIXME(#19596) this is a workaround, but there should be a better way
802 fn walk_<G>(&self, it: &mut G) -> bool
803 where G: FnMut(&Pat) -> bool
810 PatKind::Binding(.., Some(ref p)) => p.walk_(it),
811 PatKind::Struct(_, ref fields, _) => {
812 fields.iter().all(|field| field.node.pat.walk_(it))
814 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
815 s.iter().all(|p| p.walk_(it))
817 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
820 PatKind::Slice(ref before, ref slice, ref after) => {
821 before.iter().all(|p| p.walk_(it)) &&
822 slice.iter().all(|p| p.walk_(it)) &&
823 after.iter().all(|p| p.walk_(it))
828 PatKind::Binding(..) |
829 PatKind::Path(_) => {
835 pub fn walk<F>(&self, mut it: F) -> bool
836 where F: FnMut(&Pat) -> bool
842 /// A single field in a struct pattern
844 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
845 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
846 /// except is_shorthand is true
847 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
848 pub struct FieldPat {
850 /// The identifier for the field
852 /// The pattern the field is destructured to
854 pub is_shorthand: bool,
857 /// Explicit binding annotations given in the HIR for a binding. Note
858 /// that this is not the final binding *mode* that we infer after type
860 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
861 pub enum BindingAnnotation {
862 /// No binding annotation given: this means that the final binding mode
863 /// will depend on whether we have skipped through a `&` reference
864 /// when matching. For example, the `x` in `Some(x)` will have binding
865 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
866 /// ultimately be inferred to be by-reference.
868 /// Note that implicit reference skipping is not implemented yet (#42640).
871 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
874 /// Annotated as `ref`, like `ref x`
877 /// Annotated as `ref mut x`.
881 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
887 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
889 /// Represents a wildcard pattern (`_`)
892 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
893 /// The `NodeId` is the canonical ID for the variable being bound,
894 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
895 /// which is the pattern ID of the first `x`.
896 Binding(BindingAnnotation, NodeId, Ident, Option<P<Pat>>),
898 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
899 /// The `bool` is `true` in the presence of a `..`.
900 Struct(QPath, HirVec<Spanned<FieldPat>>, bool),
902 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
903 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
904 /// 0 <= position <= subpats.len()
905 TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
907 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
910 /// A tuple pattern `(a, b)`.
911 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
912 /// 0 <= position <= subpats.len()
913 Tuple(HirVec<P<Pat>>, Option<usize>),
916 /// A reference pattern, e.g. `&mut (a, b)`
917 Ref(P<Pat>, Mutability),
920 /// A range pattern, e.g. `1...2` or `1..2`
921 Range(P<Expr>, P<Expr>, RangeEnd),
922 /// `[a, b, ..i, y, z]` is represented as:
923 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
924 Slice(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
927 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
928 pub enum Mutability {
934 /// Return MutMutable only if both arguments are mutable.
935 pub fn and(self, other: Self) -> Self {
938 MutImmutable => MutImmutable,
943 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
945 /// The `+` operator (addition)
947 /// The `-` operator (subtraction)
949 /// The `*` operator (multiplication)
951 /// The `/` operator (division)
953 /// The `%` operator (modulus)
955 /// The `&&` operator (logical and)
957 /// The `||` operator (logical or)
959 /// The `^` operator (bitwise xor)
961 /// The `&` operator (bitwise and)
963 /// The `|` operator (bitwise or)
965 /// The `<<` operator (shift left)
967 /// The `>>` operator (shift right)
969 /// The `==` operator (equality)
971 /// The `<` operator (less than)
973 /// The `<=` operator (less than or equal to)
975 /// The `!=` operator (not equal to)
977 /// The `>=` operator (greater than or equal to)
979 /// The `>` operator (greater than)
984 pub fn as_str(self) -> &'static str {
1007 pub fn is_lazy(self) -> bool {
1009 BiAnd | BiOr => true,
1014 pub fn is_shift(self) -> bool {
1016 BiShl | BiShr => true,
1021 pub fn is_comparison(self) -> bool {
1023 BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
1039 /// Returns `true` if the binary operator takes its arguments by value
1040 pub fn is_by_value(self) -> bool {
1041 !self.is_comparison()
1045 impl Into<ast::BinOpKind> for BinOp_ {
1046 fn into(self) -> ast::BinOpKind {
1048 BiAdd => ast::BinOpKind::Add,
1049 BiSub => ast::BinOpKind::Sub,
1050 BiMul => ast::BinOpKind::Mul,
1051 BiDiv => ast::BinOpKind::Div,
1052 BiRem => ast::BinOpKind::Rem,
1053 BiAnd => ast::BinOpKind::And,
1054 BiOr => ast::BinOpKind::Or,
1055 BiBitXor => ast::BinOpKind::BitXor,
1056 BiBitAnd => ast::BinOpKind::BitAnd,
1057 BiBitOr => ast::BinOpKind::BitOr,
1058 BiShl => ast::BinOpKind::Shl,
1059 BiShr => ast::BinOpKind::Shr,
1060 BiEq => ast::BinOpKind::Eq,
1061 BiLt => ast::BinOpKind::Lt,
1062 BiLe => ast::BinOpKind::Le,
1063 BiNe => ast::BinOpKind::Ne,
1064 BiGe => ast::BinOpKind::Ge,
1065 BiGt => ast::BinOpKind::Gt,
1070 pub type BinOp = Spanned<BinOp_>;
1072 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1074 /// The `*` operator for dereferencing
1076 /// The `!` operator for logical inversion
1078 /// The `-` operator for negation
1083 pub fn as_str(self) -> &'static str {
1091 /// Returns `true` if the unary operator takes its argument by value
1092 pub fn is_by_value(self) -> bool {
1094 UnNeg | UnNot => true,
1101 pub type Stmt = Spanned<Stmt_>;
1103 impl fmt::Debug for Stmt_ {
1104 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1106 let spanned = codemap::dummy_spanned(self.clone());
1110 print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
1114 #[derive(Clone, RustcEncodable, RustcDecodable)]
1116 /// Could be an item or a local (let) binding:
1117 StmtDecl(P<Decl>, NodeId),
1119 /// Expr without trailing semi-colon (must have unit type):
1120 StmtExpr(P<Expr>, NodeId),
1122 /// Expr with trailing semi-colon (may have any type):
1123 StmtSemi(P<Expr>, NodeId),
1127 pub fn attrs(&self) -> &[Attribute] {
1129 StmtDecl(ref d, _) => d.node.attrs(),
1130 StmtExpr(ref e, _) |
1131 StmtSemi(ref e, _) => &e.attrs,
1135 pub fn id(&self) -> NodeId {
1137 StmtDecl(_, id) => id,
1138 StmtExpr(_, id) => id,
1139 StmtSemi(_, id) => id,
1144 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
1145 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1148 pub ty: Option<P<Ty>>,
1149 /// Initializer expression to set the value, if any
1150 pub init: Option<P<Expr>>,
1154 pub attrs: ThinVec<Attribute>,
1155 pub source: LocalSource,
1158 pub type Decl = Spanned<Decl_>;
1160 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1162 /// A local (let) binding:
1163 DeclLocal(P<Local>),
1164 /// An item binding:
1169 pub fn attrs(&self) -> &[Attribute] {
1171 DeclLocal(ref l) => &l.attrs,
1176 pub fn is_local(&self) -> bool {
1178 Decl_::DeclLocal(_) => true,
1184 /// represents one arm of a 'match'
1185 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1187 pub attrs: HirVec<Attribute>,
1188 pub pats: HirVec<P<Pat>>,
1189 pub guard: Option<P<Expr>>,
1193 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1199 pub is_shorthand: bool,
1202 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1203 pub enum BlockCheckMode {
1205 UnsafeBlock(UnsafeSource),
1206 PushUnsafeBlock(UnsafeSource),
1207 PopUnsafeBlock(UnsafeSource),
1210 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1211 pub enum UnsafeSource {
1216 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1218 pub node_id: NodeId,
1221 /// The body of a function, closure, or constant value. In the case of
1222 /// a function, the body contains not only the function body itself
1223 /// (which is an expression), but also the argument patterns, since
1224 /// those are something that the caller doesn't really care about.
1229 /// fn foo((x, y): (u32, u32)) -> u32 {
1234 /// Here, the `Body` associated with `foo()` would contain:
1236 /// - an `arguments` array containing the `(x, y)` pattern
1237 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1238 /// - `is_generator` would be false
1240 /// All bodies have an **owner**, which can be accessed via the HIR
1241 /// map using `body_owner_def_id()`.
1242 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1244 pub arguments: HirVec<Arg>,
1246 pub is_generator: bool,
1250 pub fn id(&self) -> BodyId {
1252 node_id: self.value.id
1257 #[derive(Copy, Clone, Debug)]
1258 pub enum BodyOwnerKind {
1259 /// Functions and methods.
1262 /// Constants and associated constants.
1265 /// Initializer of a `static` item.
1269 /// A constant (expression) that's not an item or associated item,
1270 /// but needs its own `DefId` for type-checking, const-eval, etc.
1271 /// These are usually found nested inside types (e.g. array lengths)
1272 /// or expressions (e.g. repeat counts), and also used to define
1273 /// explicit discriminant values for enum variants.
1274 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1275 pub struct AnonConst {
1282 #[derive(Clone, RustcEncodable, RustcDecodable)]
1287 pub attrs: ThinVec<Attribute>,
1292 pub fn precedence(&self) -> ExprPrecedence {
1294 ExprBox(_) => ExprPrecedence::Box,
1295 ExprArray(_) => ExprPrecedence::Array,
1296 ExprCall(..) => ExprPrecedence::Call,
1297 ExprMethodCall(..) => ExprPrecedence::MethodCall,
1298 ExprTup(_) => ExprPrecedence::Tup,
1299 ExprBinary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1300 ExprUnary(..) => ExprPrecedence::Unary,
1301 ExprLit(_) => ExprPrecedence::Lit,
1302 ExprType(..) | ExprCast(..) => ExprPrecedence::Cast,
1303 ExprIf(..) => ExprPrecedence::If,
1304 ExprWhile(..) => ExprPrecedence::While,
1305 ExprLoop(..) => ExprPrecedence::Loop,
1306 ExprMatch(..) => ExprPrecedence::Match,
1307 ExprClosure(..) => ExprPrecedence::Closure,
1308 ExprBlock(..) => ExprPrecedence::Block,
1309 ExprAssign(..) => ExprPrecedence::Assign,
1310 ExprAssignOp(..) => ExprPrecedence::AssignOp,
1311 ExprField(..) => ExprPrecedence::Field,
1312 ExprIndex(..) => ExprPrecedence::Index,
1313 ExprPath(..) => ExprPrecedence::Path,
1314 ExprAddrOf(..) => ExprPrecedence::AddrOf,
1315 ExprBreak(..) => ExprPrecedence::Break,
1316 ExprContinue(..) => ExprPrecedence::Continue,
1317 ExprRet(..) => ExprPrecedence::Ret,
1318 ExprInlineAsm(..) => ExprPrecedence::InlineAsm,
1319 ExprStruct(..) => ExprPrecedence::Struct,
1320 ExprRepeat(..) => ExprPrecedence::Repeat,
1321 ExprYield(..) => ExprPrecedence::Yield,
1326 impl fmt::Debug for Expr {
1327 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1328 write!(f, "expr({}: {})", self.id,
1329 print::to_string(print::NO_ANN, |s| s.print_expr(self)))
1333 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1335 /// A `box x` expression.
1337 /// An array (`[a, b, c, d]`)
1338 ExprArray(HirVec<Expr>),
1341 /// The first field resolves to the function itself (usually an `ExprPath`),
1342 /// and the second field is the list of arguments.
1343 /// This also represents calling the constructor of
1344 /// tuple-like ADTs such as tuple structs and enum variants.
1345 ExprCall(P<Expr>, HirVec<Expr>),
1346 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1348 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1349 /// (within the angle brackets).
1350 /// The first element of the vector of `Expr`s is the expression that evaluates
1351 /// to the object on which the method is being called on (the receiver),
1352 /// and the remaining elements are the rest of the arguments.
1353 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1354 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1355 ExprMethodCall(PathSegment, Span, HirVec<Expr>),
1356 /// A tuple (`(a, b, c ,d)`)
1357 ExprTup(HirVec<Expr>),
1358 /// A binary operation (For example: `a + b`, `a * b`)
1359 ExprBinary(BinOp, P<Expr>, P<Expr>),
1360 /// A unary operation (For example: `!x`, `*x`)
1361 ExprUnary(UnOp, P<Expr>),
1362 /// A literal (For example: `1`, `"foo"`)
1364 /// A cast (`foo as f64`)
1365 ExprCast(P<Expr>, P<Ty>),
1366 ExprType(P<Expr>, P<Ty>),
1367 /// An `if` block, with an optional else block
1369 /// `if expr { expr } else { expr }`
1370 ExprIf(P<Expr>, P<Expr>, Option<P<Expr>>),
1371 /// A while loop, with an optional label
1373 /// `'label: while expr { block }`
1374 ExprWhile(P<Expr>, P<Block>, Option<Label>),
1375 /// Conditionless loop (can be exited with break, continue, or return)
1377 /// `'label: loop { block }`
1378 ExprLoop(P<Block>, Option<Label>, LoopSource),
1379 /// A `match` block, with a source that indicates whether or not it is
1380 /// the result of a desugaring, and if so, which kind.
1381 ExprMatch(P<Expr>, HirVec<Arm>, MatchSource),
1382 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1384 /// The final span is the span of the argument block `|...|`
1386 /// This may also be a generator literal, indicated by the final boolean,
1387 /// in that case there is an GeneratorClause.
1388 ExprClosure(CaptureClause, P<FnDecl>, BodyId, Span, Option<GeneratorMovability>),
1389 /// A block (`'label: { ... }`)
1390 ExprBlock(P<Block>, Option<Label>),
1392 /// An assignment (`a = foo()`)
1393 ExprAssign(P<Expr>, P<Expr>),
1394 /// An assignment with an operator
1396 /// For example, `a += 1`.
1397 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
1398 /// Access of a named (`obj.foo`) or unnamed (`obj.0`) struct or tuple field
1399 ExprField(P<Expr>, Ident),
1400 /// An indexing operation (`foo[2]`)
1401 ExprIndex(P<Expr>, P<Expr>),
1403 /// Path to a definition, possibly containing lifetime or type parameters.
1406 /// A referencing operation (`&a` or `&mut a`)
1407 ExprAddrOf(Mutability, P<Expr>),
1408 /// A `break`, with an optional label to break
1409 ExprBreak(Destination, Option<P<Expr>>),
1410 /// A `continue`, with an optional label
1411 ExprContinue(Destination),
1412 /// A `return`, with an optional value to be returned
1413 ExprRet(Option<P<Expr>>),
1415 /// Inline assembly (from `asm!`), with its outputs and inputs.
1416 ExprInlineAsm(P<InlineAsm>, HirVec<Expr>, HirVec<Expr>),
1418 /// A struct or struct-like variant literal expression.
1420 /// For example, `Foo {x: 1, y: 2}`, or
1421 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1422 ExprStruct(QPath, HirVec<Field>, Option<P<Expr>>),
1424 /// An array literal constructed from one repeated element.
1426 /// For example, `[1; 5]`. The first expression is the element
1427 /// to be repeated; the second is the number of times to repeat it.
1428 ExprRepeat(P<Expr>, AnonConst),
1430 /// A suspension point for generators. This is `yield <expr>` in Rust.
1434 /// Optionally `Self`-qualified value/type path or associated extension.
1435 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1437 /// Path to a definition, optionally "fully-qualified" with a `Self`
1438 /// type, if the path points to an associated item in a trait.
1440 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1441 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1442 /// even though they both have the same two-segment `Clone::clone` `Path`.
1443 Resolved(Option<P<Ty>>, P<Path>),
1445 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1446 /// Will be resolved by type-checking to an associated item.
1448 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1449 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1450 /// the `X` and `Y` nodes each being a `TyPath(QPath::TypeRelative(..))`.
1451 TypeRelative(P<Ty>, P<PathSegment>)
1454 /// Hints at the original code for a let statement
1455 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1456 pub enum LocalSource {
1457 /// A `match _ { .. }`
1459 /// A desugared `for _ in _ { .. }` loop
1463 /// Hints at the original code for a `match _ { .. }`
1464 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1465 pub enum MatchSource {
1466 /// A `match _ { .. }`
1468 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1470 contains_else_clause: bool,
1472 /// A `while let _ = _ { .. }` (which was desugared to a
1473 /// `loop { match _ { .. } }`)
1475 /// A desugared `for _ in _ { .. }` loop
1477 /// A desugared `?` operator
1481 /// The loop type that yielded an ExprLoop
1482 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1483 pub enum LoopSource {
1484 /// A `loop { .. }` loop
1486 /// A `while let _ = _ { .. }` loop
1488 /// A `for _ in _ { .. }` loop
1492 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1493 pub enum LoopIdError {
1495 UnlabeledCfInWhileCondition,
1499 impl fmt::Display for LoopIdError {
1500 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1501 fmt::Display::fmt(match *self {
1502 LoopIdError::OutsideLoopScope => "not inside loop scope",
1503 LoopIdError::UnlabeledCfInWhileCondition =>
1504 "unlabeled control flow (break or continue) in while condition",
1505 LoopIdError::UnresolvedLabel => "label not found",
1510 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1511 pub struct Destination {
1512 // This is `Some(_)` iff there is an explicit user-specified `label
1513 pub label: Option<Label>,
1515 // These errors are caught and then reported during the diagnostics pass in
1516 // librustc_passes/loops.rs
1517 pub target_id: Result<NodeId, LoopIdError>,
1520 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1521 pub enum GeneratorMovability {
1526 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
1527 pub enum CaptureClause {
1532 // NB: If you change this, you'll probably want to change the corresponding
1533 // type structure in middle/ty.rs as well.
1534 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1537 pub mutbl: Mutability,
1540 /// Represents a method's signature in a trait declaration or implementation.
1541 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1542 pub struct MethodSig {
1543 pub header: FnHeader,
1544 pub decl: P<FnDecl>,
1547 // The bodies for items are stored "out of line", in a separate
1548 // hashmap in the `Crate`. Here we just record the node-id of the item
1549 // so it can fetched later.
1550 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1551 pub struct TraitItemId {
1552 pub node_id: NodeId,
1555 /// Represents an item declaration within a trait declaration,
1556 /// possibly including a default implementation. A trait item is
1557 /// either required (meaning it doesn't have an implementation, just a
1558 /// signature) or provided (meaning it has a default implementation).
1559 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1560 pub struct TraitItem {
1564 pub attrs: HirVec<Attribute>,
1565 pub generics: Generics,
1566 pub node: TraitItemKind,
1570 /// A trait method's body (or just argument names).
1571 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1572 pub enum TraitMethod {
1573 /// No default body in the trait, just a signature.
1574 Required(HirVec<Ident>),
1576 /// Both signature and body are provided in the trait.
1580 /// Represents a trait method or associated constant or type
1581 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1582 pub enum TraitItemKind {
1583 /// An associated constant with an optional value (otherwise `impl`s
1584 /// must contain a value)
1585 Const(P<Ty>, Option<BodyId>),
1586 /// A method with an optional body
1587 Method(MethodSig, TraitMethod),
1588 /// An associated type with (possibly empty) bounds and optional concrete
1590 Type(GenericBounds, Option<P<Ty>>),
1593 // The bodies for items are stored "out of line", in a separate
1594 // hashmap in the `Crate`. Here we just record the node-id of the item
1595 // so it can fetched later.
1596 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1597 pub struct ImplItemId {
1598 pub node_id: NodeId,
1601 /// Represents anything within an `impl` block
1602 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1603 pub struct ImplItem {
1607 pub vis: Visibility,
1608 pub defaultness: Defaultness,
1609 pub attrs: HirVec<Attribute>,
1610 pub generics: Generics,
1611 pub node: ImplItemKind,
1615 /// Represents different contents within `impl`s
1616 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1617 pub enum ImplItemKind {
1618 /// An associated constant of the given type, set to the constant result
1619 /// of the expression
1620 Const(P<Ty>, BodyId),
1621 /// A method implementation with the given signature and body
1622 Method(MethodSig, BodyId),
1623 /// An associated type
1627 // Bind a type to an associated type: `A=Foo`.
1628 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1629 pub struct TypeBinding {
1637 #[derive(Clone, RustcEncodable, RustcDecodable)]
1645 impl fmt::Debug for Ty {
1646 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1647 write!(f, "type({})",
1648 print::to_string(print::NO_ANN, |s| s.print_type(self)))
1652 /// Not represented directly in the AST, referred to by name through a ty_path.
1653 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1663 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1664 pub struct BareFnTy {
1665 pub unsafety: Unsafety,
1667 pub generic_params: HirVec<GenericParam>,
1668 pub decl: P<FnDecl>,
1669 pub arg_names: HirVec<Ident>,
1672 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1673 pub struct ExistTy {
1674 pub generics: Generics,
1675 pub bounds: GenericBounds,
1676 pub impl_trait_fn: Option<DefId>,
1679 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1680 /// The different kinds of types recognized by the compiler
1682 /// A variable length slice (`[T]`)
1684 /// A fixed length array (`[T; n]`)
1685 TyArray(P<Ty>, AnonConst),
1686 /// A raw pointer (`*const T` or `*mut T`)
1688 /// A reference (`&'a T` or `&'a mut T`)
1689 TyRptr(Lifetime, MutTy),
1690 /// A bare function (e.g. `fn(usize) -> bool`)
1691 TyBareFn(P<BareFnTy>),
1692 /// The never type (`!`)
1694 /// A tuple (`(A, B, C, D,...)`)
1696 /// A path to a type definition (`module::module::...::Type`), or an
1697 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1699 /// Type parameters may be stored in each `PathSegment`.
1701 /// A trait object type `Bound1 + Bound2 + Bound3`
1702 /// where `Bound` is a trait or a lifetime.
1703 TyTraitObject(HirVec<PolyTraitRef>, Lifetime),
1705 TyTypeof(AnonConst),
1706 /// TyInfer means the type should be inferred instead of it having been
1707 /// specified. This can appear anywhere in a type.
1709 /// Placeholder for a type that has failed to be defined.
1713 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1714 pub struct InlineAsmOutput {
1715 pub constraint: Symbol,
1717 pub is_indirect: bool,
1720 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1721 pub struct InlineAsm {
1723 pub asm_str_style: StrStyle,
1724 pub outputs: HirVec<InlineAsmOutput>,
1725 pub inputs: HirVec<Symbol>,
1726 pub clobbers: HirVec<Symbol>,
1728 pub alignstack: bool,
1729 pub dialect: AsmDialect,
1730 pub ctxt: SyntaxContext,
1733 /// represents an argument in a function header
1734 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1741 /// Represents the header (not the body) of a function declaration
1742 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1744 pub inputs: HirVec<Ty>,
1745 pub output: FunctionRetTy,
1747 /// True if this function has an `self`, `&self` or `&mut self` receiver
1748 /// (but not a `self: Xxx` one).
1749 pub has_implicit_self: bool,
1752 /// Is the trait definition an auto trait?
1753 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1759 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Debug)]
1765 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1771 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1772 pub enum Constness {
1777 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1778 pub enum Defaultness {
1779 Default { has_value: bool },
1784 pub fn has_value(&self) -> bool {
1786 Defaultness::Default { has_value, .. } => has_value,
1787 Defaultness::Final => true,
1791 pub fn is_final(&self) -> bool {
1792 *self == Defaultness::Final
1795 pub fn is_default(&self) -> bool {
1797 Defaultness::Default { .. } => true,
1803 impl fmt::Display for Unsafety {
1804 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1805 fmt::Display::fmt(match *self {
1806 Unsafety::Normal => "normal",
1807 Unsafety::Unsafe => "unsafe",
1813 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1814 pub enum ImplPolarity {
1815 /// `impl Trait for Type`
1817 /// `impl !Trait for Type`
1821 impl fmt::Debug for ImplPolarity {
1822 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1824 ImplPolarity::Positive => "positive".fmt(f),
1825 ImplPolarity::Negative => "negative".fmt(f),
1831 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1832 pub enum FunctionRetTy {
1833 /// Return type is not specified.
1835 /// Functions default to `()` and
1836 /// closures default to inference. Span points to where return
1837 /// type would be inserted.
1838 DefaultReturn(Span),
1843 impl FunctionRetTy {
1844 pub fn span(&self) -> Span {
1846 DefaultReturn(span) => span,
1847 Return(ref ty) => ty.span,
1852 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1854 /// A span from the first token past `{` to the last token until `}`.
1855 /// For `mod foo;`, the inner span ranges from the first token
1856 /// to the last token in the external file.
1858 pub item_ids: HirVec<ItemId>,
1861 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1862 pub struct ForeignMod {
1864 pub items: HirVec<ForeignItem>,
1867 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1868 pub struct GlobalAsm {
1870 pub ctxt: SyntaxContext,
1873 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1874 pub struct EnumDef {
1875 pub variants: HirVec<Variant>,
1878 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1879 pub struct Variant_ {
1881 pub attrs: HirVec<Attribute>,
1882 pub data: VariantData,
1883 /// Explicit discriminant, eg `Foo = 1`
1884 pub disr_expr: Option<AnonConst>,
1887 pub type Variant = Spanned<Variant_>;
1889 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1891 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1892 /// Also produced for each element of a list `use`, e.g.
1893 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1896 /// Glob import, e.g. `use foo::*`.
1899 /// Degenerate list import, e.g. `use foo::{a, b}` produces
1900 /// an additional `use foo::{}` for performing checks such as
1901 /// unstable feature gating. May be removed in the future.
1905 /// TraitRef's appear in impls.
1907 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1908 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1909 /// trait being referred to but just a unique NodeId that serves as a key
1910 /// within the DefMap.
1911 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1912 pub struct TraitRef {
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 },
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 ItemExternCrate(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 ItemUse(P<Path>, UseKind),
2072 ItemStatic(P<Ty>, Mutability, BodyId),
2074 ItemConst(P<Ty>, BodyId),
2075 /// A function declaration
2076 ItemFn(P<FnDecl>, FnHeader, Generics, BodyId),
2079 /// An external module
2080 ItemForeignMod(ForeignMod),
2081 /// Module-level inline assembly (from global_asm!)
2082 ItemGlobalAsm(P<GlobalAsm>),
2083 /// A type alias, e.g. `type Foo = Bar<u8>`
2084 ItemTy(P<Ty>, Generics),
2085 /// A type alias, e.g. `type Foo = Bar<u8>`
2086 ItemExistential(ExistTy),
2087 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
2088 ItemEnum(EnumDef, Generics),
2089 /// A struct definition, e.g. `struct Foo<A> {x: A}`
2090 ItemStruct(VariantData, Generics),
2091 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
2092 ItemUnion(VariantData, Generics),
2093 /// Represents a Trait Declaration
2094 ItemTrait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
2095 /// Represents a Trait Alias Declaration
2096 ItemTraitAlias(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 ItemExternCrate(..) => "extern crate",
2112 ItemUse(..) => "use",
2113 ItemStatic(..) => "static item",
2114 ItemConst(..) => "constant item",
2115 ItemFn(..) => "function",
2116 ItemMod(..) => "module",
2117 ItemForeignMod(..) => "foreign module",
2118 ItemGlobalAsm(..) => "global asm",
2119 ItemTy(..) => "type alias",
2120 ItemExistential(..) => "existential type",
2121 ItemEnum(..) => "enum",
2122 ItemStruct(..) => "struct",
2123 ItemUnion(..) => "union",
2124 ItemTrait(..) => "trait",
2125 ItemTraitAlias(..) => "trait alias",
2126 ItemImpl(..) => "item",
2130 pub fn adt_kind(&self) -> Option<AdtKind> {
2132 ItemStruct(..) => Some(AdtKind::Struct),
2133 ItemUnion(..) => Some(AdtKind::Union),
2134 ItemEnum(..) => Some(AdtKind::Enum),
2139 pub fn generics(&self) -> Option<&Generics> {
2141 ItemFn(_, _, ref generics, _) |
2142 ItemTy(_, ref generics) |
2143 ItemEnum(_, ref generics) |
2144 ItemStruct(_, ref generics) |
2145 ItemUnion(_, ref generics) |
2146 ItemTrait(_, _, ref generics, _, _) |
2147 ItemImpl(_, _, _, ref generics, _, _, _)=> generics,
2153 /// A reference from an trait to one of its associated items. This
2154 /// contains the item's id, naturally, but also the item's name and
2155 /// some other high-level details (like whether it is an associated
2156 /// type or method, and whether it is public). This allows other
2157 /// passes to find the impl they want without loading the id (which
2158 /// means fewer edges in the incremental compilation graph).
2159 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2160 pub struct TraitItemRef {
2161 pub id: TraitItemId,
2163 pub kind: AssociatedItemKind,
2165 pub defaultness: Defaultness,
2168 /// A reference from an impl to one of its associated items. This
2169 /// contains the item's id, naturally, but also the item's name and
2170 /// some other high-level details (like whether it is an associated
2171 /// type or method, and whether it is public). This allows other
2172 /// passes to find the impl they want without loading the id (which
2173 /// means fewer edges in the incremental compilation graph).
2174 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2175 pub struct ImplItemRef {
2178 pub kind: AssociatedItemKind,
2180 pub vis: Visibility,
2181 pub defaultness: Defaultness,
2184 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
2185 pub enum AssociatedItemKind {
2187 Method { has_self: bool },
2191 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2192 pub struct ForeignItem {
2194 pub attrs: HirVec<Attribute>,
2195 pub node: ForeignItem_,
2198 pub vis: Visibility,
2201 /// An item within an `extern` block
2202 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2203 pub enum ForeignItem_ {
2204 /// A foreign function
2205 ForeignItemFn(P<FnDecl>, HirVec<Ident>, Generics),
2206 /// A foreign static item (`static ext: u8`), with optional mutability
2207 /// (the boolean is true when mutable)
2208 ForeignItemStatic(P<Ty>, bool),
2214 pub fn descriptive_variant(&self) -> &str {
2216 ForeignItemFn(..) => "foreign function",
2217 ForeignItemStatic(..) => "foreign static item",
2218 ForeignItemType => "foreign type",
2223 /// A free variable referred to in a function.
2224 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
2225 pub struct Freevar {
2226 /// The variable being accessed free.
2229 // First span where it is accessed (there can be multiple).
2234 pub fn var_id(&self) -> NodeId {
2236 Def::Local(id) | Def::Upvar(id, ..) => id,
2237 _ => bug!("Freevar::var_id: bad def ({:?})", self.def)
2242 pub type FreevarMap = NodeMap<Vec<Freevar>>;
2244 pub type CaptureModeMap = NodeMap<CaptureClause>;
2246 #[derive(Clone, Debug)]
2247 pub struct TraitCandidate {
2249 pub import_id: Option<NodeId>,
2252 // Trait method resolution
2253 pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
2255 // Map from the NodeId of a glob import to a list of items which are actually
2257 pub type GlobMap = NodeMap<FxHashSet<Name>>;
2260 pub fn provide(providers: &mut Providers) {
2261 providers.describe_def = map::describe_def;
2264 #[derive(Clone, RustcEncodable, RustcDecodable)]
2265 pub struct CodegenFnAttrs {
2266 pub flags: CodegenFnAttrFlags,
2267 pub inline: InlineAttr,
2268 pub export_name: Option<Symbol>,
2269 pub target_features: Vec<Symbol>,
2270 pub linkage: Option<Linkage>,
2271 pub wasm_custom_section: Option<Symbol>,
2275 #[derive(RustcEncodable, RustcDecodable)]
2276 pub struct CodegenFnAttrFlags: u8 {
2277 const COLD = 0b0000_0001;
2278 const ALLOCATOR = 0b0000_0010;
2279 const UNWIND = 0b0000_0100;
2280 const RUSTC_ALLOCATOR_NOUNWIND = 0b0000_1000;
2281 const NAKED = 0b0001_0000;
2282 const NO_MANGLE = 0b0010_0000;
2283 const RUSTC_STD_INTERNAL_SYMBOL = 0b0100_0000;
2284 const NO_DEBUG = 0b1000_0000;
2288 impl CodegenFnAttrs {
2289 pub fn new() -> CodegenFnAttrs {
2291 flags: CodegenFnAttrFlags::empty(),
2292 inline: InlineAttr::None,
2294 target_features: vec![],
2296 wasm_custom_section: None,
2300 /// True if `#[inline]` or `#[inline(always)]` is present.
2301 pub fn requests_inline(&self) -> bool {
2303 InlineAttr::Hint | InlineAttr::Always => true,
2304 InlineAttr::None | InlineAttr::Never => false,
2308 /// True if `#[no_mangle]` or `#[export_name(...)]` is present.
2309 pub fn contains_extern_indicator(&self) -> bool {
2310 self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) || self.export_name.is_some()