]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast_util.rs
Auto merge of #28148 - eefriedman:binary_heap, r=alexcrichton
[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 ptr::P;
20 use visit::{FnKind, Visitor};
21 use visit;
22
23 use std::cmp;
24 use std::u32;
25
26 pub fn path_name_i(idents: &[Ident]) -> String {
27     // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
28     idents.iter().map(|i| i.to_string()).collect::<Vec<String>>().join("::")
29 }
30
31 pub fn stmt_id(s: &Stmt) -> NodeId {
32     match s.node {
33       StmtDecl(_, id) => id,
34       StmtExpr(_, id) => id,
35       StmtSemi(_, id) => id,
36       StmtMac(..) => panic!("attempted to analyze unexpanded stmt")
37     }
38 }
39
40 pub fn binop_to_string(op: BinOp_) -> &'static str {
41     match op {
42         BiAdd => "+",
43         BiSub => "-",
44         BiMul => "*",
45         BiDiv => "/",
46         BiRem => "%",
47         BiAnd => "&&",
48         BiOr => "||",
49         BiBitXor => "^",
50         BiBitAnd => "&",
51         BiBitOr => "|",
52         BiShl => "<<",
53         BiShr => ">>",
54         BiEq => "==",
55         BiLt => "<",
56         BiLe => "<=",
57         BiNe => "!=",
58         BiGe => ">=",
59         BiGt => ">"
60     }
61 }
62
63 pub fn lazy_binop(b: BinOp_) -> bool {
64     match b {
65       BiAnd => true,
66       BiOr => true,
67       _ => false
68     }
69 }
70
71 pub fn is_shift_binop(b: BinOp_) -> bool {
72     match b {
73       BiShl => true,
74       BiShr => true,
75       _ => false
76     }
77 }
78
79 pub fn is_comparison_binop(b: BinOp_) -> bool {
80     match b {
81         BiEq | BiLt | BiLe | BiNe | BiGt | BiGe =>
82             true,
83         BiAnd | BiOr | BiAdd | BiSub | BiMul | BiDiv | BiRem |
84         BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr =>
85             false,
86     }
87 }
88
89 /// Returns `true` if the binary operator takes its arguments by value
90 pub fn is_by_value_binop(b: BinOp_) -> bool {
91     !is_comparison_binop(b)
92 }
93
94 /// Returns `true` if the unary operator takes its argument by value
95 pub fn is_by_value_unop(u: UnOp) -> bool {
96     match u {
97         UnNeg | UnNot => true,
98         _ => false,
99     }
100 }
101
102 pub fn unop_to_string(op: UnOp) -> &'static str {
103     match op {
104       UnUniq => "box() ",
105       UnDeref => "*",
106       UnNot => "!",
107       UnNeg => "-",
108     }
109 }
110
111 pub fn is_path(e: P<Expr>) -> bool {
112     match e.node { ExprPath(..) => true, _ => false }
113 }
114
115 /// Get a string representation of a signed int type, with its value.
116 /// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
117 pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
118     let s = match t {
119         TyIs => "isize",
120         TyI8 => "i8",
121         TyI16 => "i16",
122         TyI32 => "i32",
123         TyI64 => "i64"
124     };
125
126     match val {
127         // cast to a u64 so we can correctly print INT64_MIN. All integral types
128         // are parsed as u64, so we wouldn't want to print an extra negative
129         // sign.
130         Some(n) => format!("{}{}", n as u64, s),
131         None => s.to_string()
132     }
133 }
134
135 pub fn int_ty_max(t: IntTy) -> u64 {
136     match t {
137         TyI8 => 0x80,
138         TyI16 => 0x8000,
139         TyIs | TyI32 => 0x80000000, // actually ni about TyIs
140         TyI64 => 0x8000000000000000
141     }
142 }
143
144 /// Get a string representation of an unsigned int type, with its value.
145 /// We want to avoid "42u" in favor of "42us". "42uint" is right out.
146 pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
147     let s = match t {
148         TyUs => "usize",
149         TyU8 => "u8",
150         TyU16 => "u16",
151         TyU32 => "u32",
152         TyU64 => "u64"
153     };
154
155     match val {
156         Some(n) => format!("{}{}", n, s),
157         None => s.to_string()
158     }
159 }
160
161 pub fn uint_ty_max(t: UintTy) -> u64 {
162     match t {
163         TyU8 => 0xff,
164         TyU16 => 0xffff,
165         TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
166         TyU64 => 0xffffffffffffffff
167     }
168 }
169
170 pub fn float_ty_to_string(t: FloatTy) -> String {
171     match t {
172         TyF32 => "f32".to_string(),
173         TyF64 => "f64".to_string(),
174     }
175 }
176
177 // convert a span and an identifier to the corresponding
178 // 1-segment path
179 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
180     ast::Path {
181         span: s,
182         global: false,
183         segments: vec!(
184             ast::PathSegment {
185                 identifier: identifier,
186                 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
187                     lifetimes: Vec::new(),
188                     types: OwnedSlice::empty(),
189                     bindings: OwnedSlice::empty(),
190                 })
191             }
192         ),
193     }
194 }
195
196 // If path is a single segment ident path, return that ident. Otherwise, return
197 // None.
198 pub fn path_to_ident(path: &Path) -> Option<Ident> {
199     if path.segments.len() != 1 {
200         return None;
201     }
202
203     let segment = &path.segments[0];
204     if !segment.parameters.is_empty() {
205         return None;
206     }
207
208     Some(segment.identifier)
209 }
210
211 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
212     P(Pat {
213         id: id,
214         node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
215         span: s
216     })
217 }
218
219 pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
220     Lifetime { id: DUMMY_NODE_ID,
221                span: codemap::DUMMY_SP,
222                name: name }
223 }
224
225 /// Generate a "pretty" name for an `impl` from its type and trait.
226 /// This is designed so that symbols of `impl`'d methods give some
227 /// hint of where they came from, (previously they would all just be
228 /// listed as `__extensions__::method_name::hash`, with no indication
229 /// of the type).
230 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: Option<&Ty>) -> Ident {
231     let mut pretty = match ty {
232         Some(t) => pprust::ty_to_string(t),
233         None => String::from("..")
234     };
235
236     match *trait_ref {
237         Some(ref trait_ref) => {
238             pretty.push('.');
239             pretty.push_str(&pprust::path_to_string(&trait_ref.path));
240         }
241         None => {}
242     }
243     token::gensym_ident(&pretty[..])
244 }
245
246 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
247     match field.node.kind {
248         ast::NamedField(_, v) | ast::UnnamedField(v) => v
249     }
250 }
251
252 /// Maps a binary operator to its precedence
253 pub fn operator_prec(op: ast::BinOp_) -> usize {
254   match op {
255       // 'as' sits here with 12
256       BiMul | BiDiv | BiRem     => 11,
257       BiAdd | BiSub             => 10,
258       BiShl | BiShr             =>  9,
259       BiBitAnd                  =>  8,
260       BiBitXor                  =>  7,
261       BiBitOr                   =>  6,
262       BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3,
263       BiAnd                     =>  2,
264       BiOr                      =>  1
265   }
266 }
267
268 /// Precedence of the `as` operator, which is a binary operator
269 /// not appearing in the prior table.
270 pub const AS_PREC: usize = 12;
271
272 pub fn empty_generics() -> Generics {
273     Generics {
274         lifetimes: Vec::new(),
275         ty_params: OwnedSlice::empty(),
276         where_clause: WhereClause {
277             id: DUMMY_NODE_ID,
278             predicates: Vec::new(),
279         }
280     }
281 }
282
283 // ______________________________________________________________________
284 // Enumerating the IDs which appear in an AST
285
286 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
287 pub struct IdRange {
288     pub min: NodeId,
289     pub max: NodeId,
290 }
291
292 impl IdRange {
293     pub fn max() -> IdRange {
294         IdRange {
295             min: u32::MAX,
296             max: u32::MIN,
297         }
298     }
299
300     pub fn empty(&self) -> bool {
301         self.min >= self.max
302     }
303
304     pub fn add(&mut self, id: NodeId) {
305         self.min = cmp::min(self.min, id);
306         self.max = cmp::max(self.max, id + 1);
307     }
308 }
309
310 pub trait IdVisitingOperation {
311     fn visit_id(&mut self, node_id: NodeId);
312 }
313
314 /// A visitor that applies its operation to all of the node IDs
315 /// in a visitable thing.
316
317 pub struct IdVisitor<'a, O:'a> {
318     pub operation: &'a mut O,
319     pub pass_through_items: bool,
320     pub visited_outermost: bool,
321 }
322
323 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
324     fn visit_generics_helper(&mut self, generics: &Generics) {
325         for type_parameter in generics.ty_params.iter() {
326             self.operation.visit_id(type_parameter.id)
327         }
328         for lifetime in &generics.lifetimes {
329             self.operation.visit_id(lifetime.lifetime.id)
330         }
331     }
332 }
333
334 impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
335     fn visit_mod(&mut self,
336                  module: &Mod,
337                  _: Span,
338                  node_id: NodeId) {
339         self.operation.visit_id(node_id);
340         visit::walk_mod(self, module)
341     }
342
343     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
344         self.operation.visit_id(foreign_item.id);
345         visit::walk_foreign_item(self, foreign_item)
346     }
347
348     fn visit_item(&mut self, item: &Item) {
349         if !self.pass_through_items {
350             if self.visited_outermost {
351                 return
352             } else {
353                 self.visited_outermost = true
354             }
355         }
356
357         self.operation.visit_id(item.id);
358         match item.node {
359             ItemUse(ref view_path) => {
360                 match view_path.node {
361                     ViewPathSimple(_, _) |
362                     ViewPathGlob(_) => {}
363                     ViewPathList(_, ref paths) => {
364                         for path in paths {
365                             self.operation.visit_id(path.node.id())
366                         }
367                     }
368                 }
369             }
370             ItemEnum(ref enum_definition, _) => {
371                 for variant in &enum_definition.variants {
372                     self.operation.visit_id(variant.node.id)
373                 }
374             }
375             _ => {}
376         }
377
378         visit::walk_item(self, item);
379
380         self.visited_outermost = false
381     }
382
383     fn visit_local(&mut self, local: &Local) {
384         self.operation.visit_id(local.id);
385         visit::walk_local(self, local)
386     }
387
388     fn visit_block(&mut self, block: &Block) {
389         self.operation.visit_id(block.id);
390         visit::walk_block(self, block)
391     }
392
393     fn visit_stmt(&mut self, statement: &Stmt) {
394         self.operation.visit_id(ast_util::stmt_id(statement));
395         visit::walk_stmt(self, statement)
396     }
397
398     fn visit_pat(&mut self, pattern: &Pat) {
399         self.operation.visit_id(pattern.id);
400         visit::walk_pat(self, pattern)
401     }
402
403     fn visit_expr(&mut self, expression: &Expr) {
404         self.operation.visit_id(expression.id);
405         visit::walk_expr(self, expression)
406     }
407
408     fn visit_ty(&mut self, typ: &Ty) {
409         self.operation.visit_id(typ.id);
410         visit::walk_ty(self, typ)
411     }
412
413     fn visit_generics(&mut self, generics: &Generics) {
414         self.visit_generics_helper(generics);
415         visit::walk_generics(self, generics)
416     }
417
418     fn visit_fn(&mut self,
419                 function_kind: visit::FnKind<'v>,
420                 function_declaration: &'v FnDecl,
421                 block: &'v Block,
422                 span: Span,
423                 node_id: NodeId) {
424         if !self.pass_through_items {
425             match function_kind {
426                 FnKind::Method(..) if self.visited_outermost => return,
427                 FnKind::Method(..) => self.visited_outermost = true,
428                 _ => {}
429             }
430         }
431
432         self.operation.visit_id(node_id);
433
434         match function_kind {
435             FnKind::ItemFn(_, generics, _, _, _, _) => {
436                 self.visit_generics_helper(generics)
437             }
438             FnKind::Method(_, sig, _) => {
439                 self.visit_generics_helper(&sig.generics)
440             }
441             FnKind::Closure => {}
442         }
443
444         for argument in &function_declaration.inputs {
445             self.operation.visit_id(argument.id)
446         }
447
448         visit::walk_fn(self,
449                        function_kind,
450                        function_declaration,
451                        block,
452                        span);
453
454         if !self.pass_through_items {
455             if let FnKind::Method(..) = function_kind {
456                 self.visited_outermost = false;
457             }
458         }
459     }
460
461     fn visit_struct_field(&mut self, struct_field: &StructField) {
462         self.operation.visit_id(struct_field.node.id);
463         visit::walk_struct_field(self, struct_field)
464     }
465
466     fn visit_struct_def(&mut self,
467                         struct_def: &StructDef,
468                         _: ast::Ident,
469                         _: &ast::Generics,
470                         id: NodeId) {
471         self.operation.visit_id(id);
472         struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
473         visit::walk_struct_def(self, struct_def);
474     }
475
476     fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
477         self.operation.visit_id(ti.id);
478         visit::walk_trait_item(self, ti);
479     }
480
481     fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
482         self.operation.visit_id(ii.id);
483         visit::walk_impl_item(self, ii);
484     }
485
486     fn visit_lifetime_ref(&mut self, lifetime: &Lifetime) {
487         self.operation.visit_id(lifetime.id);
488     }
489
490     fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
491         self.visit_lifetime_ref(&def.lifetime);
492     }
493
494     fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
495         self.operation.visit_id(trait_ref.ref_id);
496         visit::walk_trait_ref(self, trait_ref);
497     }
498 }
499
500 pub struct IdRangeComputingVisitor {
501     result: IdRange,
502 }
503
504 impl IdRangeComputingVisitor {
505     pub fn new() -> IdRangeComputingVisitor {
506         IdRangeComputingVisitor { result: IdRange::max() }
507     }
508
509     pub fn result(&self) -> IdRange {
510         self.result
511     }
512 }
513
514 impl IdVisitingOperation for IdRangeComputingVisitor {
515     fn visit_id(&mut self, id: NodeId) {
516         self.result.add(id);
517     }
518 }
519
520 /// Computes the id range for a single fn body, ignoring nested items.
521 pub fn compute_id_range_for_fn_body(fk: FnKind,
522                                     decl: &FnDecl,
523                                     body: &Block,
524                                     sp: Span,
525                                     id: NodeId)
526                                     -> IdRange
527 {
528     let mut visitor = IdRangeComputingVisitor::new();
529     let mut id_visitor = IdVisitor {
530         operation: &mut visitor,
531         pass_through_items: false,
532         visited_outermost: false,
533     };
534     id_visitor.visit_fn(fk, decl, body, sp, id);
535     id_visitor.operation.result
536 }
537
538 pub fn walk_pat<F>(pat: &Pat, mut it: F) -> bool where F: FnMut(&Pat) -> bool {
539     // FIXME(#19596) this is a workaround, but there should be a better way
540     fn walk_pat_<G>(pat: &Pat, it: &mut G) -> bool where G: FnMut(&Pat) -> bool {
541         if !(*it)(pat) {
542             return false;
543         }
544
545         match pat.node {
546             PatIdent(_, _, Some(ref p)) => walk_pat_(&**p, it),
547             PatStruct(_, ref fields, _) => {
548                 fields.iter().all(|field| walk_pat_(&*field.node.pat, it))
549             }
550             PatEnum(_, Some(ref s)) | PatTup(ref s) => {
551                 s.iter().all(|p| walk_pat_(&**p, it))
552             }
553             PatBox(ref s) | PatRegion(ref s, _) => {
554                 walk_pat_(&**s, it)
555             }
556             PatVec(ref before, ref slice, ref after) => {
557                 before.iter().all(|p| walk_pat_(&**p, it)) &&
558                 slice.iter().all(|p| walk_pat_(&**p, it)) &&
559                 after.iter().all(|p| walk_pat_(&**p, it))
560             }
561             PatMac(_) => panic!("attempted to analyze unexpanded pattern"),
562             PatWild(_) | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
563             PatEnum(_, _) | PatQPath(_, _) => {
564                 true
565             }
566         }
567     }
568
569     walk_pat_(pat, &mut it)
570 }
571
572 /// Returns true if the given struct def is tuple-like; i.e. that its fields
573 /// are unnamed.
574 pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
575     struct_def.ctor_id.is_some()
576 }
577
578 /// Returns true if the given pattern consists solely of an identifier
579 /// and false otherwise.
580 pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
581     match pat.node {
582         ast::PatIdent(..) => true,
583         _ => false,
584     }
585 }
586
587 // are two paths equal when compared unhygienically?
588 // since I'm using this to replace ==, it seems appropriate
589 // to compare the span, global, etc. fields as well.
590 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
591     (a.span == b.span)
592     && (a.global == b.global)
593     && (segments_name_eq(&a.segments[..], &b.segments[..]))
594 }
595
596 // are two arrays of segments equal when compared unhygienically?
597 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
598     a.len() == b.len() &&
599     a.iter().zip(b).all(|(s, t)| {
600         s.identifier.name == t.identifier.name &&
601         // FIXME #7743: ident -> name problems in lifetime comparison?
602         // can types contain idents?
603         s.parameters == t.parameters
604     })
605 }
606
607 /// Returns true if this literal is a string and false otherwise.
608 pub fn lit_is_str(lit: &Lit) -> bool {
609     match lit.node {
610         LitStr(..) => true,
611         _ => false,
612     }
613 }
614
615 #[cfg(test)]
616 mod tests {
617     use ast::*;
618     use super::*;
619
620     fn ident_to_segment(id : &Ident) -> PathSegment {
621         PathSegment {identifier: id.clone(),
622                      parameters: PathParameters::none()}
623     }
624
625     #[test] fn idents_name_eq_test() {
626         assert!(segments_name_eq(
627             &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
628                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>(),
629             &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}]
630                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()));
631         assert!(!segments_name_eq(
632             &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}]
633                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>(),
634             &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}]
635                 .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()));
636     }
637 }