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