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