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::BindingMode::*;
14 pub use self::BinOp_::*;
15 pub use self::BlockCheckMode::*;
16 pub use self::CaptureClause::*;
17 pub use self::Decl_::*;
18 pub use self::ExplicitSelf_::*;
19 pub use self::Expr_::*;
20 pub use self::FunctionRetTy::*;
21 pub use self::ForeignItem_::*;
22 pub use self::Item_::*;
23 pub use self::Mutability::*;
24 pub use self::Pat_::*;
25 pub use self::PathListItem_::*;
26 pub use self::PrimTy::*;
27 pub use self::Stmt_::*;
28 pub use self::StructFieldKind::*;
29 pub use self::TraitItem_::*;
31 pub use self::TyParamBound::*;
32 pub use self::UnOp::*;
33 pub use self::UnsafeSource::*;
34 pub use self::ViewPath_::*;
35 pub use self::Visibility::*;
36 pub use self::PathParameters::*;
38 use intravisit::Visitor;
39 use std::collections::BTreeMap;
40 use syntax::codemap::{self, Span, Spanned, DUMMY_SP, ExpnId};
42 use syntax::ast::{Name, NodeId, DUMMY_NODE_ID, TokenTree, AsmDialect};
43 use syntax::ast::{Attribute, Lit, StrStyle, FloatTy, IntTy, UintTy, MetaItem};
44 use syntax::attr::ThinAttributes;
45 use syntax::parse::token::InternedString;
52 use std::hash::{Hash, Hasher};
53 use serialize::{Encodable, Decodable, Encoder, Decoder};
55 /// HIR doesn't commit to a concrete storage type and have 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,)*) => (vec![$($x),*])
72 #[derive(Clone, Copy, Eq)]
74 /// Hygienic name (renamed), should be used by default
76 /// Unhygienic name (original, not renamed), needed in few places in name resolution
77 pub unhygienic_name: Name,
81 /// Creates a HIR identifier with both `name` and `unhygienic_name` initialized with
82 /// the argument. Hygiene properties of the created identifier depend entirely on this
83 /// argument. If the argument is a plain interned string `intern("iter")`, then the result
84 /// is unhygienic and can interfere with other entities named "iter". If the argument is
85 /// a "fresh" name created with `gensym("iter")`, then the result is hygienic and can't
86 /// interfere with other entities having the same string as a name.
87 pub fn from_name(name: Name) -> Ident {
88 Ident { name: name, unhygienic_name: name }
92 impl PartialEq for Ident {
93 fn eq(&self, other: &Ident) -> bool {
94 self.name == other.name
99 fn hash<H: Hasher>(&self, state: &mut H) {
100 self.name.hash(state)
104 impl fmt::Debug for Ident {
105 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
106 fmt::Debug::fmt(&self.name, f)
110 impl fmt::Display for Ident {
111 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
112 fmt::Display::fmt(&self.name, f)
116 impl Encodable for Ident {
117 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
122 impl Decodable for Ident {
123 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
124 Ok(Ident::from_name(try!(Name::decode(d))))
128 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
129 pub struct Lifetime {
135 impl fmt::Debug for Lifetime {
136 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140 pprust::lifetime_to_string(self))
144 /// A lifetime definition, eg `'a: 'b+'c+'d`
145 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
146 pub struct LifetimeDef {
147 pub lifetime: Lifetime,
148 pub bounds: HirVec<Lifetime>,
151 /// A "Path" is essentially Rust's notion of a name; for instance:
152 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
153 /// along with a bunch of supporting information.
154 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
157 /// A `::foo` path, is relative to the crate root rather than current
158 /// module (like paths in an import).
160 /// The segments in the path: the things separated by `::`.
161 pub segments: HirVec<PathSegment>,
164 impl fmt::Debug for Path {
165 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
166 write!(f, "path({})", pprust::path_to_string(self))
170 impl fmt::Display for Path {
171 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
172 write!(f, "{}", pprust::path_to_string(self))
176 /// A segment of a path: an identifier, an optional lifetime, and a set of
178 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
179 pub struct PathSegment {
180 /// The identifier portion of this path segment.
182 /// Hygiene properties of this identifier are worth noting.
183 /// Most path segments are not hygienic and they are not renamed during
184 /// lowering from AST to HIR (see comments to `fn lower_path`). However segments from
185 /// unqualified paths with one segment originating from `ExprPath` (local-variable-like paths)
186 /// can be hygienic, so they are renamed. You should not normally care about this peculiarity
187 /// and just use `identifier.name` unless you modify identifier resolution code
188 /// (`fn resolve_identifier` and other functions called by it in `rustc_resolve`).
189 pub identifier: Ident,
191 /// Type/lifetime parameters attached to this path. They come in
192 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
193 /// this is more than just simple syntactic sugar; the use of
194 /// parens affects the region binding rules, so we preserve the
196 pub parameters: PathParameters,
199 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
200 pub enum PathParameters {
201 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
202 AngleBracketedParameters(AngleBracketedParameterData),
203 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
204 ParenthesizedParameters(ParenthesizedParameterData),
207 impl PathParameters {
208 pub fn none() -> PathParameters {
209 AngleBracketedParameters(AngleBracketedParameterData {
210 lifetimes: HirVec::new(),
211 types: HirVec::new(),
212 bindings: HirVec::new(),
216 pub fn is_empty(&self) -> bool {
218 AngleBracketedParameters(ref data) => data.is_empty(),
220 // Even if the user supplied no types, something like
221 // `X()` is equivalent to `X<(),()>`.
222 ParenthesizedParameters(..) => false,
226 pub fn has_lifetimes(&self) -> bool {
228 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
229 ParenthesizedParameters(_) => false,
233 pub fn has_types(&self) -> bool {
235 AngleBracketedParameters(ref data) => !data.types.is_empty(),
236 ParenthesizedParameters(..) => true,
240 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
241 /// parameters in the parenthesized case.
242 pub fn types(&self) -> HirVec<&P<Ty>> {
244 AngleBracketedParameters(ref data) => {
245 data.types.iter().collect()
247 ParenthesizedParameters(ref data) => {
250 .chain(data.output.iter())
256 pub fn lifetimes(&self) -> HirVec<&Lifetime> {
258 AngleBracketedParameters(ref data) => {
259 data.lifetimes.iter().collect()
261 ParenthesizedParameters(_) => {
267 pub fn bindings(&self) -> HirVec<&TypeBinding> {
269 AngleBracketedParameters(ref data) => {
270 data.bindings.iter().collect()
272 ParenthesizedParameters(_) => {
279 /// A path like `Foo<'a, T>`
280 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
281 pub struct AngleBracketedParameterData {
282 /// The lifetime parameters for this path segment.
283 pub lifetimes: HirVec<Lifetime>,
284 /// The type parameters for this path segment, if present.
285 pub types: HirVec<P<Ty>>,
286 /// Bindings (equality constraints) on associated types, if present.
287 /// E.g., `Foo<A=Bar>`.
288 pub bindings: HirVec<TypeBinding>,
291 impl AngleBracketedParameterData {
292 fn is_empty(&self) -> bool {
293 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
297 /// A path like `Foo(A,B) -> C`
298 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
299 pub struct ParenthesizedParameterData {
304 pub inputs: HirVec<P<Ty>>,
307 pub output: Option<P<Ty>>,
310 /// The AST represents all type param bounds as types.
311 /// typeck::collect::compute_bounds matches these against
312 /// the "special" built-in traits (see middle::lang_items) and
313 /// detects Copy, Send and Sync.
314 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
315 pub enum TyParamBound {
316 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
317 RegionTyParamBound(Lifetime),
320 /// A modifier on a bound, currently this is only used for `?Sized`, where the
321 /// modifier is `Maybe`. Negative bounds should also be handled here.
322 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
323 pub enum TraitBoundModifier {
328 pub type TyParamBounds = HirVec<TyParamBound>;
330 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
334 pub bounds: TyParamBounds,
335 pub default: Option<P<Ty>>,
339 /// Represents lifetimes and type parameters attached to a declaration
340 /// of a function, enum, trait, etc.
341 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
342 pub struct Generics {
343 pub lifetimes: HirVec<LifetimeDef>,
344 pub ty_params: HirVec<TyParam>,
345 pub where_clause: WhereClause,
349 pub fn is_lt_parameterized(&self) -> bool {
350 !self.lifetimes.is_empty()
352 pub fn is_type_parameterized(&self) -> bool {
353 !self.ty_params.is_empty()
355 pub fn is_parameterized(&self) -> bool {
356 self.is_lt_parameterized() || self.is_type_parameterized()
360 /// A `where` clause in a definition
361 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
362 pub struct WhereClause {
364 pub predicates: HirVec<WherePredicate>,
367 /// A single predicate in a `where` clause
368 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
369 pub enum WherePredicate {
370 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
371 BoundPredicate(WhereBoundPredicate),
372 /// A lifetime predicate, e.g. `'a: 'b+'c`
373 RegionPredicate(WhereRegionPredicate),
374 /// An equality predicate (unsupported)
375 EqPredicate(WhereEqPredicate),
378 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
379 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
380 pub struct WhereBoundPredicate {
382 /// Any lifetimes from a `for` binding
383 pub bound_lifetimes: HirVec<LifetimeDef>,
384 /// The type being bounded
385 pub bounded_ty: P<Ty>,
386 /// Trait and lifetime bounds (`Clone+Send+'static`)
387 pub bounds: TyParamBounds,
390 /// A lifetime predicate, e.g. `'a: 'b+'c`
391 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
392 pub struct WhereRegionPredicate {
394 pub lifetime: Lifetime,
395 pub bounds: HirVec<Lifetime>,
398 /// An equality predicate (unsupported), e.g. `T=int`
399 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
400 pub struct WhereEqPredicate {
407 pub type CrateConfig = HirVec<P<MetaItem>>;
409 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
412 pub attrs: HirVec<Attribute>,
413 pub config: CrateConfig,
415 pub exported_macros: HirVec<MacroDef>,
417 // NB: We use a BTreeMap here so that `visit_all_items` iterates
418 // over the ids in increasing order. In principle it should not
419 // matter what order we visit things in, but in *practice* it
420 // does, because it can affect the order in which errors are
421 // detected, which in turn can make compile-fail tests yield
422 // slightly different results.
423 pub items: BTreeMap<NodeId, Item>,
427 pub fn item(&self, id: NodeId) -> &Item {
431 /// Visits all items in the crate in some determinstic (but
432 /// unspecified) order. If you just need to process every item,
433 /// but don't care about nesting, this method is the best choice.
435 /// If you do care about nesting -- usually because your algorithm
436 /// follows lexical scoping rules -- then you want a different
437 /// approach. You should override `visit_nested_item` in your
438 /// visitor and then call `intravisit::walk_crate` instead.
439 pub fn visit_all_items<'hir, V:Visitor<'hir>>(&'hir self, visitor: &mut V) {
440 for (_, item) in &self.items {
441 visitor.visit_item(item);
446 /// A macro definition, in this crate or imported from another.
448 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
449 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
450 pub struct MacroDef {
452 pub attrs: HirVec<Attribute>,
455 pub imported_from: Option<Name>,
457 pub use_locally: bool,
458 pub allow_internal_unstable: bool,
459 pub body: HirVec<TokenTree>,
462 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
464 /// Statements in a block
465 pub stmts: HirVec<Stmt>,
466 /// An expression at the end of the block
467 /// without a semicolon, if any
468 pub expr: Option<P<Expr>>,
470 /// Distinguishes between `unsafe { ... }` and `{ ... }`
471 pub rules: BlockCheckMode,
475 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
482 impl fmt::Debug for Pat {
483 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
484 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
488 /// A single field in a struct pattern
490 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
491 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
492 /// except is_shorthand is true
493 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
494 pub struct FieldPat {
495 /// The identifier for the field
497 /// The pattern the field is destructured to
499 pub is_shorthand: bool,
502 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
503 pub enum BindingMode {
504 BindByRef(Mutability),
505 BindByValue(Mutability),
508 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
510 /// Represents a wildcard pattern (`_`)
513 /// A PatIdent may either be a new bound variable,
514 /// or a nullary enum (in which case the third field
517 /// In the nullary enum case, the parser can't determine
518 /// which it is. The resolver determines this, and
519 /// records this pattern's NodeId in an auxiliary
520 /// set (of "PatIdents that refer to nullary enums")
521 PatIdent(BindingMode, Spanned<Ident>, Option<P<Pat>>),
523 /// "None" means a `Variant(..)` pattern where we don't bind the fields to names.
524 PatEnum(Path, Option<HirVec<P<Pat>>>),
526 /// An associated const named using the qualified path `<T>::CONST` or
527 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
528 /// referred to as simply `T::CONST`, in which case they will end up as
529 /// PatEnum, and the resolver will have to sort that out.
530 PatQPath(QSelf, Path),
532 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
533 /// The `bool` is `true` in the presence of a `..`
534 PatStruct(Path, HirVec<Spanned<FieldPat>>, bool),
535 /// A tuple pattern `(a, b)`
536 PatTup(HirVec<P<Pat>>),
539 /// A reference pattern, e.g. `&mut (a, b)`
540 PatRegion(P<Pat>, Mutability),
543 /// A range pattern, e.g. `1...2`
544 PatRange(P<Expr>, P<Expr>),
545 /// `[a, b, ..i, y, z]` is represented as:
546 /// `PatVec(box [a, b], Some(i), box [y, z])`
547 PatVec(HirVec<P<Pat>>, Option<P<Pat>>, HirVec<P<Pat>>),
550 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
551 pub enum Mutability {
556 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
558 /// The `+` operator (addition)
560 /// The `-` operator (subtraction)
562 /// The `*` operator (multiplication)
564 /// The `/` operator (division)
566 /// The `%` operator (modulus)
568 /// The `&&` operator (logical and)
570 /// The `||` operator (logical or)
572 /// The `^` operator (bitwise xor)
574 /// The `&` operator (bitwise and)
576 /// The `|` operator (bitwise or)
578 /// The `<<` operator (shift left)
580 /// The `>>` operator (shift right)
582 /// The `==` operator (equality)
584 /// The `<` operator (less than)
586 /// The `<=` operator (less than or equal to)
588 /// The `!=` operator (not equal to)
590 /// The `>=` operator (greater than or equal to)
592 /// The `>` operator (greater than)
596 pub type BinOp = Spanned<BinOp_>;
598 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
600 /// The `*` operator for dereferencing
602 /// The `!` operator for logical inversion
604 /// The `-` operator for negation
609 pub type Stmt = Spanned<Stmt_>;
611 impl fmt::Debug for Stmt_ {
612 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
614 let spanned = codemap::dummy_spanned(self.clone());
617 util::stmt_id(&spanned),
618 pprust::stmt_to_string(&spanned))
622 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
624 /// Could be an item or a local (let) binding:
625 StmtDecl(P<Decl>, NodeId),
627 /// Expr without trailing semi-colon (must have unit type):
628 StmtExpr(P<Expr>, NodeId),
630 /// Expr with trailing semi-colon (may have any type):
631 StmtSemi(P<Expr>, NodeId),
634 // FIXME (pending discussion of #1697, #2178...): local should really be
635 // a refinement on pat.
636 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
637 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
640 pub ty: Option<P<Ty>>,
641 /// Initializer expression to set the value, if any
642 pub init: Option<P<Expr>>,
645 pub attrs: ThinAttributes,
648 pub type Decl = Spanned<Decl_>;
650 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
652 /// A local (let) binding:
658 /// represents one arm of a 'match'
659 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
661 pub attrs: HirVec<Attribute>,
662 pub pats: HirVec<P<Pat>>,
663 pub guard: Option<P<Expr>>,
667 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
669 pub name: Spanned<Name>,
674 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
675 pub enum BlockCheckMode {
677 UnsafeBlock(UnsafeSource),
678 PushUnsafeBlock(UnsafeSource),
679 PopUnsafeBlock(UnsafeSource),
680 // Within this block (but outside a PopUnstableBlock), we suspend checking of stability.
685 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
686 pub enum UnsafeSource {
692 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
697 pub attrs: ThinAttributes,
700 impl fmt::Debug for Expr {
701 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
702 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
706 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
708 /// A `box x` expression.
710 /// An array (`[a, b, c, d]`)
711 ExprVec(HirVec<P<Expr>>),
714 /// The first field resolves to the function itself,
715 /// and the second field is the list of arguments
716 ExprCall(P<Expr>, HirVec<P<Expr>>),
717 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
719 /// The `Spanned<Name>` is the identifier for the method name.
720 /// The vector of `Ty`s are the ascripted type parameters for the method
721 /// (within the angle brackets).
723 /// The first element of the vector of `Expr`s is the expression that evaluates
724 /// to the object on which the method is being called on (the receiver),
725 /// and the remaining elements are the rest of the arguments.
727 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
728 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
729 ExprMethodCall(Spanned<Name>, HirVec<P<Ty>>, HirVec<P<Expr>>),
730 /// A tuple (`(a, b, c ,d)`)
731 ExprTup(HirVec<P<Expr>>),
732 /// A binary operation (For example: `a + b`, `a * b`)
733 ExprBinary(BinOp, P<Expr>, P<Expr>),
734 /// A unary operation (For example: `!x`, `*x`)
735 ExprUnary(UnOp, P<Expr>),
736 /// A literal (For example: `1u8`, `"foo"`)
738 /// A cast (`foo as f64`)
739 ExprCast(P<Expr>, P<Ty>),
740 ExprType(P<Expr>, P<Ty>),
741 /// An `if` block, with an optional else block
743 /// `if expr { block } else { expr }`
744 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
745 /// A while loop, with an optional label
747 /// `'label: while expr { block }`
748 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
749 /// Conditionless loop (can be exited with break, continue, or return)
751 /// `'label: loop { block }`
752 ExprLoop(P<Block>, Option<Ident>),
753 /// A `match` block, with a source that indicates whether or not it is
754 /// the result of a desugaring, and if so, which kind.
755 ExprMatch(P<Expr>, HirVec<Arm>, MatchSource),
756 /// A closure (for example, `move |a, b, c| {a + b + c}`)
757 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
758 /// A block (`{ ... }`)
761 /// An assignment (`a = foo()`)
762 ExprAssign(P<Expr>, P<Expr>),
763 /// An assignment with an operator
765 /// For example, `a += 1`.
766 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
767 /// Access of a named struct field (`obj.foo`)
768 ExprField(P<Expr>, Spanned<Name>),
769 /// Access of an unnamed field of a struct or tuple-struct
771 /// For example, `foo.0`.
772 ExprTupField(P<Expr>, Spanned<usize>),
773 /// An indexing operation (`foo[2]`)
774 ExprIndex(P<Expr>, P<Expr>),
775 /// A range (`1..2`, `1..`, or `..2`)
776 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
778 /// Variable reference, possibly containing `::` and/or type
779 /// parameters, e.g. foo::bar::<baz>.
781 /// Optionally "qualified",
782 /// e.g. `<HirVec<T> as SomeTrait>::SomeType`.
783 ExprPath(Option<QSelf>, Path),
785 /// A referencing operation (`&a` or `&mut a`)
786 ExprAddrOf(Mutability, P<Expr>),
787 /// A `break`, with an optional label to break
788 ExprBreak(Option<Spanned<Ident>>),
789 /// A `continue`, with an optional label
790 ExprAgain(Option<Spanned<Ident>>),
791 /// A `return`, with an optional value to be returned
792 ExprRet(Option<P<Expr>>),
794 /// Output of the `asm!()` macro
795 ExprInlineAsm(InlineAsm),
797 /// A struct literal expression.
799 /// For example, `Foo {x: 1, y: 2}`, or
800 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
801 ExprStruct(Path, HirVec<Field>, Option<P<Expr>>),
803 /// A vector literal constructed from one repeated element.
805 /// For example, `[1u8; 5]`. The first expression is the element
806 /// to be repeated; the second is the number of times to repeat it.
807 ExprRepeat(P<Expr>, P<Expr>),
810 /// The explicit Self type in a "qualified path". The actual
811 /// path, including the trait and the associated item, is stored
812 /// separately. `position` represents the index of the associated
813 /// item qualified with this Self type.
815 /// <HirVec<T> as a::b::Trait>::AssociatedItem
816 /// ^~~~~ ~~~~~~~~~~~~~~^
819 /// <HirVec<T>>::AssociatedItem
822 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
828 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
829 pub enum MatchSource {
832 contains_else_clause: bool,
838 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
839 pub enum CaptureClause {
844 // NB: If you change this, you'll probably want to change the corresponding
845 // type structure in middle/ty.rs as well.
846 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
849 pub mutbl: Mutability,
852 /// Represents a method's signature in a trait declaration,
853 /// or in an implementation.
854 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
855 pub struct MethodSig {
856 pub unsafety: Unsafety,
857 pub constness: Constness,
860 pub generics: Generics,
861 pub explicit_self: ExplicitSelf,
864 /// Represents a method declaration in a trait declaration, possibly including
865 /// a default implementation A trait method is either required (meaning it
866 /// doesn't have an implementation, just a signature) or provided (meaning it
867 /// has a default implementation).
868 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
869 pub struct TraitItem {
872 pub attrs: HirVec<Attribute>,
873 pub node: TraitItem_,
877 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
878 pub enum TraitItem_ {
879 ConstTraitItem(P<Ty>, Option<P<Expr>>),
880 MethodTraitItem(MethodSig, Option<P<Block>>),
881 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
884 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
885 pub struct ImplItem {
889 pub attrs: HirVec<Attribute>,
890 pub node: ImplItemKind,
894 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
895 pub enum ImplItemKind {
896 Const(P<Ty>, P<Expr>),
897 Method(MethodSig, P<Block>),
901 // Bind a type to an associated type: `A=Foo`.
902 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
903 pub struct TypeBinding {
911 // NB PartialEq method appears below.
912 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
919 impl fmt::Debug for Ty {
920 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
921 write!(f, "type({})", pprust::ty_to_string(self))
925 /// Not represented directly in the AST, referred to by name through a ty_path.
926 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
936 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
937 pub struct BareFnTy {
938 pub unsafety: Unsafety,
940 pub lifetimes: HirVec<LifetimeDef>,
944 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
945 /// The different kinds of types recognized by the compiler
948 /// A fixed length array (`[T; n]`)
949 TyFixedLengthVec(P<Ty>, P<Expr>),
950 /// A raw pointer (`*const T` or `*mut T`)
952 /// A reference (`&'a T` or `&'a mut T`)
953 TyRptr(Option<Lifetime>, MutTy),
954 /// A bare function (e.g. `fn(usize) -> bool`)
955 TyBareFn(P<BareFnTy>),
956 /// A tuple (`(A, B, C, D,...)`)
957 TyTup(HirVec<P<Ty>>),
958 /// A path (`module::module::...::Type`), optionally
959 /// "qualified", e.g. `<HirVec<T> as SomeTrait>::SomeType`.
961 /// Type parameters are stored in the Path itself
962 TyPath(Option<QSelf>, Path),
963 /// Something like `A+B`. Note that `B` must always be a path.
964 TyObjectSum(P<Ty>, TyParamBounds),
965 /// A type like `for<'a> Foo<&'a Bar>`
966 TyPolyTraitRef(TyParamBounds),
969 /// TyInfer means the type should be inferred instead of it having been
970 /// specified. This can appear anywhere in a type.
974 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
975 pub struct InlineAsmOutput {
976 pub constraint: InternedString,
979 pub is_indirect: bool,
982 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
983 pub struct InlineAsm {
984 pub asm: InternedString,
985 pub asm_str_style: StrStyle,
986 pub outputs: HirVec<InlineAsmOutput>,
987 pub inputs: HirVec<(InternedString, P<Expr>)>,
988 pub clobbers: HirVec<InternedString>,
990 pub alignstack: bool,
991 pub dialect: AsmDialect,
995 /// represents an argument in a function header
996 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1004 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1005 let path = Spanned {
1010 // HACK(eddyb) fake type for the self argument.
1018 node: PatIdent(BindByValue(mutability), path, None),
1026 /// Represents the header (not the body) of a function declaration
1027 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1029 pub inputs: HirVec<Arg>,
1030 pub output: FunctionRetTy,
1034 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1040 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1041 pub enum Constness {
1046 impl fmt::Display for Unsafety {
1047 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1048 fmt::Display::fmt(match *self {
1049 Unsafety::Normal => "normal",
1050 Unsafety::Unsafe => "unsafe",
1056 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1057 pub enum ImplPolarity {
1058 /// `impl Trait for Type`
1060 /// `impl !Trait for Type`
1064 impl fmt::Debug for ImplPolarity {
1065 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1067 ImplPolarity::Positive => "positive".fmt(f),
1068 ImplPolarity::Negative => "negative".fmt(f),
1074 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1075 pub enum FunctionRetTy {
1076 /// Functions with return type `!`that always
1077 /// raise an error or exit (i.e. never return to the caller)
1079 /// Return type is not specified.
1081 /// Functions default to `()` and
1082 /// closures default to inference. Span points to where return
1083 /// type would be inserted.
1084 DefaultReturn(Span),
1089 impl FunctionRetTy {
1090 pub fn span(&self) -> Span {
1092 NoReturn(span) => span,
1093 DefaultReturn(span) => span,
1094 Return(ref ty) => ty.span,
1099 /// Represents the kind of 'self' associated with a method
1100 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1101 pub enum ExplicitSelf_ {
1106 /// `&'lt self`, `&'lt mut self`
1107 SelfRegion(Option<Lifetime>, Mutability, Name),
1109 SelfExplicit(P<Ty>, Name),
1112 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1114 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1116 /// A span from the first token past `{` to the last token until `}`.
1117 /// For `mod foo;`, the inner span ranges from the first token
1118 /// to the last token in the external file.
1120 pub item_ids: HirVec<ItemId>,
1123 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1124 pub struct ForeignMod {
1126 pub items: HirVec<ForeignItem>,
1129 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1130 pub struct EnumDef {
1131 pub variants: HirVec<Variant>,
1134 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1135 pub struct Variant_ {
1137 pub attrs: HirVec<Attribute>,
1138 pub data: VariantData,
1139 /// Explicit discriminant, eg `Foo = 1`
1140 pub disr_expr: Option<P<Expr>>,
1143 pub type Variant = Spanned<Variant_>;
1145 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1146 pub enum PathListItem_ {
1149 /// renamed in list, eg `use foo::{bar as baz};`
1150 rename: Option<Name>,
1154 /// renamed in list, eg `use foo::{self as baz};`
1155 rename: Option<Name>,
1160 impl PathListItem_ {
1161 pub fn id(&self) -> NodeId {
1163 PathListIdent { id, .. } | PathListMod { id, .. } => id,
1167 pub fn name(&self) -> Option<Name> {
1169 PathListIdent { name, .. } => Some(name),
1170 PathListMod { .. } => None,
1174 pub fn rename(&self) -> Option<Name> {
1176 PathListIdent { rename, .. } | PathListMod { rename, .. } => rename,
1181 pub type PathListItem = Spanned<PathListItem_>;
1183 pub type ViewPath = Spanned<ViewPath_>;
1185 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1186 pub enum ViewPath_ {
1187 /// `foo::bar::baz as quux`
1191 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1192 ViewPathSimple(Name, Path),
1197 /// `foo::bar::{a,b,c}`
1198 ViewPathList(Path, HirVec<PathListItem>),
1201 /// TraitRef's appear in impls.
1203 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1204 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1205 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1206 /// same as the impl's node id).
1207 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1208 pub struct TraitRef {
1213 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1214 pub struct PolyTraitRef {
1215 /// The `'a` in `<'a> Foo<&'a T>`
1216 pub bound_lifetimes: HirVec<LifetimeDef>,
1218 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1219 pub trait_ref: TraitRef,
1224 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1225 pub enum Visibility {
1231 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1233 &Inherited => parent_visibility,
1239 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1240 pub struct StructField_ {
1241 pub kind: StructFieldKind,
1244 pub attrs: HirVec<Attribute>,
1248 pub fn name(&self) -> Option<Name> {
1250 NamedField(name, _) => Some(name),
1251 UnnamedField(_) => None,
1256 pub type StructField = Spanned<StructField_>;
1258 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1259 pub enum StructFieldKind {
1260 NamedField(Name, Visibility),
1261 /// Element of a tuple-like struct
1262 UnnamedField(Visibility),
1265 impl StructFieldKind {
1266 pub fn is_unnamed(&self) -> bool {
1268 UnnamedField(..) => true,
1269 NamedField(..) => false,
1273 pub fn visibility(&self) -> Visibility {
1275 NamedField(_, vis) | UnnamedField(vis) => vis,
1280 /// Fields and Ids of enum variants and structs
1282 /// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1283 /// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1284 /// One shared Id can be successfully used for these two purposes.
1285 /// Id of the whole enum lives in `Item`.
1287 /// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1288 /// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1289 /// the variant itself" from enum variants.
1290 /// Id of the whole struct lives in `Item`.
1291 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1292 pub enum VariantData {
1293 Struct(HirVec<StructField>, NodeId),
1294 Tuple(HirVec<StructField>, NodeId),
1299 pub fn fields(&self) -> &[StructField] {
1301 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1305 pub fn id(&self) -> NodeId {
1307 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id,
1310 pub fn is_struct(&self) -> bool {
1311 if let VariantData::Struct(..) = *self {
1317 pub fn is_tuple(&self) -> bool {
1318 if let VariantData::Tuple(..) = *self {
1324 pub fn is_unit(&self) -> bool {
1325 if let VariantData::Unit(..) = *self {
1333 // The bodies for items are stored "out of line", in a separate
1334 // hashmap in the `Crate`. Here we just record the node-id of the item
1335 // so it can fetched later.
1336 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1341 // FIXME (#3300): Should allow items to be anonymous. Right now
1342 // we just use dummy names for anon items.
1345 /// The name might be a dummy name in case of anonymous items
1346 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1349 pub attrs: HirVec<Attribute>,
1352 pub vis: Visibility,
1356 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1358 /// An`extern crate` item, with optional original crate name,
1360 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1361 ItemExternCrate(Option<Name>),
1362 /// A `use` or `pub use` item
1363 ItemUse(P<ViewPath>),
1366 ItemStatic(P<Ty>, Mutability, P<Expr>),
1368 ItemConst(P<Ty>, P<Expr>),
1369 /// A function declaration
1370 ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1373 /// An external module
1374 ItemForeignMod(ForeignMod),
1375 /// A type alias, e.g. `type Foo = Bar<u8>`
1376 ItemTy(P<Ty>, Generics),
1377 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1378 ItemEnum(EnumDef, Generics),
1379 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1380 ItemStruct(VariantData, Generics),
1381 /// Represents a Trait Declaration
1382 ItemTrait(Unsafety, Generics, TyParamBounds, HirVec<TraitItem>),
1384 // Default trait implementations
1386 /// `impl Trait for .. {}`
1387 ItemDefaultImpl(Unsafety, TraitRef),
1388 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1392 Option<TraitRef>, // (optional) trait this impl implements
1398 pub fn descriptive_variant(&self) -> &str {
1400 ItemExternCrate(..) => "extern crate",
1401 ItemUse(..) => "use",
1402 ItemStatic(..) => "static item",
1403 ItemConst(..) => "constant item",
1404 ItemFn(..) => "function",
1405 ItemMod(..) => "module",
1406 ItemForeignMod(..) => "foreign module",
1407 ItemTy(..) => "type alias",
1408 ItemEnum(..) => "enum",
1409 ItemStruct(..) => "struct",
1410 ItemTrait(..) => "trait",
1412 ItemDefaultImpl(..) => "item",
1417 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1418 pub struct ForeignItem {
1420 pub attrs: HirVec<Attribute>,
1421 pub node: ForeignItem_,
1424 pub vis: Visibility,
1427 /// An item within an `extern` block
1428 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1429 pub enum ForeignItem_ {
1430 /// A foreign function
1431 ForeignItemFn(P<FnDecl>, Generics),
1432 /// A foreign static item (`static ext: u8`), with optional mutability
1433 /// (the boolean is true when mutable)
1434 ForeignItemStatic(P<Ty>, bool),
1438 pub fn descriptive_variant(&self) -> &str {
1440 ForeignItemFn(..) => "foreign function",
1441 ForeignItemStatic(..) => "foreign static item",