]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Implement Rewrite for ast::Stmt
[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::parse::ParseSess;
14 use syntax::visit;
15
16 use strings::string_buffer::StringBuffer;
17
18 use {Indent, WriteMode};
19 use utils;
20 use config::Config;
21 use rewrite::{Rewrite, RewriteContext};
22 use comment::rewrite_comment;
23 use macros::rewrite_macro;
24 use items::rewrite_static;
25
26 pub struct FmtVisitor<'a> {
27     pub parse_session: &'a ParseSess,
28     pub codemap: &'a CodeMap,
29     pub buffer: StringBuffer,
30     pub last_pos: BytePos,
31     // TODO: RAII util for indenting
32     pub block_indent: Indent,
33     pub config: &'a Config,
34     pub write_mode: Option<WriteMode>,
35 }
36
37 impl<'a> FmtVisitor<'a> {
38     fn visit_stmt(&mut self, stmt: &ast::Stmt) {
39         match stmt.node {
40             ast::Stmt_::StmtDecl(ref decl, _) => {
41                 if let ast::Decl_::DeclItem(ref item) = decl.node {
42                     self.visit_item(item);
43                 } else {
44                     let rewrite = stmt.rewrite(&self.get_context(),
45                                                self.config.max_width - self.block_indent.width(),
46                                                self.block_indent);
47
48                     self.push_rewrite(stmt.span, rewrite);
49                 }
50             }
51             ast::Stmt_::StmtExpr(..) | ast::Stmt_::StmtSemi(..) => {
52                 let rewrite = stmt.rewrite(&self.get_context(),
53                                            self.config.max_width - self.block_indent.width(),
54                                            self.block_indent);
55
56                 self.push_rewrite(stmt.span, rewrite);
57             }
58             ast::Stmt_::StmtMac(ref mac, _macro_style) => {
59                 self.format_missing_with_indent(stmt.span.lo);
60                 self.visit_mac(mac);
61             }
62         }
63     }
64
65     pub fn visit_block(&mut self, b: &ast::Block) {
66         debug!("visit_block: {:?} {:?}",
67                self.codemap.lookup_char_pos(b.span.lo),
68                self.codemap.lookup_char_pos(b.span.hi));
69
70         // Check if this block has braces.
71         let snippet = self.snippet(b.span);
72         let has_braces = &snippet[..1] == "{" || &snippet[..6] == "unsafe";
73         let brace_compensation = if has_braces {
74             BytePos(1)
75         } else {
76             BytePos(0)
77         };
78
79         self.last_pos = self.last_pos + brace_compensation;
80         self.block_indent = self.block_indent.block_indent(self.config);
81         self.buffer.push_str("{");
82
83         for stmt in &b.stmts {
84             self.visit_stmt(&stmt)
85         }
86
87         if let Some(ref e) = b.expr {
88             self.format_missing_with_indent(e.span.lo);
89             let rewrite = e.rewrite(&self.get_context(),
90                                     self.config.max_width - self.block_indent.width(),
91                                     self.block_indent)
92                            .unwrap_or_else(|| self.snippet(e.span));
93
94             self.buffer.push_str(&rewrite);
95             self.last_pos = e.span.hi;
96
97             if utils::semicolon_for_expr(e) {
98                 self.buffer.push_str(";");
99             }
100         }
101
102         // TODO: we should compress any newlines here to just one
103         self.format_missing_with_indent(b.span.hi - brace_compensation);
104         // FIXME: this is a terrible hack to indent the comments between the last
105         // item in the block and the closing brace to the block's level.
106         // The closing brace itself, however, should be indented at a shallower
107         // level.
108         let total_len = self.buffer.len;
109         let chars_too_many = if self.config.hard_tabs {
110             1
111         } else {
112             self.config.tab_spaces
113         };
114         self.buffer.truncate(total_len - chars_too_many);
115         self.buffer.push_str("}");
116         self.last_pos = b.span.hi;
117         self.block_indent = self.block_indent.block_unindent(self.config);
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,
124                 fd: &ast::FnDecl,
125                 b: &ast::Block,
126                 s: Span,
127                 _: ast::NodeId) {
128         let indent = self.block_indent;
129         let rewrite = match fk {
130             visit::FnKind::ItemFn(ident, ref generics, unsafety, constness, abi, vis) => {
131                 self.rewrite_fn(indent,
132                                 ident,
133                                 fd,
134                                 None,
135                                 generics,
136                                 unsafety,
137                                 constness,
138                                 abi,
139                                 vis,
140                                 codemap::mk_sp(s.lo, b.span.lo))
141             }
142             visit::FnKind::Method(ident, ref sig, vis) => {
143                 self.rewrite_fn(indent,
144                                 ident,
145                                 fd,
146                                 Some(&sig.explicit_self),
147                                 &sig.generics,
148                                 sig.unsafety,
149                                 sig.constness,
150                                 sig.abi,
151                                 vis.unwrap_or(ast::Visibility::Inherited),
152                                 codemap::mk_sp(s.lo, b.span.lo))
153             }
154             visit::FnKind::Closure => None,
155         };
156
157         if let Some(ref single_line_fn) = self.rewrite_single_line_fn(&rewrite, &b) {
158             self.format_missing_with_indent(s.lo);
159             self.buffer.push_str(single_line_fn);
160             self.last_pos = b.span.hi;
161             return;
162         }
163
164         if let Some(fn_str) = rewrite {
165             self.format_missing_with_indent(s.lo);
166             self.buffer.push_str(&fn_str);
167         } else {
168             self.format_missing(b.span.lo);
169         }
170
171         self.last_pos = b.span.lo;
172         self.visit_block(b)
173     }
174
175     fn visit_item(&mut self, item: &ast::Item) {
176         // Don't look at attributes for modules.
177         // We want to avoid looking at attributes in another file, which the AST
178         // doesn't distinguish. FIXME This is overly conservative and means we miss
179         // attributes on inline modules.
180         match item.node {
181             ast::Item_::ItemMod(_) => {}
182             _ => {
183                 if self.visit_attrs(&item.attrs) {
184                     return;
185                 }
186             }
187         }
188
189         match item.node {
190             ast::Item_::ItemUse(ref vp) => {
191                 self.format_import(item.vis, vp, item.span);
192             }
193             // FIXME(#78): format impl definitions.
194             ast::Item_::ItemImpl(_, _, _, _, _, ref impl_items) => {
195                 self.format_missing_with_indent(item.span.lo);
196                 self.block_indent = self.block_indent.block_indent(self.config);
197                 for item in impl_items {
198                     self.visit_impl_item(&item);
199                 }
200                 self.block_indent = self.block_indent.block_unindent(self.config);
201             }
202             // FIXME(#78): format traits.
203             ast::Item_::ItemTrait(_, _, _, ref trait_items) => {
204                 self.format_missing_with_indent(item.span.lo);
205                 self.block_indent = self.block_indent.block_indent(self.config);
206                 for item in trait_items {
207                     self.visit_trait_item(&item);
208                 }
209                 self.block_indent = self.block_indent.block_unindent(self.config);
210             }
211             ast::Item_::ItemExternCrate(_) => {
212                 self.format_missing_with_indent(item.span.lo);
213                 let new_str = self.snippet(item.span);
214                 self.buffer.push_str(&new_str);
215                 self.last_pos = item.span.hi;
216             }
217             ast::Item_::ItemStruct(ref def, ref generics) => {
218                 let indent = self.block_indent;
219                 let rewrite = self.format_struct("struct ",
220                                                  item.ident,
221                                                  item.vis,
222                                                  def,
223                                                  Some(generics),
224                                                  item.span,
225                                                  indent)
226                                   .map(|s| {
227                                       match *def {
228                                           ast::VariantData::Tuple(..) => s + ";",
229                                           _ => s,
230                                       }
231                                   });
232                 self.push_rewrite(item.span, rewrite);
233             }
234             ast::Item_::ItemEnum(ref def, ref generics) => {
235                 self.format_missing_with_indent(item.span.lo);
236                 self.visit_enum(item.ident, item.vis, def, generics, item.span);
237                 self.last_pos = item.span.hi;
238             }
239             ast::Item_::ItemMod(ref module) => {
240                 self.format_missing_with_indent(item.span.lo);
241                 self.format_mod(module, item.span, item.ident);
242             }
243             ast::Item_::ItemMac(..) => {
244                 self.format_missing_with_indent(item.span.lo);
245                 let snippet = self.snippet(item.span);
246                 self.buffer.push_str(&snippet);
247                 self.last_pos = item.span.hi;
248                 // FIXME: we cannot format these yet, because of a bad span.
249                 // See rust lang issue #28424.
250             }
251             ast::Item_::ItemForeignMod(ref foreign_mod) => {
252                 self.format_missing_with_indent(item.span.lo);
253                 self.format_foreign_mod(foreign_mod, item.span);
254             }
255             ast::Item_::ItemStatic(ref ty, mutability, ref expr) => {
256                 let rewrite = rewrite_static("static",
257                                              item.vis,
258                                              item.ident,
259                                              ty,
260                                              mutability,
261                                              expr,
262                                              &self.get_context());
263                 self.push_rewrite(item.span, rewrite);
264             }
265             ast::Item_::ItemConst(ref ty, ref expr) => {
266                 let rewrite = rewrite_static("const",
267                                              item.vis,
268                                              item.ident,
269                                              ty,
270                                              ast::Mutability::MutImmutable,
271                                              expr,
272                                              &self.get_context());
273                 self.push_rewrite(item.span, rewrite);
274             }
275             ast::Item_::ItemDefaultImpl(..) => {
276                 // FIXME(#78): format impl definitions.
277             }
278             ast::ItemFn(ref declaration, unsafety, constness, abi, ref generics, ref body) => {
279                 self.visit_fn(visit::FnKind::ItemFn(item.ident,
280                                                     generics,
281                                                     unsafety,
282                                                     constness,
283                                                     abi,
284                                                     item.vis),
285                               declaration,
286                               body,
287                               item.span,
288                               item.id)
289             }
290             ast::Item_::ItemTy(..) => {
291                 // FIXME(#486): format type aliases.
292             }
293         }
294     }
295
296     fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
297         if self.visit_attrs(&ti.attrs) {
298             return;
299         }
300
301         match ti.node {
302             ast::ConstTraitItem(..) => {
303                 // FIXME: Implement
304             }
305             ast::MethodTraitItem(ref sig, None) => {
306                 let indent = self.block_indent;
307                 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
308                 self.push_rewrite(ti.span, rewrite);
309             }
310             ast::MethodTraitItem(ref sig, Some(ref body)) => {
311                 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
312                               &sig.decl,
313                               &body,
314                               ti.span,
315                               ti.id);
316             }
317             ast::TypeTraitItem(..) => {
318                 // FIXME: Implement
319             }
320         }
321     }
322
323     fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
324         if self.visit_attrs(&ii.attrs) {
325             return;
326         }
327
328         match ii.node {
329             ast::MethodImplItem(ref sig, ref body) => {
330                 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(ii.vis)),
331                               &sig.decl,
332                               body,
333                               ii.span,
334                               ii.id);
335             }
336             ast::ConstImplItem(..) => {
337                 // FIXME: Implement
338             }
339             ast::TypeImplItem(_) => {
340                 // FIXME: Implement
341             }
342             ast::MacImplItem(ref mac) => {
343                 self.visit_mac(mac);
344             }
345         }
346     }
347
348     fn visit_mac(&mut self, mac: &ast::Mac) {
349         // 1 = ;
350         let width = self.config.max_width - self.block_indent.width() - 1;
351         let rewrite = rewrite_macro(mac, &self.get_context(), width, self.block_indent);
352
353         if let Some(res) = rewrite {
354             self.buffer.push_str(&res);
355             self.last_pos = mac.span.hi;
356         }
357     }
358
359     fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
360         self.format_missing_with_indent(span.lo);
361
362         if let Some(res) = rewrite {
363             self.buffer.push_str(&res);
364             self.last_pos = span.hi;
365         }
366     }
367
368     pub fn from_codemap(parse_session: &'a ParseSess,
369                         config: &'a Config,
370                         mode: Option<WriteMode>)
371                         -> FmtVisitor<'a> {
372         FmtVisitor {
373             parse_session: parse_session,
374             codemap: parse_session.codemap(),
375             buffer: StringBuffer::new(),
376             last_pos: BytePos(0),
377             block_indent: Indent {
378                 block_indent: 0,
379                 alignment: 0,
380             },
381             config: config,
382             write_mode: mode,
383         }
384     }
385
386     pub fn snippet(&self, span: Span) -> String {
387         match self.codemap.span_to_snippet(span) {
388             Ok(s) => s,
389             Err(_) => {
390                 println!("Couldn't make snippet for span {:?}->{:?}",
391                          self.codemap.lookup_char_pos(span.lo),
392                          self.codemap.lookup_char_pos(span.hi));
393                 "".to_owned()
394             }
395         }
396     }
397
398     // Returns true if we should skip the following item.
399     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
400         if attrs.is_empty() {
401             return false;
402         }
403
404         if utils::contains_skip(attrs) {
405             return true;
406         }
407
408         let outers: Vec<_> = attrs.iter()
409                                   .filter(|a| a.node.style == ast::AttrStyle::Outer)
410                                   .map(|a| a.clone())
411                                   .collect();
412         if outers.is_empty() {
413             return false;
414         }
415
416         let first = &outers[0];
417         self.format_missing_with_indent(first.span.lo);
418
419         let rewrite = outers.rewrite(&self.get_context(),
420                                      self.config.max_width - self.block_indent.width(),
421                                      self.block_indent)
422                             .unwrap();
423         self.buffer.push_str(&rewrite);
424         let last = outers.last().unwrap();
425         self.last_pos = last.span.hi;
426         false
427     }
428
429     fn walk_mod_items(&mut self, m: &ast::Mod) {
430         for item in &m.items {
431             self.visit_item(&item);
432         }
433     }
434
435     fn format_mod(&mut self, m: &ast::Mod, s: Span, ident: ast::Ident) {
436         debug!("FmtVisitor::format_mod: ident: {:?}, span: {:?}", ident, s);
437
438         // Decide whether this is an inline mod or an external mod.
439         let local_file_name = self.codemap.span_to_filename(s);
440         let is_internal = local_file_name == self.codemap.span_to_filename(m.inner);
441
442         // TODO: Should rewrite properly `mod X;`
443
444         if is_internal {
445             self.block_indent = self.block_indent.block_indent(self.config);
446             self.walk_mod_items(m);
447             self.block_indent = self.block_indent.block_unindent(self.config);
448
449             self.format_missing_with_indent(m.inner.hi - BytePos(1));
450             self.buffer.push_str("}");
451             self.last_pos = m.inner.hi;
452         }
453     }
454
455     pub fn format_separate_mod(&mut self, m: &ast::Mod, filename: &str) {
456         let filemap = self.codemap.get_filemap(filename);
457         self.last_pos = filemap.start_pos;
458         self.block_indent = Indent::empty();
459         self.walk_mod_items(m);
460         self.format_missing(filemap.end_pos);
461     }
462
463     fn format_import(&mut self, vis: ast::Visibility, vp: &ast::ViewPath, span: Span) {
464         let vis = utils::format_visibility(vis);
465         let mut offset = self.block_indent;
466         offset.alignment += vis.len() + "use ".len();
467         // 1 = ";"
468         match vp.rewrite(&self.get_context(),
469                          self.config.max_width - offset.width() - 1,
470                          offset) {
471             Some(ref s) if s.is_empty() => {
472                 // Format up to last newline
473                 let prev_span = codemap::mk_sp(self.last_pos, span.lo);
474                 let span_end = match self.snippet(prev_span).rfind('\n') {
475                     Some(offset) => self.last_pos + BytePos(offset as u32),
476                     None => span.lo,
477                 };
478                 self.format_missing(span_end);
479                 self.last_pos = span.hi;
480             }
481             Some(ref s) => {
482                 let s = format!("{}use {};", vis, s);
483                 self.format_missing_with_indent(span.lo);
484                 self.buffer.push_str(&s);
485                 self.last_pos = span.hi;
486             }
487             None => {
488                 self.format_missing_with_indent(span.lo);
489                 self.format_missing(span.hi);
490             }
491         }
492     }
493
494     pub fn get_context(&self) -> RewriteContext {
495         RewriteContext {
496             parse_session: self.parse_session,
497             codemap: self.codemap,
498             config: self.config,
499             block_indent: self.block_indent,
500         }
501     }
502 }
503
504 impl<'a> Rewrite for [ast::Attribute] {
505     fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
506         let mut result = String::new();
507         if self.is_empty() {
508             return Some(result);
509         }
510         let indent = offset.to_string(context.config);
511
512         for (i, a) in self.iter().enumerate() {
513             let a_str = context.snippet(a.span);
514
515             if i > 0 {
516                 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
517                 // This particular horror show is to preserve line breaks in between doc
518                 // comments. An alternative would be to force such line breaks to start
519                 // with the usual doc comment token.
520                 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
521                 let comment = comment.trim();
522                 if !comment.is_empty() {
523                     let comment = try_opt!(rewrite_comment(comment,
524                                                            false,
525                                                            context.config.max_width -
526                                                            offset.width(),
527                                                            offset,
528                                                            context.config));
529                     result.push_str(&indent);
530                     result.push_str(&comment);
531                     result.push('\n');
532                 } else if multi_line {
533                     result.push('\n');
534                 }
535                 result.push_str(&indent);
536             }
537
538             result.push_str(&a_str);
539
540             if i < self.len() - 1 {
541                 result.push('\n');
542             }
543         }
544
545         Some(result)
546     }
547 }