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.
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.
11 // The Rust abstract syntax tree.
13 use codemap::{Span, Spanned, DUMMY_SP};
17 use parse::token::{InternedString, special_idents, str_to_ident};
22 use std::cell::RefCell;
23 use collections::HashMap;
24 use std::option::Option;
27 use serialize::{Encodable, Decodable, Encoder, Decoder};
29 /// A pointer abstraction. FIXME(eddyb) #10676 use Rc<T> in the future.
32 /// Construct a P<T> from a T value.
33 pub fn P<T: 'static>(value: T) -> P<T> {
37 // FIXME #6993: in librustc, uses of "ident" should be replaced
40 // an identifier contains a Name (index into the interner
41 // table) and a SyntaxContext to track renaming and
42 // macro expansion per Flatt et al., "Macros
43 // That Work Together"
44 #[deriving(Clone, Hash, TotalEq, TotalOrd, Show)]
45 pub struct Ident { name: Name, ctxt: SyntaxContext }
48 /// Construct an identifier with the given name and an empty context:
49 pub fn new(name: Name) -> Ident { Ident {name: name, ctxt: EMPTY_CTXT}}
53 fn eq(&self, other: &Ident) -> bool {
54 if self.ctxt == other.ctxt {
55 self.name == other.name
57 // IF YOU SEE ONE OF THESE FAILS: it means that you're comparing
58 // idents that have different contexts. You can't fix this without
59 // knowing whether the comparison should be hygienic or non-hygienic.
60 // if it should be non-hygienic (most things are), just compare the
61 // 'name' fields of the idents. Or, even better, replace the idents
64 // On the other hand, if the comparison does need to be hygienic,
65 // one example and its non-hygienic counterpart would be:
66 // syntax::parse::token::mtwt_token_eq
67 // syntax::ext::tt::macro_parser::token_name_eq
68 fail!("not allowed to compare these idents: {:?}, {:?}. \
69 Probably related to issue \\#6993", self, other);
72 fn ne(&self, other: &Ident) -> bool {
77 /// A SyntaxContext represents a chain of macro-expandings
78 /// and renamings. Each macro expansion corresponds to
81 // I'm representing this syntax context as an index into
82 // a table, in order to work around a compiler bug
83 // that's causing unreleased memory to cause core dumps
84 // and also perhaps to save some work in destructor checks.
85 // the special uint '0' will be used to indicate an empty
88 // this uint is a reference to a table stored in thread-local
90 pub type SyntaxContext = u32;
92 // the SCTable contains a table of SyntaxContext_'s. It
93 // represents a flattened tree structure, to avoid having
94 // managed pointers everywhere (that caused an ICE).
95 // the mark_memo and rename_memo fields are side-tables
96 // that ensure that adding the same mark to the same context
97 // gives you back the same context as before. This shouldn't
98 // change the semantics--everything here is immutable--but
99 // it should cut down on memory use *a lot*; applying a mark
100 // to a tree containing 50 identifiers would otherwise generate
102 table: RefCell<Vec<SyntaxContext_> >,
103 mark_memo: RefCell<HashMap<(SyntaxContext,Mrk),SyntaxContext>>,
104 rename_memo: RefCell<HashMap<(SyntaxContext,Ident,Name),SyntaxContext>>,
107 // NB: these must be placed in any SCTable...
108 pub static EMPTY_CTXT : SyntaxContext = 0;
109 pub static ILLEGAL_CTXT : SyntaxContext = 1;
111 #[deriving(Eq, Encodable, Decodable, Hash)]
112 pub enum SyntaxContext_ {
114 Mark (Mrk,SyntaxContext),
115 // flattening the name and syntaxcontext into the rename...
116 // HIDDEN INVARIANTS:
117 // 1) the first name in a Rename node
118 // can only be a programmer-supplied name.
119 // 2) Every Rename node with a given Name in the
120 // "to" slot must have the same name and context
121 // in the "from" slot. In essence, they're all
122 // pointers to a single "rename" event node.
123 Rename (Ident,Name,SyntaxContext),
124 // actually, IllegalCtxt may not be necessary.
128 /// A name is a part of an identifier, representing a string or gensym. It's
129 /// the result of interning.
132 /// A mark represents a unique id associated with a macro expansion
135 impl<S: Encoder> Encodable<S> for Ident {
136 fn encode(&self, s: &mut S) {
137 s.emit_str(token::get_ident(*self).get());
141 impl<D:Decoder> Decodable<D> for Ident {
142 fn decode(d: &mut D) -> Ident {
143 str_to_ident(d.read_str())
147 /// Function name (not all functions have names)
148 pub type FnIdent = Option<Ident>;
150 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
151 pub struct Lifetime {
157 // a "Path" is essentially Rust's notion of a name;
158 // for instance: std::cmp::Eq . It's represented
159 // as a sequence of identifiers, along with a bunch
160 // of supporting information.
161 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
164 /// A `::foo` path, is relative to the crate root rather than current
165 /// module (like paths in an import).
167 /// The segments in the path: the things separated by `::`.
168 segments: Vec<PathSegment> ,
171 /// A segment of a path: an identifier, an optional lifetime, and a set of
173 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
174 pub struct PathSegment {
175 /// The identifier portion of this path segment.
177 /// The lifetime parameters for this path segment.
178 lifetimes: OptVec<Lifetime>,
179 /// The type parameters for this path segment, if present.
180 types: OptVec<P<Ty>>,
183 pub type CrateNum = u32;
185 pub type NodeId = u32;
187 #[deriving(Clone, TotalEq, TotalOrd, Eq, Encodable, Decodable, Hash, Show)]
193 /// Item definitions in the currently-compiled crate would have the CrateNum
194 /// LOCAL_CRATE in their DefId.
195 pub static LOCAL_CRATE: CrateNum = 0;
196 pub static CRATE_NODE_ID: NodeId = 0;
198 // When parsing and doing expansions, we initially give all AST nodes this AST
199 // node value. Then later, in the renumber pass, we renumber them to have
200 // small, positive ids.
201 pub static DUMMY_NODE_ID: NodeId = -1;
203 // The AST represents all type param bounds as types.
204 // typeck::collect::compute_bounds matches these against
205 // the "special" built-in traits (see middle::lang_items) and
206 // detects Copy, Send, Send, and Freeze.
207 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
208 pub enum TyParamBound {
209 TraitTyParamBound(TraitRef),
213 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
217 bounds: OptVec<TyParamBound>,
218 default: Option<P<Ty>>
221 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
222 pub struct Generics {
223 lifetimes: OptVec<Lifetime>,
224 ty_params: OptVec<TyParam>,
228 pub fn is_parameterized(&self) -> bool {
229 self.lifetimes.len() + self.ty_params.len() > 0
231 pub fn is_lt_parameterized(&self) -> bool {
232 self.lifetimes.len() > 0
234 pub fn is_type_parameterized(&self) -> bool {
235 self.ty_params.len() > 0
239 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
240 pub enum MethodProvenance {
245 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
247 DefFn(DefId, Purity),
248 DefStaticMethod(/* method */ DefId, MethodProvenance, Purity),
249 DefSelfTy(/* trait id */ NodeId),
251 DefForeignMod(DefId),
252 DefStatic(DefId, bool /* is_mutbl */),
253 DefArg(NodeId, BindingMode),
254 DefLocal(NodeId, BindingMode),
255 DefVariant(DefId /* enum */, DefId /* variant */, bool /* is_structure */),
259 DefTyParam(DefId, uint),
260 DefBinding(NodeId, BindingMode),
262 DefUpvar(NodeId, // id of closed over var
263 @Def, // closed over def
264 NodeId, // expr node that creates the closure
265 NodeId), // id for the block/body of the closure expr
267 /// Note that if it's a tuple struct's definition, the node id of the DefId
268 /// may either refer to the item definition's id or the StructDef.ctor_id.
270 /// The cases that I have encountered so far are (this is not exhaustive):
271 /// - If it's a ty_path referring to some tuple struct, then DefMap maps
272 /// it to a def whose id is the item definition's id.
273 /// - If it's an ExprPath referring to some tuple struct, then DefMap maps
274 /// it to a def whose id is the StructDef.ctor_id.
276 DefTyParamBinder(NodeId), /* struct, impl or trait with ty params */
279 DefMethod(DefId /* method */, Option<DefId> /* trait */),
282 #[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)]
285 DefEarlyBoundRegion(/* index */ uint, /* lifetime decl */ NodeId),
286 DefLateBoundRegion(/* binder_id */ NodeId, /* depth */ uint, /* lifetime decl */ NodeId),
287 DefFreeRegion(/* block scope */ NodeId, /* lifetime decl */ NodeId),
290 // The set of MetaItems that define the compilation environment of the crate,
291 // used to drive conditional compilation
292 pub type CrateConfig = Vec<@MetaItem> ;
294 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
297 attrs: Vec<Attribute> ,
302 pub type MetaItem = Spanned<MetaItem_>;
304 #[deriving(Clone, Encodable, Decodable, Hash)]
306 MetaWord(InternedString),
307 MetaList(InternedString, Vec<@MetaItem> ),
308 MetaNameValue(InternedString, Lit),
311 // can't be derived because the MetaList requires an unordered comparison
312 impl Eq for MetaItem_ {
313 fn eq(&self, other: &MetaItem_) -> bool {
315 MetaWord(ref ns) => match *other {
316 MetaWord(ref no) => (*ns) == (*no),
319 MetaNameValue(ref ns, ref vs) => match *other {
320 MetaNameValue(ref no, ref vo) => {
321 (*ns) == (*no) && vs.node == vo.node
325 MetaList(ref ns, ref miss) => match *other {
326 MetaList(ref no, ref miso) => {
328 miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
336 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
338 view_items: Vec<ViewItem> ,
342 rules: BlockCheckMode,
346 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
353 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
354 pub struct FieldPat {
359 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
360 pub enum BindingMode {
361 BindByRef(Mutability),
362 BindByValue(Mutability),
365 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
369 // A PatIdent may either be a new bound variable,
370 // or a nullary enum (in which case the second field
372 // In the nullary enum case, the parser can't determine
373 // which it is. The resolver determines this, and
374 // records this pattern's NodeId in an auxiliary
375 // set (of "pat_idents that refer to nullary enums")
376 PatIdent(BindingMode, Path, Option<@Pat>),
377 PatEnum(Path, Option<Vec<@Pat> >), /* "none" means a * pattern where
378 * we don't bind the fields to names */
379 PatStruct(Path, Vec<FieldPat> , bool),
382 PatRegion(@Pat), // reference pattern
384 PatRange(@Expr, @Expr),
385 // [a, b, ..i, y, z] is represented as
386 // PatVec(~[a, b], Some(i), ~[y, z])
387 PatVec(Vec<@Pat> , Option<@Pat>, Vec<@Pat> )
390 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
391 pub enum Mutability {
396 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
403 impl fmt::Show for Sigil {
404 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
406 BorrowedSigil => "&".fmt(f),
407 OwnedSigil => "~".fmt(f),
408 ManagedSigil => "@".fmt(f),
413 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
414 pub enum ExprVstore {
415 ExprVstoreUniq, // ~[1,2,3,4]
416 ExprVstoreSlice, // &[1,2,3,4]
417 ExprVstoreMutSlice, // &mut [1,2,3,4]
420 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
442 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
451 pub type Stmt = Spanned<Stmt_>;
453 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
455 // could be an item or a local (let) binding:
456 StmtDecl(@Decl, NodeId),
458 // expr without trailing semi-colon (must have unit type):
459 StmtExpr(@Expr, NodeId),
461 // expr with trailing semi-colon (may have any type):
462 StmtSemi(@Expr, NodeId),
464 // bool: is there a trailing sem-colon?
468 // FIXME (pending discussion of #1697, #2178...): local should really be
469 // a refinement on pat.
470 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
471 #[deriving(Eq, Encodable, Decodable, Hash)]
480 pub type Decl = Spanned<Decl_>;
482 #[deriving(Eq, Encodable, Decodable, Hash)]
484 // a local (let) binding:
490 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
493 guard: Option<@Expr>,
497 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
504 pub type SpannedIdent = Spanned<Ident>;
506 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
507 pub enum BlockCheckMode {
509 UnsafeBlock(UnsafeSource),
512 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
513 pub enum UnsafeSource {
518 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
525 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
527 ExprVstore(@Expr, ExprVstore),
528 // First expr is the place; second expr is the value.
529 ExprBox(@Expr, @Expr),
530 ExprVec(Vec<@Expr> , Mutability),
531 ExprCall(@Expr, Vec<@Expr> ),
532 ExprMethodCall(Ident, Vec<P<Ty>> , Vec<@Expr> ),
533 ExprTup(Vec<@Expr> ),
534 ExprBinary(BinOp, @Expr, @Expr),
535 ExprUnary(UnOp, @Expr),
537 ExprCast(@Expr, P<Ty>),
538 ExprIf(@Expr, P<Block>, Option<@Expr>),
539 ExprWhile(@Expr, P<Block>),
540 // FIXME #6993: change to Option<Name>
541 ExprForLoop(@Pat, @Expr, P<Block>, Option<Ident>),
542 // Conditionless loop (can be exited with break, cont, or ret)
543 // FIXME #6993: change to Option<Name>
544 ExprLoop(P<Block>, Option<Ident>),
545 ExprMatch(@Expr, Vec<Arm> ),
546 ExprFnBlock(P<FnDecl>, P<Block>),
547 ExprProc(P<FnDecl>, P<Block>),
550 ExprAssign(@Expr, @Expr),
551 ExprAssignOp(BinOp, @Expr, @Expr),
552 ExprField(@Expr, Ident, Vec<P<Ty>> ),
553 ExprIndex(@Expr, @Expr),
555 /// Expression that looks like a "name". For example,
556 /// `std::vec::from_elem::<uint>` is an ExprPath that's the "name" part
557 /// of a function call.
560 ExprAddrOf(Mutability, @Expr),
561 ExprBreak(Option<Ident>),
562 ExprAgain(Option<Ident>),
563 ExprRet(Option<@Expr>),
565 /// Gets the log level for the enclosing module
568 ExprInlineAsm(InlineAsm),
572 // A struct literal expression.
573 ExprStruct(Path, Vec<Field> , Option<@Expr> /* base */),
575 // A vector literal constructed from one repeated element.
576 ExprRepeat(@Expr /* element */, @Expr /* count */, Mutability),
578 // No-op: used solely so we can pretty-print faithfully
582 // When the main rust parser encounters a syntax-extension invocation, it
583 // parses the arguments to the invocation as a token-tree. This is a very
584 // loose structure, such that all sorts of different AST-fragments can
585 // be passed to syntax extensions using a uniform type.
587 // If the syntax extension is an MBE macro, it will attempt to match its
588 // LHS "matchers" against the provided token tree, and if it finds a
589 // match, will transcribe the RHS token tree, splicing in any captured
590 // macro_parser::matched_nonterminals into the TTNonterminals it finds.
592 // The RHS of an MBE macro is the only place a TTNonterminal or TTSeq
593 // makes any real sense. You could write them elsewhere but nothing
594 // else knows what to do with them, so you'll probably get a syntax
597 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
598 #[doc="For macro invocations; parsing is delegated to the macro"]
601 TTTok(Span, ::parse::token::Token),
602 // a delimited sequence (the delimiters appear as the first
603 // and last elements of the vector)
604 TTDelim(@Vec<TokenTree> ),
606 // These only make sense for right-hand-sides of MBE macros:
608 // a kleene-style repetition sequence with a span, a TTForest,
609 // an optional separator, and a boolean where true indicates
610 // zero or more (..), and false indicates one or more (+).
611 TTSeq(Span, @Vec<TokenTree> , Option<::parse::token::Token>, bool),
613 // a syntactic variable that will be filled in by macro expansion.
614 TTNonterminal(Span, Ident)
618 // Matchers are nodes defined-by and recognized-by the main rust parser and
619 // language, but they're only ever found inside syntax-extension invocations;
620 // indeed, the only thing that ever _activates_ the rules in the rust parser
621 // for parsing a matcher is a matcher looking for the 'matchers' nonterminal
622 // itself. Matchers represent a small sub-language for pattern-matching
623 // token-trees, and are thus primarily used by the macro-defining extension
629 // A matcher that matches a single token, denoted by the token itself. So
630 // long as there's no $ involved.
636 // A matcher that matches a sequence of sub-matchers, denoted various
639 // $(M)* zero or more Ms
640 // $(M)+ one or more Ms
641 // $(M),+ one or more comma-separated Ms
642 // $(A B C);* zero or more semi-separated 'A B C' seqs
648 // A matcher that matches one of a few interesting named rust
649 // nonterminals, such as types, expressions, items, or raw token-trees. A
650 // black-box matcher on expr, for example, binds an expr to a given ident,
651 // and that ident can re-occur as an interpolation in the RHS of a
652 // macro-by-example rule. For example:
654 // $foo:expr => 1 + $foo // interpolate an expr
655 // $foo:tt => $foo // interpolate a token-tree
656 // $foo:tt => bar! $foo // only other valid interpolation
657 // // is in arg position for another
660 // As a final, horrifying aside, note that macro-by-example's input is
661 // also matched by one of these matchers. Holy self-referential! It is matched
662 // by a MatchSeq, specifically this one:
664 // $( $lhs:matchers => $rhs:tt );+
666 // If you understand that, you have closed to loop and understand the whole
667 // macro system. Congratulations.
669 pub type Matcher = Spanned<Matcher_>;
671 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
674 MatchTok(::parse::token::Token),
675 // match repetitions of a sequence: body, separator, zero ok?,
676 // lo, hi position-in-match-array used:
677 MatchSeq(Vec<Matcher> , Option<::parse::token::Token>, bool, uint, uint),
678 // parse a Rust NT: name to bind, name of NT, position in match array:
679 MatchNonterminal(Ident, Ident, uint)
682 pub type Mac = Spanned<Mac_>;
684 // represents a macro invocation. The Path indicates which macro
685 // is being invoked, and the vector of token-trees contains the source
686 // of the macro invocation.
687 // There's only one flavor, now, so this could presumably be simplified.
688 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
690 MacInvocTT(Path, Vec<TokenTree> , SyntaxContext), // new macro-invocation
693 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
699 pub type Lit = Spanned<Lit_>;
701 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
703 LitStr(InternedString, StrStyle),
704 LitBinary(Rc<Vec<u8> >),
707 LitUint(u64, UintTy),
708 LitIntUnsuffixed(i64),
709 LitFloat(InternedString, FloatTy),
710 LitFloatUnsuffixed(InternedString),
715 // NB: If you change this, you'll probably want to change the corresponding
716 // type structure in middle/ty.rs as well.
717 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
723 #[deriving(Eq, Encodable, Decodable, Hash)]
724 pub struct TypeField {
730 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
731 pub struct TypeMethod {
733 attrs: Vec<Attribute> ,
737 explicit_self: ExplicitSelf,
742 // A trait method is either required (meaning it doesn't have an
743 // implementation, just a signature) or provided (meaning it has a default
745 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
746 pub enum TraitMethod {
747 Required(TypeMethod),
751 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
760 impl fmt::Show for IntTy {
761 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
762 write!(f.buf, "{}", ast_util::int_ty_to_str(*self))
766 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
775 impl fmt::Show for UintTy {
776 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
777 write!(f.buf, "{}", ast_util::uint_ty_to_str(*self))
781 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
787 impl fmt::Show for FloatTy {
788 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
789 write!(f.buf, "{}", ast_util::float_ty_to_str(*self))
793 // NB Eq method appears below.
794 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
801 // Not represented directly in the AST, referred to by name through a ty_path.
802 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
812 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
818 impl fmt::Show for Onceness {
819 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
821 Once => "once".fmt(f),
822 Many => "many".fmt(f),
827 #[deriving(Eq, Encodable, Decodable, Hash)]
828 pub struct ClosureTy {
830 region: Option<Lifetime>,
831 lifetimes: OptVec<Lifetime>,
835 // Optional optvec distinguishes between "fn()" and "fn:()" so we can
836 // implement issue #7264. None means "fn()", which means infer a default
837 // bound based on pointer sigil during typeck. Some(Empty) means "fn:()",
838 // which means use no bounds (e.g., not even Owned on a ~fn()).
839 bounds: Option<OptVec<TyParamBound>>,
842 #[deriving(Eq, Encodable, Decodable, Hash)]
843 pub struct BareFnTy {
846 lifetimes: OptVec<Lifetime>,
850 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
853 TyBot, /* bottom type */
857 TyFixedLengthVec(P<Ty>, @Expr),
859 TyRptr(Option<Lifetime>, MutTy),
860 TyClosure(@ClosureTy),
863 TyPath(Path, Option<OptVec<TyParamBound>>, NodeId), // for #7264; see above
865 // TyInfer means the type should be inferred instead of it having been
866 // specified. This should only appear at the "top level" of a type and not
871 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
872 pub enum AsmDialect {
877 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
878 pub struct InlineAsm {
880 asm_str_style: StrStyle,
881 clobbers: InternedString,
882 inputs: Vec<(InternedString, @Expr)> ,
883 outputs: Vec<(InternedString, @Expr)> ,
889 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
897 pub fn new_self(span: Span, mutability: Mutability) -> Arg {
898 let path = ast_util::ident_to_path(span, special_idents::self_);
900 // HACK(eddyb) fake type for the self argument.
908 node: PatIdent(BindByValue(mutability), path, None),
916 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
924 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
926 UnsafeFn, // declared with "unsafe fn"
927 ImpureFn, // declared with "fn"
928 ExternFn, // declared with "extern fn"
931 impl fmt::Show for Purity {
932 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
934 ImpureFn => "impure".fmt(f),
935 UnsafeFn => "unsafe".fmt(f),
936 ExternFn => "extern".fmt(f),
941 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
943 NoReturn, // functions with return type _|_ that always
944 // raise an error or exit (i.e. never return to the caller)
945 Return, // everything else
948 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
949 pub enum ExplicitSelf_ {
950 SelfStatic, // no self
952 SelfRegion(Option<Lifetime>, Mutability), // `&'lt self`, `&'lt mut self`
956 pub type ExplicitSelf = Spanned<ExplicitSelf_>;
958 #[deriving(Eq, Encodable, Decodable, Hash)]
961 attrs: Vec<Attribute> ,
963 explicit_self: ExplicitSelf,
972 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
974 view_items: Vec<ViewItem> ,
978 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
979 pub struct ForeignMod {
981 view_items: Vec<ViewItem> ,
982 items: Vec<@ForeignItem> ,
985 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
986 pub struct VariantArg {
991 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
992 pub enum VariantKind {
993 TupleVariantKind(Vec<VariantArg> ),
994 StructVariantKind(@StructDef),
997 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
999 variants: Vec<P<Variant>> ,
1002 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
1003 pub struct Variant_ {
1005 attrs: Vec<Attribute> ,
1008 disr_expr: Option<@Expr>,
1012 pub type Variant = Spanned<Variant_>;
1014 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
1015 pub struct PathListIdent_ {
1020 pub type PathListIdent = Spanned<PathListIdent_>;
1022 pub type ViewPath = Spanned<ViewPath_>;
1024 #[deriving(Eq, Encodable, Decodable, Hash)]
1025 pub enum ViewPath_ {
1027 // quux = foo::bar::baz
1031 // foo::bar::baz (with 'baz =' implicitly on the left)
1032 ViewPathSimple(Ident, Path, NodeId),
1035 ViewPathGlob(Path, NodeId),
1037 // foo::bar::{a,b,c}
1038 ViewPathList(Path, Vec<PathListIdent> , NodeId)
1041 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
1042 pub struct ViewItem {
1044 attrs: Vec<Attribute> ,
1049 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
1050 pub enum ViewItem_ {
1051 // ident: name used to refer to this crate in the code
1052 // optional (InternedString,StrStyle): if present, this is a location
1053 // (containing arbitrary characters) from which to fetch the crate sources
1054 // For example, extern crate whatever = "github.com/mozilla/rust"
1055 ViewItemExternMod(Ident, Option<(InternedString,StrStyle)>, NodeId),
1056 ViewItemUse(Vec<@ViewPath> ),
1059 // Meta-data associated with an item
1060 pub type Attribute = Spanned<Attribute_>;
1062 // Distinguishes between Attributes that decorate items and Attributes that
1063 // are contained as statements within items. These two cases need to be
1064 // distinguished for pretty-printing.
1065 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
1066 pub enum AttrStyle {
1071 // doc-comments are promoted to attributes that have is_sugared_doc = true
1072 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
1073 pub struct Attribute_ {
1076 is_sugared_doc: bool,
1080 TraitRef's appear in impls.
1081 resolve maps each TraitRef's ref_id to its defining trait; that's all
1082 that the ref_id is for. The impl_id maps to the "self type" of this impl.
1083 If this impl is an ItemImpl, the impl_id is redundant (it could be the
1084 same as the impl's node id).
1086 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
1087 pub struct TraitRef {
1092 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
1093 pub enum Visibility {
1100 pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility {
1102 &Inherited => parent_visibility,
1103 &Public | &Private => *self
1108 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
1109 pub struct StructField_ {
1110 kind: StructFieldKind,
1113 attrs: Vec<Attribute> ,
1116 pub type StructField = Spanned<StructField_>;
1118 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
1119 pub enum StructFieldKind {
1120 NamedField(Ident, Visibility),
1121 UnnamedField // element of a tuple-like struct
1124 #[deriving(Eq, Encodable, Decodable, Hash)]
1125 pub struct StructDef {
1126 fields: Vec<StructField> , /* fields, not including ctor */
1127 /* ID of the constructor. This is only used for tuple- or enum-like
1129 ctor_id: Option<NodeId>
1133 FIXME (#3300): Should allow items to be anonymous. Right now
1134 we just use dummy names for anon items.
1136 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
1139 attrs: Vec<Attribute> ,
1146 #[deriving(Clone, Eq, Encodable, Decodable, Hash)]
1148 ItemStatic(P<Ty>, Mutability, @Expr),
1149 ItemFn(P<FnDecl>, Purity, AbiSet, Generics, P<Block>),
1151 ItemForeignMod(ForeignMod),
1152 ItemTy(P<Ty>, Generics),
1153 ItemEnum(EnumDef, Generics),
1154 ItemStruct(@StructDef, Generics),
1155 ItemTrait(Generics, Vec<TraitRef> , Vec<TraitMethod> ),
1157 Option<TraitRef>, // (optional) trait this impl implements
1160 // a macro invocation (which includes macro definition)
1164 #[deriving(Eq, Encodable, Decodable, Hash)]
1165 pub struct ForeignItem {
1167 attrs: Vec<Attribute> ,
1174 #[deriving(Eq, Encodable, Decodable, Hash)]
1175 pub enum ForeignItem_ {
1176 ForeignItemFn(P<FnDecl>, Generics),
1177 ForeignItemStatic(P<Ty>, /* is_mutbl */ bool),
1180 // The data we save and restore about an inlined item or method. This is not
1181 // part of the AST that we parse from a file, but it becomes part of the tree
1183 #[deriving(Eq, Encodable, Decodable, Hash)]
1184 pub enum InlinedItem {
1186 IIMethod(DefId /* impl id */, bool /* is provided */, @Method),
1187 IIForeign(@ForeignItem),
1192 use serialize::json;
1197 use std::vec_ng::Vec;
1199 fn is_freeze<T: Freeze>() {}
1201 // Assert that the AST remains Freeze (#10693).
1203 fn ast_is_freeze() {
1204 is_freeze::<Item>();
1207 // are ASTs encodable?
1209 fn check_asts_encodable() {
1211 module: Mod {view_items: Vec::new(), items: Vec::new()},
1220 // doesn't matter which encoder we use....
1221 let _f = &e as &serialize::Encodable<json::Encoder>;