]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Merge pull request #309 from marcusklaas/array-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 strings::string_buffer::StringBuffer;
16
17 use utils;
18 use config::Config;
19 use rewrite::{Rewrite, RewriteContext};
20 use comment::rewrite_comment;
21
22 pub struct FmtVisitor<'a> {
23     pub codemap: &'a CodeMap,
24     pub buffer: StringBuffer,
25     pub last_pos: BytePos,
26     // TODO RAII util for indenting
27     pub block_indent: usize,
28     pub config: &'a Config,
29 }
30
31 impl<'a, 'v> visit::Visitor<'v> for FmtVisitor<'a> {
32     // FIXME: We'd rather not format expressions here, as we have little
33     // context. How are we still reaching this?
34     fn visit_expr(&mut self, ex: &'v ast::Expr) {
35         debug!("visit_expr: {:?} {:?}",
36                self.codemap.lookup_char_pos(ex.span.lo),
37                self.codemap.lookup_char_pos(ex.span.hi));
38         self.format_missing(ex.span.lo);
39
40         let offset = self.buffer.cur_offset();
41         let rewrite = ex.rewrite(&self.get_context(), self.config.max_width - offset, offset);
42
43         if let Some(new_str) = rewrite {
44             self.buffer.push_str(&new_str);
45             self.last_pos = ex.span.hi;
46         }
47     }
48
49     fn visit_stmt(&mut self, stmt: &'v ast::Stmt) {
50         match stmt.node {
51             ast::Stmt_::StmtDecl(ref decl, _) => {
52                 match decl.node {
53                     ast::Decl_::DeclLocal(ref local) => self.visit_let(local, stmt.span),
54                     ast::Decl_::DeclItem(..) => visit::walk_stmt(self, stmt),
55                 }
56             }
57             ast::Stmt_::StmtExpr(ref ex, _) | ast::Stmt_::StmtSemi(ref ex, _) => {
58                 self.format_missing_with_indent(stmt.span.lo);
59                 let suffix = if let ast::Stmt_::StmtExpr(..) = stmt.node {
60                     ""
61                 } else {
62                     ";"
63                 };
64
65                 // 1 = trailing semicolon;
66                 let rewrite = ex.rewrite(&self.get_context(),
67                                          self.config.max_width - self.block_indent - suffix.len(),
68                                          self.block_indent);
69
70                 if let Some(new_str) = rewrite {
71                     self.buffer.push_str(&new_str);
72                     self.buffer.push_str(suffix);
73                     self.last_pos = stmt.span.hi;
74                 }
75             }
76             ast::Stmt_::StmtMac(..) => {
77                 self.format_missing_with_indent(stmt.span.lo);
78                 visit::walk_stmt(self, stmt);
79             }
80         }
81     }
82
83     fn visit_block(&mut self, b: &'v ast::Block) {
84         debug!("visit_block: {:?} {:?}",
85                self.codemap.lookup_char_pos(b.span.lo),
86                self.codemap.lookup_char_pos(b.span.hi));
87
88         // Check if this block has braces.
89         let snippet = self.snippet(b.span);
90         let has_braces = &snippet[..1] == "{" || &snippet[..6] == "unsafe";
91         let brace_compensation = if has_braces {
92             BytePos(1)
93         } else {
94             BytePos(0)
95         };
96
97         self.last_pos = self.last_pos + brace_compensation;
98         self.block_indent += self.config.tab_spaces;
99         self.buffer.push_str("{");
100
101         for stmt in &b.stmts {
102             self.visit_stmt(&stmt)
103         }
104
105         match b.expr {
106             Some(ref e) => {
107                 self.format_missing_with_indent(e.span.lo);
108                 self.visit_expr(e);
109             }
110             None => {}
111         }
112
113         self.block_indent -= self.config.tab_spaces;
114         // TODO we should compress any newlines here to just one
115         self.format_missing_with_indent(b.span.hi - brace_compensation);
116         self.buffer.push_str("}");
117         self.last_pos = b.span.hi;
118     }
119
120     // Note that this only gets called for function definitions. Required methods
121     // on traits do not get handled here.
122     fn visit_fn(&mut self,
123                 fk: visit::FnKind<'v>,
124                 fd: &'v ast::FnDecl,
125                 b: &'v ast::Block,
126                 s: Span,
127                 _: ast::NodeId) {
128         let indent = self.block_indent;
129         let rewrite = match fk {
130             visit::FnKind::ItemFn(ident,
131                                   ref generics,
132                                   ref unsafety,
133                                   ref constness,
134                                   ref abi,
135                                   vis) => {
136                 self.rewrite_fn(indent,
137                                 ident,
138                                 fd,
139                                 None,
140                                 generics,
141                                 unsafety,
142                                 constness,
143                                 abi,
144                                 vis,
145                                 codemap::mk_sp(s.lo, b.span.lo))
146             }
147             visit::FnKind::Method(ident, ref sig, vis) => {
148                 self.rewrite_fn(indent,
149                                 ident,
150                                 fd,
151                                 Some(&sig.explicit_self),
152                                 &sig.generics,
153                                 &sig.unsafety,
154                                 &sig.constness,
155                                 &sig.abi,
156                                 vis.unwrap_or(ast::Visibility::Inherited),
157                                 codemap::mk_sp(s.lo, b.span.lo))
158             }
159             visit::FnKind::Closure => None,
160         };
161
162         if let Some(fn_str) = rewrite {
163             self.format_missing_with_indent(s.lo);
164             self.buffer.push_str(&fn_str);
165         } else {
166             self.format_missing(b.span.lo);
167         }
168
169         self.last_pos = b.span.lo;
170         self.visit_block(b)
171     }
172
173     fn visit_item(&mut self, item: &'v ast::Item) {
174         // Don't look at attributes for modules.
175         // We want to avoid looking at attributes in another file, which the AST
176         // doesn't distinguish. FIXME This is overly conservative and means we miss
177         // attributes on inline modules.
178         match item.node {
179             ast::Item_::ItemMod(_) => {}
180             _ => {
181                 if self.visit_attrs(&item.attrs) {
182                     return;
183                 }
184             }
185         }
186
187         match item.node {
188             ast::Item_::ItemUse(ref vp) => {
189                 self.format_import(item.vis, vp, item.span);
190             }
191             ast::Item_::ItemImpl(..) |
192             ast::Item_::ItemTrait(..) => {
193                 self.block_indent += self.config.tab_spaces;
194                 visit::walk_item(self, item);
195                 self.block_indent -= self.config.tab_spaces;
196             }
197             ast::Item_::ItemExternCrate(_) => {
198                 self.format_missing_with_indent(item.span.lo);
199                 let new_str = self.snippet(item.span);
200                 self.buffer.push_str(&new_str);
201                 self.last_pos = item.span.hi;
202             }
203             ast::Item_::ItemStruct(ref def, ref generics) => {
204                 self.format_missing_with_indent(item.span.lo);
205                 self.visit_struct(item.ident, item.vis, def, generics, item.span);
206             }
207             ast::Item_::ItemEnum(ref def, ref generics) => {
208                 self.format_missing_with_indent(item.span.lo);
209                 self.visit_enum(item.ident, item.vis, def, generics, item.span);
210                 self.last_pos = item.span.hi;
211             }
212             ast::Item_::ItemMod(ref module) => {
213                 self.format_missing_with_indent(item.span.lo);
214                 self.format_mod(module, item.span, item.ident);
215             }
216             _ => {
217                 visit::walk_item(self, item);
218             }
219         }
220     }
221
222     fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
223         if self.visit_attrs(&ti.attrs) {
224             return;
225         }
226
227         if let ast::TraitItem_::MethodTraitItem(ref sig, None) = ti.node {
228             self.format_missing_with_indent(ti.span.lo);
229
230             let indent = self.block_indent;
231             let new_fn = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
232
233
234             if let Some(fn_str) = new_fn {
235                 self.buffer.push_str(&fn_str);
236                 self.last_pos = ti.span.hi;
237             }
238         }
239         // TODO format trait types
240
241         visit::walk_trait_item(self, ti)
242     }
243
244     fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
245         if self.visit_attrs(&ii.attrs) {
246             return;
247         }
248         visit::walk_impl_item(self, ii)
249     }
250
251     fn visit_mac(&mut self, mac: &'v ast::Mac) {
252         visit::walk_mac(self, mac)
253     }
254 }
255
256 impl<'a> FmtVisitor<'a> {
257     pub fn from_codemap<'b>(codemap: &'b CodeMap, config: &'b Config) -> FmtVisitor<'b> {
258         FmtVisitor {
259             codemap: codemap,
260             buffer: StringBuffer::new(),
261             last_pos: BytePos(0),
262             block_indent: 0,
263             config: config,
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.is_empty() {
282             return false;
283         }
284
285         let first = &attrs[0];
286         self.format_missing_with_indent(first.span.lo);
287
288         if utils::contains_skip(attrs) {
289             true
290         } else {
291             let rewrite = attrs.rewrite(&self.get_context(),
292                                         self.config.max_width - self.block_indent,
293                                         self.block_indent)
294                                .unwrap();
295             self.buffer.push_str(&rewrite);
296             let last = attrs.last().unwrap();
297             self.last_pos = last.span.hi;
298             false
299         }
300     }
301
302     fn format_mod(&mut self, m: &ast::Mod, s: Span, ident: ast::Ident) {
303         debug!("FmtVisitor::format_mod: ident: {:?}, span: {:?}", ident, s);
304
305         // Decide whether this is an inline mod or an external mod.
306         let local_file_name = self.codemap.span_to_filename(s);
307         let is_internal = local_file_name == self.codemap.span_to_filename(m.inner);
308
309         // TODO Should rewrite properly `mod X;`
310
311         if is_internal {
312             debug!("FmtVisitor::format_mod: internal mod");
313             self.block_indent += self.config.tab_spaces;
314             visit::walk_mod(self, m);
315             debug!("... last_pos after: {:?}", self.last_pos);
316             self.block_indent -= self.config.tab_spaces;
317         }
318     }
319
320     pub fn format_separate_mod(&mut self, m: &ast::Mod, filename: &str) {
321         let filemap = self.codemap.get_filemap(filename);
322         self.last_pos = filemap.start_pos;
323         self.block_indent = 0;
324         visit::walk_mod(self, m);
325         self.format_missing(filemap.end_pos);
326     }
327
328     fn format_import(&mut self, vis: ast::Visibility, vp: &ast::ViewPath, span: Span) {
329         let vis = utils::format_visibility(vis);
330         let offset = self.block_indent + vis.len() + "use ".len();
331         let context = RewriteContext {
332             codemap: self.codemap,
333             config: self.config,
334             block_indent: self.block_indent,
335             overflow_indent: 0,
336         };
337         // 1 = ";"
338         match vp.rewrite(&context, self.config.max_width - offset - 1, offset) {
339             Some(ref s) if s.is_empty() => {
340                 // Format up to last newline
341                 let prev_span = codemap::mk_sp(self.last_pos, span.lo);
342                 let span_end = match self.snippet(prev_span).rfind('\n') {
343                     Some(offset) => self.last_pos + BytePos(offset as u32),
344                     None => span.lo,
345                 };
346                 self.format_missing(span_end);
347                 self.last_pos = span.hi;
348             }
349             Some(ref s) => {
350                 let s = format!("{}use {};", vis, s);
351                 self.format_missing_with_indent(span.lo);
352                 self.buffer.push_str(&s);
353                 self.last_pos = span.hi;
354             }
355             None => {
356                 self.format_missing_with_indent(span.lo);
357                 self.format_missing(span.hi);
358             }
359         }
360     }
361
362     pub fn get_context(&self) -> RewriteContext {
363         RewriteContext {
364             codemap: self.codemap,
365             config: self.config,
366             block_indent: self.block_indent,
367             overflow_indent: 0,
368         }
369     }
370 }
371
372 impl<'a> Rewrite for [ast::Attribute] {
373     fn rewrite(&self, context: &RewriteContext, _: usize, offset: usize) -> Option<String> {
374         let mut result = String::new();
375         if self.is_empty() {
376             return Some(result);
377         }
378         let indent = utils::make_indent(offset);
379
380         for (i, a) in self.iter().enumerate() {
381             let a_str = context.snippet(a.span);
382
383             if i > 0 {
384                 let comment = context.snippet(codemap::mk_sp(self[i-1].span.hi, a.span.lo));
385                 // This particular horror show is to preserve line breaks in between doc
386                 // comments. An alternative would be to force such line breaks to start
387                 // with the usual doc comment token.
388                 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
389                 let comment = comment.trim();
390                 if !comment.is_empty() {
391                     let comment = rewrite_comment(comment,
392                                                   false,
393                                                   context.config.max_width - offset,
394                                                   offset);
395                     result.push_str(&indent);
396                     result.push_str(&comment);
397                     result.push('\n');
398                 } else if multi_line {
399                     result.push('\n');
400                 }
401                 result.push_str(&indent);
402             }
403
404             result.push_str(&a_str);
405
406             if i < self.len() - 1 {
407                 result.push('\n');
408             }
409         }
410
411         Some(result)
412     }
413 }