]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Merge pull request #668 from marcusklaas/regression-tests
[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, rewrite_type_alias, format_impl};
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     // FIXME: use an RAII util or closure 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.starts_with("{") || snippet.starts_with("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         // FIXME: we should compress any newlines here to just one
103         self.format_missing_with_indent(b.span.hi - brace_compensation);
104         self.close_block();
105         self.last_pos = b.span.hi;
106     }
107
108     // FIXME: this is a terrible hack to indent the comments between the last
109     // item in the block and the closing brace to the block's level.
110     // The closing brace itself, however, should be indented at a shallower
111     // level.
112     fn close_block(&mut self) {
113         let total_len = self.buffer.len;
114         let chars_too_many = if self.config.hard_tabs {
115             1
116         } else {
117             self.config.tab_spaces
118         };
119         self.buffer.truncate(total_len - chars_too_many);
120         self.buffer.push_str("}");
121         self.block_indent = self.block_indent.block_unindent(self.config);
122     }
123
124     // Note that this only gets called for function definitions. Required methods
125     // on traits do not get handled here.
126     fn visit_fn(&mut self,
127                 fk: visit::FnKind,
128                 fd: &ast::FnDecl,
129                 b: &ast::Block,
130                 s: Span,
131                 _: ast::NodeId) {
132         let indent = self.block_indent;
133         let rewrite = match fk {
134             visit::FnKind::ItemFn(ident, ref generics, unsafety, constness, abi, vis) => {
135                 self.rewrite_fn(indent,
136                                 ident,
137                                 fd,
138                                 None,
139                                 generics,
140                                 unsafety,
141                                 constness,
142                                 abi,
143                                 vis,
144                                 codemap::mk_sp(s.lo, b.span.lo),
145                                 &b)
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                                 &b)
159             }
160             visit::FnKind::Closure => None,
161         };
162
163         if let Some(fn_str) = rewrite {
164             self.format_missing_with_indent(s.lo);
165             self.buffer.push_str(&fn_str);
166             if let Some(c) = fn_str.chars().last() {
167                 if c == '}' {
168                     self.last_pos = b.span.hi;
169                     return;
170                 }
171             }
172         } else {
173             self.format_missing(b.span.lo);
174         }
175
176         self.last_pos = b.span.lo;
177         self.visit_block(b)
178     }
179
180     fn visit_item(&mut self, item: &ast::Item) {
181         // Don't look at attributes for modules (except for rustfmt_skip).
182         // We want to avoid looking at attributes in another file, which the AST
183         // doesn't distinguish.
184         // FIXME This is overly conservative and means we miss attributes on
185         // inline modules.
186         match item.node {
187             ast::Item_::ItemMod(_) => {
188                 if utils::contains_skip(&item.attrs) {
189                     return;
190                 }
191             }
192             _ => {
193                 if self.visit_attrs(&item.attrs) {
194                     return;
195                 }
196             }
197         }
198
199         match item.node {
200             ast::Item_::ItemUse(ref vp) => {
201                 self.format_import(item.vis, vp, item.span);
202             }
203             ast::Item_::ItemImpl(..) => {
204                 self.format_missing_with_indent(item.span.lo);
205                 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
206                     self.buffer.push_str(&impl_str);
207                     self.last_pos = item.span.hi;
208                 }
209             }
210             // FIXME(#78): format traits.
211             ast::Item_::ItemTrait(_, _, _, ref trait_items) => {
212                 self.format_missing_with_indent(item.span.lo);
213                 self.block_indent = self.block_indent.block_indent(self.config);
214                 for item in trait_items {
215                     self.visit_trait_item(&item);
216                 }
217                 self.block_indent = self.block_indent.block_unindent(self.config);
218             }
219             ast::Item_::ItemExternCrate(_) => {
220                 self.format_missing_with_indent(item.span.lo);
221                 let new_str = self.snippet(item.span);
222                 self.buffer.push_str(&new_str);
223                 self.last_pos = item.span.hi;
224             }
225             ast::Item_::ItemStruct(ref def, ref generics) => {
226                 let rewrite = {
227                     let indent = self.block_indent;
228                     let context = self.get_context();
229                     ::items::format_struct(&context,
230                                            "struct ",
231                                            item.ident,
232                                            item.vis,
233                                            def,
234                                            Some(generics),
235                                            item.span,
236                                            indent)
237                         .map(|s| {
238                             match *def {
239                                 ast::VariantData::Tuple(..) => s + ";",
240                                 _ => s,
241                             }
242                         })
243                 };
244                 self.push_rewrite(item.span, rewrite);
245             }
246             ast::Item_::ItemEnum(ref def, ref generics) => {
247                 self.format_missing_with_indent(item.span.lo);
248                 self.visit_enum(item.ident, item.vis, def, generics, item.span);
249                 self.last_pos = item.span.hi;
250             }
251             ast::Item_::ItemMod(ref module) => {
252                 self.format_missing_with_indent(item.span.lo);
253                 self.format_mod(module, item.vis, item.span, item.ident);
254             }
255             ast::Item_::ItemMac(..) => {
256                 self.format_missing_with_indent(item.span.lo);
257                 let snippet = self.snippet(item.span);
258                 self.buffer.push_str(&snippet);
259                 self.last_pos = item.span.hi;
260                 // FIXME: we cannot format these yet, because of a bad span.
261                 // See rust lang issue #28424.
262             }
263             ast::Item_::ItemForeignMod(ref foreign_mod) => {
264                 self.format_missing_with_indent(item.span.lo);
265                 self.format_foreign_mod(foreign_mod, item.span);
266             }
267             ast::Item_::ItemStatic(ref ty, mutability, ref expr) => {
268                 let rewrite = rewrite_static("static",
269                                              item.vis,
270                                              item.ident,
271                                              ty,
272                                              mutability,
273                                              expr,
274                                              &self.get_context());
275                 self.push_rewrite(item.span, rewrite);
276             }
277             ast::Item_::ItemConst(ref ty, ref expr) => {
278                 let rewrite = rewrite_static("const",
279                                              item.vis,
280                                              item.ident,
281                                              ty,
282                                              ast::Mutability::MutImmutable,
283                                              expr,
284                                              &self.get_context());
285                 self.push_rewrite(item.span, rewrite);
286             }
287             ast::Item_::ItemDefaultImpl(..) => {
288                 // FIXME(#78): format impl definitions.
289             }
290             ast::ItemFn(ref declaration, unsafety, constness, abi, ref generics, ref body) => {
291                 self.visit_fn(visit::FnKind::ItemFn(item.ident,
292                                                     generics,
293                                                     unsafety,
294                                                     constness,
295                                                     abi,
296                                                     item.vis),
297                               declaration,
298                               body,
299                               item.span,
300                               item.id)
301             }
302             ast::Item_::ItemTy(ref ty, ref generics) => {
303                 let rewrite = rewrite_type_alias(&self.get_context(),
304                                                  self.block_indent,
305                                                  item.ident,
306                                                  ty,
307                                                  generics,
308                                                  item.vis,
309                                                  item.span);
310                 self.push_rewrite(item.span, rewrite);
311             }
312         }
313     }
314
315     fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
316         if self.visit_attrs(&ti.attrs) {
317             return;
318         }
319
320         match ti.node {
321             ast::ConstTraitItem(..) => {
322                 // FIXME: Implement
323             }
324             ast::MethodTraitItem(ref sig, None) => {
325                 let indent = self.block_indent;
326                 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
327                 self.push_rewrite(ti.span, rewrite);
328             }
329             ast::MethodTraitItem(ref sig, Some(ref body)) => {
330                 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
331                               &sig.decl,
332                               &body,
333                               ti.span,
334                               ti.id);
335             }
336             ast::TypeTraitItem(..) => {
337                 // FIXME: Implement
338             }
339         }
340     }
341
342     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
343         if self.visit_attrs(&ii.attrs) {
344             return;
345         }
346
347         match ii.node {
348             ast::ImplItemKind::Method(ref sig, ref body) => {
349                 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(ii.vis)),
350                               &sig.decl,
351                               body,
352                               ii.span,
353                               ii.id);
354             }
355             ast::ImplItemKind::Const(..) => {
356                 // FIXME: Implement
357             }
358             ast::ImplItemKind::Type(_) => {
359                 // FIXME: Implement
360             }
361             ast::ImplItemKind::Macro(ref mac) => {
362                 self.visit_mac(mac);
363             }
364         }
365     }
366
367     fn visit_mac(&mut self, mac: &ast::Mac) {
368         // 1 = ;
369         let width = self.config.max_width - self.block_indent.width() - 1;
370         let rewrite = rewrite_macro(mac, &self.get_context(), width, self.block_indent);
371
372         if let Some(res) = rewrite {
373             self.buffer.push_str(&res);
374             self.last_pos = mac.span.hi;
375         }
376     }
377
378     fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
379         self.format_missing_with_indent(span.lo);
380
381         if let Some(res) = rewrite {
382             self.buffer.push_str(&res);
383             self.last_pos = span.hi;
384         }
385     }
386
387     pub fn from_codemap(parse_session: &'a ParseSess,
388                         config: &'a Config,
389                         mode: Option<WriteMode>)
390                         -> FmtVisitor<'a> {
391         FmtVisitor {
392             parse_session: parse_session,
393             codemap: parse_session.codemap(),
394             buffer: StringBuffer::new(),
395             last_pos: BytePos(0),
396             block_indent: Indent {
397                 block_indent: 0,
398                 alignment: 0,
399             },
400             config: config,
401             write_mode: mode,
402         }
403     }
404
405     pub fn snippet(&self, span: Span) -> String {
406         match self.codemap.span_to_snippet(span) {
407             Ok(s) => s,
408             Err(_) => {
409                 println!("Couldn't make snippet for span {:?}->{:?}",
410                          self.codemap.lookup_char_pos(span.lo),
411                          self.codemap.lookup_char_pos(span.hi));
412                 "".to_owned()
413             }
414         }
415     }
416
417     // Returns true if we should skip the following item.
418     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
419         if utils::contains_skip(attrs) {
420             return true;
421         }
422
423         let outers: Vec<_> = attrs.iter()
424                                   .filter(|a| a.node.style == ast::AttrStyle::Outer)
425                                   .cloned()
426                                   .collect();
427         if outers.is_empty() {
428             return false;
429         }
430
431         let first = &outers[0];
432         self.format_missing_with_indent(first.span.lo);
433
434         let rewrite = outers.rewrite(&self.get_context(),
435                                      self.config.max_width - self.block_indent.width(),
436                                      self.block_indent)
437                             .unwrap();
438         self.buffer.push_str(&rewrite);
439         let last = outers.last().unwrap();
440         self.last_pos = last.span.hi;
441         false
442     }
443
444     fn walk_mod_items(&mut self, m: &ast::Mod) {
445         for item in &m.items {
446             self.visit_item(&item);
447         }
448     }
449
450     fn format_mod(&mut self, m: &ast::Mod, vis: ast::Visibility, s: Span, ident: ast::Ident) {
451         // Decide whether this is an inline mod or an external mod.
452         let local_file_name = self.codemap.span_to_filename(s);
453         let is_internal = local_file_name == self.codemap.span_to_filename(m.inner);
454
455         self.buffer.push_str(utils::format_visibility(vis));
456         self.buffer.push_str("mod ");
457         self.buffer.push_str(&ident.to_string());
458
459         if is_internal {
460             self.buffer.push_str(" {");
461             self.last_pos = ::utils::span_after(s, "{", self.codemap);
462             self.block_indent = self.block_indent.block_indent(self.config);
463             self.walk_mod_items(m);
464             self.format_missing_with_indent(m.inner.hi - BytePos(1));
465             self.close_block();
466             self.last_pos = m.inner.hi;
467         } else {
468             self.buffer.push_str(";");
469             self.last_pos = s.hi;
470         }
471     }
472
473     pub fn format_separate_mod(&mut self, m: &ast::Mod) {
474         let filemap = self.codemap.lookup_char_pos(m.inner.lo).file;
475         self.last_pos = filemap.start_pos;
476         self.block_indent = Indent::empty();
477         self.walk_mod_items(m);
478         self.format_missing(filemap.end_pos);
479     }
480
481     fn format_import(&mut self, vis: ast::Visibility, vp: &ast::ViewPath, span: Span) {
482         let vis = utils::format_visibility(vis);
483         let mut offset = self.block_indent;
484         offset.alignment += vis.len() + "use ".len();
485         // 1 = ";"
486         match vp.rewrite(&self.get_context(),
487                          self.config.max_width - offset.width() - 1,
488                          offset) {
489             Some(ref s) if s.is_empty() => {
490                 // Format up to last newline
491                 let prev_span = codemap::mk_sp(self.last_pos, span.lo);
492                 let span_end = match self.snippet(prev_span).rfind('\n') {
493                     Some(offset) => self.last_pos + BytePos(offset as u32),
494                     None => span.lo,
495                 };
496                 self.format_missing(span_end);
497                 self.last_pos = span.hi;
498             }
499             Some(ref s) => {
500                 let s = format!("{}use {};", vis, s);
501                 self.format_missing_with_indent(span.lo);
502                 self.buffer.push_str(&s);
503                 self.last_pos = span.hi;
504             }
505             None => {
506                 self.format_missing_with_indent(span.lo);
507                 self.format_missing(span.hi);
508             }
509         }
510     }
511
512     pub fn get_context(&self) -> RewriteContext {
513         RewriteContext {
514             parse_session: self.parse_session,
515             codemap: self.codemap,
516             config: self.config,
517             block_indent: self.block_indent,
518         }
519     }
520 }
521
522 impl<'a> Rewrite for [ast::Attribute] {
523     fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
524         let mut result = String::new();
525         if self.is_empty() {
526             return Some(result);
527         }
528         let indent = offset.to_string(context.config);
529
530         for (i, a) in self.iter().enumerate() {
531             let a_str = context.snippet(a.span);
532
533             if i > 0 {
534                 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
535                 // This particular horror show is to preserve line breaks in between doc
536                 // comments. An alternative would be to force such line breaks to start
537                 // with the usual doc comment token.
538                 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
539                 let comment = comment.trim();
540                 if !comment.is_empty() {
541                     let comment = try_opt!(rewrite_comment(comment,
542                                                            false,
543                                                            context.config.max_width -
544                                                            offset.width(),
545                                                            offset,
546                                                            context.config));
547                     result.push_str(&indent);
548                     result.push_str(&comment);
549                     result.push('\n');
550                 } else if multi_line {
551                     result.push('\n');
552                 }
553                 result.push_str(&indent);
554             }
555
556             result.push_str(&a_str);
557
558             if i < self.len() - 1 {
559                 result.push('\n');
560             }
561         }
562
563         Some(result)
564     }
565 }