]> git.proxmox.com Git - rustc.git/blob - src/libsyntax/ast.rs
Imported Upstream version 1.3.0+dfsg1
[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::Mac_::*;
33 pub use self::MacStmtStyle::*;
34 pub use self::MetaItem_::*;
35 pub use self::Mutability::*;
36 pub use self::Pat_::*;
37 pub use self::PathListItem_::*;
38 pub use self::PatWildKind::*;
39 pub use self::PrimTy::*;
40 pub use self::Sign::*;
41 pub use self::Stmt_::*;
42 pub use self::StrStyle::*;
43 pub use self::StructFieldKind::*;
44 pub use self::TokenTree::*;
45 pub use self::TraitItem_::*;
46 pub use self::Ty_::*;
47 pub use self::TyParamBound::*;
48 pub use self::UintTy::*;
49 pub use self::UnOp::*;
50 pub use self::UnsafeSource::*;
51 pub use self::VariantKind::*;
52 pub use self::ViewPath_::*;
53 pub use self::Visibility::*;
54 pub use self::PathParameters::*;
55
56 use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
57 use abi::Abi;
58 use ast_util;
59 use ext::base;
60 use ext::tt::macro_parser;
61 use owned_slice::OwnedSlice;
62 use parse::token::{InternedString, str_to_ident};
63 use parse::token;
64 use parse::lexer;
65 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
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
92 impl fmt::Debug for Ident {
93 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94 write!(f, "{}#{}", self.name, self.ctxt)
95 }
96 }
97
98 impl fmt::Display for Ident {
99 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
100 fmt::Display::fmt(&self.name, f)
101 }
102 }
103
104 impl fmt::Debug for Name {
105 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
106 let Name(nm) = *self;
107 write!(f, "{}({})", self, nm)
108 }
109 }
110
111 impl fmt::Display for Name {
112 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
113 fmt::Display::fmt(&self.as_str(), f)
114 }
115 }
116
117 impl PartialEq for Ident {
118 fn eq(&self, other: &Ident) -> bool {
119 if self.ctxt == other.ctxt {
120 self.name == other.name
121 } else {
122 // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
123 // idents that have different contexts. You can't fix this without
124 // knowing whether the comparison should be hygienic or non-hygienic.
125 // if it should be non-hygienic (most things are), just compare the
126 // 'name' fields of the idents. Or, even better, replace the idents
127 // with Name's.
128 //
129 // On the other hand, if the comparison does need to be hygienic,
130 // one example and its non-hygienic counterpart would be:
131 // syntax::parse::token::Token::mtwt_eq
132 // syntax::ext::tt::macro_parser::token_name_eq
133 panic!("not allowed to compare these idents: {:?}, {:?}. \
134 Probably related to issue \\#6993", self, other);
135 }
136 }
137 }
138
139 /// A SyntaxContext represents a chain of macro-expandings
140 /// and renamings. Each macro expansion corresponds to
141 /// a fresh u32
142
143 // I'm representing this syntax context as an index into
144 // a table, in order to work around a compiler bug
145 // that's causing unreleased memory to cause core dumps
146 // and also perhaps to save some work in destructor checks.
147 // the special uint '0' will be used to indicate an empty
148 // syntax context.
149
150 // this uint is a reference to a table stored in thread-local
151 // storage.
152 pub type SyntaxContext = u32;
153 pub const EMPTY_CTXT : SyntaxContext = 0;
154 pub const ILLEGAL_CTXT : SyntaxContext = 1;
155
156 /// A name is a part of an identifier, representing a string or gensym. It's
157 /// the result of interning.
158 #[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
159 RustcEncodable, RustcDecodable, Clone, Copy)]
160 pub struct Name(pub u32);
161
162 impl<T: AsRef<str>> PartialEq<T> for Name {
163 fn eq(&self, other: &T) -> bool {
164 self.as_str() == other.as_ref()
165 }
166 }
167
168 impl Name {
169 pub fn as_str(&self) -> token::InternedString {
170 token::InternedString::new_from_name(*self)
171 }
172
173 pub fn usize(&self) -> usize {
174 let Name(nm) = *self;
175 nm as usize
176 }
177
178 pub fn ident(&self) -> Ident {
179 Ident { name: *self, ctxt: 0 }
180 }
181 }
182
183 /// A mark represents a unique id associated with a macro expansion
184 pub type Mrk = u32;
185
186 impl Encodable for Ident {
187 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
188 s.emit_str(&self.name.as_str())
189 }
190 }
191
192 impl Decodable for Ident {
193 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
194 Ok(str_to_ident(&try!(d.read_str())[..]))
195 }
196 }
197
198 /// Function name (not all functions have names)
199 pub type FnIdent = Option<Ident>;
200
201 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
202 pub struct Lifetime {
203 pub id: NodeId,
204 pub span: Span,
205 pub name: Name
206 }
207
208 impl fmt::Debug for Lifetime {
209 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
210 write!(f, "lifetime({}: {})", self.id, pprust::lifetime_to_string(self))
211 }
212 }
213
214 /// A lifetime definition, eg `'a: 'b+'c+'d`
215 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
216 pub struct LifetimeDef {
217 pub lifetime: Lifetime,
218 pub bounds: Vec<Lifetime>
219 }
220
221 /// A "Path" is essentially Rust's notion of a name; for instance:
222 /// std::cmp::PartialEq . It's represented as a sequence of identifiers,
223 /// along with a bunch of supporting information.
224 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
225 pub struct Path {
226 pub span: Span,
227 /// A `::foo` path, is relative to the crate root rather than current
228 /// module (like paths in an import).
229 pub global: bool,
230 /// The segments in the path: the things separated by `::`.
231 pub segments: Vec<PathSegment>,
232 }
233
234 impl fmt::Debug for Path {
235 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
236 write!(f, "path({})", pprust::path_to_string(self))
237 }
238 }
239
240 impl fmt::Display for Path {
241 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
242 write!(f, "{}", pprust::path_to_string(self))
243 }
244 }
245
246 /// A segment of a path: an identifier, an optional lifetime, and a set of
247 /// types.
248 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
249 pub struct PathSegment {
250 /// The identifier portion of this path segment.
251 pub identifier: Ident,
252
253 /// Type/lifetime parameters attached to this path. They come in
254 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
255 /// this is more than just simple syntactic sugar; the use of
256 /// parens affects the region binding rules, so we preserve the
257 /// distinction.
258 pub parameters: PathParameters,
259 }
260
261 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
262 pub enum PathParameters {
263 /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
264 AngleBracketedParameters(AngleBracketedParameterData),
265 /// The `(A,B)` and `C` in `Foo(A,B) -> C`
266 ParenthesizedParameters(ParenthesizedParameterData),
267 }
268
269 impl PathParameters {
270 pub fn none() -> PathParameters {
271 AngleBracketedParameters(AngleBracketedParameterData {
272 lifetimes: Vec::new(),
273 types: OwnedSlice::empty(),
274 bindings: OwnedSlice::empty(),
275 })
276 }
277
278 pub fn is_empty(&self) -> bool {
279 match *self {
280 AngleBracketedParameters(ref data) => data.is_empty(),
281
282 // Even if the user supplied no types, something like
283 // `X()` is equivalent to `X<(),()>`.
284 ParenthesizedParameters(..) => false,
285 }
286 }
287
288 pub fn has_lifetimes(&self) -> bool {
289 match *self {
290 AngleBracketedParameters(ref data) => !data.lifetimes.is_empty(),
291 ParenthesizedParameters(_) => false,
292 }
293 }
294
295 pub fn has_types(&self) -> bool {
296 match *self {
297 AngleBracketedParameters(ref data) => !data.types.is_empty(),
298 ParenthesizedParameters(..) => true,
299 }
300 }
301
302 /// Returns the types that the user wrote. Note that these do not necessarily map to the type
303 /// parameters in the parenthesized case.
304 pub fn types(&self) -> Vec<&P<Ty>> {
305 match *self {
306 AngleBracketedParameters(ref data) => {
307 data.types.iter().collect()
308 }
309 ParenthesizedParameters(ref data) => {
310 data.inputs.iter()
311 .chain(data.output.iter())
312 .collect()
313 }
314 }
315 }
316
317 pub fn lifetimes(&self) -> Vec<&Lifetime> {
318 match *self {
319 AngleBracketedParameters(ref data) => {
320 data.lifetimes.iter().collect()
321 }
322 ParenthesizedParameters(_) => {
323 Vec::new()
324 }
325 }
326 }
327
328 pub fn bindings(&self) -> Vec<&P<TypeBinding>> {
329 match *self {
330 AngleBracketedParameters(ref data) => {
331 data.bindings.iter().collect()
332 }
333 ParenthesizedParameters(_) => {
334 Vec::new()
335 }
336 }
337 }
338 }
339
340 /// A path like `Foo<'a, T>`
341 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
342 pub struct AngleBracketedParameterData {
343 /// The lifetime parameters for this path segment.
344 pub lifetimes: Vec<Lifetime>,
345 /// The type parameters for this path segment, if present.
346 pub types: OwnedSlice<P<Ty>>,
347 /// Bindings (equality constraints) on associated types, if present.
348 /// E.g., `Foo<A=Bar>`.
349 pub bindings: OwnedSlice<P<TypeBinding>>,
350 }
351
352 impl AngleBracketedParameterData {
353 fn is_empty(&self) -> bool {
354 self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
355 }
356 }
357
358 /// A path like `Foo(A,B) -> C`
359 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
360 pub struct ParenthesizedParameterData {
361 /// Overall span
362 pub span: Span,
363
364 /// `(A,B)`
365 pub inputs: Vec<P<Ty>>,
366
367 /// `C`
368 pub output: Option<P<Ty>>,
369 }
370
371 pub type CrateNum = u32;
372
373 pub type NodeId = u32;
374
375 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
376 RustcDecodable, Hash, Copy)]
377 pub struct DefId {
378 pub krate: CrateNum,
379 pub node: NodeId,
380 }
381
382 fn default_def_id_debug(_: DefId, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) }
383
384 thread_local!(pub static DEF_ID_DEBUG: Cell<fn(DefId, &mut fmt::Formatter) -> fmt::Result> =
385 Cell::new(default_def_id_debug));
386
387 impl fmt::Debug for DefId {
388 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
389 try!(write!(f, "DefId {{ krate: {}, node: {} }}",
390 self.krate, self.node));
391 DEF_ID_DEBUG.with(|def_id_debug| def_id_debug.get()(*self, f))
392 }
393 }
394
395 impl DefId {
396 /// Read the node id, asserting that this def-id is krate-local.
397 pub fn local_id(&self) -> NodeId {
398 assert_eq!(self.krate, LOCAL_CRATE);
399 self.node
400 }
401 }
402
403 /// Item definitions in the currently-compiled crate would have the CrateNum
404 /// LOCAL_CRATE in their DefId.
405 pub const LOCAL_CRATE: CrateNum = 0;
406 pub const CRATE_NODE_ID: NodeId = 0;
407
408 /// When parsing and doing expansions, we initially give all AST nodes this AST
409 /// node value. Then later, in the renumber pass, we renumber them to have
410 /// small, positive ids.
411 pub const DUMMY_NODE_ID: NodeId = !0;
412
413 /// The AST represents all type param bounds as types.
414 /// typeck::collect::compute_bounds matches these against
415 /// the "special" built-in traits (see middle::lang_items) and
416 /// detects Copy, Send and Sync.
417 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
418 pub enum TyParamBound {
419 TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
420 RegionTyParamBound(Lifetime)
421 }
422
423 /// A modifier on a bound, currently this is only used for `?Sized`, where the
424 /// modifier is `Maybe`. Negative bounds should also be handled here.
425 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
426 pub enum TraitBoundModifier {
427 None,
428 Maybe,
429 }
430
431 pub type TyParamBounds = OwnedSlice<TyParamBound>;
432
433 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
434 pub struct TyParam {
435 pub ident: Ident,
436 pub id: NodeId,
437 pub bounds: TyParamBounds,
438 pub default: Option<P<Ty>>,
439 pub span: Span
440 }
441
442 /// Represents lifetimes and type parameters attached to a declaration
443 /// of a function, enum, trait, etc.
444 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
445 pub struct Generics {
446 pub lifetimes: Vec<LifetimeDef>,
447 pub ty_params: OwnedSlice<TyParam>,
448 pub where_clause: WhereClause,
449 }
450
451 impl Generics {
452 pub fn is_lt_parameterized(&self) -> bool {
453 !self.lifetimes.is_empty()
454 }
455 pub fn is_type_parameterized(&self) -> bool {
456 !self.ty_params.is_empty()
457 }
458 pub fn is_parameterized(&self) -> bool {
459 self.is_lt_parameterized() || self.is_type_parameterized()
460 }
461 }
462
463 /// A `where` clause in a definition
464 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
465 pub struct WhereClause {
466 pub id: NodeId,
467 pub predicates: Vec<WherePredicate>,
468 }
469
470 /// A single predicate in a `where` clause
471 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
472 pub enum WherePredicate {
473 /// A type binding, eg `for<'c> Foo: Send+Clone+'c`
474 BoundPredicate(WhereBoundPredicate),
475 /// A lifetime predicate, e.g. `'a: 'b+'c`
476 RegionPredicate(WhereRegionPredicate),
477 /// An equality predicate (unsupported)
478 EqPredicate(WhereEqPredicate)
479 }
480
481 /// A type bound, eg `for<'c> Foo: Send+Clone+'c`
482 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
483 pub struct WhereBoundPredicate {
484 pub span: Span,
485 /// Any lifetimes from a `for` binding
486 pub bound_lifetimes: Vec<LifetimeDef>,
487 /// The type being bounded
488 pub bounded_ty: P<Ty>,
489 /// Trait and lifetime bounds (`Clone+Send+'static`)
490 pub bounds: OwnedSlice<TyParamBound>,
491 }
492
493 /// A lifetime predicate, e.g. `'a: 'b+'c`
494 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
495 pub struct WhereRegionPredicate {
496 pub span: Span,
497 pub lifetime: Lifetime,
498 pub bounds: Vec<Lifetime>,
499 }
500
501 /// An equality predicate (unsupported), e.g. `T=int`
502 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
503 pub struct WhereEqPredicate {
504 pub id: NodeId,
505 pub span: Span,
506 pub path: Path,
507 pub ty: P<Ty>,
508 }
509
510 /// The set of MetaItems that define the compilation environment of the crate,
511 /// used to drive conditional compilation
512 pub type CrateConfig = Vec<P<MetaItem>> ;
513
514 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
515 pub struct Crate {
516 pub module: Mod,
517 pub attrs: Vec<Attribute>,
518 pub config: CrateConfig,
519 pub span: Span,
520 pub exported_macros: Vec<MacroDef>,
521 }
522
523 pub type MetaItem = Spanned<MetaItem_>;
524
525 #[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
526 pub enum MetaItem_ {
527 MetaWord(InternedString),
528 MetaList(InternedString, Vec<P<MetaItem>>),
529 MetaNameValue(InternedString, Lit),
530 }
531
532 // can't be derived because the MetaList requires an unordered comparison
533 impl PartialEq for MetaItem_ {
534 fn eq(&self, other: &MetaItem_) -> bool {
535 match *self {
536 MetaWord(ref ns) => match *other {
537 MetaWord(ref no) => (*ns) == (*no),
538 _ => false
539 },
540 MetaNameValue(ref ns, ref vs) => match *other {
541 MetaNameValue(ref no, ref vo) => {
542 (*ns) == (*no) && vs.node == vo.node
543 }
544 _ => false
545 },
546 MetaList(ref ns, ref miss) => match *other {
547 MetaList(ref no, ref miso) => {
548 ns == no &&
549 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
550 }
551 _ => false
552 }
553 }
554 }
555 }
556
557 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
558 pub struct Block {
559 /// Statements in a block
560 pub stmts: Vec<P<Stmt>>,
561 /// An expression at the end of the block
562 /// without a semicolon, if any
563 pub expr: Option<P<Expr>>,
564 pub id: NodeId,
565 /// Distinguishes between `unsafe { ... }` and `{ ... }`
566 pub rules: BlockCheckMode,
567 pub span: Span,
568 }
569
570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
571 pub struct Pat {
572 pub id: NodeId,
573 pub node: Pat_,
574 pub span: Span,
575 }
576
577 impl fmt::Debug for Pat {
578 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
579 write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
580 }
581 }
582
583 /// A single field in a struct pattern
584 ///
585 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
586 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
587 /// except is_shorthand is true
588 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
589 pub struct FieldPat {
590 /// The identifier for the field
591 pub ident: Ident,
592 /// The pattern the field is destructured to
593 pub pat: P<Pat>,
594 pub is_shorthand: bool,
595 }
596
597 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
598 pub enum BindingMode {
599 BindByRef(Mutability),
600 BindByValue(Mutability),
601 }
602
603 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
604 pub enum PatWildKind {
605 /// Represents the wildcard pattern `_`
606 PatWildSingle,
607
608 /// Represents the wildcard pattern `..`
609 PatWildMulti,
610 }
611
612 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
613 pub enum Pat_ {
614 /// Represents a wildcard pattern (either `_` or `..`)
615 PatWild(PatWildKind),
616
617 /// A PatIdent may either be a new bound variable,
618 /// or a nullary enum (in which case the third field
619 /// is None).
620 ///
621 /// In the nullary enum case, the parser can't determine
622 /// which it is. The resolver determines this, and
623 /// records this pattern's NodeId in an auxiliary
624 /// set (of "PatIdents that refer to nullary enums")
625 PatIdent(BindingMode, SpannedIdent, Option<P<Pat>>),
626
627 /// "None" means a * pattern where we don't bind the fields to names.
628 PatEnum(Path, Option<Vec<P<Pat>>>),
629
630 /// An associated const named using the qualified path `<T>::CONST` or
631 /// `<T as Trait>::CONST`. Associated consts from inherent impls can be
632 /// referred to as simply `T::CONST`, in which case they will end up as
633 /// PatEnum, and the resolver will have to sort that out.
634 PatQPath(QSelf, Path),
635
636 /// Destructuring of a struct, e.g. `Foo {x, y, ..}`
637 /// The `bool` is `true` in the presence of a `..`
638 PatStruct(Path, Vec<Spanned<FieldPat>>, bool),
639 /// A tuple pattern `(a, b)`
640 PatTup(Vec<P<Pat>>),
641 /// A `box` pattern
642 PatBox(P<Pat>),
643 /// A reference pattern, e.g. `&mut (a, b)`
644 PatRegion(P<Pat>, Mutability),
645 /// A literal
646 PatLit(P<Expr>),
647 /// A range pattern, e.g. `1...2`
648 PatRange(P<Expr>, P<Expr>),
649 /// [a, b, ..i, y, z] is represented as:
650 /// PatVec(box [a, b], Some(i), box [y, z])
651 PatVec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
652 /// A macro pattern; pre-expansion
653 PatMac(Mac),
654 }
655
656 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
657 pub enum Mutability {
658 MutMutable,
659 MutImmutable,
660 }
661
662 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
663 pub enum BinOp_ {
664 /// The `+` operator (addition)
665 BiAdd,
666 /// The `-` operator (subtraction)
667 BiSub,
668 /// The `*` operator (multiplication)
669 BiMul,
670 /// The `/` operator (division)
671 BiDiv,
672 /// The `%` operator (modulus)
673 BiRem,
674 /// The `&&` operator (logical and)
675 BiAnd,
676 /// The `||` operator (logical or)
677 BiOr,
678 /// The `^` operator (bitwise xor)
679 BiBitXor,
680 /// The `&` operator (bitwise and)
681 BiBitAnd,
682 /// The `|` operator (bitwise or)
683 BiBitOr,
684 /// The `<<` operator (shift left)
685 BiShl,
686 /// The `>>` operator (shift right)
687 BiShr,
688 /// The `==` operator (equality)
689 BiEq,
690 /// The `<` operator (less than)
691 BiLt,
692 /// The `<=` operator (less than or equal to)
693 BiLe,
694 /// The `!=` operator (not equal to)
695 BiNe,
696 /// The `>=` operator (greater than or equal to)
697 BiGe,
698 /// The `>` operator (greater than)
699 BiGt,
700 }
701
702 pub type BinOp = Spanned<BinOp_>;
703
704 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
705 pub enum UnOp {
706 /// The `box` operator
707 UnUniq,
708 /// The `*` operator for dereferencing
709 UnDeref,
710 /// The `!` operator for logical inversion
711 UnNot,
712 /// The `-` operator for negation
713 UnNeg
714 }
715
716 /// A statement
717 pub type Stmt = Spanned<Stmt_>;
718
719 impl fmt::Debug for Stmt {
720 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
721 write!(f, "stmt({}: {})",
722 ast_util::stmt_id(self),
723 pprust::stmt_to_string(self))
724 }
725 }
726
727
728 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
729 pub enum Stmt_ {
730 /// Could be an item or a local (let) binding:
731 StmtDecl(P<Decl>, NodeId),
732
733 /// Expr without trailing semi-colon (must have unit type):
734 StmtExpr(P<Expr>, NodeId),
735
736 /// Expr with trailing semi-colon (may have any type):
737 StmtSemi(P<Expr>, NodeId),
738
739 StmtMac(P<Mac>, MacStmtStyle),
740 }
741 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
742 pub enum MacStmtStyle {
743 /// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
744 /// `foo!(...);`, `foo![...];`
745 MacStmtWithSemicolon,
746 /// The macro statement had braces; e.g. foo! { ... }
747 MacStmtWithBraces,
748 /// The macro statement had parentheses or brackets and no semicolon; e.g.
749 /// `foo!(...)`. All of these will end up being converted into macro
750 /// expressions.
751 MacStmtWithoutBraces,
752 }
753
754 // FIXME (pending discussion of #1697, #2178...): local should really be
755 // a refinement on pat.
756 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
757 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
758 pub struct Local {
759 pub pat: P<Pat>,
760 pub ty: Option<P<Ty>>,
761 /// Initializer expression to set the value, if any
762 pub init: Option<P<Expr>>,
763 pub id: NodeId,
764 pub span: Span,
765 }
766
767 pub type Decl = Spanned<Decl_>;
768
769 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
770 pub enum Decl_ {
771 /// A local (let) binding:
772 DeclLocal(P<Local>),
773 /// An item binding:
774 DeclItem(P<Item>),
775 }
776
777 /// represents one arm of a 'match'
778 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
779 pub struct Arm {
780 pub attrs: Vec<Attribute>,
781 pub pats: Vec<P<Pat>>,
782 pub guard: Option<P<Expr>>,
783 pub body: P<Expr>,
784 }
785
786 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
787 pub struct Field {
788 pub ident: SpannedIdent,
789 pub expr: P<Expr>,
790 pub span: Span,
791 }
792
793 pub type SpannedIdent = Spanned<Ident>;
794
795 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
796 pub enum BlockCheckMode {
797 DefaultBlock,
798 UnsafeBlock(UnsafeSource),
799 PushUnsafeBlock(UnsafeSource),
800 PopUnsafeBlock(UnsafeSource),
801 }
802
803 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
804 pub enum UnsafeSource {
805 CompilerGenerated,
806 UserProvided,
807 }
808
809 /// An expression
810 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
811 pub struct Expr {
812 pub id: NodeId,
813 pub node: Expr_,
814 pub span: Span,
815 }
816
817 impl fmt::Debug for Expr {
818 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
819 write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
820 }
821 }
822
823 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
824 pub enum Expr_ {
825 /// First expr is the place; second expr is the value.
826 ExprBox(Option<P<Expr>>, P<Expr>),
827 /// An array (`[a, b, c, d]`)
828 ExprVec(Vec<P<Expr>>),
829 /// A function call
830 ///
831 /// The first field resolves to the function itself,
832 /// and the second field is the list of arguments
833 ExprCall(P<Expr>, Vec<P<Expr>>),
834 /// A method call (`x.foo::<Bar, Baz>(a, b, c, d)`)
835 ///
836 /// The `SpannedIdent` is the identifier for the method name.
837 /// The vector of `Ty`s are the ascripted type parameters for the method
838 /// (within the angle brackets).
839 ///
840 /// The first element of the vector of `Expr`s is the expression that evaluates
841 /// to the object on which the method is being called on (the receiver),
842 /// and the remaining elements are the rest of the arguments.
843 ///
844 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
845 /// `ExprMethodCall(foo, [Bar, Baz], [x, a, b, c, d])`.
846 ExprMethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
847 /// A tuple (`(a, b, c ,d)`)
848 ExprTup(Vec<P<Expr>>),
849 /// A binary operation (For example: `a + b`, `a * b`)
850 ExprBinary(BinOp, P<Expr>, P<Expr>),
851 /// A unary operation (For example: `!x`, `*x`)
852 ExprUnary(UnOp, P<Expr>),
853 /// A literal (For example: `1u8`, `"foo"`)
854 ExprLit(P<Lit>),
855 /// A cast (`foo as f64`)
856 ExprCast(P<Expr>, P<Ty>),
857 /// An `if` block, with an optional else block
858 ///
859 /// `if expr { block } else { expr }`
860 ExprIf(P<Expr>, P<Block>, Option<P<Expr>>),
861 /// An `if let` expression with an optional else block
862 ///
863 /// `if let pat = expr { block } else { expr }`
864 ///
865 /// This is desugared to a `match` expression.
866 ExprIfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
867 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
868 /// A while loop, with an optional label
869 ///
870 /// `'label: while expr { block }`
871 ExprWhile(P<Expr>, P<Block>, Option<Ident>),
872 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
873 /// A while-let loop, with an optional label
874 ///
875 /// `'label: while let pat = expr { block }`
876 ///
877 /// This is desugared to a combination of `loop` and `match` expressions.
878 ExprWhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
879 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
880 /// A for loop, with an optional label
881 ///
882 /// `'label: for pat in expr { block }`
883 ///
884 /// This is desugared to a combination of `loop` and `match` expressions.
885 ExprForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
886 /// Conditionless loop (can be exited with break, continue, or return)
887 ///
888 /// `'label: loop { block }`
889 // FIXME #6993: change to Option<Name> ... or not, if these are hygienic.
890 ExprLoop(P<Block>, Option<Ident>),
891 /// A `match` block, with a source that indicates whether or not it is
892 /// the result of a desugaring, and if so, which kind.
893 ExprMatch(P<Expr>, Vec<Arm>, MatchSource),
894 /// A closure (for example, `move |a, b, c| {a + b + c}`)
895 ExprClosure(CaptureClause, P<FnDecl>, P<Block>),
896 /// A block (`{ ... }`)
897 ExprBlock(P<Block>),
898
899 /// An assignment (`a = foo()`)
900 ExprAssign(P<Expr>, P<Expr>),
901 /// An assignment with an operator
902 ///
903 /// For example, `a += 1`.
904 ExprAssignOp(BinOp, P<Expr>, P<Expr>),
905 /// Access of a named struct field (`obj.foo`)
906 ExprField(P<Expr>, SpannedIdent),
907 /// Access of an unnamed field of a struct or tuple-struct
908 ///
909 /// For example, `foo.0`.
910 ExprTupField(P<Expr>, Spanned<usize>),
911 /// An indexing operation (`foo[2]`)
912 ExprIndex(P<Expr>, P<Expr>),
913 /// A range (`1..2`, `1..`, or `..2`)
914 ExprRange(Option<P<Expr>>, Option<P<Expr>>),
915
916 /// Variable reference, possibly containing `::` and/or type
917 /// parameters, e.g. foo::bar::<baz>.
918 ///
919 /// Optionally "qualified",
920 /// e.g. `<Vec<T> as SomeTrait>::SomeType`.
921 ExprPath(Option<QSelf>, Path),
922
923 /// A referencing operation (`&a` or `&mut a`)
924 ExprAddrOf(Mutability, P<Expr>),
925 /// A `break`, with an optional label to break
926 ExprBreak(Option<Ident>),
927 /// A `continue`, with an optional label
928 ExprAgain(Option<Ident>),
929 /// A `return`, with an optional value to be returned
930 ExprRet(Option<P<Expr>>),
931
932 /// Output of the `asm!()` macro
933 ExprInlineAsm(InlineAsm),
934
935 /// A macro invocation; pre-expansion
936 ExprMac(Mac),
937
938 /// A struct literal expression.
939 ///
940 /// For example, `Foo {x: 1, y: 2}`, or
941 /// `Foo {x: 1, .. base}`, where `base` is the `Option<Expr>`.
942 ExprStruct(Path, Vec<Field>, Option<P<Expr>>),
943
944 /// A vector literal constructed from one repeated element.
945 ///
946 /// For example, `[1u8; 5]`. The first expression is the element
947 /// to be repeated; the second is the number of times to repeat it.
948 ExprRepeat(P<Expr>, P<Expr>),
949
950 /// No-op: used solely so we can pretty-print faithfully
951 ExprParen(P<Expr>)
952 }
953
954 /// The explicit Self type in a "qualified path". The actual
955 /// path, including the trait and the associated item, is stored
956 /// separately. `position` represents the index of the associated
957 /// item qualified with this Self type.
958 ///
959 /// <Vec<T> as a::b::Trait>::AssociatedItem
960 /// ^~~~~ ~~~~~~~~~~~~~~^
961 /// ty position = 3
962 ///
963 /// <Vec<T>>::AssociatedItem
964 /// ^~~~~ ^
965 /// ty position = 0
966 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
967 pub struct QSelf {
968 pub ty: P<Ty>,
969 pub position: usize
970 }
971
972 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
973 pub enum MatchSource {
974 Normal,
975 IfLetDesugar { contains_else_clause: bool },
976 WhileLetDesugar,
977 ForLoopDesugar,
978 }
979
980 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
981 pub enum CaptureClause {
982 CaptureByValue,
983 CaptureByRef,
984 }
985
986 /// A delimited sequence of token trees
987 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
988 pub struct Delimited {
989 /// The type of delimiter
990 pub delim: token::DelimToken,
991 /// The span covering the opening delimiter
992 pub open_span: Span,
993 /// The delimited sequence of token trees
994 pub tts: Vec<TokenTree>,
995 /// The span covering the closing delimiter
996 pub close_span: Span,
997 }
998
999 impl Delimited {
1000 /// Returns the opening delimiter as a token.
1001 pub fn open_token(&self) -> token::Token {
1002 token::OpenDelim(self.delim)
1003 }
1004
1005 /// Returns the closing delimiter as a token.
1006 pub fn close_token(&self) -> token::Token {
1007 token::CloseDelim(self.delim)
1008 }
1009
1010 /// Returns the opening delimiter as a token tree.
1011 pub fn open_tt(&self) -> TokenTree {
1012 TtToken(self.open_span, self.open_token())
1013 }
1014
1015 /// Returns the closing delimiter as a token tree.
1016 pub fn close_tt(&self) -> TokenTree {
1017 TtToken(self.close_span, self.close_token())
1018 }
1019 }
1020
1021 /// A sequence of token treesee
1022 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1023 pub struct SequenceRepetition {
1024 /// The sequence of token trees
1025 pub tts: Vec<TokenTree>,
1026 /// The optional separator
1027 pub separator: Option<token::Token>,
1028 /// Whether the sequence can be repeated zero (*), or one or more times (+)
1029 pub op: KleeneOp,
1030 /// The number of `MatchNt`s that appear in the sequence (and subsequences)
1031 pub num_captures: usize,
1032 }
1033
1034 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
1035 /// for token sequences.
1036 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
1037 pub enum KleeneOp {
1038 ZeroOrMore,
1039 OneOrMore,
1040 }
1041
1042 /// When the main rust parser encounters a syntax-extension invocation, it
1043 /// parses the arguments to the invocation as a token-tree. This is a very
1044 /// loose structure, such that all sorts of different AST-fragments can
1045 /// be passed to syntax extensions using a uniform type.
1046 ///
1047 /// If the syntax extension is an MBE macro, it will attempt to match its
1048 /// LHS token tree against the provided token tree, and if it finds a
1049 /// match, will transcribe the RHS token tree, splicing in any captured
1050 /// macro_parser::matched_nonterminals into the `SubstNt`s it finds.
1051 ///
1052 /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
1053 /// Nothing special happens to misnamed or misplaced `SubstNt`s.
1054 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
1055 pub enum TokenTree {
1056 /// A single token
1057 TtToken(Span, token::Token),
1058 /// A delimited sequence of token trees
1059 TtDelimited(Span, Rc<Delimited>),
1060
1061 // This only makes sense in MBE macros.
1062
1063 /// A kleene-style repetition sequence with a span
1064 // FIXME(eddyb) #12938 Use DST.
1065 TtSequence(Span, Rc<SequenceRepetition>),
1066 }
1067
1068 impl TokenTree {
1069 pub fn len(&self) -> usize {
1070 match *self {
1071 TtToken(_, token::DocComment(name)) => {
1072 match doc_comment_style(&name.as_str()) {
1073 AttrOuter => 2,
1074 AttrInner => 3
1075 }
1076 }
1077 TtToken(_, token::SpecialVarNt(..)) => 2,
1078 TtToken(_, token::MatchNt(..)) => 3,
1079 TtDelimited(_, ref delimed) => {
1080 delimed.tts.len() + 2
1081 }
1082 TtSequence(_, ref seq) => {
1083 seq.tts.len()
1084 }
1085 TtToken(..) => 0
1086 }
1087 }
1088
1089 pub fn get_tt(&self, index: usize) -> TokenTree {
1090 match (self, index) {
1091 (&TtToken(sp, token::DocComment(_)), 0) => {
1092 TtToken(sp, token::Pound)
1093 }
1094 (&TtToken(sp, token::DocComment(name)), 1)
1095 if doc_comment_style(&name.as_str()) == AttrInner => {
1096 TtToken(sp, token::Not)
1097 }
1098 (&TtToken(sp, token::DocComment(name)), _) => {
1099 let stripped = strip_doc_comment_decoration(&name.as_str());
1100 TtDelimited(sp, Rc::new(Delimited {
1101 delim: token::Bracket,
1102 open_span: sp,
1103 tts: vec![TtToken(sp, token::Ident(token::str_to_ident("doc"),
1104 token::Plain)),
1105 TtToken(sp, token::Eq),
1106 TtToken(sp, token::Literal(
1107 token::StrRaw(token::intern(&stripped), 0), 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 }