]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast_util.rs
libstd: Implement `StrBuf`, a new string buffer type like `Vec`, and
[rust.git] / src / libsyntax / ast_util.rs
1 // Copyright 2012-2013 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]) -> ~str {
28     // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
29     idents.iter().map(|i| {
30         token::get_ident(*i).get().to_str()
31     }).collect::<Vec<~str>>().connect("::")
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 => "~",
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 fn int_ty_to_str(t: IntTy) -> ~str {
136     match t {
137         TyI => ~"",
138         TyI8 => ~"i8",
139         TyI16 => ~"i16",
140         TyI32 => ~"i32",
141         TyI64 => ~"i64"
142     }
143 }
144
145 pub fn int_ty_max(t: IntTy) -> u64 {
146     match t {
147         TyI8 => 0x80u64,
148         TyI16 => 0x8000u64,
149         TyI | TyI32 => 0x80000000u64, // actually ni about TyI
150         TyI64 => 0x8000000000000000u64
151     }
152 }
153
154 pub fn uint_ty_to_str(t: UintTy) -> ~str {
155     match t {
156         TyU => ~"u",
157         TyU8 => ~"u8",
158         TyU16 => ~"u16",
159         TyU32 => ~"u32",
160         TyU64 => ~"u64"
161     }
162 }
163
164 pub fn uint_ty_max(t: UintTy) -> u64 {
165     match t {
166         TyU8 => 0xffu64,
167         TyU16 => 0xffffu64,
168         TyU | TyU32 => 0xffffffffu64, // actually ni about TyU
169         TyU64 => 0xffffffffffffffffu64
170     }
171 }
172
173 pub fn float_ty_to_str(t: FloatTy) -> ~str {
174     match t { TyF32 => ~"f32", TyF64 => ~"f64" }
175 }
176
177 pub fn is_call_expr(e: @Expr) -> bool {
178     match e.node { ExprCall(..) => true, _ => false }
179 }
180
181 pub fn block_from_expr(e: @Expr) -> P<Block> {
182     P(Block {
183         view_items: Vec::new(),
184         stmts: Vec::new(),
185         expr: Some(e),
186         id: e.id,
187         rules: DefaultBlock,
188         span: e.span
189     })
190 }
191
192 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
193     ast::Path {
194         span: s,
195         global: false,
196         segments: vec!(
197             ast::PathSegment {
198                 identifier: identifier,
199                 lifetimes: Vec::new(),
200                 types: OwnedSlice::empty(),
201             }
202         ),
203     }
204 }
205
206 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> @Pat {
207     @ast::Pat { id: id,
208                 node: PatIdent(BindByValue(MutImmutable), ident_to_path(s, i), None),
209                 span: s }
210 }
211
212 pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
213     Lifetime { id: DUMMY_NODE_ID,
214                span: codemap::DUMMY_SP,
215                name: name }
216 }
217
218 pub fn is_unguarded(a: &Arm) -> bool {
219     match a.guard {
220       None => true,
221       _    => false
222     }
223 }
224
225 pub fn unguarded_pat(a: &Arm) -> Option<Vec<@Pat> > {
226     if is_unguarded(a) {
227         Some(/* FIXME (#2543) */ a.pats.clone())
228     } else {
229         None
230     }
231 }
232
233 /// Generate a "pretty" name for an `impl` from its type and trait.
234 /// This is designed so that symbols of `impl`'d methods give some
235 /// hint of where they came from, (previously they would all just be
236 /// listed as `__extensions__::method_name::hash`, with no indication
237 /// of the type).
238 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident {
239     let mut pretty = StrBuf::from_owned_str(pprust::ty_to_str(ty));
240     match *trait_ref {
241         Some(ref trait_ref) => {
242             pretty.push_char('.');
243             pretty.push_str(pprust::path_to_str(&trait_ref.path));
244         }
245         None => {}
246     }
247     token::gensym_ident(pretty.as_slice())
248 }
249
250 pub fn public_methods(ms: Vec<@Method> ) -> Vec<@Method> {
251     ms.move_iter().filter(|m| {
252         match m.vis {
253             Public => true,
254             _   => false
255         }
256     }).collect()
257 }
258
259 // extract a TypeMethod from a TraitMethod. if the TraitMethod is
260 // a default, pull out the useful fields to make a TypeMethod
261 pub fn trait_method_to_ty_method(method: &TraitMethod) -> TypeMethod {
262     match *method {
263         Required(ref m) => (*m).clone(),
264         Provided(ref m) => {
265             TypeMethod {
266                 ident: m.ident,
267                 attrs: m.attrs.clone(),
268                 purity: m.purity,
269                 decl: m.decl,
270                 generics: m.generics.clone(),
271                 explicit_self: m.explicit_self,
272                 id: m.id,
273                 span: m.span,
274             }
275         }
276     }
277 }
278
279 pub fn split_trait_methods(trait_methods: &[TraitMethod])
280     -> (Vec<TypeMethod> , Vec<@Method> ) {
281     let mut reqd = Vec::new();
282     let mut provd = Vec::new();
283     for trt_method in trait_methods.iter() {
284         match *trt_method {
285             Required(ref tm) => reqd.push((*tm).clone()),
286             Provided(m) => provd.push(m)
287         }
288     };
289     (reqd, provd)
290 }
291
292 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
293     match field.node.kind {
294         ast::NamedField(_, v) | ast::UnnamedField(v) => v
295     }
296 }
297
298 /// Maps a binary operator to its precedence
299 pub fn operator_prec(op: ast::BinOp) -> uint {
300   match op {
301       // 'as' sits here with 12
302       BiMul | BiDiv | BiRem     => 11u,
303       BiAdd | BiSub             => 10u,
304       BiShl | BiShr             =>  9u,
305       BiBitAnd                  =>  8u,
306       BiBitXor                  =>  7u,
307       BiBitOr                   =>  6u,
308       BiLt | BiLe | BiGe | BiGt =>  4u,
309       BiEq | BiNe               =>  3u,
310       BiAnd                     =>  2u,
311       BiOr                      =>  1u
312   }
313 }
314
315 /// Precedence of the `as` operator, which is a binary operator
316 /// not appearing in the prior table.
317 pub static as_prec: uint = 12u;
318
319 pub fn empty_generics() -> Generics {
320     Generics {lifetimes: Vec::new(),
321               ty_params: OwnedSlice::empty()}
322 }
323
324 // ______________________________________________________________________
325 // Enumerating the IDs which appear in an AST
326
327 #[deriving(Encodable, Decodable)]
328 pub struct IdRange {
329     pub min: NodeId,
330     pub max: NodeId,
331 }
332
333 impl IdRange {
334     pub fn max() -> IdRange {
335         IdRange {
336             min: u32::MAX,
337             max: u32::MIN,
338         }
339     }
340
341     pub fn empty(&self) -> bool {
342         self.min >= self.max
343     }
344
345     pub fn add(&mut self, id: NodeId) {
346         self.min = cmp::min(self.min, id);
347         self.max = cmp::max(self.max, id + 1);
348     }
349 }
350
351 pub trait IdVisitingOperation {
352     fn visit_id(&self, node_id: NodeId);
353 }
354
355 pub struct IdVisitor<'a, O> {
356     pub operation: &'a O,
357     pub pass_through_items: bool,
358     pub visited_outermost: bool,
359 }
360
361 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
362     fn visit_generics_helper(&self, generics: &Generics) {
363         for type_parameter in generics.ty_params.iter() {
364             self.operation.visit_id(type_parameter.id)
365         }
366         for lifetime in generics.lifetimes.iter() {
367             self.operation.visit_id(lifetime.id)
368         }
369     }
370 }
371
372 impl<'a, O: IdVisitingOperation> Visitor<()> for IdVisitor<'a, O> {
373     fn visit_mod(&mut self,
374                  module: &Mod,
375                  _: Span,
376                  node_id: NodeId,
377                  env: ()) {
378         self.operation.visit_id(node_id);
379         visit::walk_mod(self, module, env)
380     }
381
382     fn visit_view_item(&mut self, view_item: &ViewItem, env: ()) {
383         match view_item.node {
384             ViewItemExternCrate(_, _, node_id) => {
385                 self.operation.visit_id(node_id)
386             }
387             ViewItemUse(ref view_paths) => {
388                 for view_path in view_paths.iter() {
389                     match view_path.node {
390                         ViewPathSimple(_, _, node_id) |
391                         ViewPathGlob(_, node_id) => {
392                             self.operation.visit_id(node_id)
393                         }
394                         ViewPathList(_, ref paths, node_id) => {
395                             self.operation.visit_id(node_id);
396                             for path in paths.iter() {
397                                 self.operation.visit_id(path.node.id)
398                             }
399                         }
400                     }
401                 }
402             }
403         }
404         visit::walk_view_item(self, view_item, env)
405     }
406
407     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem, env: ()) {
408         self.operation.visit_id(foreign_item.id);
409         visit::walk_foreign_item(self, foreign_item, env)
410     }
411
412     fn visit_item(&mut self, item: &Item, env: ()) {
413         if !self.pass_through_items {
414             if self.visited_outermost {
415                 return
416             } else {
417                 self.visited_outermost = true
418             }
419         }
420
421         self.operation.visit_id(item.id);
422         match item.node {
423             ItemEnum(ref enum_definition, _) => {
424                 for variant in enum_definition.variants.iter() {
425                     self.operation.visit_id(variant.node.id)
426                 }
427             }
428             _ => {}
429         }
430
431         visit::walk_item(self, item, env);
432
433         self.visited_outermost = false
434     }
435
436     fn visit_local(&mut self, local: &Local, env: ()) {
437         self.operation.visit_id(local.id);
438         visit::walk_local(self, local, env)
439     }
440
441     fn visit_block(&mut self, block: &Block, env: ()) {
442         self.operation.visit_id(block.id);
443         visit::walk_block(self, block, env)
444     }
445
446     fn visit_stmt(&mut self, statement: &Stmt, env: ()) {
447         self.operation.visit_id(ast_util::stmt_id(statement));
448         visit::walk_stmt(self, statement, env)
449     }
450
451     fn visit_pat(&mut self, pattern: &Pat, env: ()) {
452         self.operation.visit_id(pattern.id);
453         visit::walk_pat(self, pattern, env)
454     }
455
456
457     fn visit_expr(&mut self, expression: &Expr, env: ()) {
458         self.operation.visit_id(expression.id);
459         visit::walk_expr(self, expression, env)
460     }
461
462     fn visit_ty(&mut self, typ: &Ty, env: ()) {
463         self.operation.visit_id(typ.id);
464         match typ.node {
465             TyPath(_, _, id) => self.operation.visit_id(id),
466             _ => {}
467         }
468         visit::walk_ty(self, typ, env)
469     }
470
471     fn visit_generics(&mut self, generics: &Generics, env: ()) {
472         self.visit_generics_helper(generics);
473         visit::walk_generics(self, generics, env)
474     }
475
476     fn visit_fn(&mut self,
477                 function_kind: &visit::FnKind,
478                 function_declaration: &FnDecl,
479                 block: &Block,
480                 span: Span,
481                 node_id: NodeId,
482                 env: ()) {
483         if !self.pass_through_items {
484             match *function_kind {
485                 visit::FkMethod(..) if self.visited_outermost => return,
486                 visit::FkMethod(..) => self.visited_outermost = true,
487                 _ => {}
488             }
489         }
490
491         self.operation.visit_id(node_id);
492
493         match *function_kind {
494             visit::FkItemFn(_, generics, _, _) |
495             visit::FkMethod(_, generics, _) => {
496                 self.visit_generics_helper(generics)
497             }
498             visit::FkFnBlock => {}
499         }
500
501         for argument in function_declaration.inputs.iter() {
502             self.operation.visit_id(argument.id)
503         }
504
505         visit::walk_fn(self,
506                         function_kind,
507                         function_declaration,
508                         block,
509                         span,
510                         node_id,
511                         env);
512
513         if !self.pass_through_items {
514             match *function_kind {
515                 visit::FkMethod(..) => self.visited_outermost = false,
516                 _ => {}
517             }
518         }
519     }
520
521     fn visit_struct_field(&mut self, struct_field: &StructField, env: ()) {
522         self.operation.visit_id(struct_field.node.id);
523         visit::walk_struct_field(self, struct_field, env)
524     }
525
526     fn visit_struct_def(&mut self,
527                         struct_def: &StructDef,
528                         ident: ast::Ident,
529                         generics: &ast::Generics,
530                         id: NodeId,
531                         _: ()) {
532         self.operation.visit_id(id);
533         struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
534         visit::walk_struct_def(self, struct_def, ident, generics, id, ());
535     }
536
537     fn visit_trait_method(&mut self, tm: &ast::TraitMethod, _: ()) {
538         match *tm {
539             ast::Required(ref m) => self.operation.visit_id(m.id),
540             ast::Provided(ref m) => self.operation.visit_id(m.id),
541         }
542         visit::walk_trait_method(self, tm, ());
543     }
544 }
545
546 pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
547                                                           operation: &O) {
548     let mut id_visitor = IdVisitor {
549         operation: operation,
550         pass_through_items: true,
551         visited_outermost: false,
552     };
553
554     visit::walk_inlined_item(&mut id_visitor, item, ());
555 }
556
557 struct IdRangeComputingVisitor {
558     result: Cell<IdRange>,
559 }
560
561 impl IdVisitingOperation for IdRangeComputingVisitor {
562     fn visit_id(&self, id: NodeId) {
563         let mut id_range = self.result.get();
564         id_range.add(id);
565         self.result.set(id_range)
566     }
567 }
568
569 pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
570     let visitor = IdRangeComputingVisitor {
571         result: Cell::new(IdRange::max())
572     };
573     visit_ids_for_inlined_item(item, &visitor);
574     visitor.result.get()
575 }
576
577 pub fn is_item_impl(item: @ast::Item) -> bool {
578     match item.node {
579         ItemImpl(..) => true,
580         _            => false
581     }
582 }
583
584 pub fn walk_pat(pat: &Pat, it: |&Pat| -> bool) -> bool {
585     if !it(pat) {
586         return false;
587     }
588
589     match pat.node {
590         PatIdent(_, _, Some(p)) => walk_pat(p, it),
591         PatStruct(_, ref fields, _) => {
592             fields.iter().advance(|f| walk_pat(f.pat, |p| it(p)))
593         }
594         PatEnum(_, Some(ref s)) | PatTup(ref s) => {
595             s.iter().advance(|&p| walk_pat(p, |p| it(p)))
596         }
597         PatUniq(s) | PatRegion(s) => {
598             walk_pat(s, it)
599         }
600         PatVec(ref before, ref slice, ref after) => {
601             before.iter().advance(|&p| walk_pat(p, |p| it(p))) &&
602                 slice.iter().advance(|&p| walk_pat(p, |p| it(p))) &&
603                 after.iter().advance(|&p| walk_pat(p, |p| it(p)))
604         }
605         PatWild | PatWildMulti | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
606         PatEnum(_, _) => {
607             true
608         }
609     }
610 }
611
612 pub trait EachViewItem {
613     fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool;
614 }
615
616 struct EachViewItemData<'a> {
617     callback: |&ast::ViewItem|: 'a -> bool,
618 }
619
620 impl<'a> Visitor<()> for EachViewItemData<'a> {
621     fn visit_view_item(&mut self, view_item: &ast::ViewItem, _: ()) {
622         let _ = (self.callback)(view_item);
623     }
624 }
625
626 impl EachViewItem for ast::Crate {
627     fn each_view_item(&self, f: |&ast::ViewItem| -> bool) -> bool {
628         let mut visit = EachViewItemData {
629             callback: f,
630         };
631         visit::walk_crate(&mut visit, self, ());
632         true
633     }
634 }
635
636 pub fn view_path_id(p: &ViewPath) -> NodeId {
637     match p.node {
638         ViewPathSimple(_, _, id) | ViewPathGlob(_, id)
639         | ViewPathList(_, _, id) => id
640     }
641 }
642
643 /// Returns true if the given struct def is tuple-like; i.e. that its fields
644 /// are unnamed.
645 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
646     struct_def.ctor_id.is_some()
647 }
648
649 /// Returns true if the given pattern consists solely of an identifier
650 /// and false otherwise.
651 pub fn pat_is_ident(pat: @ast::Pat) -> bool {
652     match pat.node {
653         ast::PatIdent(..) => true,
654         _ => false,
655     }
656 }
657
658 // are two paths equal when compared unhygienically?
659 // since I'm using this to replace ==, it seems appropriate
660 // to compare the span, global, etc. fields as well.
661 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
662     (a.span == b.span)
663     && (a.global == b.global)
664     && (segments_name_eq(a.segments.as_slice(), b.segments.as_slice()))
665 }
666
667 // are two arrays of segments equal when compared unhygienically?
668 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
669     if a.len() != b.len() {
670         false
671     } else {
672         for (idx,seg) in a.iter().enumerate() {
673             if (seg.identifier.name != b[idx].identifier.name)
674                 // FIXME #7743: ident -> name problems in lifetime comparison?
675                 || (seg.lifetimes != b[idx].lifetimes)
676                 // can types contain idents?
677                 || (seg.types != b[idx].types) {
678                 return false;
679             }
680         }
681         true
682     }
683 }
684
685 // Returns true if this literal is a string and false otherwise.
686 pub fn lit_is_str(lit: @Lit) -> bool {
687     match lit.node {
688         LitStr(..) => true,
689         _ => false,
690     }
691 }
692
693 pub fn get_inner_tys(ty: P<Ty>) -> Vec<P<Ty>> {
694     match ty.node {
695         ast::TyRptr(_, mut_ty) | ast::TyPtr(mut_ty) => {
696             vec!(mut_ty.ty)
697         }
698         ast::TyBox(ty)
699         | ast::TyVec(ty)
700         | ast::TyUniq(ty)
701         | ast::TyFixedLengthVec(ty, _) => vec!(ty),
702         ast::TyTup(ref tys) => tys.clone(),
703         _ => Vec::new()
704     }
705 }
706
707
708 #[cfg(test)]
709 mod test {
710     use ast::*;
711     use super::*;
712     use owned_slice::OwnedSlice;
713
714     fn ident_to_segment(id : &Ident) -> PathSegment {
715         PathSegment {identifier:id.clone(),
716                      lifetimes: Vec::new(),
717                      types: OwnedSlice::empty()}
718     }
719
720     #[test] fn idents_name_eq_test() {
721         assert!(segments_name_eq(
722             [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}]
723                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(),
724             [Ident{name:3,ctxt:104}, Ident{name:78,ctxt:182}]
725                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice()));
726         assert!(!segments_name_eq(
727             [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}]
728                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(),
729             [Ident{name:3,ctxt:104}, Ident{name:77,ctxt:182}]
730                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice()));
731     }
732 }