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