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