]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Format comments in struct literals
[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
173                         if let Some(new_str) = formatted {
174                             self.format_missing_with_indent(item.span.lo);
175                             self.changes.push_str_span(item.span, &new_str);
176                         } else {
177                             // Format up to last newline
178                             let span = codemap::mk_sp(self.last_pos, item.span.lo);
179                             let span_end = match self.snippet(span).rfind('\n') {
180                                 Some(offset) => self.last_pos + BytePos(offset as u32),
181                                 None => item.span.lo
182                             };
183                             self.format_missing(span_end);
184                         }
185
186                         self.last_pos = item.span.hi;
187                     }
188                     ast::ViewPath_::ViewPathGlob(_) => {
189                         // FIXME convert to list?
190                     }
191                     ast::ViewPath_::ViewPathSimple(_,_) => {}
192                 }
193                 visit::walk_item(self, item);
194             }
195             ast::Item_::ItemImpl(..) |
196             ast::Item_::ItemMod(_) |
197             ast::Item_::ItemTrait(..) => {
198                 self.block_indent += self.config.tab_spaces;
199                 visit::walk_item(self, item);
200                 self.block_indent -= self.config.tab_spaces;
201             }
202             ast::Item_::ItemExternCrate(_) => {
203                 self.format_missing_with_indent(item.span.lo);
204                 let new_str = self.snippet(item.span);
205                 self.changes.push_str_span(item.span, &new_str);
206                 self.last_pos = item.span.hi;
207             }
208             ast::Item_::ItemStruct(ref def, ref generics) => {
209                 self.format_missing_with_indent(item.span.lo);
210                 self.visit_struct(item.ident,
211                                   item.vis,
212                                   def,
213                                   generics,
214                                   item.span);
215                 self.last_pos = item.span.hi;
216             }
217             ast::Item_::ItemEnum(ref def, ref generics) => {
218                 self.format_missing_with_indent(item.span.lo);
219                 self.visit_enum(item.ident,
220                                 item.vis,
221                                 def,
222                                 generics,
223                                 item.span);
224                 self.last_pos = item.span.hi;
225             }
226             _ => {
227                 visit::walk_item(self, item);
228             }
229         }
230     }
231
232     fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
233         if self.visit_attrs(&ti.attrs) {
234             return;
235         }
236
237         if let ast::TraitItem_::MethodTraitItem(ref sig, None) = ti.node {
238             self.format_missing_with_indent(ti.span.lo);
239
240             let indent = self.block_indent;
241             let new_fn = self.rewrite_required_fn(indent,
242                                                   ti.ident,
243                                                   sig,
244                                                   ti.span);
245
246             self.changes.push_str_span(ti.span, &new_fn);
247             self.last_pos = ti.span.hi;
248         }
249         // TODO format trait types
250
251         visit::walk_trait_item(self, ti)
252     }
253
254     fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
255         if self.visit_attrs(&ii.attrs) {
256             return;
257         }
258         visit::walk_impl_item(self, ii)
259     }
260
261     fn visit_mac(&mut self, mac: &'v ast::Mac) {
262         visit::walk_mac(self, mac)
263     }
264
265     fn visit_mod(&mut self, m: &'v ast::Mod, s: Span, _: ast::NodeId) {
266         // Only visit inline mods here.
267         if self.codemap.lookup_char_pos(s.lo).file.name !=
268            self.codemap.lookup_char_pos(m.inner.lo).file.name {
269             return;
270         }
271         visit::walk_mod(self, m);
272     }
273 }
274
275 impl<'a> FmtVisitor<'a> {
276     pub fn from_codemap<'b>(codemap: &'b CodeMap, config: &'b Config) -> FmtVisitor<'b> {
277         FmtVisitor {
278             codemap: codemap,
279             changes: ChangeSet::from_codemap(codemap),
280             last_pos: BytePos(0),
281             block_indent: 0,
282             config: config
283         }
284     }
285
286     pub fn snippet(&self, span: Span) -> String {
287         match self.codemap.span_to_snippet(span) {
288             Ok(s) => s,
289             Err(_) => {
290                 println!("Couldn't make snippet for span {:?}->{:?}",
291                          self.codemap.lookup_char_pos(span.lo),
292                          self.codemap.lookup_char_pos(span.hi));
293                 "".to_owned()
294             }
295         }
296     }
297
298     // Returns true if we should skip the following item.
299     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
300         if attrs.len() == 0 {
301             return false;
302         }
303
304         let first = &attrs[0];
305         self.format_missing_with_indent(first.span.lo);
306
307         if utils::contains_skip(attrs) {
308             true
309         } else {
310             let rewrite = self.rewrite_attrs(attrs, self.block_indent);
311             self.changes.push_str_span(first.span, &rewrite);
312             let last = attrs.last().unwrap();
313             self.last_pos = last.span.hi;
314             false
315         }
316     }
317
318     pub fn rewrite_attrs(&self, attrs: &[ast::Attribute], indent: usize) -> String {
319         let mut result = String::new();
320         let indent = utils::make_indent(indent);
321
322         for (i, a) in attrs.iter().enumerate() {
323             let a_str = self.snippet(a.span);
324
325             if i > 0 {
326                 let comment = self.snippet(codemap::mk_sp(attrs[i-1].span.hi, a.span.lo));
327                 // This particular horror show is to preserve line breaks in between doc
328                 // comments. An alternative would be to force such line breaks to start
329                 // with the usual doc comment token.
330                 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
331                 let comment = comment.trim();
332                 if comment.len() > 0 {
333                     result.push_str(&indent);
334                     result.push_str(comment);
335                     result.push('\n');
336                 } else if multi_line {
337                     result.push('\n');
338                 }
339                 result.push_str(&indent);
340             }
341
342             result.push_str(&a_str);
343
344             if i < attrs.len() -1 {
345                 result.push('\n');
346             }
347         }
348
349         result
350     }
351 }