]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/hir.rs
f8f17617310b7b4ef2beef790a21fa224cb66a33
[rust.git] / src / librustc_front / hir.rs
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.
4 //
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.
10
11 // The Rust HIR.
12
13 pub use self::AsmDialect::*;
14 pub use self::AttrStyle::*;
15 pub use self::BindingMode::*;
16 pub use self::BinOp_::*;
17 pub use self::BlockCheckMode::*;
18 pub use self::CaptureClause::*;
19 pub use self::Decl_::*;
20 pub use self::ExplicitSelf_::*;
21 pub use self::Expr_::*;
22 pub use self::FloatTy::*;
23 pub use self::FunctionRetTy::*;
24 pub use self::ForeignItem_::*;
25 pub use self::ImplItem_::*;
26 pub use self::IntTy::*;
27 pub use self::Item_::*;
28 pub use self::Lit_::*;
29 pub use self::LitIntType::*;
30 pub use self::MetaItem_::*;
31 pub use self::Mutability::*;
32 pub use self::Pat_::*;
33 pub use self::PathListItem_::*;
34 pub use self::PatWildKind::*;
35 pub use self::PrimTy::*;
36 pub use self::Sign::*;
37 pub use self::Stmt_::*;
38 pub use self::StrStyle::*;
39 pub use self::StructFieldKind::*;
40 pub use self::TraitItem_::*;
41 pub use self::Ty_::*;
42 pub use self::TyParamBound::*;
43 pub use self::UintTy::*;
44 pub use self::UnOp::*;
45 pub use self::UnsafeSource::*;
46 pub use self::VariantKind::*;
47 pub use self::ViewPath_::*;
48 pub use self::Visibility::*;
49 pub use self::PathParameters::*;
50
51 use syntax::codemap::{self, Span, Spanned, DUMMY_SP, ExpnId};
52 use syntax::abi::Abi;
53 use syntax::ast::{Name, Ident, NodeId, DUMMY_NODE_ID, TokenTree};
54 use syntax::owned_slice::OwnedSlice;
55 use syntax::parse::token::InternedString;
56 use syntax::ptr::P;
57
58 use print::pprust;
59 use util;
60
61 use std::fmt;
62 use std::rc::Rc;
63 use serialize::{Encodable, Encoder, Decoder};
64
65
66 /// Function name (not all functions have names)
67 pub type FnIdent = Option<Ident>;
68
69 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
70 pub struct Lifetime {
71     pub id: NodeId,
72     pub span: Span,
73     pub name: Name
74 }
75
76 impl fmt::Debug for Lifetime {
77     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78         write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
79     }
80 }
81
82 /// A lifetime definition, eg `'a: 'b+'c+'d`
83 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
84 pub struct LifetimeDef {
85     pub lifetime: Lifetime,
86     pub bounds: Vec<Lifetime>
87 }
88
89 /// A "Path" is essentially Rust's notion of a name; for instance:
90 /// std::cmp::PartialEq  .  It's represented as a sequence of identifiers,
91 /// along with a bunch of supporting information.
92 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
93 pub struct Path {
94     pub span: Span,
95     /// A `::foo` path, is relative to the crate root rather than current
96     /// module (like paths in an import).
97     pub global: bool,
98     /// The segments in the path: the things separated by `::`.
99     pub segments: Vec<PathSegment>,
100 }
101
102 impl fmt::Debug for Path {
103     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104         write!(f, "path({})", pprust::path_to_string(self))
105     }
106 }
107
108 impl fmt::Display for Path {
109     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110         write!(f, "{}", pprust::path_to_string(self))
111     }
112 }
113
114 /// A segment of a path: an identifier, an optional lifetime, and a set of
115 /// types.
116 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
117 pub struct PathSegment {
118     /// The identifier portion of this path segment.
119     pub identifier: Ident,
120
121     /// Type/lifetime parameters attached to this path. They come in
122     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
123     /// this is more than just simple syntactic sugar; the use of
124     /// parens affects the region binding rules, so we preserve the
125     /// distinction.
126     pub parameters: PathParameters,
127 }
128
129 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
130 pub enum PathParameters {
131     /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
132     AngleBracketedParameters(AngleBracketedParameterData),
133     /// The `(A,B)` and `C` in `Foo(A,B) -> C`
134     ParenthesizedParameters(ParenthesizedParameterData),
135 }
136
137 impl PathParameters {
138     pub fn none() -> PathParameters {
139         AngleBracketedParameters(AngleBracketedParameterData {
140             lifetimes: Vec::new(),
141             types: OwnedSlice::empty(),
142             bindings: OwnedSlice::empty(),
143         })
144     }
145
146     pub fn is_empty(&self) -> bool {
147         match *self {
148             AngleBracketedParameters(ref data) => data.is_empty(),
149
150             // Even if the user supplied no types, something like
151             // `X()` is equivalent to `X<(),()>`.
152             ParenthesizedParameters(..) => false,
153         }
154     }
155
156     pub fn has_lifetimes(&self) -> bool {
157         match *self {
158             AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
159             ParenthesizedParameters(_) => false,
160         }
161     }
162
163     pub fn has_types(&self) -> bool {
164         match *self {
165             AngleBracketedParameters(ref data) => !data.types.is_empty(),
166             ParenthesizedParameters(..) => true,
167         }
168     }
169
170     /// Returns the types that the user wrote. Note that these do not necessarily map to the type
171     /// parameters in the parenthesized case.
172     pub fn types(&self) -> Vec<&P<Ty>> {
173         match *self {
174             AngleBracketedParameters(ref data) => {
175                 data.types.iter().collect()
176             }
177             ParenthesizedParameters(ref data) => {
178                 data.inputs.iter()
179                     .chain(data.output.iter())
180                     .collect()
181             }
182         }
183     }
184
185     pub fn lifetimes(&self) -> Vec<&Lifetime> {
186         match *self {
187             AngleBracketedParameters(ref data) => {
188                 data.lifetimes.iter().collect()
189             }
190             ParenthesizedParameters(_) => {
191                 Vec::new()
192             }
193         }
194     }
195
196     pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
197         match *self {
198             AngleBracketedParameters(ref data) => {
199                 data.bindings.iter().collect()
200             }
201             ParenthesizedParameters(_) => {
202                 Vec::new()
203             }
204         }
205     }
206 }
207
208 /// A path like `Foo<'a, T>`
209 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
210 pub struct AngleBracketedParameterData {
211     /// The lifetime parameters for this path segment.
212     pub lifetimes: Vec<Lifetime>,
213     /// The type parameters for this path segment, if present.
214     pub types: OwnedSlice<P<Ty>>,
215     /// Bindings (equality constraints) on associated types, if present.
216     /// E.g., `Foo<A=Bar>`.
217     pub bindings: OwnedSlice<P<TypeBinding>>,
218 }
219
220 impl AngleBracketedParameterData {
221     fn is_empty(&self) -> bool {
222         self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
223     }
224 }
225
226 /// A path like `Foo(A,B) -> C`
227 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
228 pub struct ParenthesizedParameterData {
229     /// Overall span
230     pub span: Span,
231
232     /// `(A,B)`
233     pub inputs: Vec<P<Ty>>,
234
235     /// `C`
236     pub output: Option<P<Ty>>,
237 }
238
239 /// The AST represents all type param bounds as types.
240 /// typeck::collect::compute_bounds matches these against
241 /// the "special" built-in traits (see middle::lang_items) and
242 /// detects Copy, Send and Sync.
243 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
244 pub enum TyParamBound {
245     TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
246     RegionTyParamBound(Lifetime)
247 }
248
249 /// A modifier on a bound, currently this is only used for `?Sized`, where the
250 /// modifier is `Maybe`. Negative bounds should also be handled here.
251 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
252 pub enum TraitBoundModifier {
253     None,
254     Maybe,
255 }
256
257 pub type TyParamBounds = OwnedSlice<TyParamBound>;
258
259 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
260 pub struct TyParam {
261     pub ident: Ident,
262     pub id: NodeId,
263     pub bounds: TyParamBounds,
264     pub default: Option<P<Ty>>,
265     pub span: Span
266 }
267
268 /// Represents lifetimes and type parameters attached to a declaration
269 /// of a function, enum, trait, etc.
270 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
271 pub struct Generics {
272     pub lifetimes: Vec<LifetimeDef>,
273     pub ty_params: OwnedSlice<TyParam>,
274     pub where_clause: WhereClause,
275 }
276
277 impl Generics {
278     pub fn is_lt_parameterized(&self) -> bool {
279         !self.lifetimes.is_empty()
280     }
281     pub fn is_type_parameterized(&self) -> bool {
282         !self.ty_params.is_empty()
283     }
284     pub fn is_parameterized(&self) -> bool {
285         self.is_lt_parameterized() || self.is_type_parameterized()
286     }
287 }
288
289 /// A `where` clause in a definition
290 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
291 pub struct WhereClause {
292     pub id: NodeId,
293     pub predicates: Vec<WherePredicate>,
294 }
295
296 /// A single predicate in a `where` clause
297 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
298 pub enum WherePredicate {
299     /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
300     BoundPredicate(WhereBoundPredicate),
301     /// A lifetime predicate, e.g. `'a: 'b+'c`
302     RegionPredicate(WhereRegionPredicate),
303     /// An equality predicate (unsupported)
304     EqPredicate(WhereEqPredicate)
305 }
306
307 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
308 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
309 pub struct WhereBoundPredicate {
310     pub span: Span,
311     /// Any lifetimes from a `for` binding
312     pub bound_lifetimes: Vec<LifetimeDef>,
313     /// The type being bounded
314     pub bounded_ty: P<Ty>,
315     /// Trait and lifetime bounds (`Clone+Send+'static`)
316     pub bounds: OwnedSlice<TyParamBound>,
317 }
318
319 /// A lifetime predicate, e.g. `'a: 'b+'c`
320 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
321 pub struct WhereRegionPredicate {
322     pub span: Span,
323     pub lifetime: Lifetime,
324     pub bounds: Vec<Lifetime>,
325 }
326
327 /// An equality predicate (unsupported), e.g. `T=int`
328 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
329 pub struct WhereEqPredicate {
330     pub id: NodeId,
331     pub span: Span,
332     pub path: Path,
333     pub ty: P<Ty>,
334 }
335
336 /// The set of MetaItems that define the compilation environment of the crate,
337 /// used to drive conditional compilation
338 pub type CrateConfig = Vec<P<MetaItem>> ;
339
340 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
341 pub struct Crate {
342     pub module: Mod,
343     pub attrs: Vec<Attribute>,
344     pub config: CrateConfig,
345     pub span: Span,
346     pub exported_macros: Vec<MacroDef>,
347 }
348
349 /// A macro definition, in this crate or imported from another.
350 ///
351 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
352 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
353 pub struct MacroDef {
354     pub ident: Ident,
355     pub attrs: Vec<Attribute>,
356     pub id: NodeId,
357     pub span: Span,
358     pub imported_from: Option<Ident>,
359     pub export: bool,
360     pub use_locally: bool,
361     pub allow_internal_unstable: bool,
362     pub body: Vec<TokenTree>,
363 }
364
365 pub type MetaItem = Spanned<MetaItem_>;
366
367 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
368 pub enum MetaItem_ {
369     MetaWord(InternedString),
370     MetaList(InternedString, Vec<P<MetaItem>>),
371     MetaNameValue(InternedString, Lit),
372 }
373
374 // can't be derived because the MetaList requires an unordered comparison
375 impl PartialEq for MetaItem_ {
376     fn eq(&self, other: &MetaItem_) -> bool {
377         match *self {
378             MetaWord(ref ns) => match *other {
379                 MetaWord(ref no) => (*ns) == (*no),
380                 _ => false
381             },
382             MetaNameValue(ref ns, ref vs) => match *other {
383                 MetaNameValue(ref no, ref vo) => {
384                     (*ns) == (*no) && vs.node == vo.node
385                 }
386                 _ => false
387             },
388             MetaList(ref ns, ref miss) => match *other {
389                 MetaList(ref no, ref miso) => {
390                     ns == no &&
391                         miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
392                 }
393                 _ => false
394             }
395         }
396     }
397 }
398
399 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
400 pub struct Block {
401     /// Statements in a block
402     pub stmts: Vec<P<Stmt>>,
403     /// An expression at the end of the block
404     /// without a semicolon, if any
405     pub expr: Option<P<Expr>>,
406     pub id: NodeId,
407     /// Distinguishes between `unsafe { ... }` and `{ ... }`
408     pub rules: BlockCheckMode,
409     pub span: Span,
410 }
411
412 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
413 pub struct Pat {
414     pub id: NodeId,
415     pub node: Pat_,
416     pub span: Span,
417 }
418
419 impl fmt::Debug for Pat {
420     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
421         write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
422     }
423 }
424
425 /// A single field in a struct pattern
426 ///
427 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
428 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
429 /// except is_shorthand is true
430 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
431 pub struct FieldPat {
432     /// The identifier for the field
433     pub ident: Ident,
434     /// The pattern the field is destructured to
435     pub pat: P<Pat>,
436     pub is_shorthand: bool,
437 }
438
439 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
440 pub enum BindingMode {
441     BindByRef(Mutability),
442     BindByValue(Mutability),
443 }
444
445 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
446 pub enum PatWildKind {
447     /// Represents the wildcard pattern `_`
448     PatWildSingle,
449
450     /// Represents the wildcard pattern `..`
451     PatWildMulti,
452 }
453
454 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
455 pub enum Pat_ {
456     /// Represents a wildcard pattern (either `_` or `..`)
457     PatWild(PatWildKind),
458
459     /// A PatIdent may either be a new bound variable,
460     /// or a nullary enum (in which case the third field
461     /// is None).
462     ///
463     /// In the nullary enum case, the parser can't determine
464     /// which it is. The resolver determines this, and
465     /// records this pattern's NodeId in an auxiliary
466     /// set (of "PatIdents that refer to nullary enums")
467     PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
468
469     /// "None" means a * pattern where we don't bind the fields to names.
470     PatEnum(Path, Option<Vec<P<Pat>>>),
471
472     /// An associated const named using the qualified path `<T>::CONST` or
473     /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
474     /// referred to as simply `T::CONST`, in which case they will end up as
475     /// PatEnum, and the resolver will have to sort that out.
476     PatQPath(QSelf, Path),
477
478     /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
479     /// The `bool` is `true` in the presence of a `..`
480     PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
481     /// A tuple pattern `(a, b)`
482     PatTup(Vec<P<Pat>>),
483     /// A `box` pattern
484     PatBox(P<Pat>),
485     /// A reference pattern, e.g. `&mut (a, b)`
486     PatRegion(P<Pat>, Mutability),
487     /// A literal
488     PatLit(P<Expr>),
489     /// A range pattern, e.g. `1...2`
490     PatRange(P<Expr>, P<Expr>),
491     /// [a, b, ..i, y, z] is represented as:
492     ///     PatVec(box [a, b], Some(i), box [y, z])
493     PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
494 }
495
496 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
497 pub enum Mutability {
498     MutMutable,
499     MutImmutable,
500 }
501
502 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
503 pub enum BinOp_ {
504     /// The `+` operator (addition)
505     BiAdd,
506     /// The `-` operator (subtraction)
507     BiSub,
508     /// The `*` operator (multiplication)
509     BiMul,
510     /// The `/` operator (division)
511     BiDiv,
512     /// The `%` operator (modulus)
513     BiRem,
514     /// The `&&` operator (logical and)
515     BiAnd,
516     /// The `||` operator (logical or)
517     BiOr,
518     /// The `^` operator (bitwise xor)
519     BiBitXor,
520     /// The `&` operator (bitwise and)
521     BiBitAnd,
522     /// The `|` operator (bitwise or)
523     BiBitOr,
524     /// The `<<` operator (shift left)
525     BiShl,
526     /// The `>>` operator (shift right)
527     BiShr,
528     /// The `==` operator (equality)
529     BiEq,
530     /// The `<` operator (less than)
531     BiLt,
532     /// The `<=` operator (less than or equal to)
533     BiLe,
534     /// The `!=` operator (not equal to)
535     BiNe,
536     /// The `>=` operator (greater than or equal to)
537     BiGe,
538     /// The `>` operator (greater than)
539     BiGt,
540 }
541
542 pub type BinOp = Spanned<BinOp_>;
543
544 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
545 pub enum UnOp {
546     /// The `box` operator
547     UnUniq,
548     /// The `*` operator for dereferencing
549     UnDeref,
550     /// The `!` operator for logical inversion
551     UnNot,
552     /// The `-` operator for negation
553     UnNeg
554 }
555
556 /// A statement
557 pub type Stmt = Spanned<Stmt_>;
558
559 impl fmt::Debug for Stmt_ {
560     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
561         // Sadness.
562         let spanned = codemap::dummy_spanned(self.clone());
563         write!(f, "stmt({}: {})",
564                util::stmt_id(&spanned),
565                pprust::stmt_to_string(&spanned))
566     }
567 }
568
569 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
570 pub enum Stmt_ {
571     /// Could be an item or a local (let) binding:
572     StmtDecl(P<Decl>, NodeId),
573
574     /// Expr without trailing semi-colon (must have unit type):
575     StmtExpr(P<Expr>, NodeId),
576
577     /// Expr with trailing semi-colon (may have any type):
578     StmtSemi(P<Expr>, NodeId),
579 }
580
581 // FIXME (pending discussion of #1697, #2178...): local should really be
582 // a refinement on pat.
583 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
584 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
585 pub struct Local {
586     pub pat: P<Pat>,
587     pub ty: Option<P<Ty>>,
588     /// Initializer expression to set the value, if any
589     pub init: Option<P<Expr>>,
590     pub id: NodeId,
591     pub span: Span,
592 }
593
594 pub type Decl = Spanned<Decl_>;
595
596 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
597 pub enum Decl_ {
598     /// A local (let) binding:
599     DeclLocal(P<Local>),
600     /// An item binding:
601     DeclItem(P<Item>),
602 }
603
604 /// represents one arm of a 'match'
605 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
606 pub struct Arm {
607     pub attrs: Vec<Attribute>,
608     pub pats: Vec<P<Pat>>,
609     pub guard: Option<P<Expr>>,
610     pub body: P<Expr>,
611 }
612
613 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
614 pub struct Field {
615     pub ident: SpannedIdent,
616     pub expr: P<Expr>,
617     pub span: Span,
618 }
619
620 pub type SpannedIdent = Spanned<Ident>;
621
622 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
623 pub enum BlockCheckMode {
624     DefaultBlock,
625     UnsafeBlock(UnsafeSource),
626     PushUnsafeBlock(UnsafeSource),
627     PopUnsafeBlock(UnsafeSource),
628 }
629
630 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
631 pub enum UnsafeSource {
632     CompilerGenerated,
633     UserProvided,
634 }
635
636 /// An expression
637 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
638 pub struct Expr {
639     pub id: NodeId,
640     pub node: Expr_,
641     pub span: Span,
642 }
643
644 impl fmt::Debug for Expr {
645     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
646         write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
647     }
648 }
649
650 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
651 pub enum Expr_ {
652     /// First expr is the place; second expr is the value.
653     ExprBox(Option<P<Expr>>, P<Expr>),
654     /// An array (`[a, b, c, d]`)
655     ExprVec(Vec<P<Expr>>),
656     /// A function call
657     ///
658     /// The first field resolves to the function itself,
659     /// and the second field is the list of arguments
660     ExprCall(P<Expr>, Vec<P<Expr>>),
661     /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
662     ///
663     /// The `SpannedIdent` is the identifier for the method name.
664     /// The vector of `Ty`s are the ascripted type parameters for the method
665     /// (within the angle brackets).
666     ///
667     /// The first element of the vector of `Expr`s is the expression that evaluates
668     /// to the object on which the method is being called on (the receiver),
669     /// and the remaining elements are the rest of the arguments.
670     ///
671     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
672     /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
673     ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
674     /// A tuple (`(a, b, c ,d)`)
675     ExprTup(Vec<P<Expr>>),
676     /// A binary operation (For example: `a + b`, `a * b`)
677     ExprBinary(BinOp, P<Expr>, P<Expr>),
678     /// A unary operation (For example: `!x`, `*x`)
679     ExprUnary(UnOp, P<Expr>),
680     /// A literal (For example: `1u8`, `"foo"`)
681     ExprLit(P<Lit>),
682     /// A cast (`foo as f64`)
683     ExprCast(P<Expr>, P<Ty>),
684     /// An `if` block, with an optional else block
685     ///
686     /// `if expr { block } else { expr }`
687     ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
688     // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
689     /// A while loop, with an optional label
690     ///
691     /// `'label: while expr { block }`
692     ExprWhile(P<Expr>, P<Block>, Option<Ident>),
693     /// Conditionless loop (can be exited with break, continue, or return)
694     ///
695     /// `'label: loop { block }`
696     // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
697     ExprLoop(P<Block>, Option<Ident>),
698     /// A `match` block, with a source that indicates whether or not it is
699     /// the result of a desugaring, and if so, which kind.
700     ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
701     /// A closure (for example, `move |a, b, c| {a + b + c}`)
702     ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
703     /// A block (`{ ... }`)
704     ExprBlock(P<Block>),
705
706     /// An assignment (`a = foo()`)
707     ExprAssign(P<Expr>, P<Expr>),
708     /// An assignment with an operator
709     ///
710     /// For example, `a += 1`.
711     ExprAssignOp(BinOp, P<Expr>, P<Expr>),
712     /// Access of a named struct field (`obj.foo`)
713     ExprField(P<Expr>, SpannedIdent),
714     /// Access of an unnamed field of a struct or tuple-struct
715     ///
716     /// For example, `foo.0`.
717     ExprTupField(P<Expr>, Spanned<usize>),
718     /// An indexing operation (`foo[2]`)
719     ExprIndex(P<Expr>, P<Expr>),
720     /// A range (`1..2`, `1..`, or `..2`)
721     ExprRange(Option<P<Expr>>, Option<P<Expr>>),
722
723     /// Variable reference, possibly containing `::` and/or type
724     /// parameters, e.g. foo::bar::<baz>.
725     ///
726     /// Optionally "qualified",
727     /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
728     ExprPath(Option<QSelf>, Path),
729
730     /// A referencing operation (`&a` or `&mut a`)
731     ExprAddrOf(Mutability, P<Expr>),
732     /// A `break`, with an optional label to break
733     ExprBreak(Option<SpannedIdent>),
734     /// A `continue`, with an optional label
735     ExprAgain(Option<SpannedIdent>),
736     /// A `return`, with an optional value to be returned
737     ExprRet(Option<P<Expr>>),
738
739     /// Output of the `asm!()` macro
740     ExprInlineAsm(InlineAsm),
741
742     /// A struct literal expression.
743     ///
744     /// For example, `Foo {x: 1, y: 2}`, or
745     /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
746     ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
747
748     /// A vector literal constructed from one repeated element.
749     ///
750     /// For example, `[1u8; 5]`. The first expression is the element
751     /// to be repeated; the second is the number of times to repeat it.
752     ExprRepeat(P<Expr>, P<Expr>),
753
754     /// No-op: used solely so we can pretty-print faithfully
755     ExprParen(P<Expr>)
756 }
757
758 /// The explicit Self type in a "qualified path". The actual
759 /// path, including the trait and the associated item, is stored
760 /// separately. `position` represents the index of the associated
761 /// item qualified with this Self type.
762 ///
763 ///     <Vec<T> as a::b::Trait>::AssociatedItem
764 ///      ^~~~~     ~~~~~~~~~~~~~~^
765 ///      ty        position = 3
766 ///
767 ///     <Vec<T>>::AssociatedItem
768 ///      ^~~~~    ^
769 ///      ty       position = 0
770 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
771 pub struct QSelf {
772     pub ty: P<Ty>,
773     pub position: usize
774 }
775
776 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
777 pub enum MatchSource {
778     Normal,
779     IfLetDesugar { contains_else_clause: bool },
780     WhileLetDesugar,
781     ForLoopDesugar,
782 }
783
784 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
785 pub enum CaptureClause {
786     CaptureByValue,
787     CaptureByRef,
788 }
789
790
791 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
792 pub enum StrStyle {
793     /// A regular string, like `"foo"`
794     CookedStr,
795     /// A raw string, like `r##"foo"##`
796     ///
797     /// The uint is the number of `#` symbols used
798     RawStr(usize)
799 }
800
801 /// A literal
802 pub type Lit = Spanned<Lit_>;
803
804 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
805 pub enum Sign {
806     Minus,
807     Plus
808 }
809
810 impl Sign {
811     pub fn new<T: IntSign>(n: T) -> Sign {
812         n.sign()
813     }
814 }
815
816 pub trait IntSign {
817     fn sign(&self) -> Sign;
818 }
819 macro_rules! doit {
820     ($($t:ident)*) => ($(impl IntSign for $t {
821         #[allow(unused_comparisons)]
822         fn sign(&self) -> Sign {
823             if *self < 0 {Minus} else {Plus}
824         }
825     })*)
826 }
827 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
828
829 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
830 pub enum LitIntType {
831     SignedIntLit(IntTy, Sign),
832     UnsignedIntLit(UintTy),
833     UnsuffixedIntLit(Sign)
834 }
835
836 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
837 pub enum Lit_ {
838     /// A string literal (`"foo"`)
839     LitStr(InternedString, StrStyle),
840     /// A byte string (`b"foo"`)
841     LitByteStr(Rc<Vec<u8>>),
842     /// A byte char (`b'f'`)
843     LitByte(u8),
844     /// A character literal (`'a'`)
845     LitChar(char),
846     /// An integer literal (`1u8`)
847     LitInt(u64, LitIntType),
848     /// A float literal (`1f64` or `1E10f64`)
849     LitFloat(InternedString, FloatTy),
850     /// A float literal without a suffix (`1.0 or 1.0E10`)
851     LitFloatUnsuffixed(InternedString),
852     /// A boolean literal
853     LitBool(bool),
854 }
855
856 // NB: If you change this, you'll probably want to change the corresponding
857 // type structure in middle/ty.rs as well.
858 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
859 pub struct MutTy {
860     pub ty: P<Ty>,
861     pub mutbl: Mutability,
862 }
863
864 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
865 pub struct TypeField {
866     pub ident: Ident,
867     pub mt: MutTy,
868     pub span: Span,
869 }
870
871 /// Represents a method's signature in a trait declaration,
872 /// or in an implementation.
873 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
874 pub struct MethodSig {
875     pub unsafety: Unsafety,
876     pub constness: Constness,
877     pub abi: Abi,
878     pub decl: P<FnDecl>,
879     pub generics: Generics,
880     pub explicit_self: ExplicitSelf,
881 }
882
883 /// Represents a method declaration in a trait declaration, possibly including
884 /// a default implementation A trait method is either required (meaning it
885 /// doesn't have an implementation, just a signature) or provided (meaning it
886 /// has a default implementation).
887 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
888 pub struct TraitItem {
889     pub id: NodeId,
890     pub ident: Ident,
891     pub attrs: Vec<Attribute>,
892     pub node: TraitItem_,
893     pub span: Span,
894 }
895
896 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
897 pub enum TraitItem_ {
898     ConstTraitItem(P<Ty>, Option<P<Expr>>),
899     MethodTraitItem(MethodSig, Option<P<Block>>),
900     TypeTraitItem(TyParamBounds, Option<P<Ty>>),
901 }
902
903 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
904 pub struct ImplItem {
905     pub id: NodeId,
906     pub ident: Ident,
907     pub vis: Visibility,
908     pub attrs: Vec<Attribute>,
909     pub node: ImplItem_,
910     pub span: Span,
911 }
912
913 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
914 pub enum ImplItem_ {
915     ConstImplItem(P<Ty>, P<Expr>),
916     MethodImplItem(MethodSig, P<Block>),
917     TypeImplItem(P<Ty>),
918 }
919
920 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
921 pub enum IntTy {
922     TyIs,
923     TyI8,
924     TyI16,
925     TyI32,
926     TyI64,
927 }
928
929 impl fmt::Debug for IntTy {
930     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
931         fmt::Display::fmt(self, f)
932     }
933 }
934
935 impl fmt::Display for IntTy {
936     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
937         write!(f, "{}", util::int_ty_to_string(*self, None))
938     }
939 }
940
941 impl IntTy {
942     pub fn bit_width(&self) -> Option<usize> {
943         Some(match *self {
944             TyIs => return None,
945             TyI8 => 8,
946             TyI16 => 16,
947             TyI32 => 32,
948             TyI64 => 64,
949         })
950     }
951 }
952
953 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
954 pub enum UintTy {
955     TyUs,
956     TyU8,
957     TyU16,
958     TyU32,
959     TyU64,
960 }
961
962 impl UintTy {
963     pub fn bit_width(&self) -> Option<usize> {
964         Some(match *self {
965             TyUs => return None,
966             TyU8 => 8,
967             TyU16 => 16,
968             TyU32 => 32,
969             TyU64 => 64,
970         })
971     }
972 }
973
974 impl fmt::Debug for UintTy {
975     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
976         fmt::Display::fmt(self, f)
977     }
978 }
979
980 impl fmt::Display for UintTy {
981     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
982         write!(f, "{}", util::uint_ty_to_string(*self, None))
983     }
984 }
985
986 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
987 pub enum FloatTy {
988     TyF32,
989     TyF64,
990 }
991
992 impl fmt::Debug for FloatTy {
993     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
994         fmt::Display::fmt(self, f)
995     }
996 }
997
998 impl fmt::Display for FloatTy {
999     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1000         write!(f, "{}", util::float_ty_to_string(*self))
1001     }
1002 }
1003
1004 impl FloatTy {
1005     pub fn bit_width(&self) -> usize {
1006         match *self {
1007             TyF32 => 32,
1008             TyF64 => 64,
1009         }
1010     }
1011 }
1012
1013 // Bind a type to an associated type: `A=Foo`.
1014 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1015 pub struct TypeBinding {
1016     pub id: NodeId,
1017     pub ident: Ident,
1018     pub ty: P<Ty>,
1019     pub span: Span,
1020 }
1021
1022
1023 // NB PartialEq method appears below.
1024 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1025 pub struct Ty {
1026     pub id: NodeId,
1027     pub node: Ty_,
1028     pub span: Span,
1029 }
1030
1031 impl fmt::Debug for Ty {
1032     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1033         write!(f, "type({})", pprust::ty_to_string(self))
1034     }
1035 }
1036
1037 /// Not represented directly in the AST, referred to by name through a ty_path.
1038 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1039 pub enum PrimTy {
1040     TyInt(IntTy),
1041     TyUint(UintTy),
1042     TyFloat(FloatTy),
1043     TyStr,
1044     TyBool,
1045     TyChar
1046 }
1047
1048 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1049 pub struct BareFnTy {
1050     pub unsafety: Unsafety,
1051     pub abi: Abi,
1052     pub lifetimes: Vec<LifetimeDef>,
1053     pub decl: P<FnDecl>
1054 }
1055
1056 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1057 /// The different kinds of types recognized by the compiler
1058 pub enum Ty_ {
1059     TyVec(P<Ty>),
1060     /// A fixed length array (`[T; n]`)
1061     TyFixedLengthVec(P<Ty>, P<Expr>),
1062     /// A raw pointer (`*const T` or `*mut T`)
1063     TyPtr(MutTy),
1064     /// A reference (`&'a T` or `&'a mut T`)
1065     TyRptr(Option<Lifetime>, MutTy),
1066     /// A bare function (e.g. `fn(usize) -> bool`)
1067     TyBareFn(P<BareFnTy>),
1068     /// A tuple (`(A, B, C, D,...)`)
1069     TyTup(Vec<P<Ty>> ),
1070     /// A path (`module::module::...::Type`), optionally
1071     /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1072     ///
1073     /// Type parameters are stored in the Path itself
1074     TyPath(Option<QSelf>, Path),
1075     /// Something like `A+B`. Note that `B` must always be a path.
1076     TyObjectSum(P<Ty>, TyParamBounds),
1077     /// A type like `for<'a> Foo<&'a Bar>`
1078     TyPolyTraitRef(TyParamBounds),
1079     /// No-op; kept solely so that we can pretty-print faithfully
1080     TyParen(P<Ty>),
1081     /// Unused for now
1082     TyTypeof(P<Expr>),
1083     /// TyInfer means the type should be inferred instead of it having been
1084     /// specified. This can appear anywhere in a type.
1085     TyInfer,
1086 }
1087
1088 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1089 pub enum AsmDialect {
1090     AsmAtt,
1091     AsmIntel
1092 }
1093
1094 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1095 pub struct InlineAsm {
1096     pub asm: InternedString,
1097     pub asm_str_style: StrStyle,
1098     pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1099     pub inputs: Vec<(InternedString, P<Expr>)>,
1100     pub clobbers: Vec<InternedString>,
1101     pub volatile: bool,
1102     pub alignstack: bool,
1103     pub dialect: AsmDialect,
1104     pub expn_id: ExpnId,
1105 }
1106
1107 /// represents an argument in a function header
1108 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1109 pub struct Arg {
1110     pub ty: P<Ty>,
1111     pub pat: P<Pat>,
1112     pub id: NodeId,
1113 }
1114
1115 impl Arg {
1116     pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1117         let path = Spanned{span:span,node:self_ident};
1118         Arg {
1119             // HACK(eddyb) fake type for the self argument.
1120             ty: P(Ty {
1121                 id: DUMMY_NODE_ID,
1122                 node: TyInfer,
1123                 span: DUMMY_SP,
1124             }),
1125             pat: P(Pat {
1126                 id: DUMMY_NODE_ID,
1127                 node: PatIdent(BindByValue(mutability), path, None),
1128                 span: span
1129             }),
1130             id: DUMMY_NODE_ID
1131         }
1132     }
1133 }
1134
1135 /// Represents the header (not the body) of a function declaration
1136 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1137 pub struct FnDecl {
1138     pub inputs: Vec<Arg>,
1139     pub output: FunctionRetTy,
1140     pub variadic: bool
1141 }
1142
1143 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1144 pub enum Unsafety {
1145     Unsafe,
1146     Normal,
1147 }
1148
1149 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1150 pub enum Constness {
1151     Const,
1152     NotConst,
1153 }
1154
1155 impl fmt::Display for Unsafety {
1156     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1157         fmt::Display::fmt(match *self {
1158             Unsafety::Normal => "normal",
1159             Unsafety::Unsafe => "unsafe",
1160         }, f)
1161     }
1162 }
1163
1164 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1165 pub enum ImplPolarity {
1166     /// `impl Trait for Type`
1167     Positive,
1168     /// `impl !Trait for Type`
1169     Negative,
1170 }
1171
1172 impl fmt::Debug for ImplPolarity {
1173     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1174         match *self {
1175             ImplPolarity::Positive => "positive".fmt(f),
1176             ImplPolarity::Negative => "negative".fmt(f),
1177         }
1178     }
1179 }
1180
1181
1182 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1183 pub enum FunctionRetTy {
1184     /// Functions with return type `!`that always
1185     /// raise an error or exit (i.e. never return to the caller)
1186     NoReturn(Span),
1187     /// Return type is not specified.
1188     ///
1189     /// Functions default to `()` and
1190     /// closures default to inference. Span points to where return
1191     /// type would be inserted.
1192     DefaultReturn(Span),
1193     /// Everything else
1194     Return(P<Ty>),
1195 }
1196
1197 impl FunctionRetTy {
1198     pub fn span(&self) -> Span {
1199         match *self {
1200             NoReturn(span) => span,
1201             DefaultReturn(span) => span,
1202             Return(ref ty) => ty.span
1203         }
1204     }
1205 }
1206
1207 /// Represents the kind of 'self' associated with a method
1208 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1209 pub enum ExplicitSelf_ {
1210     /// No self
1211     SelfStatic,
1212     /// `self`
1213     SelfValue(Ident),
1214     /// `&'lt self`, `&'lt mut self`
1215     SelfRegion(Option<Lifetime>, Mutability, Ident),
1216     /// `self: TYPE`
1217     SelfExplicit(P<Ty>, Ident),
1218 }
1219
1220 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1221
1222 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1223 pub struct Mod {
1224     /// A span from the first token past `{` to the last token until `}`.
1225     /// For `mod foo;`, the inner span ranges from the first token
1226     /// to the last token in the external file.
1227     pub inner: Span,
1228     pub items: Vec<P<Item>>,
1229 }
1230
1231 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1232 pub struct ForeignMod {
1233     pub abi: Abi,
1234     pub items: Vec<P<ForeignItem>>,
1235 }
1236
1237 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1238 pub struct VariantArg {
1239     pub ty: P<Ty>,
1240     pub id: NodeId,
1241 }
1242
1243 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1244 pub enum VariantKind {
1245     /// Tuple variant, e.g. `Foo(A, B)`
1246     TupleVariantKind(Vec<VariantArg>),
1247     /// Struct variant, e.g. `Foo {x: A, y: B}`
1248     StructVariantKind(P<StructDef>),
1249 }
1250
1251 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1252 pub struct EnumDef {
1253     pub variants: Vec<P<Variant>>,
1254 }
1255
1256 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1257 pub struct Variant_ {
1258     pub name: Ident,
1259     pub attrs: Vec<Attribute>,
1260     pub kind: VariantKind,
1261     pub id: NodeId,
1262     /// Explicit discriminant, eg `Foo = 1`
1263     pub disr_expr: Option<P<Expr>>,
1264     pub vis: Visibility,
1265 }
1266
1267 pub type Variant = Spanned<Variant_>;
1268
1269 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1270 pub enum PathListItem_ {
1271     PathListIdent {
1272         name: Ident,
1273         /// renamed in list, eg `use foo::{bar as baz};`
1274         rename: Option<Ident>,
1275         id: NodeId
1276     },
1277     PathListMod {
1278         /// renamed in list, eg `use foo::{self as baz};`
1279         rename: Option<Ident>,
1280         id: NodeId
1281     }
1282 }
1283
1284 impl PathListItem_ {
1285     pub fn id(&self) -> NodeId {
1286         match *self {
1287             PathListIdent { id, .. } | PathListMod { id, .. } => id
1288         }
1289     }
1290
1291     pub fn rename(&self) -> Option<Ident> {
1292         match *self {
1293             PathListIdent { rename, .. } | PathListMod { rename, .. } => rename
1294         }
1295     }
1296 }
1297
1298 pub type PathListItem = Spanned<PathListItem_>;
1299
1300 pub type ViewPath = Spanned<ViewPath_>;
1301
1302 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1303 pub enum ViewPath_ {
1304
1305     /// `foo::bar::baz as quux`
1306     ///
1307     /// or just
1308     ///
1309     /// `foo::bar::baz` (with `as baz` implicitly on the right)
1310     ViewPathSimple(Ident, Path),
1311
1312     /// `foo::bar::*`
1313     ViewPathGlob(Path),
1314
1315     /// `foo::bar::{a,b,c}`
1316     ViewPathList(Path, Vec<PathListItem>)
1317 }
1318
1319 /// Meta-data associated with an item
1320 pub type Attribute = Spanned<Attribute_>;
1321
1322 /// Distinguishes between Attributes that decorate items and Attributes that
1323 /// are contained as statements within items. These two cases need to be
1324 /// distinguished for pretty-printing.
1325 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1326 pub enum AttrStyle {
1327     AttrOuter,
1328     AttrInner,
1329 }
1330
1331 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1332 pub struct AttrId(pub usize);
1333
1334 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1335 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1336 pub struct Attribute_ {
1337     pub id: AttrId,
1338     pub style: AttrStyle,
1339     pub value: P<MetaItem>,
1340     pub is_sugared_doc: bool,
1341 }
1342
1343 /// TraitRef's appear in impls.
1344 ///
1345 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1346 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1347 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1348 /// same as the impl's node id).
1349 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1350 pub struct TraitRef {
1351     pub path: Path,
1352     pub ref_id: NodeId,
1353 }
1354
1355 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1356 pub struct PolyTraitRef {
1357     /// The `'a` in `<'a> Foo<&'a T>`
1358     pub bound_lifetimes: Vec<LifetimeDef>,
1359
1360     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1361     pub trait_ref: TraitRef,
1362
1363     pub span: Span,
1364 }
1365
1366 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1367 pub enum Visibility {
1368     Public,
1369     Inherited,
1370 }
1371
1372 impl Visibility {
1373     pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1374         match self {
1375             &Inherited => parent_visibility,
1376             &Public => *self
1377         }
1378     }
1379 }
1380
1381 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1382 pub struct StructField_ {
1383     pub kind: StructFieldKind,
1384     pub id: NodeId,
1385     pub ty: P<Ty>,
1386     pub attrs: Vec<Attribute>,
1387 }
1388
1389 impl StructField_ {
1390     pub fn ident(&self) -> Option<Ident> {
1391         match self.kind {
1392             NamedField(ref ident, _) => Some(ident.clone()),
1393             UnnamedField(_) => None
1394         }
1395     }
1396 }
1397
1398 pub type StructField = Spanned<StructField_>;
1399
1400 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1401 pub enum StructFieldKind {
1402     NamedField(Ident, Visibility),
1403     /// Element of a tuple-like struct
1404     UnnamedField(Visibility),
1405 }
1406
1407 impl StructFieldKind {
1408     pub fn is_unnamed(&self) -> bool {
1409         match *self {
1410             UnnamedField(..) => true,
1411             NamedField(..) => false,
1412         }
1413     }
1414 }
1415
1416 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1417 pub struct StructDef {
1418     /// Fields, not including ctor
1419     pub fields: Vec<StructField>,
1420     /// ID of the constructor. This is only used for tuple- or enum-like
1421     /// structs.
1422     pub ctor_id: Option<NodeId>,
1423 }
1424
1425 /*
1426   FIXME (#3300): Should allow items to be anonymous. Right now
1427   we just use dummy names for anon items.
1428  */
1429 /// An item
1430 ///
1431 /// The name might be a dummy name in case of anonymous items
1432 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1433 pub struct Item {
1434     pub ident: Ident,
1435     pub attrs: Vec<Attribute>,
1436     pub id: NodeId,
1437     pub node: Item_,
1438     pub vis: Visibility,
1439     pub span: Span,
1440 }
1441
1442 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1443 pub enum Item_ {
1444     /// An`extern crate` item, with optional original crate name,
1445     ///
1446     /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1447     ItemExternCrate(Option<Name>),
1448     /// A `use` or `pub use` item
1449     ItemUse(P<ViewPath>),
1450
1451     /// A `static` item
1452     ItemStatic(P<Ty>, Mutability, P<Expr>),
1453     /// A `const` item
1454     ItemConst(P<Ty>, P<Expr>),
1455     /// A function declaration
1456     ItemFn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
1457     /// A module
1458     ItemMod(Mod),
1459     /// An external module
1460     ItemForeignMod(ForeignMod),
1461     /// A type alias, e.g. `type Foo = Bar<u8>`
1462     ItemTy(P<Ty>, Generics),
1463     /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1464     ItemEnum(EnumDef, Generics),
1465     /// A struct definition, e.g. `struct Foo<A> {x: A}`
1466     ItemStruct(P<StructDef>, Generics),
1467     /// Represents a Trait Declaration
1468     ItemTrait(Unsafety,
1469               Generics,
1470               TyParamBounds,
1471               Vec<P<TraitItem>>),
1472
1473     // Default trait implementations
1474     ///
1475     // `impl Trait for .. {}`
1476     ItemDefaultImpl(Unsafety, TraitRef),
1477     /// An implementation, eg `impl<A> Trait for Foo { .. }`
1478     ItemImpl(Unsafety,
1479              ImplPolarity,
1480              Generics,
1481              Option<TraitRef>, // (optional) trait this impl implements
1482              P<Ty>, // self
1483              Vec<P<ImplItem>>),
1484 }
1485
1486 impl Item_ {
1487     pub fn descriptive_variant(&self) -> &str {
1488         match *self {
1489             ItemExternCrate(..) => "extern crate",
1490             ItemUse(..) => "use",
1491             ItemStatic(..) => "static item",
1492             ItemConst(..) => "constant item",
1493             ItemFn(..) => "function",
1494             ItemMod(..) => "module",
1495             ItemForeignMod(..) => "foreign module",
1496             ItemTy(..) => "type alias",
1497             ItemEnum(..) => "enum",
1498             ItemStruct(..) => "struct",
1499             ItemTrait(..) => "trait",
1500             ItemImpl(..) |
1501             ItemDefaultImpl(..) => "item"
1502         }
1503     }
1504 }
1505
1506 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1507 pub struct ForeignItem {
1508     pub ident: Ident,
1509     pub attrs: Vec<Attribute>,
1510     pub node: ForeignItem_,
1511     pub id: NodeId,
1512     pub span: Span,
1513     pub vis: Visibility,
1514 }
1515
1516 /// An item within an `extern` block
1517 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1518 pub enum ForeignItem_ {
1519     /// A foreign function
1520     ForeignItemFn(P<FnDecl>, Generics),
1521     /// A foreign static item (`static ext: u8`), with optional mutability
1522     /// (the boolean is true when mutable)
1523     ForeignItemStatic(P<Ty>, bool),
1524 }
1525
1526 impl ForeignItem_ {
1527     pub fn descriptive_variant(&self) -> &str {
1528         match *self {
1529             ForeignItemFn(..) => "foreign function",
1530             ForeignItemStatic(..) => "foreign static item"
1531         }
1532     }
1533 }