1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 pub use self::BinOp_
::*;
14 pub use self::BlockCheckMode
::*;
15 pub use self::CaptureClause
::*;
16 pub use self::Decl_
::*;
17 pub use self::Expr_
::*;
18 pub use self::FunctionRetTy
::*;
19 pub use self::ForeignItem_
::*;
20 pub use self::Item_
::*;
21 pub use self::Mutability
::*;
22 pub use self::PrimTy
::*;
23 pub use self::Stmt_
::*;
25 pub use self::TyParamBound
::*;
26 pub use self::UnOp
::*;
27 pub use self::UnsafeSource
::*;
28 pub use self::Visibility
::{Public, Inherited}
;
31 use hir
::def_id
::{DefId, DefIndex, CRATE_DEF_INDEX}
;
32 use util
::nodemap
::{NodeMap, FxHashSet}
;
34 use syntax_pos
::{Span, DUMMY_SP}
;
35 use syntax
::codemap
::{self, Spanned}
;
37 use syntax
::ast
::{Ident, Name, NodeId, DUMMY_NODE_ID, AsmDialect}
;
38 use syntax
::ast
::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy, MetaItem}
;
39 use syntax
::ext
::hygiene
::SyntaxContext
;
41 use syntax
::symbol
::{Symbol, keywords}
;
42 use syntax
::tokenstream
::TokenStream
;
43 use syntax
::util
::ThinVec
;
46 use rustc_data_structures
::indexed_vec
;
48 use serialize
::{self, Encoder, Encodable, Decoder, Decodable}
;
49 use std
::collections
::BTreeMap
;
52 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
53 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
54 /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead
55 /// of `Vec` to avoid keeping extra capacity.
56 pub type HirVec
<T
> = P
<[T
]>;
58 macro_rules
! hir_vec
{
59 ($elem
:expr
; $n
:expr
) => (
60 $
crate::hir
::HirVec
::from(vec
![$elem
; $n
])
63 $
crate::hir
::HirVec
::from(vec
![$
($x
),*])
65 ($
($x
:expr
,)*) => (hir_vec
![$
($x
),*])
72 pub mod itemlikevisit
;
79 /// A HirId uniquely identifies a node in the HIR of the current crate. It is
80 /// composed of the `owner`, which is the DefIndex of the directly enclosing
81 /// hir::Item, hir::TraitItem, or hir::ImplItem (i.e. the closest "item-like"),
82 /// and the `local_id` which is unique within the given owner.
84 /// This two-level structure makes for more stable values: One can move an item
85 /// around within the source code, or add or remove stuff before it, without
86 /// the local_id part of the HirId changing, which is a very useful property in
87 /// incremental compilation where we have to persist things through changes to
89 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
92 pub local_id
: ItemLocalId
,
95 impl serialize
::UseSpecializedEncodable
for HirId
{
96 fn default_encode
<S
: Encoder
>(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
107 impl serialize
::UseSpecializedDecodable
for HirId
{
108 fn default_decode
<D
: Decoder
>(d
: &mut D
) -> Result
<HirId
, D
::Error
> {
109 let owner
= DefIndex
::decode(d
)?
;
110 let local_id
= ItemLocalId
::decode(d
)?
;
120 /// An `ItemLocalId` uniquely identifies something within a given "item-like",
121 /// that is within a hir::Item, hir::TraitItem, or hir::ImplItem. There is no
122 /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
123 /// the node's position within the owning item in any way, but there is a
124 /// guarantee that the `LocalItemId`s within an owner occupy a dense range of
125 /// integers starting at zero, so a mapping that maps all or most nodes within
126 /// an "item-like" to something else can be implement by a `Vec` instead of a
127 /// tree or hash map.
128 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug,
129 RustcEncodable
, RustcDecodable
)]
130 pub struct ItemLocalId(pub u32);
133 pub fn as_usize(&self) -> usize {
138 impl indexed_vec
::Idx
for ItemLocalId
{
139 fn new(idx
: usize) -> Self {
140 debug_assert
!((idx
as u32) as usize == idx
);
141 ItemLocalId(idx
as u32)
144 fn index(self) -> usize {
149 /// The `HirId` corresponding to CRATE_NODE_ID and CRATE_DEF_INDEX
150 pub const CRATE_HIR_ID
: HirId
= HirId
{
151 owner
: CRATE_DEF_INDEX
,
152 local_id
: ItemLocalId(0)
155 pub const DUMMY_HIR_ID
: HirId
= HirId
{
156 owner
: CRATE_DEF_INDEX
,
157 local_id
: DUMMY_ITEM_LOCAL_ID
,
160 pub const DUMMY_ITEM_LOCAL_ID
: ItemLocalId
= ItemLocalId(!0);
162 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
163 pub struct Lifetime
{
167 /// Either "'a", referring to a named lifetime definition,
168 /// or "" (aka keywords::Invalid), for elision placeholders.
170 /// HIR lowering inserts these placeholders in type paths that
171 /// refer to type definitions needing lifetime parameters,
172 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
173 pub name
: LifetimeName
,
176 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
177 pub enum LifetimeName
{
185 pub fn name(&self) -> Name
{
186 use self::LifetimeName
::*;
188 Implicit
=> keywords
::Invalid
.name(),
189 Underscore
=> Symbol
::intern("'_"),
190 Static
=> keywords
::StaticLifetime
.name(),
196 impl fmt
::Debug
for Lifetime
{
197 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
201 print
::to_string(print
::NO_ANN
, |s
| s
.print_lifetime(self)))
206 pub fn is_elided(&self) -> bool
{
207 use self::LifetimeName
::*;
209 Implicit
| Underscore
=> true,
210 Static
| Name(_
) => false,
214 pub fn is_static(&self) -> bool
{
215 self.name
== LifetimeName
::Static
219 /// A lifetime definition, eg `'a: 'b+'c+'d`
220 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
221 pub struct LifetimeDef
{
222 pub lifetime
: Lifetime
,
223 pub bounds
: HirVec
<Lifetime
>,
224 pub pure_wrt_drop
: bool
,
227 /// A "Path" is essentially Rust's notion of a name; for instance:
228 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
229 /// along with a bunch of supporting information.
230 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
233 /// The definition that the path resolved to.
235 /// The segments in the path: the things separated by `::`.
236 pub segments
: HirVec
<PathSegment
>,
240 pub fn is_global(&self) -> bool
{
241 !self.segments
.is_empty() && self.segments
[0].name
== keywords
::CrateRoot
.name()
245 impl fmt
::Debug
for Path
{
246 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
247 write
!(f
, "path({})",
248 print
::to_string(print
::NO_ANN
, |s
| s
.print_path(self, false)))
252 /// A segment of a path: an identifier, an optional lifetime, and a set of
254 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
255 pub struct PathSegment
{
256 /// The identifier portion of this path segment.
259 /// Type/lifetime parameters attached to this path. They come in
260 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
261 /// this is more than just simple syntactic sugar; the use of
262 /// parens affects the region binding rules, so we preserve the
264 pub parameters
: Option
<P
<PathParameters
>>,
266 /// Whether to infer remaining type parameters, if any.
267 /// This only applies to expression and pattern paths, and
268 /// out of those only the segments with no type parameters
269 /// to begin with, e.g. `Vec::new` is `<Vec<..>>::new::<..>`.
270 pub infer_types
: bool
,
274 /// Convert an identifier to the corresponding segment.
275 pub fn from_name(name
: Name
) -> PathSegment
{
283 pub fn new(name
: Name
, parameters
: PathParameters
, infer_types
: bool
) -> Self {
287 parameters
: if parameters
.is_empty() {
295 // FIXME: hack required because you can't create a static
296 // PathParameters, so you can't just return a &PathParameters.
297 pub fn with_parameters
<F
, R
>(&self, f
: F
) -> R
298 where F
: FnOnce(&PathParameters
) -> R
300 let dummy
= PathParameters
::none();
301 f(if let Some(ref params
) = self.parameters
{
309 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
310 pub struct PathParameters
{
311 /// The lifetime parameters for this path segment.
312 pub lifetimes
: HirVec
<Lifetime
>,
313 /// The type parameters for this path segment, if present.
314 pub types
: HirVec
<P
<Ty
>>,
315 /// Bindings (equality constraints) on associated types, if present.
316 /// E.g., `Foo<A=Bar>`.
317 pub bindings
: HirVec
<TypeBinding
>,
318 /// Were parameters written in parenthesized form `Fn(T) -> U`?
319 /// This is required mostly for pretty-printing and diagnostics,
320 /// but also for changing lifetime elision rules to be "function-like".
321 pub parenthesized
: bool
,
324 impl PathParameters
{
325 pub fn none() -> Self {
327 lifetimes
: HirVec
::new(),
328 types
: HirVec
::new(),
329 bindings
: HirVec
::new(),
330 parenthesized
: false,
334 pub fn is_empty(&self) -> bool
{
335 self.lifetimes
.is_empty() && self.types
.is_empty() &&
336 self.bindings
.is_empty() && !self.parenthesized
339 pub fn inputs(&self) -> &[P
<Ty
>] {
340 if self.parenthesized
{
341 if let Some(ref ty
) = self.types
.get(0) {
342 if let TyTup(ref tys
) = ty
.node
{
347 bug
!("PathParameters::inputs: not a `Fn(T) -> U`");
351 /// The AST represents all type param bounds as types.
352 /// typeck::collect::compute_bounds matches these against
353 /// the "special" built-in traits (see middle::lang_items) and
354 /// detects Copy, Send and Sync.
355 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
356 pub enum TyParamBound
{
357 TraitTyParamBound(PolyTraitRef
, TraitBoundModifier
),
358 RegionTyParamBound(Lifetime
),
361 /// A modifier on a bound, currently this is only used for `?Sized`, where the
362 /// modifier is `Maybe`. Negative bounds should also be handled here.
363 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
364 pub enum TraitBoundModifier
{
369 pub type TyParamBounds
= HirVec
<TyParamBound
>;
371 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
375 pub bounds
: TyParamBounds
,
376 pub default: Option
<P
<Ty
>>,
378 pub pure_wrt_drop
: bool
,
379 pub synthetic
: Option
<SyntheticTyParamKind
>,
382 /// Represents lifetimes and type parameters attached to a declaration
383 /// of a function, enum, trait, etc.
384 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
385 pub struct Generics
{
386 pub lifetimes
: HirVec
<LifetimeDef
>,
387 pub ty_params
: HirVec
<TyParam
>,
388 pub where_clause
: WhereClause
,
393 pub fn empty() -> Generics
{
395 lifetimes
: HirVec
::new(),
396 ty_params
: HirVec
::new(),
397 where_clause
: WhereClause
{
399 predicates
: HirVec
::new(),
405 pub fn is_lt_parameterized(&self) -> bool
{
406 !self.lifetimes
.is_empty()
409 pub fn is_type_parameterized(&self) -> bool
{
410 !self.ty_params
.is_empty()
413 pub fn is_parameterized(&self) -> bool
{
414 self.is_lt_parameterized() || self.is_type_parameterized()
418 pub enum UnsafeGeneric
{
419 Region(LifetimeDef
, &'
static str),
420 Type(TyParam
, &'
static str),
424 pub fn attr_name(&self) -> &'
static str {
426 UnsafeGeneric
::Region(_
, s
) => s
,
427 UnsafeGeneric
::Type(_
, s
) => s
,
433 pub fn carries_unsafe_attr(&self) -> Option
<UnsafeGeneric
> {
434 for r
in &self.lifetimes
{
436 return Some(UnsafeGeneric
::Region(r
.clone(), "may_dangle"));
439 for t
in &self.ty_params
{
441 return Some(UnsafeGeneric
::Type(t
.clone(), "may_dangle"));
448 /// Synthetic Type Parameters are converted to an other form during lowering, this allows
449 /// to track the original form they had. Usefull for error messages.
450 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
451 pub enum SyntheticTyParamKind
{
455 /// A `where` clause in a definition
456 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
457 pub struct WhereClause
{
459 pub predicates
: HirVec
<WherePredicate
>,
462 /// A single predicate in a `where` clause
463 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
464 pub enum WherePredicate
{
465 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
466 BoundPredicate(WhereBoundPredicate
),
467 /// A lifetime predicate, e.g. `'a: 'b+'c`
468 RegionPredicate(WhereRegionPredicate
),
469 /// An equality predicate (unsupported)
470 EqPredicate(WhereEqPredicate
),
473 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
474 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
475 pub struct WhereBoundPredicate
{
477 /// Any lifetimes from a `for` binding
478 pub bound_lifetimes
: HirVec
<LifetimeDef
>,
479 /// The type being bounded
480 pub bounded_ty
: P
<Ty
>,
481 /// Trait and lifetime bounds (`Clone+Send+'static`)
482 pub bounds
: TyParamBounds
,
485 /// A lifetime predicate, e.g. `'a: 'b+'c`
486 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
487 pub struct WhereRegionPredicate
{
489 pub lifetime
: Lifetime
,
490 pub bounds
: HirVec
<Lifetime
>,
493 /// An equality predicate (unsupported), e.g. `T=int`
494 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
495 pub struct WhereEqPredicate
{
502 pub type CrateConfig
= HirVec
<P
<MetaItem
>>;
504 /// The top-level data structure that stores the entire contents of
505 /// the crate currently being compiled.
507 /// For more details, see [the module-level README](README.md).
508 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
511 pub attrs
: HirVec
<Attribute
>,
513 pub exported_macros
: HirVec
<MacroDef
>,
515 // NB: We use a BTreeMap here so that `visit_all_items` iterates
516 // over the ids in increasing order. In principle it should not
517 // matter what order we visit things in, but in *practice* it
518 // does, because it can affect the order in which errors are
519 // detected, which in turn can make compile-fail tests yield
520 // slightly different results.
521 pub items
: BTreeMap
<NodeId
, Item
>,
523 pub trait_items
: BTreeMap
<TraitItemId
, TraitItem
>,
524 pub impl_items
: BTreeMap
<ImplItemId
, ImplItem
>,
525 pub bodies
: BTreeMap
<BodyId
, Body
>,
526 pub trait_impls
: BTreeMap
<DefId
, Vec
<NodeId
>>,
527 pub trait_auto_impl
: BTreeMap
<DefId
, NodeId
>,
529 /// A list of the body ids written out in the order in which they
530 /// appear in the crate. If you're going to process all the bodies
531 /// in the crate, you should iterate over this list rather than the keys
533 pub body_ids
: Vec
<BodyId
>,
537 pub fn item(&self, id
: NodeId
) -> &Item
{
541 pub fn trait_item(&self, id
: TraitItemId
) -> &TraitItem
{
542 &self.trait_items
[&id
]
545 pub fn impl_item(&self, id
: ImplItemId
) -> &ImplItem
{
546 &self.impl_items
[&id
]
549 /// Visits all items in the crate in some deterministic (but
550 /// unspecified) order. If you just need to process every item,
551 /// but don't care about nesting, this method is the best choice.
553 /// If you do care about nesting -- usually because your algorithm
554 /// follows lexical scoping rules -- then you want a different
555 /// approach. You should override `visit_nested_item` in your
556 /// visitor and then call `intravisit::walk_crate` instead.
557 pub fn visit_all_item_likes
<'hir
, V
>(&'hir
self, visitor
: &mut V
)
558 where V
: itemlikevisit
::ItemLikeVisitor
<'hir
>
560 for (_
, item
) in &self.items
{
561 visitor
.visit_item(item
);
564 for (_
, trait_item
) in &self.trait_items
{
565 visitor
.visit_trait_item(trait_item
);
568 for (_
, impl_item
) in &self.impl_items
{
569 visitor
.visit_impl_item(impl_item
);
573 pub fn body(&self, id
: BodyId
) -> &Body
{
578 /// A macro definition, in this crate or imported from another.
580 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
581 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
582 pub struct MacroDef
{
585 pub attrs
: HirVec
<Attribute
>,
588 pub body
: TokenStream
,
592 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
594 /// Statements in a block
595 pub stmts
: HirVec
<Stmt
>,
596 /// An expression at the end of the block
597 /// without a semicolon, if any
598 pub expr
: Option
<P
<Expr
>>,
601 /// Distinguishes between `unsafe { ... }` and `{ ... }`
602 pub rules
: BlockCheckMode
,
604 /// If true, then there may exist `break 'a` values that aim to
605 /// break out of this block early. As of this writing, this is not
606 /// currently permitted in Rust itself, but it is generated as
607 /// part of `catch` statements.
608 pub targeted_by_break
: bool
,
611 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
619 impl fmt
::Debug
for Pat
{
620 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
621 write
!(f
, "pat({}: {})", self.id
,
622 print
::to_string(print
::NO_ANN
, |s
| s
.print_pat(self)))
627 // FIXME(#19596) this is a workaround, but there should be a better way
628 fn walk_
<G
>(&self, it
: &mut G
) -> bool
629 where G
: FnMut(&Pat
) -> bool
636 PatKind
::Binding(.., Some(ref p
)) => p
.walk_(it
),
637 PatKind
::Struct(_
, ref fields
, _
) => {
638 fields
.iter().all(|field
| field
.node
.pat
.walk_(it
))
640 PatKind
::TupleStruct(_
, ref s
, _
) | PatKind
::Tuple(ref s
, _
) => {
641 s
.iter().all(|p
| p
.walk_(it
))
643 PatKind
::Box(ref s
) | PatKind
::Ref(ref s
, _
) => {
646 PatKind
::Slice(ref before
, ref slice
, ref after
) => {
647 before
.iter().all(|p
| p
.walk_(it
)) &&
648 slice
.iter().all(|p
| p
.walk_(it
)) &&
649 after
.iter().all(|p
| p
.walk_(it
))
654 PatKind
::Binding(..) |
655 PatKind
::Path(_
) => {
661 pub fn walk
<F
>(&self, mut it
: F
) -> bool
662 where F
: FnMut(&Pat
) -> bool
668 /// A single field in a struct pattern
670 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
671 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
672 /// except is_shorthand is true
673 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
674 pub struct FieldPat
{
675 /// The identifier for the field
677 /// The pattern the field is destructured to
679 pub is_shorthand
: bool
,
682 /// Explicit binding annotations given in the HIR for a binding. Note
683 /// that this is not the final binding *mode* that we infer after type
685 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
686 pub enum BindingAnnotation
{
687 /// No binding annotation given: this means that the final binding mode
688 /// will depend on whether we have skipped through a `&` reference
689 /// when matching. For example, the `x` in `Some(x)` will have binding
690 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
691 /// ultimately be inferred to be by-reference.
693 /// Note that implicit reference skipping is not implemented yet (#42640).
696 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
699 /// Annotated as `ref`, like `ref x`
702 /// Annotated as `ref mut x`.
706 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
712 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
714 /// Represents a wildcard pattern (`_`)
717 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
718 /// The `NodeId` is the canonical ID for the variable being bound,
719 /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID,
720 /// which is the pattern ID of the first `x`.
721 Binding(BindingAnnotation
, NodeId
, Spanned
<Name
>, Option
<P
<Pat
>>),
723 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
724 /// The `bool` is `true` in the presence of a `..`.
725 Struct(QPath
, HirVec
<Spanned
<FieldPat
>>, bool
),
727 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
728 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
729 /// 0 <= position <= subpats.len()
730 TupleStruct(QPath
, HirVec
<P
<Pat
>>, Option
<usize>),
732 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
735 /// A tuple pattern `(a, b)`.
736 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
737 /// 0 <= position <= subpats.len()
738 Tuple(HirVec
<P
<Pat
>>, Option
<usize>),
741 /// A reference pattern, e.g. `&mut (a, b)`
742 Ref(P
<Pat
>, Mutability
),
745 /// A range pattern, e.g. `1...2` or `1..2`
746 Range(P
<Expr
>, P
<Expr
>, RangeEnd
),
747 /// `[a, b, ..i, y, z]` is represented as:
748 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
749 Slice(HirVec
<P
<Pat
>>, Option
<P
<Pat
>>, HirVec
<P
<Pat
>>),
752 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
753 pub enum Mutability
{
759 /// Return MutMutable only if both arguments are mutable.
760 pub fn and(self, other
: Self) -> Self {
763 MutImmutable
=> MutImmutable
,
768 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
770 /// The `+` operator (addition)
772 /// The `-` operator (subtraction)
774 /// The `*` operator (multiplication)
776 /// The `/` operator (division)
778 /// The `%` operator (modulus)
780 /// The `&&` operator (logical and)
782 /// The `||` operator (logical or)
784 /// The `^` operator (bitwise xor)
786 /// The `&` operator (bitwise and)
788 /// The `|` operator (bitwise or)
790 /// The `<<` operator (shift left)
792 /// The `>>` operator (shift right)
794 /// The `==` operator (equality)
796 /// The `<` operator (less than)
798 /// The `<=` operator (less than or equal to)
800 /// The `!=` operator (not equal to)
802 /// The `>=` operator (greater than or equal to)
804 /// The `>` operator (greater than)
809 pub fn as_str(self) -> &'
static str {
832 pub fn is_lazy(self) -> bool
{
834 BiAnd
| BiOr
=> true,
839 pub fn is_shift(self) -> bool
{
841 BiShl
| BiShr
=> true,
846 pub fn is_comparison(self) -> bool
{
848 BiEq
| BiLt
| BiLe
| BiNe
| BiGt
| BiGe
=> true,
864 /// Returns `true` if the binary operator takes its arguments by value
865 pub fn is_by_value(self) -> bool
{
866 !self.is_comparison()
870 pub type BinOp
= Spanned
<BinOp_
>;
872 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
874 /// The `*` operator for dereferencing
876 /// The `!` operator for logical inversion
878 /// The `-` operator for negation
883 pub fn as_str(self) -> &'
static str {
891 /// Returns `true` if the unary operator takes its argument by value
892 pub fn is_by_value(self) -> bool
{
894 UnNeg
| UnNot
=> true,
901 pub type Stmt
= Spanned
<Stmt_
>;
903 impl fmt
::Debug
for Stmt_
{
904 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
906 let spanned
= codemap
::dummy_spanned(self.clone());
910 print
::to_string(print
::NO_ANN
, |s
| s
.print_stmt(&spanned
)))
914 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
916 /// Could be an item or a local (let) binding:
917 StmtDecl(P
<Decl
>, NodeId
),
919 /// Expr without trailing semi-colon (must have unit type):
920 StmtExpr(P
<Expr
>, NodeId
),
922 /// Expr with trailing semi-colon (may have any type):
923 StmtSemi(P
<Expr
>, NodeId
),
927 pub fn attrs(&self) -> &[Attribute
] {
929 StmtDecl(ref d
, _
) => d
.node
.attrs(),
931 StmtSemi(ref e
, _
) => &e
.attrs
,
935 pub fn id(&self) -> NodeId
{
937 StmtDecl(_
, id
) => id
,
938 StmtExpr(_
, id
) => id
,
939 StmtSemi(_
, id
) => id
,
944 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
945 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
948 pub ty
: Option
<P
<Ty
>>,
949 /// Initializer expression to set the value, if any
950 pub init
: Option
<P
<Expr
>>,
954 pub attrs
: ThinVec
<Attribute
>,
955 pub source
: LocalSource
,
958 pub type Decl
= Spanned
<Decl_
>;
960 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
962 /// A local (let) binding:
969 pub fn attrs(&self) -> &[Attribute
] {
971 DeclLocal(ref l
) => &l
.attrs
,
976 pub fn is_local(&self) -> bool
{
978 Decl_
::DeclLocal(_
) => true,
984 /// represents one arm of a 'match'
985 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
987 pub attrs
: HirVec
<Attribute
>,
988 pub pats
: HirVec
<P
<Pat
>>,
989 pub guard
: Option
<P
<Expr
>>,
993 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
995 pub name
: Spanned
<Name
>,
998 pub is_shorthand
: bool
,
1001 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1002 pub enum BlockCheckMode
{
1004 UnsafeBlock(UnsafeSource
),
1005 PushUnsafeBlock(UnsafeSource
),
1006 PopUnsafeBlock(UnsafeSource
),
1009 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1010 pub enum UnsafeSource
{
1015 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1017 pub node_id
: NodeId
,
1020 /// The body of a function, closure, or constant value. In the case of
1021 /// a function, the body contains not only the function body itself
1022 /// (which is an expression), but also the argument patterns, since
1023 /// those are something that the caller doesn't really care about.
1028 /// fn foo((x, y): (u32, u32)) -> u32 {
1033 /// Here, the `Body` associated with `foo()` would contain:
1035 /// - an `arguments` array containing the `(x, y)` pattern
1036 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1037 /// - `is_generator` would be false
1039 /// All bodies have an **owner**, which can be accessed via the HIR
1040 /// map using `body_owner_def_id()`.
1041 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1043 pub arguments
: HirVec
<Arg
>,
1045 pub is_generator
: bool
,
1049 pub fn id(&self) -> BodyId
{
1051 node_id
: self.value
.id
1056 #[derive(Copy, Clone, Debug)]
1057 pub enum BodyOwnerKind
{
1058 /// Functions and methods.
1061 /// Constants and associated constants.
1064 /// Initializer of a `static` item.
1069 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1074 pub attrs
: ThinVec
<Attribute
>,
1078 impl fmt
::Debug
for Expr
{
1079 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1080 write
!(f
, "expr({}: {})", self.id
,
1081 print
::to_string(print
::NO_ANN
, |s
| s
.print_expr(self)))
1085 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1087 /// A `box x` expression.
1089 /// An array (`[a, b, c, d]`)
1090 ExprArray(HirVec
<Expr
>),
1093 /// The first field resolves to the function itself (usually an `ExprPath`),
1094 /// and the second field is the list of arguments.
1095 /// This also represents calling the constructor of
1096 /// tuple-like ADTs such as tuple structs and enum variants.
1097 ExprCall(P
<Expr
>, HirVec
<Expr
>),
1098 /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1100 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1101 /// (within the angle brackets).
1102 /// The first element of the vector of `Expr`s is the expression that evaluates
1103 /// to the object on which the method is being called on (the receiver),
1104 /// and the remaining elements are the rest of the arguments.
1105 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1106 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1107 ExprMethodCall(PathSegment
, Span
, HirVec
<Expr
>),
1108 /// A tuple (`(a, b, c ,d)`)
1109 ExprTup(HirVec
<Expr
>),
1110 /// A binary operation (For example: `a + b`, `a * b`)
1111 ExprBinary(BinOp
, P
<Expr
>, P
<Expr
>),
1112 /// A unary operation (For example: `!x`, `*x`)
1113 ExprUnary(UnOp
, P
<Expr
>),
1114 /// A literal (For example: `1`, `"foo"`)
1116 /// A cast (`foo as f64`)
1117 ExprCast(P
<Expr
>, P
<Ty
>),
1118 ExprType(P
<Expr
>, P
<Ty
>),
1119 /// An `if` block, with an optional else block
1121 /// `if expr { expr } else { expr }`
1122 ExprIf(P
<Expr
>, P
<Expr
>, Option
<P
<Expr
>>),
1123 /// A while loop, with an optional label
1125 /// `'label: while expr { block }`
1126 ExprWhile(P
<Expr
>, P
<Block
>, Option
<Spanned
<Name
>>),
1127 /// Conditionless loop (can be exited with break, continue, or return)
1129 /// `'label: loop { block }`
1130 ExprLoop(P
<Block
>, Option
<Spanned
<Name
>>, LoopSource
),
1131 /// A `match` block, with a source that indicates whether or not it is
1132 /// the result of a desugaring, and if so, which kind.
1133 ExprMatch(P
<Expr
>, HirVec
<Arm
>, MatchSource
),
1134 /// A closure (for example, `move |a, b, c| {a + b + c}`).
1136 /// The final span is the span of the argument block `|...|`
1138 /// This may also be a generator literal, indicated by the final boolean,
1139 /// in that case there is an GeneratorClause.
1140 ExprClosure(CaptureClause
, P
<FnDecl
>, BodyId
, Span
, bool
),
1141 /// A block (`{ ... }`)
1142 ExprBlock(P
<Block
>),
1144 /// An assignment (`a = foo()`)
1145 ExprAssign(P
<Expr
>, P
<Expr
>),
1146 /// An assignment with an operator
1148 /// For example, `a += 1`.
1149 ExprAssignOp(BinOp
, P
<Expr
>, P
<Expr
>),
1150 /// Access of a named struct field (`obj.foo`)
1151 ExprField(P
<Expr
>, Spanned
<Name
>),
1152 /// Access of an unnamed field of a struct or tuple-struct
1154 /// For example, `foo.0`.
1155 ExprTupField(P
<Expr
>, Spanned
<usize>),
1156 /// An indexing operation (`foo[2]`)
1157 ExprIndex(P
<Expr
>, P
<Expr
>),
1159 /// Path to a definition, possibly containing lifetime or type parameters.
1162 /// A referencing operation (`&a` or `&mut a`)
1163 ExprAddrOf(Mutability
, P
<Expr
>),
1164 /// A `break`, with an optional label to break
1165 ExprBreak(Destination
, Option
<P
<Expr
>>),
1166 /// A `continue`, with an optional label
1167 ExprAgain(Destination
),
1168 /// A `return`, with an optional value to be returned
1169 ExprRet(Option
<P
<Expr
>>),
1171 /// Inline assembly (from `asm!`), with its outputs and inputs.
1172 ExprInlineAsm(P
<InlineAsm
>, HirVec
<Expr
>, HirVec
<Expr
>),
1174 /// A struct or struct-like variant literal expression.
1176 /// For example, `Foo {x: 1, y: 2}`, or
1177 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
1178 ExprStruct(QPath
, HirVec
<Field
>, Option
<P
<Expr
>>),
1180 /// An array literal constructed from one repeated element.
1182 /// For example, `[1; 5]`. The first expression is the element
1183 /// to be repeated; the second is the number of times to repeat it.
1184 ExprRepeat(P
<Expr
>, BodyId
),
1186 /// A suspension point for generators. This is `yield <expr>` in Rust.
1190 /// Optionally `Self`-qualified value/type path or associated extension.
1191 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1193 /// Path to a definition, optionally "fully-qualified" with a `Self`
1194 /// type, if the path points to an associated item in a trait.
1196 /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`,
1197 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1198 /// even though they both have the same two-segment `Clone::clone` `Path`.
1199 Resolved(Option
<P
<Ty
>>, P
<Path
>),
1201 /// Type-related paths, e.g. `<T>::default` or `<T>::Output`.
1202 /// Will be resolved by type-checking to an associated item.
1204 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1205 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1206 /// the `X` and `Y` nodes each being a `TyPath(QPath::TypeRelative(..))`.
1207 TypeRelative(P
<Ty
>, P
<PathSegment
>)
1210 /// Hints at the original code for a let statement
1211 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1212 pub enum LocalSource
{
1213 /// A `match _ { .. }`
1215 /// A desugared `for _ in _ { .. }` loop
1219 /// Hints at the original code for a `match _ { .. }`
1220 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1221 pub enum MatchSource
{
1222 /// A `match _ { .. }`
1224 /// An `if let _ = _ { .. }` (optionally with `else { .. }`)
1226 contains_else_clause
: bool
,
1228 /// A `while let _ = _ { .. }` (which was desugared to a
1229 /// `loop { match _ { .. } }`)
1231 /// A desugared `for _ in _ { .. }` loop
1233 /// A desugared `?` operator
1237 /// The loop type that yielded an ExprLoop
1238 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1239 pub enum LoopSource
{
1240 /// A `loop { .. }` loop
1242 /// A `while let _ = _ { .. }` loop
1244 /// A `for _ in _ { .. }` loop
1248 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1249 pub enum LoopIdError
{
1251 UnlabeledCfInWhileCondition
,
1255 impl fmt
::Display
for LoopIdError
{
1256 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1257 fmt
::Display
::fmt(match *self {
1258 LoopIdError
::OutsideLoopScope
=> "not inside loop scope",
1259 LoopIdError
::UnlabeledCfInWhileCondition
=>
1260 "unlabeled control flow (break or continue) in while condition",
1261 LoopIdError
::UnresolvedLabel
=> "label not found",
1266 // FIXME(cramertj) this should use `Result` once master compiles w/ a vesion of Rust where
1267 // `Result` implements `Encodable`/`Decodable`
1268 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1269 pub enum LoopIdResult
{
1273 impl Into
<Result
<NodeId
, LoopIdError
>> for LoopIdResult
{
1274 fn into(self) -> Result
<NodeId
, LoopIdError
> {
1276 LoopIdResult
::Ok(ok
) => Ok(ok
),
1277 LoopIdResult
::Err(err
) => Err(err
),
1281 impl From
<Result
<NodeId
, LoopIdError
>> for LoopIdResult
{
1282 fn from(res
: Result
<NodeId
, LoopIdError
>) -> Self {
1284 Ok(ok
) => LoopIdResult
::Ok(ok
),
1285 Err(err
) => LoopIdResult
::Err(err
),
1290 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1291 pub enum ScopeTarget
{
1297 pub fn opt_id(self) -> Option
<NodeId
> {
1299 ScopeTarget
::Block(node_id
) |
1300 ScopeTarget
::Loop(LoopIdResult
::Ok(node_id
)) => Some(node_id
),
1301 ScopeTarget
::Loop(LoopIdResult
::Err(_
)) => None
,
1306 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1307 pub struct Destination
{
1308 // This is `Some(_)` iff there is an explicit user-specified `label
1309 pub ident
: Option
<Spanned
<Ident
>>,
1311 // These errors are caught and then reported during the diagnostics pass in
1312 // librustc_passes/loops.rs
1313 pub target_id
: ScopeTarget
,
1316 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1317 pub enum CaptureClause
{
1322 // NB: If you change this, you'll probably want to change the corresponding
1323 // type structure in middle/ty.rs as well.
1324 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1327 pub mutbl
: Mutability
,
1330 /// Represents a method's signature in a trait declaration or implementation.
1331 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1332 pub struct MethodSig
{
1333 pub unsafety
: Unsafety
,
1334 pub constness
: Constness
,
1336 pub decl
: P
<FnDecl
>,
1339 // The bodies for items are stored "out of line", in a separate
1340 // hashmap in the `Crate`. Here we just record the node-id of the item
1341 // so it can fetched later.
1342 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1343 pub struct TraitItemId
{
1344 pub node_id
: NodeId
,
1347 /// Represents an item declaration within a trait declaration,
1348 /// possibly including a default implementation. A trait item is
1349 /// either required (meaning it doesn't have an implementation, just a
1350 /// signature) or provided (meaning it has a default implementation).
1351 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1352 pub struct TraitItem
{
1356 pub attrs
: HirVec
<Attribute
>,
1357 pub generics
: Generics
,
1358 pub node
: TraitItemKind
,
1362 /// A trait method's body (or just argument names).
1363 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1364 pub enum TraitMethod
{
1365 /// No default body in the trait, just a signature.
1366 Required(HirVec
<Spanned
<Name
>>),
1368 /// Both signature and body are provided in the trait.
1372 /// Represents a trait method or associated constant or type
1373 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1374 pub enum TraitItemKind
{
1375 /// An associated constant with an optional value (otherwise `impl`s
1376 /// must contain a value)
1377 Const(P
<Ty
>, Option
<BodyId
>),
1378 /// A method with an optional body
1379 Method(MethodSig
, TraitMethod
),
1380 /// An associated type with (possibly empty) bounds and optional concrete
1382 Type(TyParamBounds
, Option
<P
<Ty
>>),
1385 // The bodies for items are stored "out of line", in a separate
1386 // hashmap in the `Crate`. Here we just record the node-id of the item
1387 // so it can fetched later.
1388 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash, Debug)]
1389 pub struct ImplItemId
{
1390 pub node_id
: NodeId
,
1393 /// Represents anything within an `impl` block
1394 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1395 pub struct ImplItem
{
1399 pub vis
: Visibility
,
1400 pub defaultness
: Defaultness
,
1401 pub attrs
: HirVec
<Attribute
>,
1402 pub generics
: Generics
,
1403 pub node
: ImplItemKind
,
1407 /// Represents different contents within `impl`s
1408 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1409 pub enum ImplItemKind
{
1410 /// An associated constant of the given type, set to the constant result
1411 /// of the expression
1412 Const(P
<Ty
>, BodyId
),
1413 /// A method implementation with the given signature and body
1414 Method(MethodSig
, BodyId
),
1415 /// An associated type
1419 // Bind a type to an associated type: `A=Foo`.
1420 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1421 pub struct TypeBinding
{
1429 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1437 impl fmt
::Debug
for Ty
{
1438 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1439 write
!(f
, "type({})",
1440 print
::to_string(print
::NO_ANN
, |s
| s
.print_type(self)))
1444 /// Not represented directly in the AST, referred to by name through a ty_path.
1445 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1455 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1456 pub struct BareFnTy
{
1457 pub unsafety
: Unsafety
,
1459 pub lifetimes
: HirVec
<LifetimeDef
>,
1460 pub decl
: P
<FnDecl
>,
1461 pub arg_names
: HirVec
<Spanned
<Name
>>,
1464 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1465 /// The different kinds of types recognized by the compiler
1467 /// A variable length slice (`[T]`)
1469 /// A fixed length array (`[T; n]`)
1470 TyArray(P
<Ty
>, BodyId
),
1471 /// A raw pointer (`*const T` or `*mut T`)
1473 /// A reference (`&'a T` or `&'a mut T`)
1474 TyRptr(Lifetime
, MutTy
),
1475 /// A bare function (e.g. `fn(usize) -> bool`)
1476 TyBareFn(P
<BareFnTy
>),
1477 /// The never type (`!`)
1479 /// A tuple (`(A, B, C, D,...)`)
1480 TyTup(HirVec
<P
<Ty
>>),
1481 /// A path to a type definition (`module::module::...::Type`), or an
1482 /// associated type, e.g. `<Vec<T> as Trait>::Type` or `<T>::Target`.
1484 /// Type parameters may be stored in each `PathSegment`.
1486 /// A trait object type `Bound1 + Bound2 + Bound3`
1487 /// where `Bound` is a trait or a lifetime.
1488 TyTraitObject(HirVec
<PolyTraitRef
>, Lifetime
),
1489 /// An exsitentially quantified (there exists a type satisfying) `impl
1490 /// Bound1 + Bound2 + Bound3` type where `Bound` is a trait or a lifetime.
1491 TyImplTraitExistential(TyParamBounds
),
1492 /// An universally quantified (for all types satisfying) `impl
1493 /// Bound1 + Bound2 + Bound3` type where `Bound` is a trait or a lifetime.
1494 TyImplTraitUniversal(DefId
, TyParamBounds
),
1497 /// TyInfer means the type should be inferred instead of it having been
1498 /// specified. This can appear anywhere in a type.
1500 /// Placeholder for a type that has failed to be defined.
1504 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1505 pub struct InlineAsmOutput
{
1506 pub constraint
: Symbol
,
1508 pub is_indirect
: bool
,
1511 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1512 pub struct InlineAsm
{
1514 pub asm_str_style
: StrStyle
,
1515 pub outputs
: HirVec
<InlineAsmOutput
>,
1516 pub inputs
: HirVec
<Symbol
>,
1517 pub clobbers
: HirVec
<Symbol
>,
1519 pub alignstack
: bool
,
1520 pub dialect
: AsmDialect
,
1521 pub ctxt
: SyntaxContext
,
1524 /// represents an argument in a function header
1525 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1532 /// Represents the header (not the body) of a function declaration
1533 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1535 pub inputs
: HirVec
<P
<Ty
>>,
1536 pub output
: FunctionRetTy
,
1538 /// True if this function has an `self`, `&self` or `&mut self` receiver
1539 /// (but not a `self: Xxx` one).
1540 pub has_implicit_self
: bool
,
1543 /// Is the trait definition an auto trait?
1544 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1550 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1556 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1557 pub enum Constness
{
1562 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1563 pub enum Defaultness
{
1564 Default { has_value: bool }
,
1569 pub fn has_value(&self) -> bool
{
1571 Defaultness
::Default { has_value, .. }
=> has_value
,
1572 Defaultness
::Final
=> true,
1576 pub fn is_final(&self) -> bool
{
1577 *self == Defaultness
::Final
1580 pub fn is_default(&self) -> bool
{
1582 Defaultness
::Default { .. }
=> true,
1588 impl fmt
::Display
for Unsafety
{
1589 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1590 fmt
::Display
::fmt(match *self {
1591 Unsafety
::Normal
=> "normal",
1592 Unsafety
::Unsafe
=> "unsafe",
1598 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1599 pub enum ImplPolarity
{
1600 /// `impl Trait for Type`
1602 /// `impl !Trait for Type`
1606 impl fmt
::Debug
for ImplPolarity
{
1607 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1609 ImplPolarity
::Positive
=> "positive".fmt(f
),
1610 ImplPolarity
::Negative
=> "negative".fmt(f
),
1616 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1617 pub enum FunctionRetTy
{
1618 /// Return type is not specified.
1620 /// Functions default to `()` and
1621 /// closures default to inference. Span points to where return
1622 /// type would be inserted.
1623 DefaultReturn(Span
),
1628 impl FunctionRetTy
{
1629 pub fn span(&self) -> Span
{
1631 DefaultReturn(span
) => span
,
1632 Return(ref ty
) => ty
.span
,
1637 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1639 /// A span from the first token past `{` to the last token until `}`.
1640 /// For `mod foo;`, the inner span ranges from the first token
1641 /// to the last token in the external file.
1643 pub item_ids
: HirVec
<ItemId
>,
1646 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1647 pub struct ForeignMod
{
1649 pub items
: HirVec
<ForeignItem
>,
1652 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1653 pub struct GlobalAsm
{
1655 pub ctxt
: SyntaxContext
,
1658 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1659 pub struct EnumDef
{
1660 pub variants
: HirVec
<Variant
>,
1663 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1664 pub struct Variant_
{
1666 pub attrs
: HirVec
<Attribute
>,
1667 pub data
: VariantData
,
1668 /// Explicit discriminant, eg `Foo = 1`
1669 pub disr_expr
: Option
<BodyId
>,
1672 pub type Variant
= Spanned
<Variant_
>;
1674 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1676 /// One import, e.g. `use foo::bar` or `use foo::bar as baz`.
1677 /// Also produced for each element of a list `use`, e.g.
1678 // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
1681 /// Glob import, e.g. `use foo::*`.
1684 /// Degenerate list import, e.g. `use foo::{a, b}` produces
1685 /// an additional `use foo::{}` for performing checks such as
1686 /// unstable feature gating. May be removed in the future.
1690 /// TraitRef's appear in impls.
1692 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1693 /// that the ref_id is for. Note that ref_id's value is not the NodeId of the
1694 /// trait being referred to but just a unique NodeId that serves as a key
1695 /// within the DefMap.
1696 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1697 pub struct TraitRef
{
1702 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1703 pub struct PolyTraitRef
{
1704 /// The `'a` in `<'a> Foo<&'a T>`
1705 pub bound_lifetimes
: HirVec
<LifetimeDef
>,
1707 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1708 pub trait_ref
: TraitRef
,
1713 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1714 pub enum Visibility
{
1717 Restricted { path: P<Path>, id: NodeId }
,
1722 pub fn is_pub_restricted(&self) -> bool
{
1723 use self::Visibility
::*;
1726 &Inherited
=> false,
1728 &Restricted { .. }
=> true,
1733 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1734 pub struct StructField
{
1737 pub vis
: Visibility
,
1740 pub attrs
: HirVec
<Attribute
>,
1744 // Still necessary in couple of places
1745 pub fn is_positional(&self) -> bool
{
1746 let first
= self.name
.as_str().as_bytes()[0];
1747 first
>= b'
0'
&& first
<= b'
9'
1751 /// Fields and Ids of enum variants and structs
1753 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1754 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1755 /// One shared Id can be successfully used for these two purposes.
1756 /// Id of the whole enum lives in `Item`.
1758 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1759 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1760 /// the variant itself" from enum variants.
1761 /// Id of the whole struct lives in `Item`.
1762 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1763 pub enum VariantData
{
1764 Struct(HirVec
<StructField
>, NodeId
),
1765 Tuple(HirVec
<StructField
>, NodeId
),
1770 pub fn fields(&self) -> &[StructField
] {
1772 VariantData
::Struct(ref fields
, _
) | VariantData
::Tuple(ref fields
, _
) => fields
,
1776 pub fn id(&self) -> NodeId
{
1778 VariantData
::Struct(_
, id
) | VariantData
::Tuple(_
, id
) | VariantData
::Unit(id
) => id
,
1781 pub fn is_struct(&self) -> bool
{
1782 if let VariantData
::Struct(..) = *self {
1788 pub fn is_tuple(&self) -> bool
{
1789 if let VariantData
::Tuple(..) = *self {
1795 pub fn is_unit(&self) -> bool
{
1796 if let VariantData
::Unit(..) = *self {
1804 // The bodies for items are stored "out of line", in a separate
1805 // hashmap in the `Crate`. Here we just record the node-id of the item
1806 // so it can fetched later.
1807 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1814 /// The name might be a dummy name in case of anonymous items
1815 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1820 pub attrs
: HirVec
<Attribute
>,
1822 pub vis
: Visibility
,
1826 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1828 /// An `extern crate` item, with optional original crate name,
1830 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1831 ItemExternCrate(Option
<Name
>),
1833 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
1837 /// `use foo::bar::baz;` (with `as baz` implicitly on the right)
1838 ItemUse(P
<Path
>, UseKind
),
1841 ItemStatic(P
<Ty
>, Mutability
, BodyId
),
1843 ItemConst(P
<Ty
>, BodyId
),
1844 /// A function declaration
1845 ItemFn(P
<FnDecl
>, Unsafety
, Constness
, Abi
, Generics
, BodyId
),
1848 /// An external module
1849 ItemForeignMod(ForeignMod
),
1850 /// Module-level inline assembly (from global_asm!)
1851 ItemGlobalAsm(P
<GlobalAsm
>),
1852 /// A type alias, e.g. `type Foo = Bar<u8>`
1853 ItemTy(P
<Ty
>, Generics
),
1854 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1855 ItemEnum(EnumDef
, Generics
),
1856 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1857 ItemStruct(VariantData
, Generics
),
1858 /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
1859 ItemUnion(VariantData
, Generics
),
1860 /// Represents a Trait Declaration
1861 ItemTrait(IsAuto
, Unsafety
, Generics
, TyParamBounds
, HirVec
<TraitItemRef
>),
1863 /// Auto trait implementations
1865 /// `impl Trait for .. {}`
1866 ItemAutoImpl(Unsafety
, TraitRef
),
1867 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1872 Option
<TraitRef
>, // (optional) trait this impl implements
1874 HirVec
<ImplItemRef
>),
1878 pub fn descriptive_variant(&self) -> &str {
1880 ItemExternCrate(..) => "extern crate",
1881 ItemUse(..) => "use",
1882 ItemStatic(..) => "static item",
1883 ItemConst(..) => "constant item",
1884 ItemFn(..) => "function",
1885 ItemMod(..) => "module",
1886 ItemForeignMod(..) => "foreign module",
1887 ItemGlobalAsm(..) => "global asm",
1888 ItemTy(..) => "type alias",
1889 ItemEnum(..) => "enum",
1890 ItemStruct(..) => "struct",
1891 ItemUnion(..) => "union",
1892 ItemTrait(..) => "trait",
1894 ItemAutoImpl(..) => "item",
1898 pub fn adt_kind(&self) -> Option
<AdtKind
> {
1900 ItemStruct(..) => Some(AdtKind
::Struct
),
1901 ItemUnion(..) => Some(AdtKind
::Union
),
1902 ItemEnum(..) => Some(AdtKind
::Enum
),
1907 pub fn generics(&self) -> Option
<&Generics
> {
1909 ItemFn(_
, _
, _
, _
, ref generics
, _
) |
1910 ItemTy(_
, ref generics
) |
1911 ItemEnum(_
, ref generics
) |
1912 ItemStruct(_
, ref generics
) |
1913 ItemUnion(_
, ref generics
) |
1914 ItemTrait(_
, _
, ref generics
, _
, _
) |
1915 ItemImpl(_
, _
, _
, ref generics
, _
, _
, _
)=> generics
,
1921 /// A reference from an trait to one of its associated items. This
1922 /// contains the item's id, naturally, but also the item's name and
1923 /// some other high-level details (like whether it is an associated
1924 /// type or method, and whether it is public). This allows other
1925 /// passes to find the impl they want without loading the id (which
1926 /// means fewer edges in the incremental compilation graph).
1927 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1928 pub struct TraitItemRef
{
1929 pub id
: TraitItemId
,
1931 pub kind
: AssociatedItemKind
,
1933 pub defaultness
: Defaultness
,
1936 /// A reference from an impl to one of its associated items. This
1937 /// contains the item's id, naturally, but also the item's name and
1938 /// some other high-level details (like whether it is an associated
1939 /// type or method, and whether it is public). This allows other
1940 /// passes to find the impl they want without loading the id (which
1941 /// means fewer edges in the incremental compilation graph).
1942 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1943 pub struct ImplItemRef
{
1946 pub kind
: AssociatedItemKind
,
1948 pub vis
: Visibility
,
1949 pub defaultness
: Defaultness
,
1952 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1953 pub enum AssociatedItemKind
{
1955 Method { has_self: bool }
,
1959 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1960 pub struct ForeignItem
{
1962 pub attrs
: HirVec
<Attribute
>,
1963 pub node
: ForeignItem_
,
1966 pub vis
: Visibility
,
1969 /// An item within an `extern` block
1970 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1971 pub enum ForeignItem_
{
1972 /// A foreign function
1973 ForeignItemFn(P
<FnDecl
>, HirVec
<Spanned
<Name
>>, Generics
),
1974 /// A foreign static item (`static ext: u8`), with optional mutability
1975 /// (the boolean is true when mutable)
1976 ForeignItemStatic(P
<Ty
>, bool
),
1982 pub fn descriptive_variant(&self) -> &str {
1984 ForeignItemFn(..) => "foreign function",
1985 ForeignItemStatic(..) => "foreign static item",
1986 ForeignItemType
=> "foreign type",
1991 /// A free variable referred to in a function.
1992 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
1993 pub struct Freevar
{
1994 /// The variable being accessed free.
1997 // First span where it is accessed (there can be multiple).
2002 pub fn var_id(&self) -> NodeId
{
2004 Def
::Local(id
) | Def
::Upvar(id
, ..) => id
,
2005 _
=> bug
!("Freevar::var_id: bad def ({:?})", self.def
)
2010 pub type FreevarMap
= NodeMap
<Vec
<Freevar
>>;
2012 pub type CaptureModeMap
= NodeMap
<CaptureClause
>;
2014 #[derive(Clone, Debug)]
2015 pub struct TraitCandidate
{
2017 pub import_id
: Option
<NodeId
>,
2020 // Trait method resolution
2021 pub type TraitMap
= NodeMap
<Vec
<TraitCandidate
>>;
2023 // Map from the NodeId of a glob import to a list of items which are actually
2025 pub type GlobMap
= NodeMap
<FxHashSet
<Name
>>;