]> git.lizzy.rs Git - rust.git/blob - src/librustc_front/util.rs
07044a7bba0efc1ab4a133bb855f86f0252e8830
[rust.git] / src / librustc_front / util.rs
1 // Copyright 2015 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 hir;
12 use hir::*;
13 use visit::{self, Visitor, FnKind};
14 use syntax::ast_util;
15 use syntax::ast::{Ident, Name, NodeId, DUMMY_NODE_ID};
16 use syntax::codemap::Span;
17 use syntax::ptr::P;
18 use syntax::owned_slice::OwnedSlice;
19
20 pub fn walk_pat<F>(pat: &Pat, mut it: F) -> bool
21     where F: FnMut(&Pat) -> bool
22 {
23     // FIXME(#19596) this is a workaround, but there should be a better way
24     fn walk_pat_<G>(pat: &Pat, it: &mut G) -> bool
25         where G: FnMut(&Pat) -> bool
26     {
27         if !(*it)(pat) {
28             return false;
29         }
30
31         match pat.node {
32             PatIdent(_, _, Some(ref p)) => walk_pat_(&**p, it),
33             PatStruct(_, ref fields, _) => {
34                 fields.iter().all(|field| walk_pat_(&*field.node.pat, it))
35             }
36             PatEnum(_, Some(ref s)) | PatTup(ref s) => {
37                 s.iter().all(|p| walk_pat_(&**p, it))
38             }
39             PatBox(ref s) | PatRegion(ref s, _) => {
40                 walk_pat_(&**s, it)
41             }
42             PatVec(ref before, ref slice, ref after) => {
43                 before.iter().all(|p| walk_pat_(&**p, it)) &&
44                 slice.iter().all(|p| walk_pat_(&**p, it)) &&
45                 after.iter().all(|p| walk_pat_(&**p, it))
46             }
47             PatWild |
48             PatLit(_) |
49             PatRange(_, _) |
50             PatIdent(_, _, _) |
51             PatEnum(_, _) |
52             PatQPath(_, _) => {
53                 true
54             }
55         }
56     }
57
58     walk_pat_(pat, &mut it)
59 }
60
61 pub fn binop_to_string(op: BinOp_) -> &'static str {
62     match op {
63         BiAdd => "+",
64         BiSub => "-",
65         BiMul => "*",
66         BiDiv => "/",
67         BiRem => "%",
68         BiAnd => "&&",
69         BiOr => "||",
70         BiBitXor => "^",
71         BiBitAnd => "&",
72         BiBitOr => "|",
73         BiShl => "<<",
74         BiShr => ">>",
75         BiEq => "==",
76         BiLt => "<",
77         BiLe => "<=",
78         BiNe => "!=",
79         BiGe => ">=",
80         BiGt => ">",
81     }
82 }
83
84 pub fn stmt_id(s: &Stmt) -> NodeId {
85     match s.node {
86         StmtDecl(_, id) => id,
87         StmtExpr(_, id) => id,
88         StmtSemi(_, id) => id,
89     }
90 }
91
92 pub fn lazy_binop(b: BinOp_) -> bool {
93     match b {
94         BiAnd => true,
95         BiOr => true,
96         _ => false,
97     }
98 }
99
100 pub fn is_shift_binop(b: BinOp_) -> bool {
101     match b {
102         BiShl => true,
103         BiShr => true,
104         _ => false,
105     }
106 }
107
108 pub fn is_comparison_binop(b: BinOp_) -> bool {
109     match b {
110         BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
111         BiAnd |
112         BiOr |
113         BiAdd |
114         BiSub |
115         BiMul |
116         BiDiv |
117         BiRem |
118         BiBitXor |
119         BiBitAnd |
120         BiBitOr |
121         BiShl |
122         BiShr => false,
123     }
124 }
125
126 /// Returns `true` if the binary operator takes its arguments by value
127 pub fn is_by_value_binop(b: BinOp_) -> bool {
128     !is_comparison_binop(b)
129 }
130
131 /// Returns `true` if the unary operator takes its argument by value
132 pub fn is_by_value_unop(u: UnOp) -> bool {
133     match u {
134         UnNeg | UnNot => true,
135         _ => false,
136     }
137 }
138
139 pub fn unop_to_string(op: UnOp) -> &'static str {
140     match op {
141         UnDeref => "*",
142         UnNot => "!",
143         UnNeg => "-",
144     }
145 }
146
147 pub struct IdVisitor<'a, O: 'a> {
148     pub operation: &'a mut O,
149     pub pass_through_items: bool,
150     pub visited_outermost: bool,
151 }
152
153 impl<'a, O: ast_util::IdVisitingOperation> IdVisitor<'a, O> {
154     fn visit_generics_helper(&mut self, generics: &Generics) {
155         for type_parameter in generics.ty_params.iter() {
156             self.operation.visit_id(type_parameter.id)
157         }
158         for lifetime in &generics.lifetimes {
159             self.operation.visit_id(lifetime.lifetime.id)
160         }
161     }
162 }
163
164 impl<'a, 'v, O: ast_util::IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
165     fn visit_mod(&mut self, module: &Mod, _: Span, node_id: NodeId) {
166         self.operation.visit_id(node_id);
167         visit::walk_mod(self, module)
168     }
169
170     fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
171         self.operation.visit_id(foreign_item.id);
172         visit::walk_foreign_item(self, foreign_item)
173     }
174
175     fn visit_item(&mut self, item: &Item) {
176         if !self.pass_through_items {
177             if self.visited_outermost {
178                 return
179             } else {
180                 self.visited_outermost = true
181             }
182         }
183
184         self.operation.visit_id(item.id);
185         match item.node {
186             ItemUse(ref view_path) => {
187                 match view_path.node {
188                     ViewPathSimple(_, _) |
189                     ViewPathGlob(_) => {}
190                     ViewPathList(_, ref paths) => {
191                         for path in paths {
192                             self.operation.visit_id(path.node.id())
193                         }
194                     }
195                 }
196             }
197             _ => {}
198         }
199
200         visit::walk_item(self, item);
201
202         self.visited_outermost = false
203     }
204
205     fn visit_local(&mut self, local: &Local) {
206         self.operation.visit_id(local.id);
207         visit::walk_local(self, local)
208     }
209
210     fn visit_block(&mut self, block: &Block) {
211         self.operation.visit_id(block.id);
212         visit::walk_block(self, block)
213     }
214
215     fn visit_stmt(&mut self, statement: &Stmt) {
216         self.operation.visit_id(stmt_id(statement));
217         visit::walk_stmt(self, statement)
218     }
219
220     fn visit_pat(&mut self, pattern: &Pat) {
221         self.operation.visit_id(pattern.id);
222         visit::walk_pat(self, pattern)
223     }
224
225     fn visit_expr(&mut self, expression: &Expr) {
226         self.operation.visit_id(expression.id);
227         visit::walk_expr(self, expression)
228     }
229
230     fn visit_ty(&mut self, typ: &Ty) {
231         self.operation.visit_id(typ.id);
232         visit::walk_ty(self, typ)
233     }
234
235     fn visit_generics(&mut self, generics: &Generics) {
236         self.visit_generics_helper(generics);
237         visit::walk_generics(self, generics)
238     }
239
240     fn visit_fn(&mut self,
241                 function_kind: FnKind<'v>,
242                 function_declaration: &'v FnDecl,
243                 block: &'v Block,
244                 span: Span,
245                 node_id: NodeId) {
246         if !self.pass_through_items {
247             match function_kind {
248                 FnKind::Method(..) if self.visited_outermost => return,
249                 FnKind::Method(..) => self.visited_outermost = true,
250                 _ => {}
251             }
252         }
253
254         self.operation.visit_id(node_id);
255
256         match function_kind {
257             FnKind::ItemFn(_, generics, _, _, _, _) => {
258                 self.visit_generics_helper(generics)
259             }
260             FnKind::Method(_, sig, _) => {
261                 self.visit_generics_helper(&sig.generics)
262             }
263             FnKind::Closure => {}
264         }
265
266         for argument in &function_declaration.inputs {
267             self.operation.visit_id(argument.id)
268         }
269
270         visit::walk_fn(self, function_kind, function_declaration, block, span);
271
272         if !self.pass_through_items {
273             if let FnKind::Method(..) = function_kind {
274                 self.visited_outermost = false;
275             }
276         }
277     }
278
279     fn visit_struct_field(&mut self, struct_field: &StructField) {
280         self.operation.visit_id(struct_field.node.id);
281         visit::walk_struct_field(self, struct_field)
282     }
283
284     fn visit_variant_data(&mut self,
285                         struct_def: &VariantData,
286                         _: Name,
287                         _: &hir::Generics,
288                         _: NodeId,
289                         _: Span) {
290         self.operation.visit_id(struct_def.id());
291         visit::walk_struct_def(self, struct_def);
292     }
293
294     fn visit_trait_item(&mut self, ti: &hir::TraitItem) {
295         self.operation.visit_id(ti.id);
296         visit::walk_trait_item(self, ti);
297     }
298
299     fn visit_impl_item(&mut self, ii: &hir::ImplItem) {
300         self.operation.visit_id(ii.id);
301         visit::walk_impl_item(self, ii);
302     }
303
304     fn visit_lifetime(&mut self, lifetime: &Lifetime) {
305         self.operation.visit_id(lifetime.id);
306     }
307
308     fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
309         self.visit_lifetime(&def.lifetime);
310     }
311
312     fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
313         self.operation.visit_id(trait_ref.ref_id);
314         visit::walk_trait_ref(self, trait_ref);
315     }
316 }
317
318 /// Computes the id range for a single fn body, ignoring nested items.
319 pub fn compute_id_range_for_fn_body(fk: FnKind,
320                                     decl: &FnDecl,
321                                     body: &Block,
322                                     sp: Span,
323                                     id: NodeId)
324                                     -> ast_util::IdRange {
325     let mut visitor = ast_util::IdRangeComputingVisitor { result: ast_util::IdRange::max() };
326     let mut id_visitor = IdVisitor {
327         operation: &mut visitor,
328         pass_through_items: false,
329         visited_outermost: false,
330     };
331     id_visitor.visit_fn(fk, decl, body, sp, id);
332     id_visitor.operation.result
333 }
334
335 pub fn is_path(e: P<Expr>) -> bool {
336     match e.node {
337         ExprPath(..) => true,
338         _ => false,
339     }
340 }
341
342 pub fn empty_generics() -> Generics {
343     Generics {
344         lifetimes: Vec::new(),
345         ty_params: OwnedSlice::empty(),
346         where_clause: WhereClause {
347             id: DUMMY_NODE_ID,
348             predicates: Vec::new(),
349         },
350     }
351 }
352
353 // convert a span and an identifier to the corresponding
354 // 1-segment path
355 pub fn ident_to_path(s: Span, ident: Ident) -> Path {
356     hir::Path {
357         span: s,
358         global: false,
359         segments: vec!(hir::PathSegment {
360             identifier: ident,
361             parameters: hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
362                 lifetimes: Vec::new(),
363                 types: OwnedSlice::empty(),
364                 bindings: OwnedSlice::empty(),
365             }),
366         }),
367     }
368 }