]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast_util.rs
doc: remove incomplete sentence
[rust.git] / src / libsyntax / ast_util.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 use abi::Abi;
12 use ast::*;
13 use ast;
14 use ast_util;
15 use codemap;
16 use codemap::Span;
17 use owned_slice::OwnedSlice;
18 use parse::token;
19 use print::pprust;
20 use ptr::P;
21 use visit::Visitor;
22 use visit;
23
24 use std::cmp;
25 use std::u32;
26
27 pub fn path_name_i(idents: &[Ident]) -> String {
28     // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
29     idents.iter().map(|i| {
30         token::get_ident(*i).get().to_string()
31     }).collect::<Vec<String>>().connect("::")
32 }
33
34 pub fn local_def(id: NodeId) -> DefId {
35     ast::DefId { krate: LOCAL_CRATE, node: id }
36 }
37
38 pub fn is_local(did: ast::DefId) -> bool { did.krate == LOCAL_CRATE }
39
40 pub fn stmt_id(s: &Stmt) -> NodeId {
41     match s.node {
42       StmtDecl(_, id) => id,
43       StmtExpr(_, id) => id,
44       StmtSemi(_, id) => id,
45       StmtMac(..) => panic!("attempted to analyze unexpanded stmt")
46     }
47 }
48
49 pub fn binop_to_string(op: BinOp) -> &'static str {
50     match op {
51         BiAdd => "+",
52         BiSub => "-",
53         BiMul => "*",
54         BiDiv => "/",
55         BiRem => "%",
56         BiAnd => "&&",
57         BiOr => "||",
58         BiBitXor => "^",
59         BiBitAnd => "&",
60         BiBitOr => "|",
61         BiShl => "<<",
62         BiShr => ">>",
63         BiEq => "==",
64         BiLt => "<",
65         BiLe => "<=",
66         BiNe => "!=",
67         BiGe => ">=",
68         BiGt => ">"
69     }
70 }
71
72 pub fn lazy_binop(b: BinOp) -> bool {
73     match b {
74       BiAnd => true,
75       BiOr => true,
76       _ => false
77     }
78 }
79
80 pub fn is_shift_binop(b: BinOp) -> bool {
81     match b {
82       BiShl => true,
83       BiShr => true,
84       _ => false
85     }
86 }
87
88 /// Returns `true` if the binary operator takes its arguments by value
89 pub fn is_by_value_binop(b: BinOp) -> bool {
90     match b {
91         BiAdd | BiSub | BiMul | BiDiv | BiRem | BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr => {
92             true
93         }
94         _ => false
95     }
96 }
97
98 /// Returns `true` if the unary operator takes its argument by value
99 pub fn is_by_value_unop(u: UnOp) -> bool {
100     match u {
101         UnNeg | UnNot => true,
102         _ => false,
103     }
104 }
105
106 pub fn unop_to_string(op: UnOp) -> &'static str {
107     match op {
108       UnUniq => "box() ",
109       UnDeref => "*",
110       UnNot => "!",
111       UnNeg => "-",
112     }
113 }
114
115 pub fn is_path(e: P<Expr>) -> bool {
116     return match e.node { ExprPath(_) => true, _ => false };
117 }
118
119 /// Get a string representation of a signed int type, with its value.
120 /// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
121 pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
122     let s = match t {
123         TyI if val.is_some() => "i",
124         TyI => "int",
125         TyI8 => "i8",
126         TyI16 => "i16",
127         TyI32 => "i32",
128         TyI64 => "i64"
129     };
130
131     match val {
132         // cast to a u64 so we can correctly print INT64_MIN. All integral types
133         // are parsed as u64, so we wouldn't want to print an extra negative
134         // sign.
135         Some(n) => format!("{}{}", n as u64, s),
136         None => s.to_string()
137     }
138 }
139
140 pub fn int_ty_max(t: IntTy) -> u64 {
141     match t {
142         TyI8 => 0x80u64,
143         TyI16 => 0x8000u64,
144         TyI | TyI32 => 0x80000000u64, // actually ni about TyI
145         TyI64 => 0x8000000000000000u64
146     }
147 }
148
149 /// Get a string representation of an unsigned int type, with its value.
150 /// We want to avoid "42uint" in favor of "42u"
151 pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
152     let s = match t {
153         TyU if val.is_some() => "u",
154         TyU => "uint",
155         TyU8 => "u8",
156         TyU16 => "u16",
157         TyU32 => "u32",
158         TyU64 => "u64"
159     };
160
161     match val {
162         Some(n) => format!("{}{}", n, s),
163         None => s.to_string()
164     }
165 }
166
167 pub fn uint_ty_max(t: UintTy) -> u64 {
168     match t {
169         TyU8 => 0xffu64,
170         TyU16 => 0xffffu64,
171         TyU | TyU32 => 0xffffffffu64, // actually ni about TyU
172         TyU64 => 0xffffffffffffffffu64
173     }
174 }
175
176 pub fn float_ty_to_string(t: FloatTy) -> String {
177     match t {
178         TyF32 => "f32".to_string(),
179         TyF64 => "f64".to_string(),
180     }
181 }
182
183 // convert a span and an identifier to the corresponding
184 // 1-segment path
185 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
186     ast::Path {
187         span: s,
188         global: false,
189         segments: vec!(
190             ast::PathSegment {
191                 identifier: identifier,
192                 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
193                     lifetimes: Vec::new(),
194                     types: OwnedSlice::empty(),
195                     bindings: OwnedSlice::empty(),
196                 })
197             }
198         ),
199     }
200 }
201
202 // If path is a single segment ident path, return that ident. Otherwise, return
203 // None.
204 pub fn path_to_ident(path: &Path) -> Option<Ident> {
205     if path.segments.len() != 1 {
206         return None;
207     }
208
209     let segment = &path.segments[0];
210     if !segment.parameters.is_empty() {
211         return None;
212     }
213
214     Some(segment.identifier)
215 }
216
217 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
218     P(Pat {
219         id: id,
220         node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
221         span: s
222     })
223 }
224
225 pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
226     Lifetime { id: DUMMY_NODE_ID,
227                span: codemap::DUMMY_SP,
228                name: name }
229 }
230
231 /// Generate a "pretty" name for an `impl` from its type and trait.
232 /// This is designed so that symbols of `impl`'d methods give some
233 /// hint of where they came from, (previously they would all just be
234 /// listed as `__extensions__::method_name::hash`, with no indication
235 /// of the type).
236 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident {
237     let mut pretty = pprust::ty_to_string(ty);
238     match *trait_ref {
239         Some(ref trait_ref) => {
240             pretty.push('.');
241             pretty.push_str(pprust::path_to_string(&trait_ref.path)[]);
242         }
243         None => {}
244     }
245     token::gensym_ident(pretty[])
246 }
247
248 pub fn trait_method_to_ty_method(method: &Method) -> TypeMethod {
249     match method.node {
250         MethDecl(ident,
251                  ref generics,
252                  abi,
253                  ref explicit_self,
254                  unsafety,
255                  ref decl,
256                  _,
257                  vis) => {
258             TypeMethod {
259                 ident: ident,
260                 attrs: method.attrs.clone(),
261                 unsafety: unsafety,
262                 decl: (*decl).clone(),
263                 generics: generics.clone(),
264                 explicit_self: (*explicit_self).clone(),
265                 id: method.id,
266                 span: method.span,
267                 vis: vis,
268                 abi: abi,
269             }
270         },
271         MethMac(_) => panic!("expected non-macro method declaration")
272     }
273 }
274
275 /// extract a TypeMethod from a TraitItem. if the TraitItem is
276 /// a default, pull out the useful fields to make a TypeMethod
277 //
278 // NB: to be used only after expansion is complete, and macros are gone.
279 pub fn trait_item_to_ty_method(method: &TraitItem) -> TypeMethod {
280     match *method {
281         RequiredMethod(ref m) => (*m).clone(),
282         ProvidedMethod(ref m) => trait_method_to_ty_method(&**m),
283         TypeTraitItem(_) => {
284             panic!("trait_method_to_ty_method(): expected method but found \
285                    typedef")
286         }
287     }
288 }
289
290 pub fn split_trait_methods(trait_methods: &[TraitItem])
291                            -> (Vec<TypeMethod>, Vec<P<Method>> ) {
292     let mut reqd = Vec::new();
293     let mut provd = Vec::new();
294     for trt_method in trait_methods.iter() {
295         match *trt_method {
296             RequiredMethod(ref tm) => reqd.push((*tm).clone()),
297             ProvidedMethod(ref m) => provd.push((*m).clone()),
298             TypeTraitItem(_) => {}
299         }
300     };
301     (reqd, provd)
302 }
303
304 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
305     match field.node.kind {
306         ast::NamedField(_, v) | ast::UnnamedField(v) => v
307     }
308 }
309
310 /// Maps a binary operator to its precedence
311 pub fn operator_prec(op: ast::BinOp) -> uint {
312   match op {
313       // 'as' sits here with 12
314       BiMul | BiDiv | BiRem     => 11u,
315       BiAdd | BiSub             => 10u,
316       BiShl | BiShr             =>  9u,
317       BiBitAnd                  =>  8u,
318       BiBitXor                  =>  7u,
319       BiBitOr                   =>  6u,
320       BiLt | BiLe | BiGe | BiGt =>  4u,
321       BiEq | BiNe               =>  3u,
322       BiAnd                     =>  2u,
323       BiOr                      =>  1u
324   }
325 }
326
327 /// Precedence of the `as` operator, which is a binary operator
328 /// not appearing in the prior table.
329 #[allow(non_upper_case_globals)]
330 pub static as_prec: uint = 12u;
331
332 pub fn empty_generics() -> Generics {
333     Generics {
334         lifetimes: Vec::new(),
335         ty_params: OwnedSlice::empty(),
336         where_clause: WhereClause {
337             id: DUMMY_NODE_ID,
338             predicates: Vec::new(),
339         }
340     }
341 }
342
343 // ______________________________________________________________________
344 // Enumerating the IDs which appear in an AST
345
346 #[deriving(RustcEncodable, RustcDecodable, Show, Copy)]
347 pub struct IdRange {
348     pub min: NodeId,
349     pub max: NodeId,
350 }
351
352 impl IdRange {
353     pub fn max() -> IdRange {
354         IdRange {
355             min: u32::MAX,
356             max: u32::MIN,
357         }
358     }
359
360     pub fn empty(&self) -> bool {
361         self.min >= self.max
362     }
363
364     pub fn add(&mut self, id: NodeId) {
365         self.min = cmp::min(self.min, id);
366         self.max = cmp::max(self.max, id + 1);
367     }
368 }
369
370 pub trait IdVisitingOperation {
371     fn visit_id(&mut self, node_id: NodeId);
372 }
373
374 /// A visitor that applies its operation to all of the node IDs
375 /// in a visitable thing.
376
377 pub struct IdVisitor<'a, O:'a> {
378     pub operation: &'a mut O,
379     pub pass_through_items: bool,
380     pub visited_outermost: bool,
381 }
382
383 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
384     fn visit_generics_helper(&mut self, generics: &Generics) {
385         for type_parameter in generics.ty_params.iter() {
386             self.operation.visit_id(type_parameter.id)
387         }
388         for lifetime in generics.lifetimes.iter() {
389             self.operation.visit_id(lifetime.lifetime.id)
390         }
391     }
392 }
393
394 impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
395     fn visit_mod(&mut self,
396                  module: &Mod,
397                  _: Span,
398                  node_id: NodeId) {
399         self.operation.visit_id(node_id);
400         visit::walk_mod(self, module)
401     }
402
403     fn visit_view_item(&mut self, view_item: &ViewItem) {
404         if !self.pass_through_items {
405             if self.visited_outermost {
406                 return;
407             } else {
408                 self.visited_outermost = true;
409             }
410         }
411         match view_item.node {
412             ViewItemExternCrate(_, _, node_id) => {
413                 self.operation.visit_id(node_id)
414             }
415             ViewItemUse(ref view_path) => {
416                 match view_path.node {
417                     ViewPathSimple(_, _, node_id) |
418                     ViewPathGlob(_, node_id) => {
419                         self.operation.visit_id(node_id)
420                     }
421                     ViewPathList(_, ref paths, node_id) => {
422                         self.operation.visit_id(node_id);
423                         for path in paths.iter() {
424                             self.operation.visit_id(path.node.id())
425                         }
426                     }
427                 }
428             }
429         }
430         visit::walk_view_item(self, view_item);
431         self.visited_outermost = false;
432     }
433
434     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
435         self.operation.visit_id(foreign_item.id);
436         visit::walk_foreign_item(self, foreign_item)
437     }
438
439     fn visit_item(&mut self, item: &Item) {
440         if !self.pass_through_items {
441             if self.visited_outermost {
442                 return
443             } else {
444                 self.visited_outermost = true
445             }
446         }
447
448         self.operation.visit_id(item.id);
449         if let ItemEnum(ref enum_definition, _) = item.node {
450             for variant in enum_definition.variants.iter() {
451                 self.operation.visit_id(variant.node.id)
452             }
453         }
454
455         visit::walk_item(self, item);
456
457         self.visited_outermost = false
458     }
459
460     fn visit_local(&mut self, local: &Local) {
461         self.operation.visit_id(local.id);
462         visit::walk_local(self, local)
463     }
464
465     fn visit_block(&mut self, block: &Block) {
466         self.operation.visit_id(block.id);
467         visit::walk_block(self, block)
468     }
469
470     fn visit_stmt(&mut self, statement: &Stmt) {
471         self.operation.visit_id(ast_util::stmt_id(statement));
472         visit::walk_stmt(self, statement)
473     }
474
475     fn visit_pat(&mut self, pattern: &Pat) {
476         self.operation.visit_id(pattern.id);
477         visit::walk_pat(self, pattern)
478     }
479
480     fn visit_expr(&mut self, expression: &Expr) {
481         self.operation.visit_id(expression.id);
482         visit::walk_expr(self, expression)
483     }
484
485     fn visit_ty(&mut self, typ: &Ty) {
486         self.operation.visit_id(typ.id);
487         if let TyPath(_, id) = typ.node {
488             self.operation.visit_id(id);
489         }
490         visit::walk_ty(self, typ)
491     }
492
493     fn visit_generics(&mut self, generics: &Generics) {
494         self.visit_generics_helper(generics);
495         visit::walk_generics(self, generics)
496     }
497
498     fn visit_fn(&mut self,
499                 function_kind: visit::FnKind<'v>,
500                 function_declaration: &'v FnDecl,
501                 block: &'v Block,
502                 span: Span,
503                 node_id: NodeId) {
504         if !self.pass_through_items {
505             match function_kind {
506                 visit::FkMethod(..) if self.visited_outermost => return,
507                 visit::FkMethod(..) => self.visited_outermost = true,
508                 _ => {}
509             }
510         }
511
512         self.operation.visit_id(node_id);
513
514         match function_kind {
515             visit::FkItemFn(_, generics, _, _) |
516             visit::FkMethod(_, generics, _) => {
517                 self.visit_generics_helper(generics)
518             }
519             visit::FkFnBlock => {}
520         }
521
522         for argument in function_declaration.inputs.iter() {
523             self.operation.visit_id(argument.id)
524         }
525
526         visit::walk_fn(self,
527                        function_kind,
528                        function_declaration,
529                        block,
530                        span);
531
532         if !self.pass_through_items {
533             if let visit::FkMethod(..) = function_kind {
534                 self.visited_outermost = false;
535             }
536         }
537     }
538
539     fn visit_struct_field(&mut self, struct_field: &StructField) {
540         self.operation.visit_id(struct_field.node.id);
541         visit::walk_struct_field(self, struct_field)
542     }
543
544     fn visit_struct_def(&mut self,
545                         struct_def: &StructDef,
546                         _: ast::Ident,
547                         _: &ast::Generics,
548                         id: NodeId) {
549         self.operation.visit_id(id);
550         struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
551         visit::walk_struct_def(self, struct_def);
552     }
553
554     fn visit_trait_item(&mut self, tm: &ast::TraitItem) {
555         match *tm {
556             ast::RequiredMethod(ref m) => self.operation.visit_id(m.id),
557             ast::ProvidedMethod(ref m) => self.operation.visit_id(m.id),
558             ast::TypeTraitItem(ref typ) => self.operation.visit_id(typ.ty_param.id),
559         }
560         visit::walk_trait_item(self, tm);
561     }
562
563     fn visit_lifetime_ref(&mut self, lifetime: &'v Lifetime) {
564         self.operation.visit_id(lifetime.id);
565     }
566
567     fn visit_lifetime_def(&mut self, def: &'v LifetimeDef) {
568         self.visit_lifetime_ref(&def.lifetime);
569     }
570 }
571
572 pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
573                                                           operation: &mut O) {
574     let mut id_visitor = IdVisitor {
575         operation: operation,
576         pass_through_items: true,
577         visited_outermost: false,
578     };
579
580     visit::walk_inlined_item(&mut id_visitor, item);
581 }
582
583 struct IdRangeComputingVisitor {
584     result: IdRange,
585 }
586
587 impl IdVisitingOperation for IdRangeComputingVisitor {
588     fn visit_id(&mut self, id: NodeId) {
589         self.result.add(id);
590     }
591 }
592
593 pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
594     let mut visitor = IdRangeComputingVisitor {
595         result: IdRange::max()
596     };
597     visit_ids_for_inlined_item(item, &mut visitor);
598     visitor.result
599 }
600
601 /// Computes the id range for a single fn body, ignoring nested items.
602 pub fn compute_id_range_for_fn_body(fk: visit::FnKind,
603                                     decl: &FnDecl,
604                                     body: &Block,
605                                     sp: Span,
606                                     id: NodeId)
607                                     -> IdRange
608 {
609     let mut visitor = IdRangeComputingVisitor {
610         result: IdRange::max()
611     };
612     let mut id_visitor = IdVisitor {
613         operation: &mut visitor,
614         pass_through_items: false,
615         visited_outermost: false,
616     };
617     id_visitor.visit_fn(fk, decl, body, sp, id);
618     id_visitor.operation.result
619 }
620
621 pub fn walk_pat<F>(pat: &Pat, mut it: F) -> bool where F: FnMut(&Pat) -> bool {
622     // FIXME(#19596) this is a workaround, but there should be a better way
623     fn walk_pat_<G>(pat: &Pat, it: &mut G) -> bool where G: FnMut(&Pat) -> bool {
624         if !(*it)(pat) {
625             return false;
626         }
627
628         match pat.node {
629             PatIdent(_, _, Some(ref p)) => walk_pat_(&**p, it),
630             PatStruct(_, ref fields, _) => {
631                 fields.iter().all(|field| walk_pat_(&*field.node.pat, it))
632             }
633             PatEnum(_, Some(ref s)) | PatTup(ref s) => {
634                 s.iter().all(|p| walk_pat_(&**p, it))
635             }
636             PatBox(ref s) | PatRegion(ref s) => {
637                 walk_pat_(&**s, it)
638             }
639             PatVec(ref before, ref slice, ref after) => {
640                 before.iter().all(|p| walk_pat_(&**p, it)) &&
641                 slice.iter().all(|p| walk_pat_(&**p, it)) &&
642                 after.iter().all(|p| walk_pat_(&**p, it))
643             }
644             PatMac(_) => panic!("attempted to analyze unexpanded pattern"),
645             PatWild(_) | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
646             PatEnum(_, _) => {
647                 true
648             }
649         }
650     }
651
652     walk_pat_(pat, &mut it)
653 }
654
655 pub trait EachViewItem {
656     fn each_view_item<F>(&self, f: F) -> bool where F: FnMut(&ast::ViewItem) -> bool;
657 }
658
659 struct EachViewItemData<F> where F: FnMut(&ast::ViewItem) -> bool {
660     callback: F,
661 }
662
663 impl<'v, F> Visitor<'v> for EachViewItemData<F> where F: FnMut(&ast::ViewItem) -> bool {
664     fn visit_view_item(&mut self, view_item: &ast::ViewItem) {
665         let _ = (self.callback)(view_item);
666     }
667 }
668
669 impl EachViewItem for ast::Crate {
670     fn each_view_item<F>(&self, f: F) -> bool where F: FnMut(&ast::ViewItem) -> bool {
671         let mut visit = EachViewItemData {
672             callback: f,
673         };
674         visit::walk_crate(&mut visit, self);
675         true
676     }
677 }
678
679 pub fn view_path_id(p: &ViewPath) -> NodeId {
680     match p.node {
681         ViewPathSimple(_, _, id) | ViewPathGlob(_, id)
682         | ViewPathList(_, _, id) => id
683     }
684 }
685
686 /// Returns true if the given struct def is tuple-like; i.e. that its fields
687 /// are unnamed.
688 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
689     struct_def.ctor_id.is_some()
690 }
691
692 /// Returns true if the given pattern consists solely of an identifier
693 /// and false otherwise.
694 pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
695     match pat.node {
696         ast::PatIdent(..) => true,
697         _ => false,
698     }
699 }
700
701 // are two paths equal when compared unhygienically?
702 // since I'm using this to replace ==, it seems appropriate
703 // to compare the span, global, etc. fields as well.
704 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
705     (a.span == b.span)
706     && (a.global == b.global)
707     && (segments_name_eq(a.segments[], b.segments[]))
708 }
709
710 // are two arrays of segments equal when compared unhygienically?
711 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
712     if a.len() != b.len() {
713         false
714     } else {
715         for (idx,seg) in a.iter().enumerate() {
716             if seg.identifier.name != b[idx].identifier.name
717                 // FIXME #7743: ident -> name problems in lifetime comparison?
718                 // can types contain idents?
719                 || seg.parameters != b[idx].parameters
720             {
721                 return false;
722             }
723         }
724         true
725     }
726 }
727
728 /// Returns true if this literal is a string and false otherwise.
729 pub fn lit_is_str(lit: &Lit) -> bool {
730     match lit.node {
731         LitStr(..) => true,
732         _ => false,
733     }
734 }
735
736 /// Macro invocations are guaranteed not to occur after expansion is complete.
737 /// Extracting fields of a method requires a dynamic check to make sure that it's
738 /// not a macro invocation. This check is guaranteed to succeed, assuming
739 /// that the invocations are indeed gone.
740 pub trait PostExpansionMethod {
741     fn pe_ident(&self) -> ast::Ident;
742     fn pe_generics<'a>(&'a self) -> &'a ast::Generics;
743     fn pe_abi(&self) -> Abi;
744     fn pe_explicit_self<'a>(&'a self) -> &'a ast::ExplicitSelf;
745     fn pe_unsafety(&self) -> ast::Unsafety;
746     fn pe_fn_decl<'a>(&'a self) -> &'a ast::FnDecl;
747     fn pe_body<'a>(&'a self) -> &'a ast::Block;
748     fn pe_vis(&self) -> ast::Visibility;
749 }
750
751 macro_rules! mf_method{
752     ($meth_name:ident, $field_ty:ty, $field_pat:pat, $result:expr) => {
753         fn $meth_name<'a>(&'a self) -> $field_ty {
754             match self.node {
755                 $field_pat => $result,
756                 MethMac(_) => {
757                     panic!("expected an AST without macro invocations");
758                 }
759             }
760         }
761     }
762 }
763
764
765 impl PostExpansionMethod for Method {
766     mf_method! { pe_ident,ast::Ident,MethDecl(ident,_,_,_,_,_,_,_),ident }
767     mf_method! {
768         pe_generics,&'a ast::Generics,
769         MethDecl(_,ref generics,_,_,_,_,_,_),generics
770     }
771     mf_method! { pe_abi,Abi,MethDecl(_,_,abi,_,_,_,_,_),abi }
772     mf_method! {
773         pe_explicit_self,&'a ast::ExplicitSelf,
774         MethDecl(_,_,_,ref explicit_self,_,_,_,_),explicit_self
775     }
776     mf_method! { pe_unsafety,ast::Unsafety,MethDecl(_,_,_,_,unsafety,_,_,_),unsafety }
777     mf_method! { pe_fn_decl,&'a ast::FnDecl,MethDecl(_,_,_,_,_,ref decl,_,_),&**decl }
778     mf_method! { pe_body,&'a ast::Block,MethDecl(_,_,_,_,_,_,ref body,_),&**body }
779     mf_method! { pe_vis,ast::Visibility,MethDecl(_,_,_,_,_,_,_,vis),vis }
780 }
781
782 #[cfg(test)]
783 mod test {
784     use ast::*;
785     use super::*;
786
787     fn ident_to_segment(id : &Ident) -> PathSegment {
788         PathSegment {identifier: id.clone(),
789                      parameters: PathParameters::none()}
790     }
791
792     #[test] fn idents_name_eq_test() {
793         assert!(segments_name_eq(
794             [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
795                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[],
796             [Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}]
797                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[]));
798         assert!(!segments_name_eq(
799             [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
800                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[],
801             [Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}]
802                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[]));
803     }
804 }