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