]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast_util.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[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).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 pub fn is_comparison_binop(b: BinOp_) -> bool {
89     match b {
90         BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
91         _ => false
92     }
93 }
94
95 /// Returns `true` if the binary operator takes its arguments by value
96 pub fn is_by_value_binop(b: BinOp_) -> bool {
97     match b {
98         BiAdd | BiSub | BiMul | BiDiv | BiRem | BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr => {
99             true
100         }
101         _ => false
102     }
103 }
104
105 /// Returns `true` if the binary operator is symmetric in the sense that LHS
106 /// and RHS must have the same type. So the type of LHS can serve as an hint
107 /// for the type of RHS and vice versa.
108 pub fn is_symmetric_binop(b: BinOp_) -> bool {
109     match b {
110         BiAdd | BiSub | BiMul | BiDiv | BiRem |
111         BiBitXor | BiBitAnd | BiBitOr |
112         BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => {
113             true
114         }
115         _ => false
116     }
117 }
118
119 /// Returns `true` if the unary operator takes its argument by value
120 pub fn is_by_value_unop(u: UnOp) -> bool {
121     match u {
122         UnNeg | UnNot => true,
123         _ => false,
124     }
125 }
126
127 pub fn unop_to_string(op: UnOp) -> &'static str {
128     match op {
129       UnUniq => "box() ",
130       UnDeref => "*",
131       UnNot => "!",
132       UnNeg => "-",
133     }
134 }
135
136 pub fn is_path(e: P<Expr>) -> bool {
137     return match e.node { ExprPath(_) => true, _ => false };
138 }
139
140 /// Get a string representation of a signed int type, with its value.
141 /// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
142 pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
143     let s = match t {
144         TyIs(_) => "isize",
145         TyI8 => "i8",
146         TyI16 => "i16",
147         TyI32 => "i32",
148         TyI64 => "i64"
149     };
150
151     match val {
152         // cast to a u64 so we can correctly print INT64_MIN. All integral types
153         // are parsed as u64, so we wouldn't want to print an extra negative
154         // sign.
155         Some(n) => format!("{}{}", n as u64, s),
156         None => s.to_string()
157     }
158 }
159
160 pub fn int_ty_max(t: IntTy) -> u64 {
161     match t {
162         TyI8 => 0x80u64,
163         TyI16 => 0x8000u64,
164         TyIs(_) | TyI32 => 0x80000000u64, // actually ni about TyIs
165         TyI64 => 0x8000000000000000u64
166     }
167 }
168
169 /// Get a string representation of an unsigned int type, with its value.
170 /// We want to avoid "42u" in favor of "42us". "42uint" is right out.
171 pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
172     let s = match t {
173         TyUs(_) => "usize",
174         TyU8 => "u8",
175         TyU16 => "u16",
176         TyU32 => "u32",
177         TyU64 => "u64"
178     };
179
180     match val {
181         Some(n) => format!("{}{}", n, s),
182         None => s.to_string()
183     }
184 }
185
186 pub fn uint_ty_max(t: UintTy) -> u64 {
187     match t {
188         TyU8 => 0xffu64,
189         TyU16 => 0xffffu64,
190         TyUs(_) | TyU32 => 0xffffffffu64, // actually ni about TyUs
191         TyU64 => 0xffffffffffffffffu64
192     }
193 }
194
195 pub fn float_ty_to_string(t: FloatTy) -> String {
196     match t {
197         TyF32 => "f32".to_string(),
198         TyF64 => "f64".to_string(),
199     }
200 }
201
202 // convert a span and an identifier to the corresponding
203 // 1-segment path
204 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
205     ast::Path {
206         span: s,
207         global: false,
208         segments: vec!(
209             ast::PathSegment {
210                 identifier: identifier,
211                 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
212                     lifetimes: Vec::new(),
213                     types: OwnedSlice::empty(),
214                     bindings: OwnedSlice::empty(),
215                 })
216             }
217         ),
218     }
219 }
220
221 // If path is a single segment ident path, return that ident. Otherwise, return
222 // None.
223 pub fn path_to_ident(path: &Path) -> Option<Ident> {
224     if path.segments.len() != 1 {
225         return None;
226     }
227
228     let segment = &path.segments[0];
229     if !segment.parameters.is_empty() {
230         return None;
231     }
232
233     Some(segment.identifier)
234 }
235
236 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
237     P(Pat {
238         id: id,
239         node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
240         span: s
241     })
242 }
243
244 pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
245     Lifetime { id: DUMMY_NODE_ID,
246                span: codemap::DUMMY_SP,
247                name: name }
248 }
249
250 /// Generate a "pretty" name for an `impl` from its type and trait.
251 /// This is designed so that symbols of `impl`'d methods give some
252 /// hint of where they came from, (previously they would all just be
253 /// listed as `__extensions__::method_name::hash`, with no indication
254 /// of the type).
255 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident {
256     let mut pretty = pprust::ty_to_string(ty);
257     match *trait_ref {
258         Some(ref trait_ref) => {
259             pretty.push('.');
260             pretty.push_str(&pprust::path_to_string(&trait_ref.path));
261         }
262         None => {}
263     }
264     token::gensym_ident(&pretty[..])
265 }
266
267 pub fn trait_method_to_ty_method(method: &Method) -> TypeMethod {
268     match method.node {
269         MethDecl(ident,
270                  ref generics,
271                  abi,
272                  ref explicit_self,
273                  unsafety,
274                  ref decl,
275                  _,
276                  vis) => {
277             TypeMethod {
278                 ident: ident,
279                 attrs: method.attrs.clone(),
280                 unsafety: unsafety,
281                 decl: (*decl).clone(),
282                 generics: generics.clone(),
283                 explicit_self: (*explicit_self).clone(),
284                 id: method.id,
285                 span: method.span,
286                 vis: vis,
287                 abi: abi,
288             }
289         },
290         MethMac(_) => panic!("expected non-macro method declaration")
291     }
292 }
293
294 /// extract a TypeMethod from a TraitItem. if the TraitItem is
295 /// a default, pull out the useful fields to make a TypeMethod
296 //
297 // NB: to be used only after expansion is complete, and macros are gone.
298 pub fn trait_item_to_ty_method(method: &TraitItem) -> TypeMethod {
299     match *method {
300         RequiredMethod(ref m) => (*m).clone(),
301         ProvidedMethod(ref m) => trait_method_to_ty_method(&**m),
302         TypeTraitItem(_) => {
303             panic!("trait_method_to_ty_method(): expected method but found \
304                    typedef")
305         }
306     }
307 }
308
309 pub fn split_trait_methods(trait_methods: &[TraitItem])
310                            -> (Vec<TypeMethod>, Vec<P<Method>> ) {
311     let mut reqd = Vec::new();
312     let mut provd = Vec::new();
313     for trt_method in trait_methods {
314         match *trt_method {
315             RequiredMethod(ref tm) => reqd.push((*tm).clone()),
316             ProvidedMethod(ref m) => provd.push((*m).clone()),
317             TypeTraitItem(_) => {}
318         }
319     };
320     (reqd, provd)
321 }
322
323 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
324     match field.node.kind {
325         ast::NamedField(_, v) | ast::UnnamedField(v) => v
326     }
327 }
328
329 /// Maps a binary operator to its precedence
330 pub fn operator_prec(op: ast::BinOp_) -> usize {
331   match op {
332       // 'as' sits here with 12
333       BiMul | BiDiv | BiRem     => 11,
334       BiAdd | BiSub             => 10,
335       BiShl | BiShr             =>  9,
336       BiBitAnd                  =>  8,
337       BiBitXor                  =>  7,
338       BiBitOr                   =>  6,
339       BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3,
340       BiAnd                     =>  2,
341       BiOr                      =>  1
342   }
343 }
344
345 /// Precedence of the `as` operator, which is a binary operator
346 /// not appearing in the prior table.
347 pub const AS_PREC: usize = 12;
348
349 pub fn empty_generics() -> Generics {
350     Generics {
351         lifetimes: Vec::new(),
352         ty_params: OwnedSlice::empty(),
353         where_clause: WhereClause {
354             id: DUMMY_NODE_ID,
355             predicates: Vec::new(),
356         }
357     }
358 }
359
360 // ______________________________________________________________________
361 // Enumerating the IDs which appear in an AST
362
363 #[derive(RustcEncodable, RustcDecodable, Debug, Copy)]
364 pub struct IdRange {
365     pub min: NodeId,
366     pub max: NodeId,
367 }
368
369 impl IdRange {
370     pub fn max() -> IdRange {
371         IdRange {
372             min: u32::MAX,
373             max: u32::MIN,
374         }
375     }
376
377     pub fn empty(&self) -> bool {
378         self.min >= self.max
379     }
380
381     pub fn add(&mut self, id: NodeId) {
382         self.min = cmp::min(self.min, id);
383         self.max = cmp::max(self.max, id + 1);
384     }
385 }
386
387 pub trait IdVisitingOperation {
388     fn visit_id(&mut self, node_id: NodeId);
389 }
390
391 /// A visitor that applies its operation to all of the node IDs
392 /// in a visitable thing.
393
394 pub struct IdVisitor<'a, O:'a> {
395     pub operation: &'a mut O,
396     pub pass_through_items: bool,
397     pub visited_outermost: bool,
398 }
399
400 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
401     fn visit_generics_helper(&mut self, generics: &Generics) {
402         for type_parameter in &*generics.ty_params {
403             self.operation.visit_id(type_parameter.id)
404         }
405         for lifetime in &generics.lifetimes {
406             self.operation.visit_id(lifetime.lifetime.id)
407         }
408     }
409 }
410
411 impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
412     fn visit_mod(&mut self,
413                  module: &Mod,
414                  _: Span,
415                  node_id: NodeId) {
416         self.operation.visit_id(node_id);
417         visit::walk_mod(self, module)
418     }
419
420     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
421         self.operation.visit_id(foreign_item.id);
422         visit::walk_foreign_item(self, foreign_item)
423     }
424
425     fn visit_item(&mut self, item: &Item) {
426         if !self.pass_through_items {
427             if self.visited_outermost {
428                 return
429             } else {
430                 self.visited_outermost = true
431             }
432         }
433
434         self.operation.visit_id(item.id);
435         match item.node {
436             ItemUse(ref view_path) => {
437                 match view_path.node {
438                     ViewPathSimple(_, _) |
439                     ViewPathGlob(_) => {}
440                     ViewPathList(_, ref paths) => {
441                         for path in paths {
442                             self.operation.visit_id(path.node.id())
443                         }
444                     }
445                 }
446             }
447             ItemEnum(ref enum_definition, _) => {
448                 for variant in &enum_definition.variants {
449                     self.operation.visit_id(variant.node.id)
450                 }
451             }
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 {
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 /// Returns true if the given struct def is tuple-like; i.e. that its fields
656 /// are unnamed.
657 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
658     struct_def.ctor_id.is_some()
659 }
660
661 /// Returns true if the given pattern consists solely of an identifier
662 /// and false otherwise.
663 pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
664     match pat.node {
665         ast::PatIdent(..) => true,
666         _ => false,
667     }
668 }
669
670 // are two paths equal when compared unhygienically?
671 // since I'm using this to replace ==, it seems appropriate
672 // to compare the span, global, etc. fields as well.
673 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
674     (a.span == b.span)
675     && (a.global == b.global)
676     && (segments_name_eq(&a.segments[..], &b.segments[..]))
677 }
678
679 // are two arrays of segments equal when compared unhygienically?
680 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
681     a.len() == b.len() &&
682     a.iter().zip(b.iter()).all(|(s, t)| {
683         s.identifier.name == t.identifier.name &&
684         // FIXME #7743: ident -> name problems in lifetime comparison?
685         // can types contain idents?
686         s.parameters == t.parameters
687     })
688 }
689
690 /// Returns true if this literal is a string and false otherwise.
691 pub fn lit_is_str(lit: &Lit) -> bool {
692     match lit.node {
693         LitStr(..) => true,
694         _ => false,
695     }
696 }
697
698 /// Macro invocations are guaranteed not to occur after expansion is complete.
699 /// Extracting fields of a method requires a dynamic check to make sure that it's
700 /// not a macro invocation. This check is guaranteed to succeed, assuming
701 /// that the invocations are indeed gone.
702 pub trait PostExpansionMethod {
703     fn pe_ident(&self) -> ast::Ident;
704     fn pe_generics<'a>(&'a self) -> &'a ast::Generics;
705     fn pe_abi(&self) -> Abi;
706     fn pe_explicit_self<'a>(&'a self) -> &'a ast::ExplicitSelf;
707     fn pe_unsafety(&self) -> ast::Unsafety;
708     fn pe_fn_decl<'a>(&'a self) -> &'a ast::FnDecl;
709     fn pe_body<'a>(&'a self) -> &'a ast::Block;
710     fn pe_vis(&self) -> ast::Visibility;
711 }
712
713 macro_rules! mf_method{
714     ($meth_name:ident, $field_ty:ty, $field_pat:pat, $result:expr) => {
715         fn $meth_name<'a>(&'a self) -> $field_ty {
716             match self.node {
717                 $field_pat => $result,
718                 MethMac(_) => {
719                     panic!("expected an AST without macro invocations");
720                 }
721             }
722         }
723     }
724 }
725
726
727 impl PostExpansionMethod for Method {
728     mf_method! { pe_ident,ast::Ident,MethDecl(ident,_,_,_,_,_,_,_),ident }
729     mf_method! {
730         pe_generics,&'a ast::Generics,
731         MethDecl(_,ref generics,_,_,_,_,_,_),generics
732     }
733     mf_method! { pe_abi,Abi,MethDecl(_,_,abi,_,_,_,_,_),abi }
734     mf_method! {
735         pe_explicit_self,&'a ast::ExplicitSelf,
736         MethDecl(_,_,_,ref explicit_self,_,_,_,_),explicit_self
737     }
738     mf_method! { pe_unsafety,ast::Unsafety,MethDecl(_,_,_,_,unsafety,_,_,_),unsafety }
739     mf_method! { pe_fn_decl,&'a ast::FnDecl,MethDecl(_,_,_,_,_,ref decl,_,_),&**decl }
740     mf_method! { pe_body,&'a ast::Block,MethDecl(_,_,_,_,_,_,ref body,_),&**body }
741     mf_method! { pe_vis,ast::Visibility,MethDecl(_,_,_,_,_,_,_,vis),vis }
742 }
743
744 #[cfg(test)]
745 mod test {
746     use ast::*;
747     use super::*;
748
749     fn ident_to_segment(id : &Ident) -> PathSegment {
750         PathSegment {identifier: id.clone(),
751                      parameters: PathParameters::none()}
752     }
753
754     #[test] fn idents_name_eq_test() {
755         assert!(segments_name_eq(
756             &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
757                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[],
758             &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}]
759                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[]));
760         assert!(!segments_name_eq(
761             &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
762                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[],
763             &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}]
764                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[]));
765     }
766 }