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