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