]> git.proxmox.com Git - rustc.git/blob - src/libsyntax/ast.rs
e00cb82649b7b6bb538948623d1f1215eafbcd6e
[rustc.git] / src / libsyntax / ast.rs
1 // Copyright 2012-2014 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 abstract syntax tree.
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::InlinedItem::*;
27 pub use self::IntTy::*;
28 pub use self::Item_::*;
29 pub use self::KleeneOp::*;
30 pub use self::Lit_::*;
31 pub use self::LitIntType::*;
32 pub use self::LocalSource::*;
33 pub use self::Mac_::*;
34 pub use self::MacStmtStyle::*;
35 pub use self::MetaItem_::*;
36 pub use self::Mutability::*;
37 pub use self::Pat_::*;
38 pub use self::PathListItem_::*;
39 pub use self::PatWildKind::*;
40 pub use self::PrimTy::*;
41 pub use self::Sign::*;
42 pub use self::Stmt_::*;
43 pub use self::StrStyle::*;
44 pub use self::StructFieldKind::*;
45 pub use self::TokenTree::*;
46 pub use self::TraitItem_::*;
47 pub use self::Ty_::*;
48 pub use self::TyParamBound::*;
49 pub use self::UintTy::*;
50 pub use self::UnOp::*;
51 pub use self::UnsafeSource::*;
52 pub use self::VariantKind::*;
53 pub use self::ViewPath_::*;
54 pub use self::Visibility::*;
55 pub use self::PathParameters::*;
56
57 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
58 use abi::Abi;
59 use ast_util;
60 use ext::base;
61 use ext::tt::macro_parser;
62 use owned_slice::OwnedSlice;
63 use parse::token::{InternedString, str_to_ident};
64 use parse::token;
65 use parse::lexer;
66 use ptr::P;
67
68 use std::fmt;
69 use std::rc::Rc;
70 use serialize::{Encodable, Decodable, Encoder, Decoder};
71
72 // FIXME #6993: in librustc, uses of "ident" should be replaced
73 // by just "Name".
74
75 /// An identifier contains a Name (index into the interner
76 /// table) and a SyntaxContext to track renaming and
77 /// macro expansion per Flatt et al., "Macros
78 /// That Work Together"
79 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
80 pub struct Ident {
81 pub name: Name,
82 pub ctxt: SyntaxContext
83 }
84
85 impl Ident {
86 /// Construct an identifier with the given name and an empty context:
87 pub fn new(name: Name) -> Ident { Ident {name: name, ctxt: EMPTY_CTXT}}
88
89 pub fn as_str<'a>(&'a self) -> &'a str {
90 self.name.as_str()
91 }
92 }
93
94 impl fmt::Debug for Ident {
95 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96 write!(f, "{}#{}", self.name, self.ctxt)
97 }
98 }
99
100 impl fmt::Display for Ident {
101 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
102 fmt::Display::fmt(&self.name, f)
103 }
104 }
105
106 impl fmt::Debug for Name {
107 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108 let Name(nm) = *self;
109 write!(f, "{:?}({})", token::get_name(*self), nm)
110 }
111 }
112
113 impl fmt::Display for Name {
114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115 fmt::Display::fmt(&token::get_name(*self), f)
116 }
117 }
118
119 impl PartialEq for Ident {
120 fn eq(&self, other: &Ident) -> bool {
121 if self.ctxt == other.ctxt {
122 self.name == other.name
123 } else {
124 // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
125 // idents that have different contexts. You can't fix this without
126 // knowing whether the comparison should be hygienic or non-hygienic.
127 // if it should be non-hygienic (most things are), just compare the
128 // 'name' fields of the idents. Or, even better, replace the idents
129 // with Name's.
130 //
131 // On the other hand, if the comparison does need to be hygienic,
132 // one example and its non-hygienic counterpart would be:
133 // syntax::parse::token::Token::mtwt_eq
134 // syntax::ext::tt::macro_parser::token_name_eq
135 panic!("not allowed to compare these idents: {}, {}. \
136 Probably related to issue \\#6993", self, other);
137 }
138 }
139 fn ne(&self, other: &Ident) -> bool {
140 ! self.eq(other)
141 }
142 }
143
144 /// A SyntaxContext represents a chain of macro-expandings
145 /// and renamings. Each macro expansion corresponds to
146 /// a fresh u32
147
148 // I'm representing this syntax context as an index into
149 // a table, in order to work around a compiler bug
150 // that's causing unreleased memory to cause core dumps
151 // and also perhaps to save some work in destructor checks.
152 // the special uint '0' will be used to indicate an empty
153 // syntax context.
154
155 // this uint is a reference to a table stored in thread-local
156 // storage.
157 pub type SyntaxContext = u32;
158 pub const EMPTY_CTXT : SyntaxContext = 0;
159 pub const ILLEGAL_CTXT : SyntaxContext = 1;
160
161 /// A name is a part of an identifier, representing a string or gensym. It's
162 /// the result of interning.
163 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
164 RustcEncodable, RustcDecodable, Clone, Copy)]
165 pub struct Name(pub u32);
166
167 impl Name {
168 pub fn as_str<'a>(&'a self) -> &'a str {
169 unsafe {
170 // FIXME #12938: can't use copy_lifetime since &str isn't a &T
171 ::std::mem::transmute::<&str,&str>(&token::get_name(*self))
172 }
173 }
174
175 pub fn usize(&self) -> usize {
176 let Name(nm) = *self;
177 nm as usize
178 }
179
180 pub fn ident(&self) -> Ident {
181 Ident { name: *self, ctxt: 0 }
182 }
183 }
184
185 /// A mark represents a unique id associated with a macro expansion
186 pub type Mrk = u32;
187
188 impl Encodable for Ident {
189 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
190 s.emit_str(&token::get_ident(*self))
191 }
192 }
193
194 impl Decodable for Ident {
195 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
196 Ok(str_to_ident(&try!(d.read_str())[..]))
197 }
198 }
199
200 /// Function name (not all functions have names)
201 pub type FnIdent = Option<Ident>;
202
203 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,
204 Debug, Copy)]
205 pub struct Lifetime {
206 pub id: NodeId,
207 pub span: Span,
208 pub name: Name
209 }
210
211 /// A lifetime definition, eg `'a: 'b+'c+'d`
212 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
213 pub struct LifetimeDef {
214 pub lifetime: Lifetime,
215 pub bounds: Vec<Lifetime>
216 }
217
218 /// A "Path" is essentially Rust's notion of a name; for instance:
219 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
220 /// along with a bunch of supporting information.
221 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
222 pub struct Path {
223 pub span: Span,
224 /// A `::foo` path, is relative to the crate root rather than current
225 /// module (like paths in an import).
226 pub global: bool,
227 /// The segments in the path: the things separated by `::`.
228 pub segments: Vec<PathSegment>,
229 }
230
231 /// A segment of a path: an identifier, an optional lifetime, and a set of
232 /// types.
233 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
234 pub struct PathSegment {
235 /// The identifier portion of this path segment.
236 pub identifier: Ident,
237
238 /// Type/lifetime parameters attached to this path. They come in
239 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
240 /// this is more than just simple syntactic sugar; the use of
241 /// parens affects the region binding rules, so we preserve the
242 /// distinction.
243 pub parameters: PathParameters,
244 }
245
246 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
247 pub enum PathParameters {
248 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
249 AngleBracketedParameters(AngleBracketedParameterData),
250 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
251 ParenthesizedParameters(ParenthesizedParameterData),
252 }
253
254 impl PathParameters {
255 pub fn none() -> PathParameters {
256 AngleBracketedParameters(AngleBracketedParameterData {
257 lifetimes: Vec::new(),
258 types: OwnedSlice::empty(),
259 bindings: OwnedSlice::empty(),
260 })
261 }
262
263 pub fn is_empty(&self) -> bool {
264 match *self {
265 AngleBracketedParameters(ref data) => data.is_empty(),
266
267 // Even if the user supplied no types, something like
268 // `X()` is equivalent to `X<(),()>`.
269 ParenthesizedParameters(..) => false,
270 }
271 }
272
273 pub fn has_lifetimes(&self) -> bool {
274 match *self {
275 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
276 ParenthesizedParameters(_) => false,
277 }
278 }
279
280 pub fn has_types(&self) -> bool {
281 match *self {
282 AngleBracketedParameters(ref data) => !data.types.is_empty(),
283 ParenthesizedParameters(..) => true,
284 }
285 }
286
287 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
288 /// parameters in the parenthesized case.
289 pub fn types(&self) -> Vec<&P<Ty>> {
290 match *self {
291 AngleBracketedParameters(ref data) => {
292 data.types.iter().collect()
293 }
294 ParenthesizedParameters(ref data) => {
295 data.inputs.iter()
296 .chain(data.output.iter())
297 .collect()
298 }
299 }
300 }
301
302 pub fn lifetimes(&self) -> Vec<&Lifetime> {
303 match *self {
304 AngleBracketedParameters(ref data) => {
305 data.lifetimes.iter().collect()
306 }
307 ParenthesizedParameters(_) => {
308 Vec::new()
309 }
310 }
311 }
312
313 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
314 match *self {
315 AngleBracketedParameters(ref data) => {
316 data.bindings.iter().collect()
317 }
318 ParenthesizedParameters(_) => {
319 Vec::new()
320 }
321 }
322 }
323 }
324
325 /// A path like `Foo<'a, T>`
326 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
327 pub struct AngleBracketedParameterData {
328 /// The lifetime parameters for this path segment.
329 pub lifetimes: Vec<Lifetime>,
330 /// The type parameters for this path segment, if present.
331 pub types: OwnedSlice<P<Ty>>,
332 /// Bindings (equality constraints) on associated types, if present.
333 /// E.g., `Foo<A=Bar>`.
334 pub bindings: OwnedSlice<P<TypeBinding>>,
335 }
336
337 impl AngleBracketedParameterData {
338 fn is_empty(&self) -> bool {
339 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
340 }
341 }
342
343 /// A path like `Foo(A,B) -> C`
344 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
345 pub struct ParenthesizedParameterData {
346 /// Overall span
347 pub span: Span,
348
349 /// `(A,B)`
350 pub inputs: Vec<P<Ty>>,
351
352 /// `C`
353 pub output: Option<P<Ty>>,
354 }
355
356 pub type CrateNum = u32;
357
358 pub type NodeId = u32;
359
360 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
361 RustcDecodable, Hash, Debug, Copy)]
362 pub struct DefId {
363 pub krate: CrateNum,
364 pub node: NodeId,
365 }
366
367 impl DefId {
368 /// Read the node id, asserting that this def-id is krate-local.
369 pub fn local_id(&self) -> NodeId {
370 assert_eq!(self.krate, LOCAL_CRATE);
371 self.node
372 }
373 }
374
375 /// Item definitions in the currently-compiled crate would have the CrateNum
376 /// LOCAL_CRATE in their DefId.
377 pub const LOCAL_CRATE: CrateNum = 0;
378 pub const CRATE_NODE_ID: NodeId = 0;
379
380 /// When parsing and doing expansions, we initially give all AST nodes this AST
381 /// node value. Then later, in the renumber pass, we renumber them to have
382 /// small, positive ids.
383 pub const DUMMY_NODE_ID: NodeId = !0;
384
385 /// The AST represents all type param bounds as types.
386 /// typeck::collect::compute_bounds matches these against
387 /// the "special" built-in traits (see middle::lang_items) and
388 /// detects Copy, Send and Sync.
389 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
390 pub enum TyParamBound {
391 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
392 RegionTyParamBound(Lifetime)
393 }
394
395 /// A modifier on a bound, currently this is only used for `?Sized`, where the
396 /// modifier is `Maybe`. Negative bounds should also be handled here.
397 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
398 pub enum TraitBoundModifier {
399 None,
400 Maybe,
401 }
402
403 pub type TyParamBounds = OwnedSlice<TyParamBound>;
404
405 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
406 pub struct TyParam {
407 pub ident: Ident,
408 pub id: NodeId,
409 pub bounds: TyParamBounds,
410 pub default: Option<P<Ty>>,
411 pub span: Span
412 }
413
414 /// Represents lifetimes and type parameters attached to a declaration
415 /// of a function, enum, trait, etc.
416 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
417 pub struct Generics {
418 pub lifetimes: Vec<LifetimeDef>,
419 pub ty_params: OwnedSlice<TyParam>,
420 pub where_clause: WhereClause,
421 }
422
423 impl Generics {
424 pub fn is_lt_parameterized(&self) -> bool {
425 !self.lifetimes.is_empty()
426 }
427 pub fn is_type_parameterized(&self) -> bool {
428 !self.ty_params.is_empty()
429 }
430 pub fn is_parameterized(&self) -> bool {
431 self.is_lt_parameterized() || self.is_type_parameterized()
432 }
433 }
434
435 /// A `where` clause in a definition
436 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
437 pub struct WhereClause {
438 pub id: NodeId,
439 pub predicates: Vec<WherePredicate>,
440 }
441
442 /// A single predicate in a `where` clause
443 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
444 pub enum WherePredicate {
445 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
446 BoundPredicate(WhereBoundPredicate),
447 /// A lifetime predicate, e.g. `'a: 'b+'c`
448 RegionPredicate(WhereRegionPredicate),
449 /// An equality predicate (unsupported)
450 EqPredicate(WhereEqPredicate)
451 }
452
453 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
454 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
455 pub struct WhereBoundPredicate {
456 pub span: Span,
457 /// Any lifetimes from a `for` binding
458 pub bound_lifetimes: Vec<LifetimeDef>,
459 /// The type being bounded
460 pub bounded_ty: P<Ty>,
461 /// Trait and lifetime bounds (`Clone+Send+'static`)
462 pub bounds: OwnedSlice<TyParamBound>,
463 }
464
465 /// A lifetime predicate, e.g. `'a: 'b+'c`
466 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
467 pub struct WhereRegionPredicate {
468 pub span: Span,
469 pub lifetime: Lifetime,
470 pub bounds: Vec<Lifetime>,
471 }
472
473 /// An equality predicate (unsupported), e.g. `T=int`
474 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
475 pub struct WhereEqPredicate {
476 pub id: NodeId,
477 pub span: Span,
478 pub path: Path,
479 pub ty: P<Ty>,
480 }
481
482 /// The set of MetaItems that define the compilation environment of the crate,
483 /// used to drive conditional compilation
484 pub type CrateConfig = Vec<P<MetaItem>> ;
485
486 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
487 pub struct Crate {
488 pub module: Mod,
489 pub attrs: Vec<Attribute>,
490 pub config: CrateConfig,
491 pub span: Span,
492 pub exported_macros: Vec<MacroDef>,
493 }
494
495 pub type MetaItem = Spanned<MetaItem_>;
496
497 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
498 pub enum MetaItem_ {
499 MetaWord(InternedString),
500 MetaList(InternedString, Vec<P<MetaItem>>),
501 MetaNameValue(InternedString, Lit),
502 }
503
504 // can't be derived because the MetaList requires an unordered comparison
505 impl PartialEq for MetaItem_ {
506 fn eq(&self, other: &MetaItem_) -> bool {
507 match *self {
508 MetaWord(ref ns) => match *other {
509 MetaWord(ref no) => (*ns) == (*no),
510 _ => false
511 },
512 MetaNameValue(ref ns, ref vs) => match *other {
513 MetaNameValue(ref no, ref vo) => {
514 (*ns) == (*no) && vs.node == vo.node
515 }
516 _ => false
517 },
518 MetaList(ref ns, ref miss) => match *other {
519 MetaList(ref no, ref miso) => {
520 ns == no &&
521 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
522 }
523 _ => false
524 }
525 }
526 }
527 }
528
529 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
530 pub struct Block {
531 /// Statements in a block
532 pub stmts: Vec<P<Stmt>>,
533 /// An expression at the end of the block
534 /// without a semicolon, if any
535 pub expr: Option<P<Expr>>,
536 pub id: NodeId,
537 /// Distinguishes between `unsafe { ... }` and `{ ... }`
538 pub rules: BlockCheckMode,
539 pub span: Span,
540 }
541
542 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
543 pub struct Pat {
544 pub id: NodeId,
545 pub node: Pat_,
546 pub span: Span,
547 }
548
549 /// A single field in a struct pattern
550 ///
551 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
552 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
553 /// except is_shorthand is true
554 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
555 pub struct FieldPat {
556 /// The identifier for the field
557 pub ident: Ident,
558 /// The pattern the field is destructured to
559 pub pat: P<Pat>,
560 pub is_shorthand: bool,
561 }
562
563 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
564 pub enum BindingMode {
565 BindByRef(Mutability),
566 BindByValue(Mutability),
567 }
568
569 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
570 pub enum PatWildKind {
571 /// Represents the wildcard pattern `_`
572 PatWildSingle,
573
574 /// Represents the wildcard pattern `..`
575 PatWildMulti,
576 }
577
578 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
579 pub enum Pat_ {
580 /// Represents a wildcard pattern (either `_` or `..`)
581 PatWild(PatWildKind),
582
583 /// A PatIdent may either be a new bound variable,
584 /// or a nullary enum (in which case the third field
585 /// is None).
586 ///
587 /// In the nullary enum case, the parser can't determine
588 /// which it is. The resolver determines this, and
589 /// records this pattern's NodeId in an auxiliary
590 /// set (of "PatIdents that refer to nullary enums")
591 PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
592
593 /// "None" means a * pattern where we don't bind the fields to names.
594 PatEnum(Path, Option<Vec<P<Pat>>>),
595
596 /// An associated const named using the qualified path `<T>::CONST` or
597 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
598 /// referred to as simply `T::CONST`, in which case they will end up as
599 /// PatEnum, and the resolver will have to sort that out.
600 PatQPath(QSelf, Path),
601
602 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
603 /// The `bool` is `true` in the presence of a `..`
604 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
605 /// A tuple pattern `(a, b)`
606 PatTup(Vec<P<Pat>>),
607 /// A `box` pattern
608 PatBox(P<Pat>),
609 /// A reference pattern, e.g. `&mut (a, b)`
610 PatRegion(P<Pat>, Mutability),
611 /// A literal
612 PatLit(P<Expr>),
613 /// A range pattern, e.g. `1...2`
614 PatRange(P<Expr>, P<Expr>),
615 /// [a, b, ..i, y, z] is represented as:
616 /// PatVec(box [a, b], Some(i), box [y, z])
617 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
618 /// A macro pattern; pre-expansion
619 PatMac(Mac),
620 }
621
622 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
623 pub enum Mutability {
624 MutMutable,
625 MutImmutable,
626 }
627
628 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
629 pub enum BinOp_ {
630 /// The `+` operator (addition)
631 BiAdd,
632 /// The `-` operator (subtraction)
633 BiSub,
634 /// The `*` operator (multiplication)
635 BiMul,
636 /// The `/` operator (division)
637 BiDiv,
638 /// The `%` operator (modulus)
639 BiRem,
640 /// The `&&` operator (logical and)
641 BiAnd,
642 /// The `||` operator (logical or)
643 BiOr,
644 /// The `^` operator (bitwise xor)
645 BiBitXor,
646 /// The `&` operator (bitwise and)
647 BiBitAnd,
648 /// The `|` operator (bitwise or)
649 BiBitOr,
650 /// The `<<` operator (shift left)
651 BiShl,
652 /// The `>>` operator (shift right)
653 BiShr,
654 /// The `==` operator (equality)
655 BiEq,
656 /// The `<` operator (less than)
657 BiLt,
658 /// The `<=` operator (less than or equal to)
659 BiLe,
660 /// The `!=` operator (not equal to)
661 BiNe,
662 /// The `>=` operator (greater than or equal to)
663 BiGe,
664 /// The `>` operator (greater than)
665 BiGt,
666 }
667
668 pub type BinOp = Spanned<BinOp_>;
669
670 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
671 pub enum UnOp {
672 /// The `box` operator
673 UnUniq,
674 /// The `*` operator for dereferencing
675 UnDeref,
676 /// The `!` operator for logical inversion
677 UnNot,
678 /// The `-` operator for negation
679 UnNeg
680 }
681
682 /// A statement
683 pub type Stmt = Spanned<Stmt_>;
684
685 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
686 pub enum Stmt_ {
687 /// Could be an item or a local (let) binding:
688 StmtDecl(P<Decl>, NodeId),
689
690 /// Expr without trailing semi-colon (must have unit type):
691 StmtExpr(P<Expr>, NodeId),
692
693 /// Expr with trailing semi-colon (may have any type):
694 StmtSemi(P<Expr>, NodeId),
695
696 StmtMac(P<Mac>, MacStmtStyle),
697 }
698
699 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
700 pub enum MacStmtStyle {
701 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
702 /// `foo!(...);`, `foo![...];`
703 MacStmtWithSemicolon,
704 /// The macro statement had braces; e.g. foo! { ... }
705 MacStmtWithBraces,
706 /// The macro statement had parentheses or brackets and no semicolon; e.g.
707 /// `foo!(...)`. All of these will end up being converted into macro
708 /// expressions.
709 MacStmtWithoutBraces,
710 }
711
712 /// Where a local declaration came from: either a true `let ... =
713 /// ...;`, or one desugared from the pattern of a for loop.
714 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
715 pub enum LocalSource {
716 LocalLet,
717 LocalFor,
718 }
719
720 // FIXME (pending discussion of #1697, #2178...): local should really be
721 // a refinement on pat.
722 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
723 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
724 pub struct Local {
725 pub pat: P<Pat>,
726 pub ty: Option<P<Ty>>,
727 /// Initializer expression to set the value, if any
728 pub init: Option<P<Expr>>,
729 pub id: NodeId,
730 pub span: Span,
731 pub source: LocalSource,
732 }
733
734 pub type Decl = Spanned<Decl_>;
735
736 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
737 pub enum Decl_ {
738 /// A local (let) binding:
739 DeclLocal(P<Local>),
740 /// An item binding:
741 DeclItem(P<Item>),
742 }
743
744 /// represents one arm of a 'match'
745 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
746 pub struct Arm {
747 pub attrs: Vec<Attribute>,
748 pub pats: Vec<P<Pat>>,
749 pub guard: Option<P<Expr>>,
750 pub body: P<Expr>,
751 }
752
753 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
754 pub struct Field {
755 pub ident: SpannedIdent,
756 pub expr: P<Expr>,
757 pub span: Span,
758 }
759
760 pub type SpannedIdent = Spanned<Ident>;
761
762 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
763 pub enum BlockCheckMode {
764 DefaultBlock,
765 UnsafeBlock(UnsafeSource),
766 }
767
768 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
769 pub enum UnsafeSource {
770 CompilerGenerated,
771 UserProvided,
772 }
773
774 /// An expression
775 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
776 pub struct Expr {
777 pub id: NodeId,
778 pub node: Expr_,
779 pub span: Span,
780 }
781
782 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
783 pub enum Expr_ {
784 /// First expr is the place; second expr is the value.
785 ExprBox(Option<P<Expr>>, P<Expr>),
786 /// An array (`[a, b, c, d]`)
787 ExprVec(Vec<P<Expr>>),
788 /// A function call
789 ///
790 /// The first field resolves to the function itself,
791 /// and the second field is the list of arguments
792 ExprCall(P<Expr>, Vec<P<Expr>>),
793 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
794 ///
795 /// The `SpannedIdent` is the identifier for the method name.
796 /// The vector of `Ty`s are the ascripted type parameters for the method
797 /// (within the angle brackets).
798 ///
799 /// The first element of the vector of `Expr`s is the expression that evaluates
800 /// to the object on which the method is being called on (the receiver),
801 /// and the remaining elements are the rest of the arguments.
802 ///
803 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
804 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
805 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
806 /// A tuple (`(a, b, c ,d)`)
807 ExprTup(Vec<P<Expr>>),
808 /// A binary operation (For example: `a + b`, `a * b`)
809 ExprBinary(BinOp, P<Expr>, P<Expr>),
810 /// A unary operation (For example: `!x`, `*x`)
811 ExprUnary(UnOp, P<Expr>),
812 /// A literal (For example: `1u8`, `"foo"`)
813 ExprLit(P<Lit>),
814 /// A cast (`foo as f64`)
815 ExprCast(P<Expr>, P<Ty>),
816 /// An `if` block, with an optional else block
817 ///
818 /// `if expr { block } else { expr }`
819 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
820 /// An `if let` expression with an optional else block
821 ///
822 /// `if let pat = expr { block } else { expr }`
823 ///
824 /// This is desugared to a `match` expression.
825 ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
826 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
827 /// A while loop, with an optional label
828 ///
829 /// `'label: while expr { block }`
830 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
831 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
832 /// A while-let loop, with an optional label
833 ///
834 /// `'label: while let pat = expr { block }`
835 ///
836 /// This is desugared to a combination of `loop` and `match` expressions.
837 ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
838 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
839 /// A for loop, with an optional label
840 ///
841 /// `'label: for pat in expr { block }`
842 ///
843 /// This is desugared to a combination of `loop` and `match` expressions.
844 ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
845 /// Conditionless loop (can be exited with break, continue, or return)
846 ///
847 /// `'label: loop { block }`
848 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
849 ExprLoop(P<Block>, Option<Ident>),
850 /// A `match` block, with a source that indicates whether or not it is
851 /// the result of a desugaring, and if so, which kind.
852 ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
853 /// A closure (for example, `move |a, b, c| {a + b + c}`)
854 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
855 /// A block (`{ ... }`)
856 ExprBlock(P<Block>),
857
858 /// An assignment (`a = foo()`)
859 ExprAssign(P<Expr>, P<Expr>),
860 /// An assignment with an operator
861 ///
862 /// For example, `a += 1`.
863 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
864 /// Access of a named struct field (`obj.foo`)
865 ExprField(P<Expr>, SpannedIdent),
866 /// Access of an unnamed field of a struct or tuple-struct
867 ///
868 /// For example, `foo.0`.
869 ExprTupField(P<Expr>, Spanned<usize>),
870 /// An indexing operation (`foo[2]`)
871 ExprIndex(P<Expr>, P<Expr>),
872 /// A range (`1..2`, `1..`, or `..2`)
873 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
874
875 /// Variable reference, possibly containing `::` and/or type
876 /// parameters, e.g. foo::bar::<baz>.
877 ///
878 /// Optionally "qualified",
879 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
880 ExprPath(Option<QSelf>, Path),
881
882 /// A referencing operation (`&a` or `&mut a`)
883 ExprAddrOf(Mutability, P<Expr>),
884 /// A `break`, with an optional label to break
885 ExprBreak(Option<Ident>),
886 /// A `continue`, with an optional label
887 ExprAgain(Option<Ident>),
888 /// A `return`, with an optional value to be returned
889 ExprRet(Option<P<Expr>>),
890
891 /// Output of the `asm!()` macro
892 ExprInlineAsm(InlineAsm),
893
894 /// A macro invocation; pre-expansion
895 ExprMac(Mac),
896
897 /// A struct literal expression.
898 ///
899 /// For example, `Foo {x: 1, y: 2}`, or
900 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
901 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
902
903 /// A vector literal constructed from one repeated element.
904 ///
905 /// For example, `[1u8; 5]`. The first expression is the element
906 /// to be repeated; the second is the number of times to repeat it.
907 ExprRepeat(P<Expr>, P<Expr>),
908
909 /// No-op: used solely so we can pretty-print faithfully
910 ExprParen(P<Expr>)
911 }
912
913 /// The explicit Self type in a "qualified path". The actual
914 /// path, including the trait and the associated item, is stored
915 /// separately. `position` represents the index of the associated
916 /// item qualified with this Self type.
917 ///
918 /// <Vec<T> as a::b::Trait>::AssociatedItem
919 /// ^~~~~ ~~~~~~~~~~~~~~^
920 /// ty position = 3
921 ///
922 /// <Vec<T>>::AssociatedItem
923 /// ^~~~~ ^
924 /// ty position = 0
925 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
926 pub struct QSelf {
927 pub ty: P<Ty>,
928 pub position: usize
929 }
930
931 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
932 pub enum MatchSource {
933 Normal,
934 IfLetDesugar { contains_else_clause: bool },
935 WhileLetDesugar,
936 ForLoopDesugar,
937 }
938
939 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
940 pub enum CaptureClause {
941 CaptureByValue,
942 CaptureByRef,
943 }
944
945 /// A delimited sequence of token trees
946 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
947 pub struct Delimited {
948 /// The type of delimiter
949 pub delim: token::DelimToken,
950 /// The span covering the opening delimiter
951 pub open_span: Span,
952 /// The delimited sequence of token trees
953 pub tts: Vec<TokenTree>,
954 /// The span covering the closing delimiter
955 pub close_span: Span,
956 }
957
958 impl Delimited {
959 /// Returns the opening delimiter as a token.
960 pub fn open_token(&self) -> token::Token {
961 token::OpenDelim(self.delim)
962 }
963
964 /// Returns the closing delimiter as a token.
965 pub fn close_token(&self) -> token::Token {
966 token::CloseDelim(self.delim)
967 }
968
969 /// Returns the opening delimiter as a token tree.
970 pub fn open_tt(&self) -> TokenTree {
971 TtToken(self.open_span, self.open_token())
972 }
973
974 /// Returns the closing delimiter as a token tree.
975 pub fn close_tt(&self) -> TokenTree {
976 TtToken(self.close_span, self.close_token())
977 }
978 }
979
980 /// A sequence of token treesee
981 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
982 pub struct SequenceRepetition {
983 /// The sequence of token trees
984 pub tts: Vec<TokenTree>,
985 /// The optional separator
986 pub separator: Option<token::Token>,
987 /// Whether the sequence can be repeated zero (*), or one or more times (+)
988 pub op: KleeneOp,
989 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
990 pub num_captures: usize,
991 }
992
993 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
994 /// for token sequences.
995 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
996 pub enum KleeneOp {
997 ZeroOrMore,
998 OneOrMore,
999 }
1000
1001 /// When the main rust parser encounters a syntax-extension invocation, it
1002 /// parses the arguments to the invocation as a token-tree. This is a very
1003 /// loose structure, such that all sorts of different AST-fragments can
1004 /// be passed to syntax extensions using a uniform type.
1005 ///
1006 /// If the syntax extension is an MBE macro, it will attempt to match its
1007 /// LHS token tree against the provided token tree, and if it finds a
1008 /// match, will transcribe the RHS token tree, splicing in any captured
1009 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1010 ///
1011 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1012 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1013 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1014 pub enum TokenTree {
1015 /// A single token
1016 TtToken(Span, token::Token),
1017 /// A delimited sequence of token trees
1018 TtDelimited(Span, Rc<Delimited>),
1019
1020 // This only makes sense in MBE macros.
1021
1022 /// A kleene-style repetition sequence with a span
1023 // FIXME(eddyb) #12938 Use DST.
1024 TtSequence(Span, Rc<SequenceRepetition>),
1025 }
1026
1027 impl TokenTree {
1028 pub fn len(&self) -> usize {
1029 match *self {
1030 TtToken(_, token::DocComment(_)) => 2,
1031 TtToken(_, token::SpecialVarNt(..)) => 2,
1032 TtToken(_, token::MatchNt(..)) => 3,
1033 TtDelimited(_, ref delimed) => {
1034 delimed.tts.len() + 2
1035 }
1036 TtSequence(_, ref seq) => {
1037 seq.tts.len()
1038 }
1039 TtToken(..) => 0
1040 }
1041 }
1042
1043 pub fn get_tt(&self, index: usize) -> TokenTree {
1044 match (self, index) {
1045 (&TtToken(sp, token::DocComment(_)), 0) => {
1046 TtToken(sp, token::Pound)
1047 }
1048 (&TtToken(sp, token::DocComment(name)), 1) => {
1049 TtDelimited(sp, Rc::new(Delimited {
1050 delim: token::Bracket,
1051 open_span: sp,
1052 tts: vec![TtToken(sp, token::Ident(token::str_to_ident("doc"),
1053 token::Plain)),
1054 TtToken(sp, token::Eq),
1055 TtToken(sp, token::Literal(token::Str_(name), None))],
1056 close_span: sp,
1057 }))
1058 }
1059 (&TtDelimited(_, ref delimed), _) => {
1060 if index == 0 {
1061 return delimed.open_tt();
1062 }
1063 if index == delimed.tts.len() + 1 {
1064 return delimed.close_tt();
1065 }
1066 delimed.tts[index - 1].clone()
1067 }
1068 (&TtToken(sp, token::SpecialVarNt(var)), _) => {
1069 let v = [TtToken(sp, token::Dollar),
1070 TtToken(sp, token::Ident(token::str_to_ident(var.as_str()),
1071 token::Plain))];
1072 v[index].clone()
1073 }
1074 (&TtToken(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
1075 let v = [TtToken(sp, token::SubstNt(name, name_st)),
1076 TtToken(sp, token::Colon),
1077 TtToken(sp, token::Ident(kind, kind_st))];
1078 v[index].clone()
1079 }
1080 (&TtSequence(_, ref seq), _) => {
1081 seq.tts[index].clone()
1082 }
1083 _ => panic!("Cannot expand a token tree")
1084 }
1085 }
1086
1087 /// Returns the `Span` corresponding to this token tree.
1088 pub fn get_span(&self) -> Span {
1089 match *self {
1090 TtToken(span, _) => span,
1091 TtDelimited(span, _) => span,
1092 TtSequence(span, _) => span,
1093 }
1094 }
1095
1096 /// Use this token tree as a matcher to parse given tts.
1097 pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
1098 -> macro_parser::NamedParseResult {
1099 // `None` is because we're not interpolating
1100 let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
1101 None,
1102 None,
1103 tts.iter().cloned().collect(),
1104 true);
1105 macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
1106 }
1107 }
1108
1109 pub type Mac = Spanned<Mac_>;
1110
1111 /// Represents a macro invocation. The Path indicates which macro
1112 /// is being invoked, and the vector of token-trees contains the source
1113 /// of the macro invocation.
1114 ///
1115 /// There's only one flavor, now, so this could presumably be simplified.
1116 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1117 pub enum Mac_ {
1118 // NB: the additional ident for a macro_rules-style macro is actually
1119 // stored in the enclosing item. Oog.
1120 MacInvocTT(Path, Vec<TokenTree>, SyntaxContext), // new macro-invocation
1121 }
1122
1123 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1124 pub enum StrStyle {
1125 /// A regular string, like `"foo"`
1126 CookedStr,
1127 /// A raw string, like `r##"foo"##`
1128 ///
1129 /// The uint is the number of `#` symbols used
1130 RawStr(usize)
1131 }
1132
1133 /// A literal
1134 pub type Lit = Spanned<Lit_>;
1135
1136 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1137 pub enum Sign {
1138 Minus,
1139 Plus
1140 }
1141
1142 impl Sign {
1143 pub fn new<T: IntSign>(n: T) -> Sign {
1144 n.sign()
1145 }
1146 }
1147
1148 pub trait IntSign {
1149 fn sign(&self) -> Sign;
1150 }
1151 macro_rules! doit {
1152 ($($t:ident)*) => ($(impl IntSign for $t {
1153 #[allow(unused_comparisons)]
1154 fn sign(&self) -> Sign {
1155 if *self < 0 {Minus} else {Plus}
1156 }
1157 })*)
1158 }
1159 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
1160
1161 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1162 pub enum LitIntType {
1163 SignedIntLit(IntTy, Sign),
1164 UnsignedIntLit(UintTy),
1165 UnsuffixedIntLit(Sign)
1166 }
1167
1168 impl LitIntType {
1169 pub fn suffix_len(&self) -> usize {
1170 match *self {
1171 UnsuffixedIntLit(_) => 0,
1172 SignedIntLit(s, _) => s.suffix_len(),
1173 UnsignedIntLit(u) => u.suffix_len()
1174 }
1175 }
1176 }
1177
1178 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1179 pub enum Lit_ {
1180 /// A string literal (`"foo"`)
1181 LitStr(InternedString, StrStyle),
1182 /// A byte string (`b"foo"`)
1183 LitBinary(Rc<Vec<u8>>),
1184 /// A byte char (`b'f'`)
1185 LitByte(u8),
1186 /// A character literal (`'a'`)
1187 LitChar(char),
1188 /// An integer literal (`1u8`)
1189 LitInt(u64, LitIntType),
1190 /// A float literal (`1f64` or `1E10f64`)
1191 LitFloat(InternedString, FloatTy),
1192 /// A float literal without a suffix (`1.0 or 1.0E10`)
1193 LitFloatUnsuffixed(InternedString),
1194 /// A boolean literal
1195 LitBool(bool),
1196 }
1197
1198 // NB: If you change this, you'll probably want to change the corresponding
1199 // type structure in middle/ty.rs as well.
1200 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1201 pub struct MutTy {
1202 pub ty: P<Ty>,
1203 pub mutbl: Mutability,
1204 }
1205
1206 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1207 pub struct TypeField {
1208 pub ident: Ident,
1209 pub mt: MutTy,
1210 pub span: Span,
1211 }
1212
1213 /// Represents a method's signature in a trait declaration,
1214 /// or in an implementation.
1215 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1216 pub struct MethodSig {
1217 pub unsafety: Unsafety,
1218 pub abi: Abi,
1219 pub decl: P<FnDecl>,
1220 pub generics: Generics,
1221 pub explicit_self: ExplicitSelf,
1222 }
1223
1224 /// Represents a method declaration in a trait declaration, possibly including
1225 /// a default implementation A trait method is either required (meaning it
1226 /// doesn't have an implementation, just a signature) or provided (meaning it
1227 /// has a default implementation).
1228 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1229 pub struct TraitItem {
1230 pub id: NodeId,
1231 pub ident: Ident,
1232 pub attrs: Vec<Attribute>,
1233 pub node: TraitItem_,
1234 pub span: Span,
1235 }
1236
1237 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1238 pub enum TraitItem_ {
1239 ConstTraitItem(P<Ty>, Option<P<Expr>>),
1240 MethodTraitItem(MethodSig, Option<P<Block>>),
1241 TypeTraitItem(TyParamBounds, Option<P<Ty>>),
1242 }
1243
1244 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1245 pub struct ImplItem {
1246 pub id: NodeId,
1247 pub ident: Ident,
1248 pub vis: Visibility,
1249 pub attrs: Vec<Attribute>,
1250 pub node: ImplItem_,
1251 pub span: Span,
1252 }
1253
1254 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1255 pub enum ImplItem_ {
1256 ConstImplItem(P<Ty>, P<Expr>),
1257 MethodImplItem(MethodSig, P<Block>),
1258 TypeImplItem(P<Ty>),
1259 MacImplItem(Mac),
1260 }
1261
1262 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1263 pub enum IntTy {
1264 TyIs,
1265 TyI8,
1266 TyI16,
1267 TyI32,
1268 TyI64,
1269 }
1270
1271 impl fmt::Debug for IntTy {
1272 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1273 fmt::Display::fmt(self, f)
1274 }
1275 }
1276
1277 impl fmt::Display for IntTy {
1278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1279 write!(f, "{}", ast_util::int_ty_to_string(*self, None))
1280 }
1281 }
1282
1283 impl IntTy {
1284 pub fn suffix_len(&self) -> usize {
1285 match *self {
1286 TyIs | TyI8 => 2,
1287 TyI16 | TyI32 | TyI64 => 3,
1288 }
1289 }
1290 }
1291
1292 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1293 pub enum UintTy {
1294 TyUs,
1295 TyU8,
1296 TyU16,
1297 TyU32,
1298 TyU64,
1299 }
1300
1301 impl UintTy {
1302 pub fn suffix_len(&self) -> usize {
1303 match *self {
1304 TyUs | TyU8 => 2,
1305 TyU16 | TyU32 | TyU64 => 3,
1306 }
1307 }
1308 }
1309
1310 impl fmt::Debug for UintTy {
1311 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1312 fmt::Display::fmt(self, f)
1313 }
1314 }
1315
1316 impl fmt::Display for UintTy {
1317 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1318 write!(f, "{}", ast_util::uint_ty_to_string(*self, None))
1319 }
1320 }
1321
1322 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
1323 pub enum FloatTy {
1324 TyF32,
1325 TyF64,
1326 }
1327
1328 impl fmt::Debug for FloatTy {
1329 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1330 fmt::Display::fmt(self, f)
1331 }
1332 }
1333
1334 impl fmt::Display for FloatTy {
1335 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1336 write!(f, "{}", ast_util::float_ty_to_string(*self))
1337 }
1338 }
1339
1340 impl FloatTy {
1341 pub fn suffix_len(&self) -> usize {
1342 match *self {
1343 TyF32 | TyF64 => 3, // add F128 handling here
1344 }
1345 }
1346 }
1347
1348 // Bind a type to an associated type: `A=Foo`.
1349 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1350 pub struct TypeBinding {
1351 pub id: NodeId,
1352 pub ident: Ident,
1353 pub ty: P<Ty>,
1354 pub span: Span,
1355 }
1356
1357
1358 // NB PartialEq method appears below.
1359 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1360 pub struct Ty {
1361 pub id: NodeId,
1362 pub node: Ty_,
1363 pub span: Span,
1364 }
1365
1366 /// Not represented directly in the AST, referred to by name through a ty_path.
1367 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1368 pub enum PrimTy {
1369 TyInt(IntTy),
1370 TyUint(UintTy),
1371 TyFloat(FloatTy),
1372 TyStr,
1373 TyBool,
1374 TyChar
1375 }
1376
1377 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1378 pub struct BareFnTy {
1379 pub unsafety: Unsafety,
1380 pub abi: Abi,
1381 pub lifetimes: Vec<LifetimeDef>,
1382 pub decl: P<FnDecl>
1383 }
1384
1385 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1386 /// The different kinds of types recognized by the compiler
1387 pub enum Ty_ {
1388 TyVec(P<Ty>),
1389 /// A fixed length array (`[T; n]`)
1390 TyFixedLengthVec(P<Ty>, P<Expr>),
1391 /// A raw pointer (`*const T` or `*mut T`)
1392 TyPtr(MutTy),
1393 /// A reference (`&'a T` or `&'a mut T`)
1394 TyRptr(Option<Lifetime>, MutTy),
1395 /// A bare function (e.g. `fn(usize) -> bool`)
1396 TyBareFn(P<BareFnTy>),
1397 /// A tuple (`(A, B, C, D,...)`)
1398 TyTup(Vec<P<Ty>> ),
1399 /// A path (`module::module::...::Type`), optionally
1400 /// "qualified", e.g. `<Vec<T> as SomeTrait>::SomeType`.
1401 ///
1402 /// Type parameters are stored in the Path itself
1403 TyPath(Option<QSelf>, Path),
1404 /// Something like `A+B`. Note that `B` must always be a path.
1405 TyObjectSum(P<Ty>, TyParamBounds),
1406 /// A type like `for<'a> Foo<&'a Bar>`
1407 TyPolyTraitRef(TyParamBounds),
1408 /// No-op; kept solely so that we can pretty-print faithfully
1409 TyParen(P<Ty>),
1410 /// Unused for now
1411 TyTypeof(P<Expr>),
1412 /// TyInfer means the type should be inferred instead of it having been
1413 /// specified. This can appear anywhere in a type.
1414 TyInfer,
1415 }
1416
1417 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1418 pub enum AsmDialect {
1419 AsmAtt,
1420 AsmIntel
1421 }
1422
1423 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1424 pub struct InlineAsm {
1425 pub asm: InternedString,
1426 pub asm_str_style: StrStyle,
1427 pub outputs: Vec<(InternedString, P<Expr>, bool)>,
1428 pub inputs: Vec<(InternedString, P<Expr>)>,
1429 pub clobbers: Vec<InternedString>,
1430 pub volatile: bool,
1431 pub alignstack: bool,
1432 pub dialect: AsmDialect,
1433 pub expn_id: ExpnId,
1434 }
1435
1436 /// represents an argument in a function header
1437 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1438 pub struct Arg {
1439 pub ty: P<Ty>,
1440 pub pat: P<Pat>,
1441 pub id: NodeId,
1442 }
1443
1444 impl Arg {
1445 pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
1446 let path = Spanned{span:span,node:self_ident};
1447 Arg {
1448 // HACK(eddyb) fake type for the self argument.
1449 ty: P(Ty {
1450 id: DUMMY_NODE_ID,
1451 node: TyInfer,
1452 span: DUMMY_SP,
1453 }),
1454 pat: P(Pat {
1455 id: DUMMY_NODE_ID,
1456 node: PatIdent(BindByValue(mutability), path, None),
1457 span: span
1458 }),
1459 id: DUMMY_NODE_ID
1460 }
1461 }
1462 }
1463
1464 /// Represents the header (not the body) of a function declaration
1465 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1466 pub struct FnDecl {
1467 pub inputs: Vec<Arg>,
1468 pub output: FunctionRetTy,
1469 pub variadic: bool
1470 }
1471
1472 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1473 pub enum Unsafety {
1474 Unsafe,
1475 Normal,
1476 }
1477
1478 impl fmt::Display for Unsafety {
1479 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1480 fmt::Display::fmt(match *self {
1481 Unsafety::Normal => "normal",
1482 Unsafety::Unsafe => "unsafe",
1483 }, f)
1484 }
1485 }
1486
1487 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
1488 pub enum ImplPolarity {
1489 /// `impl Trait for Type`
1490 Positive,
1491 /// `impl !Trait for Type`
1492 Negative,
1493 }
1494
1495 impl fmt::Debug for ImplPolarity {
1496 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1497 match *self {
1498 ImplPolarity::Positive => "positive".fmt(f),
1499 ImplPolarity::Negative => "negative".fmt(f),
1500 }
1501 }
1502 }
1503
1504
1505 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1506 pub enum FunctionRetTy {
1507 /// Functions with return type `!`that always
1508 /// raise an error or exit (i.e. never return to the caller)
1509 NoReturn(Span),
1510 /// Return type is not specified.
1511 ///
1512 /// Functions default to `()` and
1513 /// closures default to inference. Span points to where return
1514 /// type would be inserted.
1515 DefaultReturn(Span),
1516 /// Everything else
1517 Return(P<Ty>),
1518 }
1519
1520 impl FunctionRetTy {
1521 pub fn span(&self) -> Span {
1522 match *self {
1523 NoReturn(span) => span,
1524 DefaultReturn(span) => span,
1525 Return(ref ty) => ty.span
1526 }
1527 }
1528 }
1529
1530 /// Represents the kind of 'self' associated with a method
1531 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1532 pub enum ExplicitSelf_ {
1533 /// No self
1534 SelfStatic,
1535 /// `self`
1536 SelfValue(Ident),
1537 /// `&'lt self`, `&'lt mut self`
1538 SelfRegion(Option<Lifetime>, Mutability, Ident),
1539 /// `self: TYPE`
1540 SelfExplicit(P<Ty>, Ident),
1541 }
1542
1543 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
1544
1545 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1546 pub struct Mod {
1547 /// A span from the first token past `{` to the last token until `}`.
1548 /// For `mod foo;`, the inner span ranges from the first token
1549 /// to the last token in the external file.
1550 pub inner: Span,
1551 pub items: Vec<P<Item>>,
1552 }
1553
1554 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1555 pub struct ForeignMod {
1556 pub abi: Abi,
1557 pub items: Vec<P<ForeignItem>>,
1558 }
1559
1560 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1561 pub struct VariantArg {
1562 pub ty: P<Ty>,
1563 pub id: NodeId,
1564 }
1565
1566 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1567 pub enum VariantKind {
1568 /// Tuple variant, e.g. `Foo(A, B)`
1569 TupleVariantKind(Vec<VariantArg>),
1570 /// Struct variant, e.g. `Foo {x: A, y: B}`
1571 StructVariantKind(P<StructDef>),
1572 }
1573
1574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1575 pub struct EnumDef {
1576 pub variants: Vec<P<Variant>>,
1577 }
1578
1579 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1580 pub struct Variant_ {
1581 pub name: Ident,
1582 pub attrs: Vec<Attribute>,
1583 pub kind: VariantKind,
1584 pub id: NodeId,
1585 /// Explicit discriminant, eg `Foo = 1`
1586 pub disr_expr: Option<P<Expr>>,
1587 pub vis: Visibility,
1588 }
1589
1590 pub type Variant = Spanned<Variant_>;
1591
1592 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1593 pub enum PathListItem_ {
1594 PathListIdent { name: Ident, id: NodeId },
1595 PathListMod { id: NodeId }
1596 }
1597
1598 impl PathListItem_ {
1599 pub fn id(&self) -> NodeId {
1600 match *self {
1601 PathListIdent { id, .. } | PathListMod { id } => id
1602 }
1603 }
1604 }
1605
1606 pub type PathListItem = Spanned<PathListItem_>;
1607
1608 pub type ViewPath = Spanned<ViewPath_>;
1609
1610 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1611 pub enum ViewPath_ {
1612
1613 /// `foo::bar::baz as quux`
1614 ///
1615 /// or just
1616 ///
1617 /// `foo::bar::baz` (with `as baz` implicitly on the right)
1618 ViewPathSimple(Ident, Path),
1619
1620 /// `foo::bar::*`
1621 ViewPathGlob(Path),
1622
1623 /// `foo::bar::{a,b,c}`
1624 ViewPathList(Path, Vec<PathListItem>)
1625 }
1626
1627 /// Meta-data associated with an item
1628 pub type Attribute = Spanned<Attribute_>;
1629
1630 /// Distinguishes between Attributes that decorate items and Attributes that
1631 /// are contained as statements within items. These two cases need to be
1632 /// distinguished for pretty-printing.
1633 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1634 pub enum AttrStyle {
1635 AttrOuter,
1636 AttrInner,
1637 }
1638
1639 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1640 pub struct AttrId(pub usize);
1641
1642 /// Doc-comments are promoted to attributes that have is_sugared_doc = true
1643 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1644 pub struct Attribute_ {
1645 pub id: AttrId,
1646 pub style: AttrStyle,
1647 pub value: P<MetaItem>,
1648 pub is_sugared_doc: bool,
1649 }
1650
1651 /// TraitRef's appear in impls.
1652 ///
1653 /// resolve maps each TraitRef's ref_id to its defining trait; that's all
1654 /// that the ref_id is for. The impl_id maps to the "self type" of this impl.
1655 /// If this impl is an ItemImpl, the impl_id is redundant (it could be the
1656 /// same as the impl's node id).
1657 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1658 pub struct TraitRef {
1659 pub path: Path,
1660 pub ref_id: NodeId,
1661 }
1662
1663 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1664 pub struct PolyTraitRef {
1665 /// The `'a` in `<'a> Foo<&'a T>`
1666 pub bound_lifetimes: Vec<LifetimeDef>,
1667
1668 /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
1669 pub trait_ref: TraitRef,
1670
1671 pub span: Span,
1672 }
1673
1674 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1675 pub enum Visibility {
1676 Public,
1677 Inherited,
1678 }
1679
1680 impl Visibility {
1681 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1682 match self {
1683 &Inherited => parent_visibility,
1684 &Public => *self
1685 }
1686 }
1687 }
1688
1689 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1690 pub struct StructField_ {
1691 pub kind: StructFieldKind,
1692 pub id: NodeId,
1693 pub ty: P<Ty>,
1694 pub attrs: Vec<Attribute>,
1695 }
1696
1697 impl StructField_ {
1698 pub fn ident(&self) -> Option<Ident> {
1699 match self.kind {
1700 NamedField(ref ident, _) => Some(ident.clone()),
1701 UnnamedField(_) => None
1702 }
1703 }
1704 }
1705
1706 pub type StructField = Spanned<StructField_>;
1707
1708 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1709 pub enum StructFieldKind {
1710 NamedField(Ident, Visibility),
1711 /// Element of a tuple-like struct
1712 UnnamedField(Visibility),
1713 }
1714
1715 impl StructFieldKind {
1716 pub fn is_unnamed(&self) -> bool {
1717 match *self {
1718 UnnamedField(..) => true,
1719 NamedField(..) => false,
1720 }
1721 }
1722 }
1723
1724 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1725 pub struct StructDef {
1726 /// Fields, not including ctor
1727 pub fields: Vec<StructField>,
1728 /// ID of the constructor. This is only used for tuple- or enum-like
1729 /// structs.
1730 pub ctor_id: Option<NodeId>,
1731 }
1732
1733 /*
1734 FIXME (#3300): Should allow items to be anonymous. Right now
1735 we just use dummy names for anon items.
1736 */
1737 /// An item
1738 ///
1739 /// The name might be a dummy name in case of anonymous items
1740 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1741 pub struct Item {
1742 pub ident: Ident,
1743 pub attrs: Vec<Attribute>,
1744 pub id: NodeId,
1745 pub node: Item_,
1746 pub vis: Visibility,
1747 pub span: Span,
1748 }
1749
1750 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1751 pub enum Item_ {
1752 /// An`extern crate` item, with optional original crate name,
1753 ///
1754 /// e.g. `extern crate foo` or `extern crate foo_bar as foo`
1755 ItemExternCrate(Option<Name>),
1756 /// A `use` or `pub use` item
1757 ItemUse(P<ViewPath>),
1758
1759 /// A `static` item
1760 ItemStatic(P<Ty>, Mutability, P<Expr>),
1761 /// A `const` item
1762 ItemConst(P<Ty>, P<Expr>),
1763 /// A function declaration
1764 ItemFn(P<FnDecl>, Unsafety, Abi, Generics, P<Block>),
1765 /// A module
1766 ItemMod(Mod),
1767 /// An external module
1768 ItemForeignMod(ForeignMod),
1769 /// A type alias, e.g. `type Foo = Bar<u8>`
1770 ItemTy(P<Ty>, Generics),
1771 /// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
1772 ItemEnum(EnumDef, Generics),
1773 /// A struct definition, e.g. `struct Foo<A> {x: A}`
1774 ItemStruct(P<StructDef>, Generics),
1775 /// Represents a Trait Declaration
1776 ItemTrait(Unsafety,
1777 Generics,
1778 TyParamBounds,
1779 Vec<P<TraitItem>>),
1780
1781 // Default trait implementations
1782 ///
1783 // `impl Trait for .. {}`
1784 ItemDefaultImpl(Unsafety, TraitRef),
1785 /// An implementation, eg `impl<A> Trait for Foo { .. }`
1786 ItemImpl(Unsafety,
1787 ImplPolarity,
1788 Generics,
1789 Option<TraitRef>, // (optional) trait this impl implements
1790 P<Ty>, // self
1791 Vec<P<ImplItem>>),
1792 /// A macro invocation (which includes macro definition)
1793 ItemMac(Mac),
1794 }
1795
1796 impl Item_ {
1797 pub fn descriptive_variant(&self) -> &str {
1798 match *self {
1799 ItemExternCrate(..) => "extern crate",
1800 ItemUse(..) => "use",
1801 ItemStatic(..) => "static item",
1802 ItemConst(..) => "constant item",
1803 ItemFn(..) => "function",
1804 ItemMod(..) => "module",
1805 ItemForeignMod(..) => "foreign module",
1806 ItemTy(..) => "type alias",
1807 ItemEnum(..) => "enum",
1808 ItemStruct(..) => "struct",
1809 ItemTrait(..) => "trait",
1810 ItemMac(..) |
1811 ItemImpl(..) |
1812 ItemDefaultImpl(..) => "item"
1813 }
1814 }
1815 }
1816
1817 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1818 pub struct ForeignItem {
1819 pub ident: Ident,
1820 pub attrs: Vec<Attribute>,
1821 pub node: ForeignItem_,
1822 pub id: NodeId,
1823 pub span: Span,
1824 pub vis: Visibility,
1825 }
1826
1827 /// An item within an `extern` block
1828 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1829 pub enum ForeignItem_ {
1830 /// A foreign function
1831 ForeignItemFn(P<FnDecl>, Generics),
1832 /// A foreign static item (`static ext: u8`), with optional mutability
1833 /// (the boolean is true when mutable)
1834 ForeignItemStatic(P<Ty>, bool),
1835 }
1836
1837 impl ForeignItem_ {
1838 pub fn descriptive_variant(&self) -> &str {
1839 match *self {
1840 ForeignItemFn(..) => "foreign function",
1841 ForeignItemStatic(..) => "foreign static item"
1842 }
1843 }
1844 }
1845
1846 /// The data we save and restore about an inlined item or method. This is not
1847 /// part of the AST that we parse from a file, but it becomes part of the tree
1848 /// that we trans.
1849 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1850 pub enum InlinedItem {
1851 IIItem(P<Item>),
1852 IITraitItem(DefId /* impl id */, P<TraitItem>),
1853 IIImplItem(DefId /* impl id */, P<ImplItem>),
1854 IIForeign(P<ForeignItem>),
1855 }
1856
1857 /// A macro definition, in this crate or imported from another.
1858 ///
1859 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
1860 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1861 pub struct MacroDef {
1862 pub ident: Ident,
1863 pub attrs: Vec<Attribute>,
1864 pub id: NodeId,
1865 pub span: Span,
1866 pub imported_from: Option<Ident>,
1867 pub export: bool,
1868 pub use_locally: bool,
1869 pub allow_internal_unstable: bool,
1870 pub body: Vec<TokenTree>,
1871 }
1872
1873 #[cfg(test)]
1874 mod tests {
1875 use serialize;
1876 use super::*;
1877
1878 // are ASTs encodable?
1879 #[test]
1880 fn check_asts_encodable() {
1881 fn assert_encodable<T: serialize::Encodable>() {}
1882 assert_encodable::<Crate>();
1883 }
1884 }