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