]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Merge pull request #45 from tbu-/pr_toowned
[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 {MAX_WIDTH, TAB_SPACES, 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, 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 += 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 -= 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 defintions. 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(s.lo);
97         self.last_pos = s.lo;
98
99         let indent = self.block_indent;
100         match fk {
101             visit::FkItemFn(ident, ref generics, ref unsafety, ref abi, vis) => {
102                 let new_fn = self.rewrite_fn(indent,
103                                              ident,
104                                              fd,
105                                              None,
106                                              generics,
107                                              unsafety,
108                                              abi,
109                                              vis,
110                                              b.span);
111                 self.changes.push_str_span(s, &new_fn);
112             }
113             visit::FkMethod(ident, ref sig, vis) => {
114                 let new_fn = self.rewrite_fn(indent,
115                                              ident,
116                                              fd,
117                                              Some(&sig.explicit_self),
118                                              &sig.generics,
119                                              &sig.unsafety,
120                                              &sig.abi,
121                                              vis.unwrap_or(ast::Visibility::Inherited),
122                                              b.span);
123                 self.changes.push_str_span(s, &new_fn);
124             }
125             visit::FkFnBlock(..) => {}
126         }
127
128         self.last_pos = b.span.lo;
129         self.visit_block(b)
130     }
131
132     fn visit_item(&mut self, item: &'v ast::Item) {
133         // Don't look at attributes for modules.
134         // We want to avoid looking at attributes in another file, which the AST
135         // doesn't distinguish. FIXME This is overly conservative and means we miss
136         // attributes on inline modules.
137         match item.node {
138             ast::Item_::ItemMod(_) => {}
139             _ => {
140                 if self.visit_attrs(&item.attrs) {
141                     return;
142                 }
143             }
144         }
145
146         match item.node {
147             ast::Item_::ItemUse(ref vp) => {
148                 match vp.node {
149                     ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
150                         self.format_missing(item.span.lo);
151                         let new_str = self.rewrite_use_list(path,
152                                                             path_list,
153                                                             item.vis,
154                                                             vp.span);
155                         self.changes.push_str_span(item.span, &new_str);
156                         self.last_pos = item.span.hi;
157                     }
158                     ast::ViewPath_::ViewPathGlob(_) => {
159                         // FIXME convert to list?
160                     }
161                     _ => {}
162                 }
163                 visit::walk_item(self, item);
164             }
165             ast::Item_::ItemImpl(..) |
166             ast::Item_::ItemMod(_) |
167             ast::Item_::ItemTrait(..) => {
168                 self.block_indent += TAB_SPACES;
169                 visit::walk_item(self, item);
170                 self.block_indent -= TAB_SPACES;
171             }
172             ast::Item_::ItemExternCrate(_) => {
173                 self.format_missing_with_indent(item.span.lo);
174                 let new_str = self.snippet(item.span);
175                 self.changes.push_str_span(item.span, &new_str);
176                 self.last_pos = item.span.hi;
177             }
178             _ => {
179                 visit::walk_item(self, item);
180             }
181         }
182     }
183
184     fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
185         if self.visit_attrs(&ti.attrs) {
186             return;
187         }
188         visit::walk_trait_item(self, ti)
189     }
190
191     fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
192         if self.visit_attrs(&ii.attrs) {
193             return;
194         }
195         visit::walk_impl_item(self, ii)
196     }
197
198     fn visit_mac(&mut self, mac: &'v ast::Mac) {
199         visit::walk_mac(self, mac)
200     }
201
202     fn visit_mod(&mut self, m: &'v ast::Mod, s: Span, _: ast::NodeId) {
203         // Only visit inline mods here.
204         if self.codemap.lookup_char_pos(s.lo).file.name !=
205            self.codemap.lookup_char_pos(m.inner.lo).file.name {
206             return;
207         }
208         visit::walk_mod(self, m);
209     }
210 }
211
212 impl<'a> FmtVisitor<'a> {
213     pub fn from_codemap<'b>(codemap: &'b CodeMap) -> FmtVisitor<'b> {
214         FmtVisitor {
215             codemap: codemap,
216             changes: ChangeSet::from_codemap(codemap),
217             last_pos: BytePos(0),
218             block_indent: 0,
219         }
220     }
221
222     pub fn snippet(&self, span: Span) -> String {
223         match self.codemap.span_to_snippet(span) {
224             Ok(s) => s,
225             Err(_) => {
226                 println!("Couldn't make snippet for span {:?}->{:?}",
227                          self.codemap.lookup_char_pos(span.lo),
228                          self.codemap.lookup_char_pos(span.hi));
229                 "".to_owned()
230             }
231         }
232     }
233
234     // Returns true if we should skip the following item.
235     fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
236         if attrs.len() == 0 {
237             return false;
238         }
239
240         let first = &attrs[0];
241         self.format_missing_with_indent(first.span.lo);
242
243         match self.rewrite_attrs(attrs, self.block_indent) {
244             Some(s) => {
245                 self.changes.push_str_span(first.span, &s);
246                 let last = attrs.last().unwrap();
247                 self.last_pos = last.span.hi;
248                 false
249             }
250             None => true
251         }
252     }
253
254     fn rewrite_attrs(&self, attrs: &[ast::Attribute], indent: usize) -> Option<String> {
255         let mut result = String::new();
256         let indent = utils::make_indent(indent);
257
258         for (i, a) in attrs.iter().enumerate() {
259             if is_skip(&a.node.value) {
260                 return None;
261             }
262
263             let a_str = self.snippet(a.span);
264
265             if i > 0 {
266                 let comment = self.snippet(codemap::mk_sp(attrs[i-1].span.hi, a.span.lo));
267                 // This particular horror show is to preserve line breaks in between doc
268                 // comments. An alternative would be to force such line breaks to start
269                 // with the usual doc comment token.
270                 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
271                 let comment = comment.trim();
272                 if comment.len() > 0 {
273                     result.push_str(&indent);
274                     result.push_str(comment);
275                     result.push('\n');
276                 } else if multi_line {
277                     result.push('\n');
278                 }
279                 result.push_str(&indent);
280             }
281
282             result.push_str(&a_str);
283
284             if i < attrs.len() -1 {
285                 result.push('\n');
286             }
287         }
288
289         Some(result)
290     }
291 }
292
293 fn is_skip(meta_item: &ast::MetaItem) -> bool {
294     match meta_item.node {
295         ast::MetaItem_::MetaWord(ref s) => *s == SKIP_ANNOTATION,
296         _ => false,
297     }
298 }