]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast_util.rs
Rollup merge of #29397 - dylanmckay:llvmdeps-deps, r=brson
[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) -> Option<NodeId> {
32     match s.node {
33       StmtDecl(_, id) => Some(id),
34       StmtExpr(_, id) => Some(id),
35       StmtSemi(_, id) => Some(id),
36       StmtMac(..) => None,
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         UnDeref => "*",
105         UnNot => "!",
106         UnNeg => "-",
107     }
108 }
109
110 pub fn is_path(e: P<Expr>) -> bool {
111     match e.node { ExprPath(..) => true, _ => false }
112 }
113
114 /// Get a string representation of a signed int type, with its value.
115 /// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
116 pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
117     let s = match t {
118         TyIs => "isize",
119         TyI8 => "i8",
120         TyI16 => "i16",
121         TyI32 => "i32",
122         TyI64 => "i64"
123     };
124
125     match val {
126         // cast to a u64 so we can correctly print INT64_MIN. All integral types
127         // are parsed as u64, so we wouldn't want to print an extra negative
128         // sign.
129         Some(n) => format!("{}{}", n as u64, s),
130         None => s.to_string()
131     }
132 }
133
134 pub fn int_ty_max(t: IntTy) -> u64 {
135     match t {
136         TyI8 => 0x80,
137         TyI16 => 0x8000,
138         TyIs | TyI32 => 0x80000000, // actually ni about TyIs
139         TyI64 => 0x8000000000000000
140     }
141 }
142
143 /// Get a string representation of an unsigned int type, with its value.
144 /// We want to avoid "42u" in favor of "42us". "42uint" is right out.
145 pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
146     let s = match t {
147         TyUs => "usize",
148         TyU8 => "u8",
149         TyU16 => "u16",
150         TyU32 => "u32",
151         TyU64 => "u64"
152     };
153
154     match val {
155         Some(n) => format!("{}{}", n, s),
156         None => s.to_string()
157     }
158 }
159
160 pub fn uint_ty_max(t: UintTy) -> u64 {
161     match t {
162         TyU8 => 0xff,
163         TyU16 => 0xffff,
164         TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
165         TyU64 => 0xffffffffffffffff
166     }
167 }
168
169 pub fn float_ty_to_string(t: FloatTy) -> String {
170     match t {
171         TyF32 => "f32".to_string(),
172         TyF64 => "f64".to_string(),
173     }
174 }
175
176 // convert a span and an identifier to the corresponding
177 // 1-segment path
178 pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
179     ast::Path {
180         span: s,
181         global: false,
182         segments: vec!(
183             ast::PathSegment {
184                 identifier: identifier,
185                 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
186                     lifetimes: Vec::new(),
187                     types: OwnedSlice::empty(),
188                     bindings: OwnedSlice::empty(),
189                 })
190             }
191         ),
192     }
193 }
194
195 // If path is a single segment ident path, return that ident. Otherwise, return
196 // None.
197 pub fn path_to_ident(path: &Path) -> Option<Ident> {
198     if path.segments.len() != 1 {
199         return None;
200     }
201
202     let segment = &path.segments[0];
203     if !segment.parameters.is_empty() {
204         return None;
205     }
206
207     Some(segment.identifier)
208 }
209
210 pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
211     P(Pat {
212         id: id,
213         node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
214         span: s
215     })
216 }
217
218 /// Generate a "pretty" name for an `impl` from its type and trait.
219 /// This is designed so that symbols of `impl`'d methods give some
220 /// hint of where they came from, (previously they would all just be
221 /// listed as `__extensions__::method_name::hash`, with no indication
222 /// of the type).
223 pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: Option<&Ty>) -> Ident {
224     let mut pretty = match ty {
225         Some(t) => pprust::ty_to_string(t),
226         None => String::from("..")
227     };
228
229     match *trait_ref {
230         Some(ref trait_ref) => {
231             pretty.push('.');
232             pretty.push_str(&pprust::path_to_string(&trait_ref.path));
233         }
234         None => {}
235     }
236     token::gensym_ident(&pretty[..])
237 }
238
239 pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
240     match field.node.kind {
241         ast::NamedField(_, v) | ast::UnnamedField(v) => v
242     }
243 }
244
245 pub fn empty_generics() -> Generics {
246     Generics {
247         lifetimes: Vec::new(),
248         ty_params: OwnedSlice::empty(),
249         where_clause: WhereClause {
250             id: DUMMY_NODE_ID,
251             predicates: Vec::new(),
252         }
253     }
254 }
255
256 // ______________________________________________________________________
257 // Enumerating the IDs which appear in an AST
258
259 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
260 pub struct IdRange {
261     pub min: NodeId,
262     pub max: NodeId,
263 }
264
265 impl IdRange {
266     pub fn max() -> IdRange {
267         IdRange {
268             min: u32::MAX,
269             max: u32::MIN,
270         }
271     }
272
273     pub fn empty(&self) -> bool {
274         self.min >= self.max
275     }
276
277     pub fn add(&mut self, id: NodeId) {
278         self.min = cmp::min(self.min, id);
279         self.max = cmp::max(self.max, id + 1);
280     }
281 }
282
283 pub trait IdVisitingOperation {
284     fn visit_id(&mut self, node_id: NodeId);
285 }
286
287 /// A visitor that applies its operation to all of the node IDs
288 /// in a visitable thing.
289
290 pub struct IdVisitor<'a, O:'a> {
291     pub operation: &'a mut O,
292     pub visited_outermost: bool,
293 }
294
295 impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
296     fn visit_generics_helper(&mut self, generics: &Generics) {
297         for type_parameter in generics.ty_params.iter() {
298             self.operation.visit_id(type_parameter.id)
299         }
300         for lifetime in &generics.lifetimes {
301             self.operation.visit_id(lifetime.lifetime.id)
302         }
303     }
304 }
305
306 impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
307     fn visit_mod(&mut self,
308                  module: &Mod,
309                  _: Span,
310                  node_id: NodeId) {
311         self.operation.visit_id(node_id);
312         visit::walk_mod(self, module)
313     }
314
315     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
316         self.operation.visit_id(foreign_item.id);
317         visit::walk_foreign_item(self, foreign_item)
318     }
319
320     fn visit_item(&mut self, item: &Item) {
321         if self.visited_outermost {
322             return
323         } else {
324             self.visited_outermost = true
325         }
326
327         self.operation.visit_id(item.id);
328         match item.node {
329             ItemUse(ref view_path) => {
330                 match view_path.node {
331                     ViewPathSimple(_, _) |
332                     ViewPathGlob(_) => {}
333                     ViewPathList(_, ref paths) => {
334                         for path in paths {
335                             self.operation.visit_id(path.node.id())
336                         }
337                     }
338                 }
339             }
340             _ => {}
341         }
342
343         visit::walk_item(self, item);
344
345         self.visited_outermost = false
346     }
347
348     fn visit_local(&mut self, local: &Local) {
349         self.operation.visit_id(local.id);
350         visit::walk_local(self, local)
351     }
352
353     fn visit_block(&mut self, block: &Block) {
354         self.operation.visit_id(block.id);
355         visit::walk_block(self, block)
356     }
357
358     fn visit_stmt(&mut self, statement: &Stmt) {
359         self.operation
360             .visit_id(ast_util::stmt_id(statement).expect("attempted to visit unexpanded stmt"));
361         visit::walk_stmt(self, statement)
362     }
363
364     fn visit_pat(&mut self, pattern: &Pat) {
365         self.operation.visit_id(pattern.id);
366         visit::walk_pat(self, pattern)
367     }
368
369     fn visit_expr(&mut self, expression: &Expr) {
370         self.operation.visit_id(expression.id);
371         visit::walk_expr(self, expression)
372     }
373
374     fn visit_ty(&mut self, typ: &Ty) {
375         self.operation.visit_id(typ.id);
376         visit::walk_ty(self, typ)
377     }
378
379     fn visit_generics(&mut self, generics: &Generics) {
380         self.visit_generics_helper(generics);
381         visit::walk_generics(self, generics)
382     }
383
384     fn visit_fn(&mut self,
385                 function_kind: visit::FnKind<'v>,
386                 function_declaration: &'v FnDecl,
387                 block: &'v Block,
388                 span: Span,
389                 node_id: NodeId) {
390         match function_kind {
391             FnKind::Method(..) if self.visited_outermost => return,
392             FnKind::Method(..) => self.visited_outermost = true,
393             _ => {}
394         }
395
396         self.operation.visit_id(node_id);
397
398         match function_kind {
399             FnKind::ItemFn(_, generics, _, _, _, _) => {
400                 self.visit_generics_helper(generics)
401             }
402             FnKind::Method(_, sig, _) => {
403                 self.visit_generics_helper(&sig.generics)
404             }
405             FnKind::Closure => {}
406         }
407
408         for argument in &function_declaration.inputs {
409             self.operation.visit_id(argument.id)
410         }
411
412         visit::walk_fn(self,
413                        function_kind,
414                        function_declaration,
415                        block,
416                        span);
417
418         if let FnKind::Method(..) = function_kind {
419             self.visited_outermost = false;
420         }
421     }
422
423     fn visit_struct_field(&mut self, struct_field: &StructField) {
424         self.operation.visit_id(struct_field.node.id);
425         visit::walk_struct_field(self, struct_field)
426     }
427
428     fn visit_variant_data(&mut self,
429                         struct_def: &VariantData,
430                         _: ast::Ident,
431                         _: &ast::Generics,
432                         _: NodeId,
433                         _: Span) {
434         self.operation.visit_id(struct_def.id());
435         visit::walk_struct_def(self, struct_def);
436     }
437
438     fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
439         self.operation.visit_id(ti.id);
440         visit::walk_trait_item(self, ti);
441     }
442
443     fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
444         self.operation.visit_id(ii.id);
445         visit::walk_impl_item(self, ii);
446     }
447
448     fn visit_lifetime(&mut self, lifetime: &Lifetime) {
449         self.operation.visit_id(lifetime.id);
450     }
451
452     fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
453         self.visit_lifetime(&def.lifetime);
454     }
455
456     fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
457         self.operation.visit_id(trait_ref.ref_id);
458         visit::walk_trait_ref(self, trait_ref);
459     }
460 }
461
462 pub struct IdRangeComputingVisitor {
463     pub result: IdRange,
464 }
465
466 impl IdRangeComputingVisitor {
467     pub fn new() -> IdRangeComputingVisitor {
468         IdRangeComputingVisitor { result: IdRange::max() }
469     }
470
471     pub fn result(&self) -> IdRange {
472         self.result
473     }
474 }
475
476 impl IdVisitingOperation for IdRangeComputingVisitor {
477     fn visit_id(&mut self, id: NodeId) {
478         self.result.add(id);
479     }
480 }
481
482 /// Computes the id range for a single fn body, ignoring nested items.
483 pub fn compute_id_range_for_fn_body(fk: FnKind,
484                                     decl: &FnDecl,
485                                     body: &Block,
486                                     sp: Span,
487                                     id: NodeId)
488                                     -> IdRange
489 {
490     let mut visitor = IdRangeComputingVisitor::new();
491     let mut id_visitor = IdVisitor {
492         operation: &mut visitor,
493         visited_outermost: false,
494     };
495     id_visitor.visit_fn(fk, decl, body, sp, id);
496     id_visitor.operation.result
497 }
498
499 /// Returns true if the given pattern consists solely of an identifier
500 /// and false otherwise.
501 pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
502     match pat.node {
503         ast::PatIdent(..) => true,
504         _ => false,
505     }
506 }
507
508 // are two paths equal when compared unhygienically?
509 // since I'm using this to replace ==, it seems appropriate
510 // to compare the span, global, etc. fields as well.
511 pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
512     (a.span == b.span)
513     && (a.global == b.global)
514     && (segments_name_eq(&a.segments[..], &b.segments[..]))
515 }
516
517 // are two arrays of segments equal when compared unhygienically?
518 pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
519     a.len() == b.len() &&
520     a.iter().zip(b).all(|(s, t)| {
521         s.identifier.name == t.identifier.name &&
522         // FIXME #7743: ident -> name problems in lifetime comparison?
523         // can types contain idents?
524         s.parameters == t.parameters
525     })
526 }
527
528 /// Returns true if this literal is a string and false otherwise.
529 pub fn lit_is_str(lit: &Lit) -> bool {
530     match lit.node {
531         LitStr(..) => true,
532         _ => false,
533     }
534 }
535
536 #[cfg(test)]
537 mod tests {
538     use ast::*;
539     use super::*;
540
541     fn ident_to_segment(id: Ident) -> PathSegment {
542         PathSegment {identifier: id,
543                      parameters: PathParameters::none()}
544     }
545
546     #[test] fn idents_name_eq_test() {
547         assert!(segments_name_eq(
548             &[Ident::new(Name(3),SyntaxContext(4)), Ident::new(Name(78),SyntaxContext(82))]
549                 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>(),
550             &[Ident::new(Name(3),SyntaxContext(104)), Ident::new(Name(78),SyntaxContext(182))]
551                 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>()));
552         assert!(!segments_name_eq(
553             &[Ident::new(Name(3),SyntaxContext(4)), Ident::new(Name(78),SyntaxContext(82))]
554                 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>(),
555             &[Ident::new(Name(3),SyntaxContext(104)), Ident::new(Name(77),SyntaxContext(182))]
556                 .iter().cloned().map(ident_to_segment).collect::<Vec<PathSegment>>()));
557     }
558 }