]> git.proxmox.com Git - rustc.git/blame - src/libsyntax/ast.rs
New upstream version 1.19.0+dfsg3
[rustc.git] / src / libsyntax / ast.rs
CommitLineData
1a4d82fc 1// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
223e47cc
LB
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 abstract syntax tree.
12
1a4d82fc 13pub use self::TyParamBound::*;
1a4d82fc 14pub use self::UnsafeSource::*;
1a4d82fc 15pub use self::ViewPath_::*;
1a4d82fc 16pub use self::PathParameters::*;
cc61c64b 17pub use symbol::{Ident, Symbol as Name};
3157f602 18pub use util::ThinVec;
1a4d82fc 19
cc61c64b 20use syntax_pos::{Span, DUMMY_SP};
3157f602 21use codemap::{respan, Spanned};
1a4d82fc 22use abi::Abi;
cc61c64b 23use ext::hygiene::{Mark, SyntaxContext};
62682a34 24use print::pprust;
1a4d82fc 25use ptr::P;
cc61c64b 26use rustc_data_structures::indexed_vec;
476ff2be 27use symbol::{Symbol, keywords};
8bb4bdeb 28use tokenstream::{ThinTokenStream, TokenStream};
1a4d82fc 29
cc61c64b 30use serialize::{self, Encoder, Decoder};
476ff2be 31use std::collections::HashSet;
1a4d82fc 32use std::fmt;
1a4d82fc 33use std::rc::Rc;
9e0c209e
SL
34use std::u32;
35
62682a34 36#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
223e47cc 37pub struct Lifetime {
1a4d82fc
JJ
38 pub id: NodeId,
39 pub span: Span,
7cac9316 40 pub ident: Ident,
1a4d82fc
JJ
41}
42
62682a34
SL
43impl fmt::Debug for Lifetime {
44 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
46 }
47}
48
3157f602 49/// A lifetime definition, e.g. `'a: 'b+'c+'d`
85aaf69f 50#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc 51pub struct LifetimeDef {
c30ab7b3 52 pub attrs: ThinVec<Attribute>,
1a4d82fc
JJ
53 pub lifetime: Lifetime,
54 pub bounds: Vec<Lifetime>
223e47cc
LB
55}
56
3157f602
XL
57/// A "Path" is essentially Rust's notion of a name.
58///
59/// It's represented as a sequence of identifiers,
1a4d82fc 60/// along with a bunch of supporting information.
3157f602
XL
61///
62/// E.g. `std::cmp::PartialEq`
62682a34 63#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
970d7e83 64pub struct Path {
1a4d82fc 65 pub span: Span,
1a4d82fc 66 /// The segments in the path: the things separated by `::`.
32a655c1 67 /// Global paths begin with `keywords::CrateRoot`.
1a4d82fc
JJ
68 pub segments: Vec<PathSegment>,
69}
70
cc61c64b
XL
71impl<'a> PartialEq<&'a str> for Path {
72 fn eq(&self, string: &&'a str) -> bool {
73 self.segments.len() == 1 && self.segments[0].identifier.name == *string
74 }
75}
76
62682a34
SL
77impl fmt::Debug for Path {
78 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79 write!(f, "path({})", pprust::path_to_string(self))
80 }
81}
82
83impl fmt::Display for Path {
84 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85 write!(f, "{}", pprust::path_to_string(self))
86 }
87}
88
54a0048b
SL
89impl Path {
90 // convert a span and an identifier to the corresponding
91 // 1-segment path
92 pub fn from_ident(s: Span, identifier: Ident) -> Path {
93 Path {
94 span: s,
8bb4bdeb 95 segments: vec![PathSegment::from_ident(identifier, s)],
54a0048b
SL
96 }
97 }
32a655c1
SL
98
99 pub fn default_to_global(mut self) -> Path {
100 let name = self.segments[0].identifier.name;
101 if !self.is_global() && name != "$crate" &&
102 name != keywords::SelfValue.name() && name != keywords::Super.name() {
103 self.segments.insert(0, PathSegment::crate_root());
104 }
105 self
106 }
107
108 pub fn is_global(&self) -> bool {
109 !self.segments.is_empty() && self.segments[0].identifier.name == keywords::CrateRoot.name()
110 }
54a0048b
SL
111}
112
3157f602
XL
113/// A segment of a path: an identifier, an optional lifetime, and a set of types.
114///
115/// E.g. `std`, `String` or `Box<T>`
85aaf69f 116#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
117pub struct PathSegment {
118 /// The identifier portion of this path segment.
119 pub identifier: Ident,
8bb4bdeb
XL
120 /// Span of the segment identifier.
121 pub span: Span,
1a4d82fc
JJ
122
123 /// Type/lifetime parameters attached to this path. They come in
124 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
125 /// this is more than just simple syntactic sugar; the use of
126 /// parens affects the region binding rules, so we preserve the
127 /// distinction.
32a655c1
SL
128 /// The `Option<P<..>>` wrapper is purely a size optimization;
129 /// `None` is used to represent both `Path` and `Path<>`.
130 pub parameters: Option<P<PathParameters>>,
131}
132
32a655c1 133impl PathSegment {
8bb4bdeb
XL
134 pub fn from_ident(ident: Ident, span: Span) -> Self {
135 PathSegment { identifier: ident, span: span, parameters: None }
136 }
32a655c1
SL
137 pub fn crate_root() -> Self {
138 PathSegment {
139 identifier: keywords::CrateRoot.ident(),
8bb4bdeb 140 span: DUMMY_SP,
32a655c1
SL
141 parameters: None,
142 }
143 }
1a4d82fc
JJ
144}
145
3157f602
XL
146/// Parameters of a path segment.
147///
148/// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
85aaf69f 149#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc 150pub enum PathParameters {
c34b1796 151 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
9cc50fc6 152 AngleBracketed(AngleBracketedParameterData),
c34b1796 153 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
9cc50fc6 154 Parenthesized(ParenthesizedParameterData),
1a4d82fc
JJ
155}
156
1a4d82fc 157/// A path like `Foo<'a, T>`
32a655c1 158#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
1a4d82fc
JJ
159pub struct AngleBracketedParameterData {
160 /// The lifetime parameters for this path segment.
161 pub lifetimes: Vec<Lifetime>,
162 /// The type parameters for this path segment, if present.
32a655c1 163 pub types: Vec<P<Ty>>,
1a4d82fc 164 /// Bindings (equality constraints) on associated types, if present.
3157f602
XL
165 ///
166 /// E.g., `Foo<A=Bar>`.
32a655c1 167 pub bindings: Vec<TypeBinding>,
223e47cc
LB
168}
169
32a655c1
SL
170impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
171 fn into(self) -> Option<P<PathParameters>> {
172 let empty = self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty();
173 if empty { None } else { Some(P(PathParameters::AngleBracketed(self))) }
1a4d82fc
JJ
174 }
175}
176
177/// A path like `Foo(A,B) -> C`
85aaf69f 178#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc 179pub struct ParenthesizedParameterData {
85aaf69f
SL
180 /// Overall span
181 pub span: Span,
182
1a4d82fc
JJ
183 /// `(A,B)`
184 pub inputs: Vec<P<Ty>>,
185
186 /// `C`
187 pub output: Option<P<Ty>>,
188}
189
9e0c209e
SL
190#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Debug)]
191pub struct NodeId(u32);
192
193impl NodeId {
194 pub fn new(x: usize) -> NodeId {
195 assert!(x < (u32::MAX as usize));
196 NodeId(x as u32)
197 }
198
199 pub fn from_u32(x: u32) -> NodeId {
200 NodeId(x)
201 }
223e47cc 202
9e0c209e
SL
203 pub fn as_usize(&self) -> usize {
204 self.0 as usize
205 }
206
207 pub fn as_u32(&self) -> u32 {
208 self.0
209 }
cc61c64b
XL
210
211 pub fn placeholder_from_mark(mark: Mark) -> Self {
212 NodeId(mark.as_u32())
213 }
214
215 pub fn placeholder_to_mark(self) -> Mark {
216 Mark::from_u32(self.0)
217 }
9e0c209e
SL
218}
219
220impl fmt::Display for NodeId {
221 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
222 fmt::Display::fmt(&self.0, f)
223 }
224}
225
226impl serialize::UseSpecializedEncodable for NodeId {
227 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
228 s.emit_u32(self.0)
229 }
230}
231
232impl serialize::UseSpecializedDecodable for NodeId {
233 fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
234 d.read_u32().map(NodeId)
235 }
236}
223e47cc 237
cc61c64b
XL
238impl indexed_vec::Idx for NodeId {
239 fn new(idx: usize) -> Self {
240 NodeId::new(idx)
241 }
242
243 fn index(self) -> usize {
244 self.as_usize()
245 }
246}
247
e9174d1e 248/// Node id used to represent the root of the crate.
9e0c209e 249pub const CRATE_NODE_ID: NodeId = NodeId(0);
223e47cc 250
1a4d82fc
JJ
251/// When parsing and doing expansions, we initially give all AST nodes this AST
252/// node value. Then later, in the renumber pass, we renumber them to have
253/// small, positive ids.
9e0c209e 254pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
1a4d82fc
JJ
255
256/// The AST represents all type param bounds as types.
257/// typeck::collect::compute_bounds matches these against
258/// the "special" built-in traits (see middle::lang_items) and
259/// detects Copy, Send and Sync.
85aaf69f 260#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
223e47cc 261pub enum TyParamBound {
1a4d82fc
JJ
262 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
263 RegionTyParamBound(Lifetime)
223e47cc
LB
264}
265
1a4d82fc
JJ
266/// A modifier on a bound, currently this is only used for `?Sized`, where the
267/// modifier is `Maybe`. Negative bounds should also be handled here.
85aaf69f 268#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
269pub enum TraitBoundModifier {
270 None,
271 Maybe,
272}
273
32a655c1 274pub type TyParamBounds = Vec<TyParamBound>;
1a4d82fc 275
85aaf69f 276#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
223e47cc 277pub struct TyParam {
c30ab7b3 278 pub attrs: ThinVec<Attribute>,
1a4d82fc
JJ
279 pub ident: Ident,
280 pub id: NodeId,
281 pub bounds: TyParamBounds,
282 pub default: Option<P<Ty>>,
9e0c209e 283 pub span: Span,
223e47cc
LB
284}
285
1a4d82fc
JJ
286/// Represents lifetimes and type parameters attached to a declaration
287/// of a function, enum, trait, etc.
85aaf69f 288#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
223e47cc 289pub struct Generics {
1a4d82fc 290 pub lifetimes: Vec<LifetimeDef>,
32a655c1 291 pub ty_params: Vec<TyParam>,
1a4d82fc 292 pub where_clause: WhereClause,
9e0c209e 293 pub span: Span,
223e47cc
LB
294}
295
970d7e83 296impl Generics {
970d7e83 297 pub fn is_lt_parameterized(&self) -> bool {
9346a6ac 298 !self.lifetimes.is_empty()
223e47cc 299 }
970d7e83 300 pub fn is_type_parameterized(&self) -> bool {
9346a6ac
AL
301 !self.ty_params.is_empty()
302 }
303 pub fn is_parameterized(&self) -> bool {
304 self.is_lt_parameterized() || self.is_type_parameterized()
223e47cc 305 }
476ff2be
SL
306 pub fn span_for_name(&self, name: &str) -> Option<Span> {
307 for t in &self.ty_params {
308 if t.ident.name == name {
309 return Some(t.span);
310 }
311 }
312 None
313 }
223e47cc
LB
314}
315
9cc50fc6 316impl Default for Generics {
9e0c209e 317 /// Creates an instance of `Generics`.
9cc50fc6
SL
318 fn default() -> Generics {
319 Generics {
320 lifetimes: Vec::new(),
32a655c1 321 ty_params: Vec::new(),
9cc50fc6
SL
322 where_clause: WhereClause {
323 id: DUMMY_NODE_ID,
324 predicates: Vec::new(),
9e0c209e
SL
325 },
326 span: DUMMY_SP,
9cc50fc6
SL
327 }
328 }
329}
330
c34b1796 331/// A `where` clause in a definition
85aaf69f 332#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
333pub struct WhereClause {
334 pub id: NodeId,
335 pub predicates: Vec<WherePredicate>,
223e47cc
LB
336}
337
c34b1796 338/// A single predicate in a `where` clause
85aaf69f 339#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc 340pub enum WherePredicate {
9cc50fc6 341 /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c`
1a4d82fc 342 BoundPredicate(WhereBoundPredicate),
c34b1796 343 /// A lifetime predicate, e.g. `'a: 'b+'c`
1a4d82fc 344 RegionPredicate(WhereRegionPredicate),
c34b1796 345 /// An equality predicate (unsupported)
e9174d1e 346 EqPredicate(WhereEqPredicate),
223e47cc
LB
347}
348
3157f602
XL
349/// A type bound.
350///
351/// E.g. `for<'c> Foo: Send+Clone+'c`
85aaf69f 352#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
353pub struct WhereBoundPredicate {
354 pub span: Span,
c34b1796 355 /// Any lifetimes from a `for` binding
85aaf69f 356 pub bound_lifetimes: Vec<LifetimeDef>,
c34b1796 357 /// The type being bounded
1a4d82fc 358 pub bounded_ty: P<Ty>,
c34b1796 359 /// Trait and lifetime bounds (`Clone+Send+'static`)
9cc50fc6 360 pub bounds: TyParamBounds,
223e47cc
LB
361}
362
3157f602
XL
363/// A lifetime predicate.
364///
365/// E.g. `'a: 'b+'c`
85aaf69f 366#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
367pub struct WhereRegionPredicate {
368 pub span: Span,
369 pub lifetime: Lifetime,
370 pub bounds: Vec<Lifetime>,
371}
223e47cc 372
3157f602
XL
373/// An equality predicate (unsupported).
374///
375/// E.g. `T=int`
85aaf69f 376#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
377pub struct WhereEqPredicate {
378 pub id: NodeId,
379 pub span: Span,
32a655c1
SL
380 pub lhs_ty: P<Ty>,
381 pub rhs_ty: P<Ty>,
1a4d82fc
JJ
382}
383
384/// The set of MetaItems that define the compilation environment of the crate,
385/// used to drive conditional compilation
476ff2be 386pub type CrateConfig = HashSet<(Name, Option<Symbol>)>;
223e47cc 387
85aaf69f 388#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
389pub struct Crate {
390 pub module: Mod,
391 pub attrs: Vec<Attribute>,
1a4d82fc 392 pub span: Span,
970d7e83 393}
223e47cc 394
9e0c209e
SL
395/// A spanned compile-time attribute list item.
396pub type NestedMetaItem = Spanned<NestedMetaItemKind>;
397
398/// Possible values inside of compile-time attribute lists.
399///
400/// E.g. the '..' in `#[name(..)]`.
401#[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialEq)]
402pub enum NestedMetaItemKind {
403 /// A full MetaItem, for recursive meta items.
476ff2be 404 MetaItem(MetaItem),
9e0c209e
SL
405 /// A literal.
406 ///
407 /// E.g. "foo", 64, true
408 Literal(Lit),
409}
410
3157f602
XL
411/// A spanned compile-time attribute item.
412///
413/// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
476ff2be
SL
414#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
415pub struct MetaItem {
416 pub name: Name,
417 pub node: MetaItemKind,
418 pub span: Span,
419}
1a4d82fc 420
3157f602
XL
421/// A compile-time attribute item.
422///
423/// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`
476ff2be 424#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
7453a54e 425pub enum MetaItemKind {
3157f602
XL
426 /// Word meta item.
427 ///
428 /// E.g. `test` as in `#[test]`
476ff2be 429 Word,
3157f602
XL
430 /// List meta item.
431 ///
432 /// E.g. `derive(..)` as in `#[derive(..)]`
476ff2be 433 List(Vec<NestedMetaItem>),
3157f602
XL
434 /// Name value meta item.
435 ///
436 /// E.g. `feature = "foo"` as in `#[feature = "foo"]`
476ff2be 437 NameValue(Lit)
223e47cc
LB
438}
439
3157f602
XL
440/// A Block (`{ .. }`).
441///
442/// E.g. `{ .. }` as in `fn foo() { .. }`
85aaf69f 443#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc 444pub struct Block {
c34b1796 445 /// Statements in a block
7453a54e 446 pub stmts: Vec<Stmt>,
1a4d82fc 447 pub id: NodeId,
c34b1796 448 /// Distinguishes between `unsafe { ... }` and `{ ... }`
1a4d82fc
JJ
449 pub rules: BlockCheckMode,
450 pub span: Span,
451}
452
62682a34 453#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1a4d82fc
JJ
454pub struct Pat {
455 pub id: NodeId,
7453a54e 456 pub node: PatKind,
1a4d82fc
JJ
457 pub span: Span,
458}
459
62682a34
SL
460impl fmt::Debug for Pat {
461 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
462 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
463 }
464}
465
a7813a04
XL
466impl Pat {
467 pub fn walk<F>(&self, it: &mut F) -> bool
468 where F: FnMut(&Pat) -> bool
469 {
470 if !it(self) {
471 return false;
472 }
473
474 match self.node {
475 PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
476 PatKind::Struct(_, ref fields, _) => {
477 fields.iter().all(|field| field.node.pat.walk(it))
478 }
3157f602 479 PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
a7813a04
XL
480 s.iter().all(|p| p.walk(it))
481 }
482 PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
483 s.walk(it)
484 }
c30ab7b3 485 PatKind::Slice(ref before, ref slice, ref after) => {
a7813a04
XL
486 before.iter().all(|p| p.walk(it)) &&
487 slice.iter().all(|p| p.walk(it)) &&
488 after.iter().all(|p| p.walk(it))
489 }
490 PatKind::Wild |
491 PatKind::Lit(_) |
9e0c209e
SL
492 PatKind::Range(..) |
493 PatKind::Ident(..) |
a7813a04 494 PatKind::Path(..) |
a7813a04
XL
495 PatKind::Mac(_) => {
496 true
497 }
498 }
499 }
500}
501
c34b1796
AL
502/// A single field in a struct pattern
503///
504/// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
505/// are treated the same as` x: x, y: ref y, z: ref mut z`,
506/// except is_shorthand is true
85aaf69f 507#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc 508pub struct FieldPat {
c34b1796 509 /// The identifier for the field
1a4d82fc 510 pub ident: Ident,
c34b1796 511 /// The pattern the field is destructured to
1a4d82fc
JJ
512 pub pat: P<Pat>,
513 pub is_shorthand: bool,
32a655c1 514 pub attrs: ThinVec<Attribute>,
1a4d82fc
JJ
515}
516
85aaf69f 517#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1a4d82fc 518pub enum BindingMode {
9cc50fc6
SL
519 ByRef(Mutability),
520 ByValue(Mutability),
1a4d82fc
JJ
521}
522
32a655c1
SL
523#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
524pub enum RangeEnd {
525 Included,
526 Excluded,
527}
528
85aaf69f 529#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
7453a54e 530pub enum PatKind {
92a42be0 531 /// Represents a wildcard pattern (`_`)
7453a54e 532 Wild,
1a4d82fc 533
3157f602
XL
534 /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
535 /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
536 /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
537 /// during name resolution.
7453a54e 538 Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
1a4d82fc 539
7453a54e
SL
540 /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`.
541 /// The `bool` is `true` in the presence of a `..`.
542 Struct(Path, Vec<Spanned<FieldPat>>, bool),
543
3157f602
XL
544 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
545 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
546 /// 0 <= position <= subpats.len()
547 TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
1a4d82fc 548
3157f602
XL
549 /// A possibly qualified path pattern.
550 /// Unquailfied path patterns `A::B::C` can legally refer to variants, structs, constants
551 /// or associated constants. Quailfied path patterns `<A>::B::C`/`<A as Trait>::B::C` can
552 /// only legally refer to associated constants.
553 Path(Option<QSelf>, Path),
d9579d0f 554
3157f602
XL
555 /// A tuple pattern `(a, b)`.
556 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
557 /// 0 <= position <= subpats.len()
558 Tuple(Vec<P<Pat>>, Option<usize>),
c34b1796 559 /// A `box` pattern
7453a54e 560 Box(P<Pat>),
c34b1796 561 /// A reference pattern, e.g. `&mut (a, b)`
7453a54e 562 Ref(P<Pat>, Mutability),
c34b1796 563 /// A literal
7453a54e 564 Lit(P<Expr>),
32a655c1
SL
565 /// A range pattern, e.g. `1...2` or `1..2`
566 Range(P<Expr>, P<Expr>, RangeEnd),
92a42be0 567 /// `[a, b, ..i, y, z]` is represented as:
c30ab7b3
SL
568 /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`
569 Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
c34b1796 570 /// A macro pattern; pre-expansion
7453a54e 571 Mac(Mac),
1a4d82fc
JJ
572}
573
85aaf69f 574#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1a4d82fc 575pub enum Mutability {
7453a54e
SL
576 Mutable,
577 Immutable,
1a4d82fc
JJ
578}
579
85aaf69f 580#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
7453a54e 581pub enum BinOpKind {
c34b1796 582 /// The `+` operator (addition)
7453a54e 583 Add,
c34b1796 584 /// The `-` operator (subtraction)
7453a54e 585 Sub,
c34b1796 586 /// The `*` operator (multiplication)
7453a54e 587 Mul,
c34b1796 588 /// The `/` operator (division)
7453a54e 589 Div,
c34b1796 590 /// The `%` operator (modulus)
7453a54e 591 Rem,
c34b1796 592 /// The `&&` operator (logical and)
7453a54e 593 And,
c34b1796 594 /// The `||` operator (logical or)
7453a54e 595 Or,
c34b1796 596 /// The `^` operator (bitwise xor)
7453a54e 597 BitXor,
c34b1796 598 /// The `&` operator (bitwise and)
7453a54e 599 BitAnd,
c34b1796 600 /// The `|` operator (bitwise or)
7453a54e 601 BitOr,
c34b1796 602 /// The `<<` operator (shift left)
7453a54e 603 Shl,
c34b1796 604 /// The `>>` operator (shift right)
7453a54e 605 Shr,
c34b1796 606 /// The `==` operator (equality)
7453a54e 607 Eq,
c34b1796 608 /// The `<` operator (less than)
7453a54e 609 Lt,
c34b1796 610 /// The `<=` operator (less than or equal to)
7453a54e 611 Le,
c34b1796 612 /// The `!=` operator (not equal to)
7453a54e 613 Ne,
c34b1796 614 /// The `>=` operator (greater than or equal to)
7453a54e 615 Ge,
c34b1796 616 /// The `>` operator (greater than)
7453a54e 617 Gt,
1a4d82fc
JJ
618}
619
7453a54e 620impl BinOpKind {
9cc50fc6 621 pub fn to_string(&self) -> &'static str {
7453a54e 622 use self::BinOpKind::*;
9cc50fc6 623 match *self {
7453a54e
SL
624 Add => "+",
625 Sub => "-",
626 Mul => "*",
627 Div => "/",
628 Rem => "%",
629 And => "&&",
630 Or => "||",
631 BitXor => "^",
632 BitAnd => "&",
633 BitOr => "|",
634 Shl => "<<",
635 Shr => ">>",
636 Eq => "==",
637 Lt => "<",
638 Le => "<=",
639 Ne => "!=",
640 Ge => ">=",
641 Gt => ">",
9cc50fc6
SL
642 }
643 }
644 pub fn lazy(&self) -> bool {
645 match *self {
7453a54e 646 BinOpKind::And | BinOpKind::Or => true,
9cc50fc6
SL
647 _ => false
648 }
649 }
650
651 pub fn is_shift(&self) -> bool {
652 match *self {
7453a54e 653 BinOpKind::Shl | BinOpKind::Shr => true,
9cc50fc6
SL
654 _ => false
655 }
656 }
657 pub fn is_comparison(&self) -> bool {
7453a54e 658 use self::BinOpKind::*;
9cc50fc6 659 match *self {
7453a54e 660 Eq | Lt | Le | Ne | Gt | Ge =>
9cc50fc6 661 true,
7453a54e
SL
662 And | Or | Add | Sub | Mul | Div | Rem |
663 BitXor | BitAnd | BitOr | Shl | Shr =>
9cc50fc6
SL
664 false,
665 }
666 }
667 /// Returns `true` if the binary operator takes its arguments by value
668 pub fn is_by_value(&self) -> bool {
7453a54e 669 !self.is_comparison()
9cc50fc6
SL
670 }
671}
672
7453a54e 673pub type BinOp = Spanned<BinOpKind>;
85aaf69f
SL
674
675#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1a4d82fc 676pub enum UnOp {
c34b1796 677 /// The `*` operator for dereferencing
7453a54e 678 Deref,
c34b1796 679 /// The `!` operator for logical inversion
7453a54e 680 Not,
c34b1796 681 /// The `-` operator for negation
7453a54e 682 Neg,
1a4d82fc
JJ
683}
684
9cc50fc6
SL
685impl UnOp {
686 /// Returns `true` if the unary operator takes its argument by value
687 pub fn is_by_value(u: UnOp) -> bool {
688 match u {
7453a54e 689 UnOp::Neg | UnOp::Not => true,
9cc50fc6
SL
690 _ => false,
691 }
692 }
693
694 pub fn to_string(op: UnOp) -> &'static str {
695 match op {
7453a54e
SL
696 UnOp::Deref => "*",
697 UnOp::Not => "!",
698 UnOp::Neg => "-",
9cc50fc6
SL
699 }
700 }
701}
702
c34b1796 703/// A statement
3157f602
XL
704#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
705pub struct Stmt {
706 pub id: NodeId,
707 pub node: StmtKind,
708 pub span: Span,
709}
1a4d82fc 710
5bcae85e
SL
711impl Stmt {
712 pub fn add_trailing_semicolon(mut self) -> Self {
713 self.node = match self.node {
714 StmtKind::Expr(expr) => StmtKind::Semi(expr),
715 StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
716 (mac, MacStmtStyle::Semicolon, attrs)
717 })),
7cac9316 718 node => node,
5bcae85e
SL
719 };
720 self
721 }
722}
723
62682a34
SL
724impl fmt::Debug for Stmt {
725 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3157f602 726 write!(f, "stmt({}: {})", self.id.to_string(), pprust::stmt_to_string(self))
62682a34
SL
727 }
728}
729
730
731#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
7453a54e 732pub enum StmtKind {
3157f602
XL
733 /// A local (let) binding.
734 Local(P<Local>),
1a4d82fc 735
3157f602
XL
736 /// An item definition.
737 Item(P<Item>),
1a4d82fc 738
3157f602
XL
739 /// Expr without trailing semi-colon.
740 Expr(P<Expr>),
92a42be0 741
3157f602 742 Semi(P<Expr>),
9cc50fc6 743
3157f602 744 Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
92a42be0
SL
745}
746
85aaf69f 747#[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
748pub enum MacStmtStyle {
749 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
750 /// `foo!(...);`, `foo![...];`
7453a54e 751 Semicolon,
1a4d82fc 752 /// The macro statement had braces; e.g. foo! { ... }
7453a54e 753 Braces,
1a4d82fc
JJ
754 /// The macro statement had parentheses or brackets and no semicolon; e.g.
755 /// `foo!(...)`. All of these will end up being converted into macro
756 /// expressions.
7453a54e 757 NoBraces,
1a4d82fc
JJ
758}
759
1a4d82fc
JJ
760// FIXME (pending discussion of #1697, #2178...): local should really be
761// a refinement on pat.
762/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
85aaf69f 763#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
764pub struct Local {
765 pub pat: P<Pat>,
766 pub ty: Option<P<Ty>>,
c34b1796 767 /// Initializer expression to set the value, if any
1a4d82fc
JJ
768 pub init: Option<P<Expr>>,
769 pub id: NodeId,
770 pub span: Span,
3157f602 771 pub attrs: ThinVec<Attribute>,
1a4d82fc
JJ
772}
773
3157f602
XL
774/// An arm of a 'match'.
775///
776/// E.g. `0...10 => { println!("match!") }` as in
777///
778/// ```rust,ignore
779/// match n {
780/// 0...10 => { println!("match!") },
781/// // ..
782/// }
783/// ```
85aaf69f 784#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
785pub struct Arm {
786 pub attrs: Vec<Attribute>,
787 pub pats: Vec<P<Pat>>,
788 pub guard: Option<P<Expr>>,
789 pub body: P<Expr>,
790}
791
85aaf69f 792#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
793pub struct Field {
794 pub ident: SpannedIdent,
795 pub expr: P<Expr>,
796 pub span: Span,
c30ab7b3 797 pub is_shorthand: bool,
32a655c1 798 pub attrs: ThinVec<Attribute>,
1a4d82fc
JJ
799}
800
801pub type SpannedIdent = Spanned<Ident>;
802
85aaf69f 803#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1a4d82fc 804pub enum BlockCheckMode {
7453a54e
SL
805 Default,
806 Unsafe(UnsafeSource),
1a4d82fc
JJ
807}
808
85aaf69f 809#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1a4d82fc
JJ
810pub enum UnsafeSource {
811 CompilerGenerated,
812 UserProvided,
813}
814
c34b1796 815/// An expression
62682a34 816#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
1a4d82fc
JJ
817pub struct Expr {
818 pub id: NodeId,
7453a54e 819 pub node: ExprKind,
1a4d82fc 820 pub span: Span,
3157f602 821 pub attrs: ThinVec<Attribute>
1a4d82fc
JJ
822}
823
62682a34
SL
824impl fmt::Debug for Expr {
825 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
826 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
827 }
828}
829
54a0048b
SL
830/// Limit types of a range (inclusive or exclusive)
831#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
832pub enum RangeLimits {
833 /// Inclusive at the beginning, exclusive at the end
834 HalfOpen,
835 /// Inclusive at the beginning and end
836 Closed,
837}
838
85aaf69f 839#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
7453a54e 840pub enum ExprKind {
b039eaaf 841 /// A `box x` expression.
7453a54e 842 Box(P<Expr>),
1a4d82fc 843 /// First expr is the place; second expr is the value.
7453a54e 844 InPlace(P<Expr>, P<Expr>),
c34b1796 845 /// An array (`[a, b, c, d]`)
32a655c1 846 Array(Vec<P<Expr>>),
c34b1796
AL
847 /// A function call
848 ///
849 /// The first field resolves to the function itself,
850 /// and the second field is the list of arguments
7453a54e 851 Call(P<Expr>, Vec<P<Expr>>),
c34b1796
AL
852 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
853 ///
854 /// The `SpannedIdent` is the identifier for the method name.
855 /// The vector of `Ty`s are the ascripted type parameters for the method
856 /// (within the angle brackets).
857 ///
858 /// The first element of the vector of `Expr`s is the expression that evaluates
859 /// to the object on which the method is being called on (the receiver),
860 /// and the remaining elements are the rest of the arguments.
861 ///
862 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
7453a54e
SL
863 /// `ExprKind::MethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
864 MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
c34b1796 865 /// A tuple (`(a, b, c ,d)`)
7453a54e 866 Tup(Vec<P<Expr>>),
c34b1796 867 /// A binary operation (For example: `a + b`, `a * b`)
7453a54e 868 Binary(BinOp, P<Expr>, P<Expr>),
c34b1796 869 /// A unary operation (For example: `!x`, `*x`)
7453a54e 870 Unary(UnOp, P<Expr>),
54a0048b 871 /// A literal (For example: `1`, `"foo"`)
7453a54e 872 Lit(P<Lit>),
c34b1796 873 /// A cast (`foo as f64`)
7453a54e
SL
874 Cast(P<Expr>, P<Ty>),
875 Type(P<Expr>, P<Ty>),
c34b1796
AL
876 /// An `if` block, with an optional else block
877 ///
878 /// `if expr { block } else { expr }`
7453a54e 879 If(P<Expr>, P<Block>, Option<P<Expr>>),
c34b1796
AL
880 /// An `if let` expression with an optional else block
881 ///
882 /// `if let pat = expr { block } else { expr }`
883 ///
884 /// This is desugared to a `match` expression.
7453a54e 885 IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
c34b1796
AL
886 /// A while loop, with an optional label
887 ///
888 /// `'label: while expr { block }`
3157f602 889 While(P<Expr>, P<Block>, Option<SpannedIdent>),
c34b1796
AL
890 /// A while-let loop, with an optional label
891 ///
892 /// `'label: while let pat = expr { block }`
893 ///
894 /// This is desugared to a combination of `loop` and `match` expressions.
3157f602 895 WhileLet(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
c34b1796
AL
896 /// A for loop, with an optional label
897 ///
898 /// `'label: for pat in expr { block }`
899 ///
900 /// This is desugared to a combination of `loop` and `match` expressions.
3157f602 901 ForLoop(P<Pat>, P<Expr>, P<Block>, Option<SpannedIdent>),
c34b1796
AL
902 /// Conditionless loop (can be exited with break, continue, or return)
903 ///
904 /// `'label: loop { block }`
3157f602 905 Loop(P<Block>, Option<SpannedIdent>),
b039eaaf 906 /// A `match` block.
7453a54e 907 Match(P<Expr>, Vec<Arm>),
476ff2be 908 /// A closure (for example, `move |a, b, c| a + b + c`)
a7813a04
XL
909 ///
910 /// The final span is the span of the argument block `|...|`
476ff2be 911 Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
c34b1796 912 /// A block (`{ ... }`)
7453a54e 913 Block(P<Block>),
cc61c64b
XL
914 /// A catch block (`catch { ... }`)
915 Catch(P<Block>),
1a4d82fc 916
c34b1796 917 /// An assignment (`a = foo()`)
7453a54e 918 Assign(P<Expr>, P<Expr>),
c34b1796
AL
919 /// An assignment with an operator
920 ///
921 /// For example, `a += 1`.
7453a54e 922 AssignOp(BinOp, P<Expr>, P<Expr>),
c34b1796 923 /// Access of a named struct field (`obj.foo`)
7453a54e 924 Field(P<Expr>, SpannedIdent),
c34b1796
AL
925 /// Access of an unnamed field of a struct or tuple-struct
926 ///
927 /// For example, `foo.0`.
7453a54e 928 TupField(P<Expr>, Spanned<usize>),
c34b1796 929 /// An indexing operation (`foo[2]`)
7453a54e 930 Index(P<Expr>, P<Expr>),
54a0048b
SL
931 /// A range (`1..2`, `1..`, `..2`, `1...2`, `1...`, `...2`)
932 Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1a4d82fc 933
c34b1796
AL
934 /// Variable reference, possibly containing `::` and/or type
935 /// parameters, e.g. foo::bar::<baz>.
936 ///
937 /// Optionally "qualified",
3157f602 938 /// E.g. `<Vec<T> as SomeTrait>::SomeType`.
7453a54e 939 Path(Option<QSelf>, Path),
1a4d82fc 940
c34b1796 941 /// A referencing operation (`&a` or `&mut a`)
7453a54e 942 AddrOf(Mutability, P<Expr>),
476ff2be
SL
943 /// A `break`, with an optional label to break, and an optional expression
944 Break(Option<SpannedIdent>, Option<P<Expr>>),
c34b1796 945 /// A `continue`, with an optional label
3157f602 946 Continue(Option<SpannedIdent>),
c34b1796 947 /// A `return`, with an optional value to be returned
7453a54e 948 Ret(Option<P<Expr>>),
1a4d82fc 949
c34b1796 950 /// Output of the `asm!()` macro
c30ab7b3 951 InlineAsm(P<InlineAsm>),
1a4d82fc 952
c34b1796 953 /// A macro invocation; pre-expansion
7453a54e 954 Mac(Mac),
1a4d82fc
JJ
955
956 /// A struct literal expression.
c34b1796
AL
957 ///
958 /// For example, `Foo {x: 1, y: 2}`, or
959 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
7453a54e 960 Struct(Path, Vec<Field>, Option<P<Expr>>),
1a4d82fc 961
e9174d1e 962 /// An array literal constructed from one repeated element.
c34b1796 963 ///
54a0048b 964 /// For example, `[1; 5]`. The first expression is the element
c34b1796 965 /// to be repeated; the second is the number of times to repeat it.
7453a54e 966 Repeat(P<Expr>, P<Expr>),
1a4d82fc
JJ
967
968 /// No-op: used solely so we can pretty-print faithfully
7453a54e 969 Paren(P<Expr>),
54a0048b
SL
970
971 /// `expr?`
972 Try(P<Expr>),
1a4d82fc
JJ
973}
974
c34b1796
AL
975/// The explicit Self type in a "qualified path". The actual
976/// path, including the trait and the associated item, is stored
977/// separately. `position` represents the index of the associated
978/// item qualified with this Self type.
979///
3157f602 980/// ```rust,ignore
92a42be0
SL
981/// <Vec<T> as a::b::Trait>::AssociatedItem
982/// ^~~~~ ~~~~~~~~~~~~~~^
983/// ty position = 3
1a4d82fc 984///
92a42be0
SL
985/// <Vec<T>>::AssociatedItem
986/// ^~~~~ ^
987/// ty position = 0
988/// ```
85aaf69f 989#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
c34b1796
AL
990pub struct QSelf {
991 pub ty: P<Ty>,
992 pub position: usize
1a4d82fc
JJ
993}
994
7453a54e 995/// A capture clause
85aaf69f 996#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
7453a54e
SL
997pub enum CaptureBy {
998 Value,
999 Ref,
1a4d82fc
JJ
1000}
1001
1a4d82fc 1002pub type Mac = Spanned<Mac_>;
223e47cc 1003
1a4d82fc
JJ
1004/// Represents a macro invocation. The Path indicates which macro
1005/// is being invoked, and the vector of token-trees contains the source
1006/// of the macro invocation.
c34b1796 1007///
b039eaaf
SL
1008/// NB: the additional ident for a macro_rules-style macro is actually
1009/// stored in the enclosing item. Oog.
85aaf69f 1010#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
b039eaaf
SL
1011pub struct Mac_ {
1012 pub path: Path,
8bb4bdeb
XL
1013 pub tts: ThinTokenStream,
1014}
1015
1016impl Mac_ {
1017 pub fn stream(&self) -> TokenStream {
1018 self.tts.clone().into()
1019 }
1a4d82fc 1020}
223e47cc 1021
7cac9316
XL
1022#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1023pub struct MacroDef {
1024 pub tokens: ThinTokenStream,
1025 pub legacy: bool,
1026}
1027
1028impl MacroDef {
1029 pub fn stream(&self) -> TokenStream {
1030 self.tokens.clone().into()
1031 }
1032}
1033
85aaf69f 1034#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1a4d82fc 1035pub enum StrStyle {
c34b1796 1036 /// A regular string, like `"foo"`
7453a54e 1037 Cooked,
c34b1796
AL
1038 /// A raw string, like `r##"foo"##`
1039 ///
1040 /// The uint is the number of `#` symbols used
7453a54e 1041 Raw(usize)
223e47cc
LB
1042}
1043
c34b1796 1044/// A literal
7453a54e 1045pub type Lit = Spanned<LitKind>;
9346a6ac 1046
85aaf69f 1047#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1a4d82fc 1048pub enum LitIntType {
7453a54e
SL
1049 Signed(IntTy),
1050 Unsigned(UintTy),
1051 Unsuffixed,
223e47cc
LB
1052}
1053
3157f602
XL
1054/// Literal kind.
1055///
1056/// E.g. `"foo"`, `42`, `12.34` or `bool`
85aaf69f 1057#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
7453a54e 1058pub enum LitKind {
c34b1796 1059 /// A string literal (`"foo"`)
476ff2be 1060 Str(Symbol, StrStyle),
c34b1796 1061 /// A byte string (`b"foo"`)
7453a54e 1062 ByteStr(Rc<Vec<u8>>),
c34b1796 1063 /// A byte char (`b'f'`)
7453a54e 1064 Byte(u8),
c34b1796 1065 /// A character literal (`'a'`)
7453a54e 1066 Char(char),
54a0048b 1067 /// An integer literal (`1`)
32a655c1 1068 Int(u128, LitIntType),
c34b1796 1069 /// A float literal (`1f64` or `1E10f64`)
476ff2be 1070 Float(Symbol, FloatTy),
c34b1796 1071 /// A float literal without a suffix (`1.0 or 1.0E10`)
476ff2be 1072 FloatUnsuffixed(Symbol),
c34b1796 1073 /// A boolean literal
7453a54e 1074 Bool(bool),
223e47cc
LB
1075}
1076
7453a54e 1077impl LitKind {
9cc50fc6
SL
1078 /// Returns true if this literal is a string and false otherwise.
1079 pub fn is_str(&self) -> bool {
1080 match *self {
7453a54e 1081 LitKind::Str(..) => true,
9cc50fc6
SL
1082 _ => false,
1083 }
1084 }
9e0c209e
SL
1085
1086 /// Returns true if this literal has no suffix. Note: this will return true
1087 /// for literals with prefixes such as raw strings and byte strings.
1088 pub fn is_unsuffixed(&self) -> bool {
1089 match *self {
1090 // unsuffixed variants
7cac9316
XL
1091 LitKind::Str(..) |
1092 LitKind::ByteStr(..) |
1093 LitKind::Byte(..) |
1094 LitKind::Char(..) |
1095 LitKind::Int(_, LitIntType::Unsuffixed) |
1096 LitKind::FloatUnsuffixed(..) |
9e0c209e
SL
1097 LitKind::Bool(..) => true,
1098 // suffixed variants
7cac9316
XL
1099 LitKind::Int(_, LitIntType::Signed(..)) |
1100 LitKind::Int(_, LitIntType::Unsigned(..)) |
9e0c209e
SL
1101 LitKind::Float(..) => false,
1102 }
1103 }
1104
1105 /// Returns true if this literal has a suffix.
1106 pub fn is_suffixed(&self) -> bool {
1107 !self.is_unsuffixed()
1108 }
9cc50fc6
SL
1109}
1110
223e47cc
LB
1111// NB: If you change this, you'll probably want to change the corresponding
1112// type structure in middle/ty.rs as well.
85aaf69f 1113#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1114pub struct MutTy {
1115 pub ty: P<Ty>,
1116 pub mutbl: Mutability,
1117}
1118
c34b1796
AL
1119/// Represents a method's signature in a trait declaration,
1120/// or in an implementation.
85aaf69f 1121#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
c34b1796 1122pub struct MethodSig {
1a4d82fc 1123 pub unsafety: Unsafety,
9e0c209e 1124 pub constness: Spanned<Constness>,
1a4d82fc
JJ
1125 pub abi: Abi,
1126 pub decl: P<FnDecl>,
1127 pub generics: Generics,
1a4d82fc
JJ
1128}
1129
54a0048b
SL
1130/// Represents an item declaration within a trait declaration,
1131/// possibly including a default implementation. A trait item is
1132/// either required (meaning it doesn't have an implementation, just a
1133/// signature) or provided (meaning it has a default implementation).
85aaf69f 1134#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
c34b1796
AL
1135pub struct TraitItem {
1136 pub id: NodeId,
1137 pub ident: Ident,
1138 pub attrs: Vec<Attribute>,
7453a54e 1139 pub node: TraitItemKind,
c34b1796 1140 pub span: Span,
1a4d82fc
JJ
1141}
1142
85aaf69f 1143#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
7453a54e
SL
1144pub enum TraitItemKind {
1145 Const(P<Ty>, Option<P<Expr>>),
1146 Method(MethodSig, Option<P<Block>>),
1147 Type(TyParamBounds, Option<P<Ty>>),
3157f602 1148 Macro(Mac),
1a4d82fc
JJ
1149}
1150
85aaf69f 1151#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
c34b1796 1152pub struct ImplItem {
1a4d82fc 1153 pub id: NodeId,
1a4d82fc
JJ
1154 pub ident: Ident,
1155 pub vis: Visibility,
54a0048b 1156 pub defaultness: Defaultness,
1a4d82fc 1157 pub attrs: Vec<Attribute>,
92a42be0 1158 pub node: ImplItemKind,
c34b1796
AL
1159 pub span: Span,
1160}
1161
1162#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
92a42be0
SL
1163pub enum ImplItemKind {
1164 Const(P<Ty>, P<Expr>),
1165 Method(MethodSig, P<Block>),
1166 Type(P<Ty>),
1167 Macro(Mac),
1a4d82fc
JJ
1168}
1169
c34b1796 1170#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1a4d82fc 1171pub enum IntTy {
7453a54e
SL
1172 Is,
1173 I8,
1174 I16,
1175 I32,
1176 I64,
32a655c1 1177 I128,
1a4d82fc
JJ
1178}
1179
85aaf69f 1180impl fmt::Debug for IntTy {
1a4d82fc 1181 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85aaf69f 1182 fmt::Display::fmt(self, f)
1a4d82fc 1183 }
223e47cc
LB
1184}
1185
85aaf69f 1186impl fmt::Display for IntTy {
1a4d82fc 1187 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9cc50fc6 1188 write!(f, "{}", self.ty_to_string())
1a4d82fc
JJ
1189 }
1190}
223e47cc 1191
1a4d82fc 1192impl IntTy {
9cc50fc6
SL
1193 pub fn ty_to_string(&self) -> &'static str {
1194 match *self {
7453a54e
SL
1195 IntTy::Is => "isize",
1196 IntTy::I8 => "i8",
1197 IntTy::I16 => "i16",
1198 IntTy::I32 => "i32",
32a655c1
SL
1199 IntTy::I64 => "i64",
1200 IntTy::I128 => "i128",
9cc50fc6
SL
1201 }
1202 }
1203
32a655c1
SL
1204 pub fn val_to_string(&self, val: i128) -> String {
1205 // cast to a u128 so we can correctly print INT128_MIN. All integral types
1206 // are parsed as u128, so we wouldn't want to print an extra negative
9cc50fc6 1207 // sign.
32a655c1 1208 format!("{}{}", val as u128, self.ty_to_string())
9cc50fc6
SL
1209 }
1210
e9174d1e
SL
1211 pub fn bit_width(&self) -> Option<usize> {
1212 Some(match *self {
7453a54e
SL
1213 IntTy::Is => return None,
1214 IntTy::I8 => 8,
1215 IntTy::I16 => 16,
1216 IntTy::I32 => 32,
1217 IntTy::I64 => 64,
32a655c1 1218 IntTy::I128 => 128,
e9174d1e 1219 })
1a4d82fc 1220 }
223e47cc
LB
1221}
1222
c34b1796 1223#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1a4d82fc 1224pub enum UintTy {
7453a54e
SL
1225 Us,
1226 U8,
1227 U16,
1228 U32,
1229 U64,
32a655c1 1230 U128,
1a4d82fc
JJ
1231}
1232
1a4d82fc 1233impl UintTy {
9cc50fc6
SL
1234 pub fn ty_to_string(&self) -> &'static str {
1235 match *self {
7453a54e
SL
1236 UintTy::Us => "usize",
1237 UintTy::U8 => "u8",
1238 UintTy::U16 => "u16",
1239 UintTy::U32 => "u32",
32a655c1
SL
1240 UintTy::U64 => "u64",
1241 UintTy::U128 => "u128",
9cc50fc6
SL
1242 }
1243 }
1244
32a655c1 1245 pub fn val_to_string(&self, val: u128) -> String {
9cc50fc6
SL
1246 format!("{}{}", val, self.ty_to_string())
1247 }
1248
e9174d1e
SL
1249 pub fn bit_width(&self) -> Option<usize> {
1250 Some(match *self {
7453a54e
SL
1251 UintTy::Us => return None,
1252 UintTy::U8 => 8,
1253 UintTy::U16 => 16,
1254 UintTy::U32 => 32,
1255 UintTy::U64 => 64,
32a655c1 1256 UintTy::U128 => 128,
e9174d1e 1257 })
1a4d82fc
JJ
1258 }
1259}
223e47cc 1260
85aaf69f 1261impl fmt::Debug for UintTy {
1a4d82fc 1262 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85aaf69f 1263 fmt::Display::fmt(self, f)
223e47cc
LB
1264 }
1265}
1266
85aaf69f 1267impl fmt::Display for UintTy {
1a4d82fc 1268 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9cc50fc6 1269 write!(f, "{}", self.ty_to_string())
1a4d82fc
JJ
1270 }
1271}
1272
1273#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1274pub enum FloatTy {
7453a54e
SL
1275 F32,
1276 F64,
1a4d82fc 1277}
223e47cc 1278
85aaf69f 1279impl fmt::Debug for FloatTy {
1a4d82fc 1280 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85aaf69f 1281 fmt::Display::fmt(self, f)
223e47cc
LB
1282 }
1283}
1284
85aaf69f 1285impl fmt::Display for FloatTy {
1a4d82fc 1286 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9cc50fc6 1287 write!(f, "{}", self.ty_to_string())
1a4d82fc
JJ
1288 }
1289}
223e47cc 1290
1a4d82fc 1291impl FloatTy {
9cc50fc6
SL
1292 pub fn ty_to_string(&self) -> &'static str {
1293 match *self {
7453a54e
SL
1294 FloatTy::F32 => "f32",
1295 FloatTy::F64 => "f64",
9cc50fc6
SL
1296 }
1297 }
1298
e9174d1e 1299 pub fn bit_width(&self) -> usize {
1a4d82fc 1300 match *self {
7453a54e
SL
1301 FloatTy::F32 => 32,
1302 FloatTy::F64 => 64,
1a4d82fc 1303 }
223e47cc
LB
1304 }
1305}
1306
1a4d82fc 1307// Bind a type to an associated type: `A=Foo`.
85aaf69f 1308#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1309pub struct TypeBinding {
1310 pub id: NodeId,
1311 pub ident: Ident,
1312 pub ty: P<Ty>,
1313 pub span: Span,
1314}
1315
62682a34 1316#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
223e47cc 1317pub struct Ty {
1a4d82fc 1318 pub id: NodeId,
7453a54e 1319 pub node: TyKind,
1a4d82fc 1320 pub span: Span,
223e47cc
LB
1321}
1322
62682a34
SL
1323impl fmt::Debug for Ty {
1324 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1325 write!(f, "type({})", pprust::ty_to_string(self))
1326 }
1327}
1328
85aaf69f 1329#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1330pub struct BareFnTy {
1331 pub unsafety: Unsafety,
1332 pub abi: Abi,
1333 pub lifetimes: Vec<LifetimeDef>,
1334 pub decl: P<FnDecl>
1335}
1336
1a4d82fc 1337/// The different kinds of types recognized by the compiler
3157f602 1338#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
7453a54e 1339pub enum TyKind {
c30ab7b3
SL
1340 /// A variable-length slice (`[T]`)
1341 Slice(P<Ty>),
c34b1796 1342 /// A fixed length array (`[T; n]`)
c30ab7b3 1343 Array(P<Ty>, P<Expr>),
1a4d82fc 1344 /// A raw pointer (`*const T` or `*mut T`)
7453a54e 1345 Ptr(MutTy),
1a4d82fc 1346 /// A reference (`&'a T` or `&'a mut T`)
7453a54e 1347 Rptr(Option<Lifetime>, MutTy),
85aaf69f 1348 /// A bare function (e.g. `fn(usize) -> bool`)
7453a54e 1349 BareFn(P<BareFnTy>),
5bcae85e
SL
1350 /// The never type (`!`)
1351 Never,
1a4d82fc 1352 /// A tuple (`(A, B, C, D,...)`)
7453a54e 1353 Tup(Vec<P<Ty>> ),
c34b1796
AL
1354 /// A path (`module::module::...::Type`), optionally
1355 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1a4d82fc
JJ
1356 ///
1357 /// Type parameters are stored in the Path itself
7453a54e 1358 Path(Option<QSelf>, Path),
32a655c1
SL
1359 /// A trait object type `Bound1 + Bound2 + Bound3`
1360 /// where `Bound` is a trait or a lifetime.
1361 TraitObject(TyParamBounds),
1362 /// An `impl Bound1 + Bound2 + Bound3` type
1363 /// where `Bound` is a trait or a lifetime.
5bcae85e 1364 ImplTrait(TyParamBounds),
1a4d82fc 1365 /// No-op; kept solely so that we can pretty-print faithfully
7453a54e 1366 Paren(P<Ty>),
1a4d82fc 1367 /// Unused for now
7453a54e
SL
1368 Typeof(P<Expr>),
1369 /// TyKind::Infer means the type should be inferred instead of it having been
1a4d82fc 1370 /// specified. This can appear anywhere in a type.
7453a54e 1371 Infer,
3157f602
XL
1372 /// Inferred type of a `self` or `&self` argument in a method.
1373 ImplicitSelf,
e9174d1e 1374 // A macro in the type position.
7453a54e 1375 Mac(Mac),
cc61c64b
XL
1376 /// Placeholder for a kind that has failed to be defined.
1377 Err,
1a4d82fc
JJ
1378}
1379
3157f602
XL
1380/// Inline assembly dialect.
1381///
1382/// E.g. `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
85aaf69f 1383#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1a4d82fc 1384pub enum AsmDialect {
b039eaaf
SL
1385 Att,
1386 Intel,
1a4d82fc
JJ
1387}
1388
3157f602
XL
1389/// Inline assembly.
1390///
1391/// E.g. `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")``
9cc50fc6
SL
1392#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1393pub struct InlineAsmOutput {
476ff2be 1394 pub constraint: Symbol,
9cc50fc6
SL
1395 pub expr: P<Expr>,
1396 pub is_rw: bool,
1397 pub is_indirect: bool,
1398}
1399
3157f602
XL
1400/// Inline assembly.
1401///
1402/// E.g. `asm!("NOP");`
85aaf69f 1403#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc 1404pub struct InlineAsm {
476ff2be 1405 pub asm: Symbol,
1a4d82fc 1406 pub asm_str_style: StrStyle,
9cc50fc6 1407 pub outputs: Vec<InlineAsmOutput>,
476ff2be
SL
1408 pub inputs: Vec<(Symbol, P<Expr>)>,
1409 pub clobbers: Vec<Symbol>,
1a4d82fc
JJ
1410 pub volatile: bool,
1411 pub alignstack: bool,
1412 pub dialect: AsmDialect,
cc61c64b 1413 pub ctxt: SyntaxContext,
1a4d82fc
JJ
1414}
1415
3157f602
XL
1416/// An argument in a function header.
1417///
1418/// E.g. `bar: usize` as in `fn foo(bar: usize)`
85aaf69f 1419#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1420pub struct Arg {
1421 pub ty: P<Ty>,
1422 pub pat: P<Pat>,
1423 pub id: NodeId,
1424}
1425
3157f602
XL
1426/// Alternative representation for `Arg`s describing `self` parameter of methods.
1427///
1428/// E.g. `&mut self` as in `fn foo(&mut self)`
a7813a04
XL
1429#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1430pub enum SelfKind {
a7813a04 1431 /// `self`, `mut self`
3157f602 1432 Value(Mutability),
a7813a04 1433 /// `&'lt self`, `&'lt mut self`
3157f602 1434 Region(Option<Lifetime>, Mutability),
a7813a04 1435 /// `self: TYPE`, `mut self: TYPE`
3157f602 1436 Explicit(P<Ty>, Mutability),
a7813a04
XL
1437}
1438
1439pub type ExplicitSelf = Spanned<SelfKind>;
1440
1a4d82fc 1441impl Arg {
a7813a04 1442 pub fn to_self(&self) -> Option<ExplicitSelf> {
3157f602 1443 if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
a7813a04
XL
1444 if ident.node.name == keywords::SelfValue.name() {
1445 return match self.ty.node {
3157f602
XL
1446 TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1447 TyKind::Rptr(lt, MutTy{ref ty, mutbl}) if ty.node == TyKind::ImplicitSelf => {
1448 Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
a7813a04 1449 }
cc61c64b 1450 _ => Some(respan(self.pat.span.to(self.ty.span),
3157f602 1451 SelfKind::Explicit(self.ty.clone(), mutbl))),
a7813a04
XL
1452 }
1453 }
1454 }
1455 None
1456 }
1457
3157f602
XL
1458 pub fn is_self(&self) -> bool {
1459 if let PatKind::Ident(_, ident, _) = self.pat.node {
1460 ident.node.name == keywords::SelfValue.name()
1461 } else {
1462 false
1463 }
1464 }
1465
1466 pub fn from_self(eself: ExplicitSelf, eself_ident: SpannedIdent) -> Arg {
cc61c64b 1467 let span = eself.span.to(eself_ident.span);
a7813a04
XL
1468 let infer_ty = P(Ty {
1469 id: DUMMY_NODE_ID,
3157f602 1470 node: TyKind::ImplicitSelf,
32a655c1 1471 span: span,
a7813a04 1472 });
32a655c1 1473 let arg = |mutbl, ty| Arg {
3157f602
XL
1474 pat: P(Pat {
1475 id: DUMMY_NODE_ID,
1476 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1477 span: span,
1478 }),
a7813a04
XL
1479 ty: ty,
1480 id: DUMMY_NODE_ID,
1481 };
1482 match eself.node {
32a655c1
SL
1483 SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1484 SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
3157f602 1485 SelfKind::Region(lt, mutbl) => arg(Mutability::Immutable, P(Ty {
a7813a04
XL
1486 id: DUMMY_NODE_ID,
1487 node: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl: mutbl }),
32a655c1
SL
1488 span: span,
1489 })),
a7813a04
XL
1490 }
1491 }
223e47cc
LB
1492}
1493
3157f602
XL
1494/// Header (not the body) of a function declaration.
1495///
1496/// E.g. `fn foo(bar: baz)`
85aaf69f 1497#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1498pub struct FnDecl {
1499 pub inputs: Vec<Arg>,
1500 pub output: FunctionRetTy,
1501 pub variadic: bool
1502}
1503
3157f602
XL
1504impl FnDecl {
1505 pub fn get_self(&self) -> Option<ExplicitSelf> {
1506 self.inputs.get(0).and_then(Arg::to_self)
1507 }
1508 pub fn has_self(&self) -> bool {
1509 self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1510 }
1511}
1512
85aaf69f 1513#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1514pub enum Unsafety {
1515 Unsafe,
1516 Normal,
1517}
1518
62682a34
SL
1519#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1520pub enum Constness {
1521 Const,
1522 NotConst,
1523}
1524
54a0048b
SL
1525#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1526pub enum Defaultness {
1527 Default,
1528 Final,
1529}
1530
85aaf69f 1531impl fmt::Display for Unsafety {
1a4d82fc 1532 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85aaf69f 1533 fmt::Display::fmt(match *self {
1a4d82fc
JJ
1534 Unsafety::Normal => "normal",
1535 Unsafety::Unsafe => "unsafe",
1536 }, f)
1537 }
1538}
1539
1540#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1541pub enum ImplPolarity {
c34b1796 1542 /// `impl Trait for Type`
1a4d82fc 1543 Positive,
c34b1796 1544 /// `impl !Trait for Type`
1a4d82fc
JJ
1545 Negative,
1546}
1547
85aaf69f 1548impl fmt::Debug for ImplPolarity {
1a4d82fc 1549 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
223e47cc 1550 match *self {
1a4d82fc
JJ
1551 ImplPolarity::Positive => "positive".fmt(f),
1552 ImplPolarity::Negative => "negative".fmt(f),
223e47cc
LB
1553 }
1554 }
1555}
1556
1a4d82fc 1557
85aaf69f 1558#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc 1559pub enum FunctionRetTy {
c34b1796
AL
1560 /// Return type is not specified.
1561 ///
1562 /// Functions default to `()` and
85aaf69f
SL
1563 /// closures default to inference. Span points to where return
1564 /// type would be inserted.
7453a54e 1565 Default(Span),
1a4d82fc 1566 /// Everything else
7453a54e 1567 Ty(P<Ty>),
1a4d82fc
JJ
1568}
1569
1570impl FunctionRetTy {
1571 pub fn span(&self) -> Span {
1572 match *self {
7453a54e
SL
1573 FunctionRetTy::Default(span) => span,
1574 FunctionRetTy::Ty(ref ty) => ty.span,
1a4d82fc
JJ
1575 }
1576 }
223e47cc
LB
1577}
1578
3157f602
XL
1579/// Module declaration.
1580///
1581/// E.g. `mod foo;` or `mod foo { .. }`
85aaf69f 1582#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1583pub struct Mod {
1584 /// A span from the first token past `{` to the last token until `}`.
1585 /// For `mod foo;`, the inner span ranges from the first token
1586 /// to the last token in the external file.
1587 pub inner: Span,
1a4d82fc
JJ
1588 pub items: Vec<P<Item>>,
1589}
223e47cc 1590
3157f602
XL
1591/// Foreign module declaration.
1592///
1593/// E.g. `extern { .. }` or `extern C { .. }`
85aaf69f 1594#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1595pub struct ForeignMod {
1596 pub abi: Abi,
7453a54e 1597 pub items: Vec<ForeignItem>,
223e47cc
LB
1598}
1599
cc61c64b
XL
1600/// Global inline assembly
1601///
1602/// aka module-level assembly or file-scoped assembly
1603#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1604pub struct GlobalAsm {
1605 pub asm: Symbol,
1606 pub ctxt: SyntaxContext,
1607}
1608
85aaf69f 1609#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc 1610pub struct EnumDef {
7453a54e 1611 pub variants: Vec<Variant>,
223e47cc
LB
1612}
1613
85aaf69f 1614#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1615pub struct Variant_ {
1616 pub name: Ident,
1617 pub attrs: Vec<Attribute>,
b039eaaf 1618 pub data: VariantData,
3157f602 1619 /// Explicit discriminant, e.g. `Foo = 1`
1a4d82fc 1620 pub disr_expr: Option<P<Expr>>,
223e47cc
LB
1621}
1622
1a4d82fc 1623pub type Variant = Spanned<Variant_>;
223e47cc 1624
85aaf69f 1625#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
9e0c209e
SL
1626pub struct PathListItem_ {
1627 pub name: Ident,
1628 /// renamed in list, e.g. `use foo::{bar as baz};`
1629 pub rename: Option<Ident>,
1630 pub id: NodeId,
1a4d82fc 1631}
223e47cc 1632
9e0c209e 1633pub type PathListItem = Spanned<PathListItem_>;
223e47cc 1634
1a4d82fc 1635pub type ViewPath = Spanned<ViewPath_>;
223e47cc 1636
85aaf69f 1637#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc 1638pub enum ViewPath_ {
223e47cc 1639
1a4d82fc
JJ
1640 /// `foo::bar::baz as quux`
1641 ///
1642 /// or just
1643 ///
1644 /// `foo::bar::baz` (with `as baz` implicitly on the right)
85aaf69f 1645 ViewPathSimple(Ident, Path),
223e47cc 1646
1a4d82fc 1647 /// `foo::bar::*`
85aaf69f 1648 ViewPathGlob(Path),
1a4d82fc
JJ
1649
1650 /// `foo::bar::{a,b,c}`
85aaf69f 1651 ViewPathList(Path, Vec<PathListItem>)
223e47cc
LB
1652}
1653
3157f602
XL
1654impl ViewPath_ {
1655 pub fn path(&self) -> &Path {
1656 match *self {
1657 ViewPathSimple(_, ref path) |
1658 ViewPathGlob (ref path) |
1659 ViewPathList(ref path, _) => path
1660 }
1661 }
1662}
1663
223e47cc 1664
1a4d82fc
JJ
1665/// Distinguishes between Attributes that decorate items and Attributes that
1666/// are contained as statements within items. These two cases need to be
1667/// distinguished for pretty-printing.
85aaf69f 1668#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1a4d82fc 1669pub enum AttrStyle {
b039eaaf
SL
1670 Outer,
1671 Inner,
1a4d82fc 1672}
223e47cc 1673
85aaf69f
SL
1674#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1675pub struct AttrId(pub usize);
1a4d82fc 1676
476ff2be 1677/// Meta-data associated with an item
1a4d82fc 1678/// Doc-comments are promoted to attributes that have is_sugared_doc = true
85aaf69f 1679#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
476ff2be 1680pub struct Attribute {
1a4d82fc
JJ
1681 pub id: AttrId,
1682 pub style: AttrStyle,
cc61c64b
XL
1683 pub path: Path,
1684 pub tokens: TokenStream,
1a4d82fc 1685 pub is_sugared_doc: bool,
476ff2be 1686 pub span: Span,
223e47cc
LB
1687}
1688
1a4d82fc 1689/// TraitRef's appear in impls.
c34b1796 1690///
1a4d82fc
JJ
1691/// resolve maps each TraitRef's ref_id to its defining trait; that's all
1692/// that the ref_id is for. The impl_id maps to the "self type" of this impl.
7453a54e 1693/// If this impl is an ItemKind::Impl, the impl_id is redundant (it could be the
1a4d82fc 1694/// same as the impl's node id).
85aaf69f 1695#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1696pub struct TraitRef {
1697 pub path: Path,
1698 pub ref_id: NodeId,
223e47cc
LB
1699}
1700
85aaf69f 1701#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1702pub struct PolyTraitRef {
1703 /// The `'a` in `<'a> Foo<&'a T>`
1704 pub bound_lifetimes: Vec<LifetimeDef>,
223e47cc 1705
1a4d82fc
JJ
1706 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1707 pub trait_ref: TraitRef,
85aaf69f
SL
1708
1709 pub span: Span,
1a4d82fc
JJ
1710}
1711
cc61c64b
XL
1712impl PolyTraitRef {
1713 pub fn new(lifetimes: Vec<LifetimeDef>, path: Path, span: Span) -> Self {
1714 PolyTraitRef {
1715 bound_lifetimes: lifetimes,
1716 trait_ref: TraitRef { path: path, ref_id: DUMMY_NODE_ID },
1717 span: span,
1718 }
1719 }
1720}
1721
54a0048b 1722#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1723pub enum Visibility {
1724 Public,
a7813a04 1725 Crate(Span),
54a0048b 1726 Restricted { path: P<Path>, id: NodeId },
1a4d82fc
JJ
1727 Inherited,
1728}
1729
3157f602
XL
1730/// Field of a struct.
1731///
1732/// E.g. `bar: usize` as in `struct Foo { bar: usize }`
85aaf69f 1733#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
54a0048b
SL
1734pub struct StructField {
1735 pub span: Span,
1736 pub ident: Option<Ident>,
1737 pub vis: Visibility,
1a4d82fc
JJ
1738 pub id: NodeId,
1739 pub ty: P<Ty>,
1740 pub attrs: Vec<Attribute>,
1741}
1742
b039eaaf
SL
1743/// Fields and Ids of enum variants and structs
1744///
1745/// For enum variants: `NodeId` represents both an Id of the variant itself (relevant for all
1746/// variant kinds) and an Id of the variant's constructor (not relevant for `Struct`-variants).
1747/// One shared Id can be successfully used for these two purposes.
1748/// Id of the whole enum lives in `Item`.
1749///
1750/// For structs: `NodeId` represents an Id of the structure's constructor, so it is not actually
1751/// used for `Struct`-structs (but still presents). Structures don't have an analogue of "Id of
1752/// the variant itself" from enum variants.
1753/// Id of the whole struct lives in `Item`.
85aaf69f 1754#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
b039eaaf 1755pub enum VariantData {
3157f602
XL
1756 /// Struct variant.
1757 ///
1758 /// E.g. `Bar { .. }` as in `enum Foo { Bar { .. } }`
b039eaaf 1759 Struct(Vec<StructField>, NodeId),
3157f602
XL
1760 /// Tuple variant.
1761 ///
1762 /// E.g. `Bar(..)` as in `enum Foo { Bar(..) }`
b039eaaf 1763 Tuple(Vec<StructField>, NodeId),
3157f602
XL
1764 /// Unit variant.
1765 ///
1766 /// E.g. `Bar = ..` as in `enum Foo { Bar = .. }`
b039eaaf
SL
1767 Unit(NodeId),
1768}
1769
1770impl VariantData {
1771 pub fn fields(&self) -> &[StructField] {
1772 match *self {
1773 VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
1774 _ => &[],
1775 }
1776 }
1777 pub fn id(&self) -> NodeId {
1778 match *self {
1779 VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
1780 }
1781 }
1782 pub fn is_struct(&self) -> bool {
1783 if let VariantData::Struct(..) = *self { true } else { false }
1784 }
1785 pub fn is_tuple(&self) -> bool {
1786 if let VariantData::Tuple(..) = *self { true } else { false }
1787 }
1788 pub fn is_unit(&self) -> bool {
1789 if let VariantData::Unit(..) = *self { true } else { false }
1790 }
223e47cc
LB
1791}
1792
c34b1796
AL
1793/// An item
1794///
1795/// The name might be a dummy name in case of anonymous items
85aaf69f 1796#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1797pub struct Item {
1798 pub ident: Ident,
1799 pub attrs: Vec<Attribute>,
1800 pub id: NodeId,
7453a54e 1801 pub node: ItemKind,
1a4d82fc
JJ
1802 pub vis: Visibility,
1803 pub span: Span,
1804}
1805
85aaf69f 1806#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
7453a54e 1807pub enum ItemKind {
3157f602 1808 /// An`extern crate` item, with optional original crate name.
c34b1796 1809 ///
3157f602 1810 /// E.g. `extern crate foo` or `extern crate foo_bar as foo`
7453a54e 1811 ExternCrate(Option<Name>),
3157f602
XL
1812 /// A use declaration (`use` or `pub use`) item.
1813 ///
1814 /// E.g. `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`
7453a54e 1815 Use(P<ViewPath>),
3157f602
XL
1816 /// A static item (`static` or `pub static`).
1817 ///
1818 /// E.g. `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`
7453a54e 1819 Static(P<Ty>, Mutability, P<Expr>),
3157f602
XL
1820 /// A constant item (`const` or `pub const`).
1821 ///
1822 /// E.g. `const FOO: i32 = 42;`
7453a54e 1823 Const(P<Ty>, P<Expr>),
3157f602
XL
1824 /// A function declaration (`fn` or `pub fn`).
1825 ///
1826 /// E.g. `fn foo(bar: usize) -> usize { .. }`
9e0c209e 1827 Fn(P<FnDecl>, Unsafety, Spanned<Constness>, Abi, Generics, P<Block>),
3157f602
XL
1828 /// A module declaration (`mod` or `pub mod`).
1829 ///
1830 /// E.g. `mod foo;` or `mod foo { .. }`
7453a54e 1831 Mod(Mod),
3157f602
XL
1832 /// An external module (`extern` or `pub extern`).
1833 ///
1834 /// E.g. `extern {}` or `extern "C" {}`
7453a54e 1835 ForeignMod(ForeignMod),
cc61c64b
XL
1836 /// Module-level inline assembly (from `global_asm!()`)
1837 GlobalAsm(P<GlobalAsm>),
3157f602
XL
1838 /// A type alias (`type` or `pub type`).
1839 ///
1840 /// E.g. `type Foo = Bar<u8>;`
7453a54e 1841 Ty(P<Ty>, Generics),
3157f602
XL
1842 /// An enum definition (`enum` or `pub enum`).
1843 ///
1844 /// E.g. `enum Foo<A, B> { C<A>, D<B> }`
7453a54e 1845 Enum(EnumDef, Generics),
3157f602
XL
1846 /// A struct definition (`struct` or `pub struct`).
1847 ///
1848 /// E.g. `struct Foo<A> { x: A }`
7453a54e 1849 Struct(VariantData, Generics),
9e0c209e
SL
1850 /// A union definition (`union` or `pub union`).
1851 ///
1852 /// E.g. `union Foo<A, B> { x: A, y: B }`
1853 Union(VariantData, Generics),
3157f602
XL
1854 /// A Trait declaration (`trait` or `pub trait`).
1855 ///
1856 /// E.g. `trait Foo { .. }` or `trait Foo<T> { .. }`
a7813a04 1857 Trait(Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
3157f602 1858 // Default trait implementation.
c34b1796 1859 ///
3157f602 1860 /// E.g. `impl Trait for .. {}` or `impl<T> Trait<T> for .. {}`
7453a54e 1861 DefaultImpl(Unsafety, TraitRef),
3157f602
XL
1862 /// An implementation.
1863 ///
1864 /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
7453a54e 1865 Impl(Unsafety,
1a4d82fc 1866 ImplPolarity,
7cac9316 1867 Defaultness,
1a4d82fc
JJ
1868 Generics,
1869 Option<TraitRef>, // (optional) trait this impl implements
1870 P<Ty>, // self
7453a54e 1871 Vec<ImplItem>),
8bb4bdeb 1872 /// A macro invocation.
3157f602
XL
1873 ///
1874 /// E.g. `macro_rules! foo { .. }` or `foo!(..)`
7453a54e 1875 Mac(Mac),
8bb4bdeb
XL
1876
1877 /// A macro definition.
7cac9316 1878 MacroDef(MacroDef),
1a4d82fc
JJ
1879}
1880
7453a54e 1881impl ItemKind {
1a4d82fc
JJ
1882 pub fn descriptive_variant(&self) -> &str {
1883 match *self {
7453a54e
SL
1884 ItemKind::ExternCrate(..) => "extern crate",
1885 ItemKind::Use(..) => "use",
1886 ItemKind::Static(..) => "static item",
1887 ItemKind::Const(..) => "constant item",
1888 ItemKind::Fn(..) => "function",
1889 ItemKind::Mod(..) => "module",
1890 ItemKind::ForeignMod(..) => "foreign module",
cc61c64b 1891 ItemKind::GlobalAsm(..) => "global asm",
7453a54e
SL
1892 ItemKind::Ty(..) => "type alias",
1893 ItemKind::Enum(..) => "enum",
1894 ItemKind::Struct(..) => "struct",
9e0c209e 1895 ItemKind::Union(..) => "union",
7453a54e
SL
1896 ItemKind::Trait(..) => "trait",
1897 ItemKind::Mac(..) |
8bb4bdeb 1898 ItemKind::MacroDef(..) |
7453a54e
SL
1899 ItemKind::Impl(..) |
1900 ItemKind::DefaultImpl(..) => "item"
1a4d82fc 1901 }
970d7e83 1902 }
1a4d82fc 1903}
970d7e83 1904
85aaf69f 1905#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1a4d82fc
JJ
1906pub struct ForeignItem {
1907 pub ident: Ident,
1908 pub attrs: Vec<Attribute>,
7453a54e 1909 pub node: ForeignItemKind,
1a4d82fc
JJ
1910 pub id: NodeId,
1911 pub span: Span,
1912 pub vis: Visibility,
1913}
970d7e83 1914
c34b1796 1915/// An item within an `extern` block
85aaf69f 1916#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
7453a54e 1917pub enum ForeignItemKind {
c34b1796 1918 /// A foreign function
7453a54e 1919 Fn(P<FnDecl>, Generics),
c34b1796
AL
1920 /// A foreign static item (`static ext: u8`), with optional mutability
1921 /// (the boolean is true when mutable)
7453a54e 1922 Static(P<Ty>, bool),
1a4d82fc 1923}
970d7e83 1924
7453a54e 1925impl ForeignItemKind {
1a4d82fc
JJ
1926 pub fn descriptive_variant(&self) -> &str {
1927 match *self {
7453a54e
SL
1928 ForeignItemKind::Fn(..) => "foreign function",
1929 ForeignItemKind::Static(..) => "foreign static item"
1a4d82fc 1930 }
223e47cc 1931 }
1a4d82fc 1932}
970d7e83 1933
1a4d82fc 1934#[cfg(test)]
d9579d0f 1935mod tests {
1a4d82fc
JJ
1936 use serialize;
1937 use super::*;
1938
1939 // are ASTs encodable?
1940 #[test]
1941 fn check_asts_encodable() {
1942 fn assert_encodable<T: serialize::Encodable>() {}
1943 assert_encodable::<Crate>();
1944 }
1945}