]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
A basic impl of Rewrite for ast::Expr
[rust.git] / src / visitor.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 syntax::ast;
12 use syntax::codemap::{self, CodeMap, Span, BytePos};
13 use syntax::visit;
14
15 use utils;
16
17 use SKIP_ANNOTATION;
18 use changes::ChangeSet;
19 use rewrite::{Rewrite, RewriteContext};
20
21 pub struct FmtVisitor<'a> {
22     pub codemap: &'a CodeMap,
23     pub changes: ChangeSet<'a>,
24     pub last_pos: BytePos,
25     // TODO RAII util for indenting
26     pub block_indent: usize,
27 }
28
29 impl<'a, 'v> visit::Visitor<'v> for FmtVisitor<'a> {
30     fn visit_expr(&mut self, ex: &'v ast::Expr) {
31         debug!("visit_expr: {:?} {:?}",
32                self.codemap.lookup_char_pos(ex.span.lo),
33                self.codemap.lookup_char_pos(ex.span.hi));
34         self.format_missing(ex.span.lo);
35         let offset = self.changes.cur_offset_span(ex.span);
36         match ex.rewrite(&RewriteContext { codemap: self.codemap },
37                          config!(max_width) - offset,
38                          offset) {
39             Some(new_str) => {
40                 //let new_str = self.rewrite_expr(ex, config!(max_width) - offset, offset);
41                 self.changes.push_str_span(ex.span, &new_str);
42                 self.last_pos = ex.span.hi;
43             }
44             None => { self.last_pos = ex.span.lo; }
45         }
46     }
47
48     fn visit_stmt(&mut self, stmt: &'v ast::Stmt) {
49         // If the stmt is actually an item, then we'll handle any missing spans
50         // there. This is important because of annotations.
51         // Although it might make more sense for the statement span to include
52         // any annotations on the item.
53         let skip_missing = match stmt.node {
54             ast::Stmt_::StmtDecl(ref decl, _) => {
55                 match decl.node {
56                     ast::Decl_::DeclItem(_) => true,
57                     _ => false,
58                 }
59             }
60             _ => false,
61         };
62         if !skip_missing {
63             self.format_missing_with_indent(stmt.span.lo);
64         }
65         visit::walk_stmt(self, stmt);
66     }
67
68     fn visit_block(&mut self, b: &'v ast::Block) {
69         debug!("visit_block: {:?} {:?}",
70                self.codemap.lookup_char_pos(b.span.lo),
71                self.codemap.lookup_char_pos(b.span.hi));
72         self.format_missing(b.span.lo);
73
74         self.changes.push_str_span(b.span, "{");
75         self.last_pos = self.last_pos + BytePos(1);
76         self.block_indent += config!(tab_spaces);
77
78         for stmt in &b.stmts {
79             self.visit_stmt(&stmt)
80         }
81         match b.expr {
82             Some(ref e) => {
83                 self.format_missing_with_indent(e.span.lo);
84                 self.visit_expr(e);
85             }
86             None => {}
87         }
88
89         self.block_indent -= config!(tab_spaces);
90         // TODO we should compress any newlines here to just one
91         self.format_missing_with_indent(b.span.hi - BytePos(1));
92         self.changes.push_str_span(b.span, "}");
93         self.last_pos = b.span.hi;
94     }
95
96     // Note that this only gets called for function definitions. Required methods
97     // on traits do not get handled here.
98     fn visit_fn(&mut self,
99                 fk: visit::FnKind<'v>,
100                 fd: &'v ast::FnDecl,
101                 b: &'v ast::Block,
102                 s: Span,
103                 _: ast::NodeId) {
104         self.format_missing_with_indent(s.lo);
105         self.last_pos = s.lo;
106
107         let indent = self.block_indent;
108         match fk {
109             visit::FkItemFn(ident,
110                             ref generics,
111                             ref unsafety,
112                             ref constness,
113                             ref abi,
114                             vis) => {
115                 let new_fn = self.rewrite_fn(indent,
116                                              ident,
117                                              fd,
118                                              None,
119                                              generics,
120                                              unsafety,
121                                              constness,
122                                              abi,
123                                              vis,
124                                              b.span.lo);
125                 self.changes.push_str_span(s, &new_fn);
126             }
127             visit::FkMethod(ident, ref sig, vis) => {
128                 let new_fn = self.rewrite_fn(indent,
129                                              ident,
130                                              fd,
131                                              Some(&sig.explicit_self),
132                                              &sig.generics,
133                                              &sig.unsafety,
134                                              &sig.constness,
135                                              &sig.abi,
136                                              vis.unwrap_or(ast::Visibility::Inherited),
137                                              b.span.lo);
138                 self.changes.push_str_span(s, &new_fn);
139             }
140             visit::FkFnBlock(..) => {}
141         }
142
143         self.last_pos = b.span.lo;
144         self.visit_block(b)
145     }
146
147     fn visit_item(&mut self, item: &'v ast::Item) {
148         // Don't look at attributes for modules.
149         // We want to avoid looking at attributes in another file, which the AST
150         // doesn't distinguish. FIXME This is overly conservative and means we miss
151         // attributes on inline modules.
152         match item.node {
153             ast::Item_::ItemMod(_) => {}
154             _ => {
155                 if self.visit_attrs(&item.attrs) {
156                     return;
157                 }
158             }
159         }
160
161         match item.node {
162             ast::Item_::ItemUse(ref vp) => {
163                 self.format_missing_with_indent(item.span.lo);
164                 match vp.node {
165                     ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
166                         let block_indent = self.block_indent;
167                         let one_line_budget = config!(max_width) - block_indent;
168                         let multi_line_budget = config!(ideal_width) - block_indent;
169                         let new_str = self.rewrite_use_list(block_indent,
170                                                             one_line_budget,
171                                                             multi_line_budget,
172                                                             path,
173                                                             path_list,
174                                                             item.vis);
175                         self.changes.push_str_span(item.span, &new_str);
176                         self.last_pos = item.span.hi;
177                     }
178                     ast::ViewPath_::ViewPathGlob(_) => {
179                         // FIXME convert to list?
180                     }
181                     ast::ViewPath_::ViewPathSimple(_,_) => {}
182                 }
183                 visit::walk_item(self, item);
184             }
185             ast::Item_::ItemImpl(..) |
186             ast::Item_::ItemMod(_) |
187             ast::Item_::ItemTrait(..) => {
188                 self.block_indent += config!(tab_spaces);
189                 visit::walk_item(self, item);
190                 self.block_indent -= config!(tab_spaces);
191             }
192             ast::Item_::ItemExternCrate(_) => {
193                 self.format_missing_with_indent(item.span.lo);
194                 let new_str = self.snippet(item.span);
195                 self.changes.push_str_span(item.span, &new_str);
196                 self.last_pos = item.span.hi;
197             }
198             ast::Item_::ItemStruct(ref def, ref generics) => {
199                 self.format_missing_with_indent(item.span.lo);
200                 self.visit_struct(item.ident,
201                                   item.vis,
202                                   def,
203                                   generics,
204                                   item.span);
205                 self.last_pos = item.span.hi;
206             }
207             ast::Item_::ItemEnum(ref def, ref generics) => {
208                 self.format_missing_with_indent(item.span.lo);
209                 self.visit_enum(item.ident,
210                                 item.vis,
211                                 def,
212                                 generics,
213                                 item.span);
214                 self.last_pos = item.span.hi;
215             }
216             _ => {
217                 visit::walk_item(self, item);
218             }
219         }
220     }
221
222     fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
223         if self.visit_attrs(&ti.attrs) {
224             return;
225         }
226
227         if let ast::TraitItem_::MethodTraitItem(ref sig, None) = ti.node {
228             self.format_missing_with_indent(ti.span.lo);
229
230             let indent = self.block_indent;
231             let new_fn = self.rewrite_required_fn(indent,
232                                                   ti.ident,
233                                                   sig,
234                                                   ti.span);
235
236             self.changes.push_str_span(ti.span, &new_fn);
237             self.last_pos = ti.span.hi;
238         }
239         // TODO format trait types
240
241         visit::walk_trait_item(self, ti)
242     }
243
244     fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
245         if self.visit_attrs(&ii.attrs) {
246             return;
247         }
248         visit::walk_impl_item(self, ii)
249     }
250
251     fn visit_mac(&mut self, mac: &'v ast::Mac) {
252         visit::walk_mac(self, mac)
253     }
254
255     fn visit_mod(&mut self, m: &'v ast::Mod, s: Span, _: ast::NodeId) {
256         // Only visit inline mods here.
257         if self.codemap.lookup_char_pos(s.lo).file.name !=
258            self.codemap.lookup_char_pos(m.inner.lo).file.name {
259             return;
260         }
261         visit::walk_mod(self, m);
262     }
263 }
264
265 impl<'a> FmtVisitor<'a> {
266     pub fn from_codemap<'b>(codemap: &'b CodeMap) -> FmtVisitor<'b> {
267         FmtVisitor {
268             codemap: codemap,
269             changes: ChangeSet::from_codemap(codemap),
270             last_pos: BytePos(0),
271             block_indent: 0,
272         }
273     }
274
275     pub fn snippet(&self, span: Span) -> String {
276         match self.codemap.span_to_snippet(span) {
277             Ok(s) => s,
278             Err(_) => {
279                 println!("Couldn't make snippet for span {:?}->{:?}",
280                          self.codemap.lookup_char_pos(span.lo),
281                          self.codemap.lookup_char_pos(span.hi));
282                 "".to_owned()
283             }
284         }
285     }
286
287     // Returns true if we should skip the following item.
288     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
289         if attrs.len() == 0 {
290             return false;
291         }
292
293         let first = &attrs[0];
294         self.format_missing_with_indent(first.span.lo);
295
296         match self.rewrite_attrs(attrs, self.block_indent) {
297             Some(s) => {
298                 self.changes.push_str_span(first.span, &s);
299                 let last = attrs.last().unwrap();
300                 self.last_pos = last.span.hi;
301                 false
302             }
303             None => true
304         }
305     }
306
307     fn rewrite_attrs(&self, attrs: &[ast::Attribute], indent: usize) -> Option<String> {
308         let mut result = String::new();
309         let indent = utils::make_indent(indent);
310
311         for (i, a) in attrs.iter().enumerate() {
312             if is_skip(&a.node.value) {
313                 return None;
314             }
315
316             let a_str = self.snippet(a.span);
317
318             if i > 0 {
319                 let comment = self.snippet(codemap::mk_sp(attrs[i-1].span.hi, a.span.lo));
320                 // This particular horror show is to preserve line breaks in between doc
321                 // comments. An alternative would be to force such line breaks to start
322                 // with the usual doc comment token.
323                 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
324                 let comment = comment.trim();
325                 if comment.len() > 0 {
326                     result.push_str(&indent);
327                     result.push_str(comment);
328                     result.push('\n');
329                 } else if multi_line {
330                     result.push('\n');
331                 }
332                 result.push_str(&indent);
333             }
334
335             result.push_str(&a_str);
336
337             if i < attrs.len() -1 {
338                 result.push('\n');
339             }
340         }
341
342         Some(result)
343     }
344 }
345
346 fn is_skip(meta_item: &ast::MetaItem) -> bool {
347     match meta_item.node {
348         ast::MetaItem_::MetaWord(ref s) => *s == SKIP_ANNOTATION,
349         _ => false,
350     }
351 }