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