]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Added 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;
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_associated_static, rewrite_associated_type,
25             rewrite_type_alias, format_impl, format_trait};
26
27 pub struct FmtVisitor<'a> {
28     pub parse_session: &'a ParseSess,
29     pub codemap: &'a CodeMap,
30     pub buffer: StringBuffer,
31     pub last_pos: BytePos,
32     // FIXME: use an RAII util or closure for indenting
33     pub block_indent: Indent,
34     pub config: &'a Config,
35 }
36
37 impl<'a> FmtVisitor<'a> {
38     fn visit_stmt(&mut self, stmt: &ast::Stmt) {
39         match stmt.node {
40             ast::StmtKind::Decl(ref decl, _) => {
41                 if let ast::DeclKind::Item(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::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
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::StmtKind::Mac(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::ItemKind::Mod(_) => {
188                 if utils::contains_skip(&item.attrs) {
189                     return;
190                 }
191             }
192             _ => {
193                 if self.visit_attrs(&item.attrs) {
194                     self.push_rewrite(item.span, None);
195                     return;
196                 }
197             }
198         }
199
200         match item.node {
201             ast::ItemKind::Use(ref vp) => {
202                 self.format_import(item.vis, vp, item.span);
203             }
204             ast::ItemKind::Impl(..) => {
205                 self.format_missing_with_indent(item.span.lo);
206                 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
207                     self.buffer.push_str(&impl_str);
208                     self.last_pos = item.span.hi;
209                 }
210             }
211             ast::ItemKind::Trait(..) => {
212                 self.format_missing_with_indent(item.span.lo);
213                 if let Some(trait_str) = format_trait(&self.get_context(),
214                                                       item,
215                                                       self.block_indent) {
216                     self.buffer.push_str(&trait_str);
217                     self.last_pos = item.span.hi;
218                 }
219             }
220             ast::ItemKind::ExternCrate(_) => {
221                 self.format_missing_with_indent(item.span.lo);
222                 let new_str = self.snippet(item.span);
223                 self.buffer.push_str(&new_str);
224                 self.last_pos = item.span.hi;
225             }
226             ast::ItemKind::Struct(ref def, ref generics) => {
227                 let rewrite = {
228                     let indent = self.block_indent;
229                     let context = self.get_context();
230                     ::items::format_struct(&context,
231                                            "struct ",
232                                            item.ident,
233                                            item.vis,
234                                            def,
235                                            Some(generics),
236                                            item.span,
237                                            indent)
238                         .map(|s| {
239                             match *def {
240                                 ast::VariantData::Tuple(..) => s + ";",
241                                 _ => s,
242                             }
243                         })
244                 };
245                 self.push_rewrite(item.span, rewrite);
246             }
247             ast::ItemKind::Enum(ref def, ref generics) => {
248                 self.format_missing_with_indent(item.span.lo);
249                 self.visit_enum(item.ident, item.vis, def, generics, item.span);
250                 self.last_pos = item.span.hi;
251             }
252             ast::ItemKind::Mod(ref module) => {
253                 self.format_missing_with_indent(item.span.lo);
254                 self.format_mod(module, item.vis, item.span, item.ident);
255             }
256             ast::ItemKind::Mac(ref mac) => {
257                 self.format_missing_with_indent(item.span.lo);
258                 self.visit_mac(mac);
259             }
260             ast::ItemKind::ForeignMod(ref foreign_mod) => {
261                 self.format_missing_with_indent(item.span.lo);
262                 self.format_foreign_mod(foreign_mod, item.span);
263             }
264             ast::ItemKind::Static(ref ty, mutability, ref expr) => {
265                 let rewrite = rewrite_static("static",
266                                              item.vis,
267                                              item.ident,
268                                              ty,
269                                              mutability,
270                                              expr,
271                                              &self.get_context());
272                 self.push_rewrite(item.span, rewrite);
273             }
274             ast::ItemKind::Const(ref ty, ref expr) => {
275                 let rewrite = rewrite_static("const",
276                                              item.vis,
277                                              item.ident,
278                                              ty,
279                                              ast::Mutability::Immutable,
280                                              expr,
281                                              &self.get_context());
282                 self.push_rewrite(item.span, rewrite);
283             }
284             ast::ItemKind::DefaultImpl(..) => {
285                 // FIXME(#78): format impl definitions.
286             }
287             ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
288                 self.visit_fn(visit::FnKind::ItemFn(item.ident,
289                                                     generics,
290                                                     unsafety,
291                                                     constness,
292                                                     abi,
293                                                     item.vis),
294                               decl,
295                               body,
296                               item.span,
297                               item.id)
298             }
299             ast::ItemKind::Ty(ref ty, ref generics) => {
300                 let rewrite = rewrite_type_alias(&self.get_context(),
301                                                  self.block_indent,
302                                                  item.ident,
303                                                  ty,
304                                                  generics,
305                                                  item.vis,
306                                                  item.span);
307                 self.push_rewrite(item.span, rewrite);
308             }
309         }
310     }
311
312     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
313         if self.visit_attrs(&ti.attrs) {
314             return;
315         }
316
317         match ti.node {
318             ast::TraitItemKind::Const(ref ty, ref expr) => {
319                 let rewrite = rewrite_associated_static("const",
320                                                         ast::Visibility::Inherited,
321                                                         ti.ident,
322                                                         ty,
323                                                         ast::Mutability::Immutable,
324                                                         expr,
325                                                         &self.get_context());
326                 self.push_rewrite(ti.span, rewrite);
327             }
328             ast::TraitItemKind::Method(ref sig, None) => {
329                 let indent = self.block_indent;
330                 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
331                 self.push_rewrite(ti.span, rewrite);
332             }
333             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
334                 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
335                               &sig.decl,
336                               &body,
337                               ti.span,
338                               ti.id);
339             }
340             ast::TraitItemKind::Type(ref type_param_bounds, _) => {
341                 let rewrite = rewrite_associated_type("type",
342                                                       ti.ident,
343                                                       None,
344                                                       Some(type_param_bounds),
345                                                       &self.get_context(),
346                                                       self.block_indent);
347                 self.push_rewrite(ti.span, rewrite);
348             }
349         }
350     }
351
352     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
353         if self.visit_attrs(&ii.attrs) {
354             return;
355         }
356
357         match ii.node {
358             ast::ImplItemKind::Method(ref sig, ref body) => {
359                 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(ii.vis)),
360                               &sig.decl,
361                               body,
362                               ii.span,
363                               ii.id);
364             }
365             ast::ImplItemKind::Const(ref ty, ref expr) => {
366                 let rewrite = rewrite_static("const",
367                                              ast::Visibility::Inherited,
368                                              ii.ident,
369                                              ty,
370                                              ast::Mutability::Immutable,
371                                              &expr,
372                                              &self.get_context());
373                 self.push_rewrite(ii.span, rewrite);
374             }
375             ast::ImplItemKind::Type(ref ty) => {
376                 let rewrite = rewrite_associated_type("type",
377                                                       ii.ident,
378                                                       Some(ty),
379                                                       None,
380                                                       &self.get_context(),
381                                                       self.block_indent);
382                 self.push_rewrite(ii.span, rewrite);
383             }
384             ast::ImplItemKind::Macro(ref mac) => {
385                 self.format_missing_with_indent(ii.span.lo);
386                 self.visit_mac(mac);
387             }
388         }
389     }
390
391     fn visit_mac(&mut self, mac: &ast::Mac) {
392         // 1 = ;
393         let width = self.config.max_width - self.block_indent.width() - 1;
394         let rewrite = rewrite_macro(mac, &self.get_context(), width, self.block_indent);
395
396         if let Some(res) = rewrite {
397             self.buffer.push_str(&res);
398             self.last_pos = mac.span.hi;
399         }
400     }
401
402     fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
403         self.format_missing_with_indent(span.lo);
404         let result = rewrite.unwrap_or_else(|| self.snippet(span));
405         self.buffer.push_str(&result);
406         self.last_pos = span.hi;
407     }
408
409     pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
410         FmtVisitor {
411             parse_session: parse_session,
412             codemap: parse_session.codemap(),
413             buffer: StringBuffer::new(),
414             last_pos: BytePos(0),
415             block_indent: Indent {
416                 block_indent: 0,
417                 alignment: 0,
418             },
419             config: config,
420         }
421     }
422
423     pub fn snippet(&self, span: Span) -> String {
424         match self.codemap.span_to_snippet(span) {
425             Ok(s) => s,
426             Err(_) => {
427                 println!("Couldn't make snippet for span {:?}->{:?}",
428                          self.codemap.lookup_char_pos(span.lo),
429                          self.codemap.lookup_char_pos(span.hi));
430                 "".to_owned()
431             }
432         }
433     }
434
435     // Returns true if we should skip the following item.
436     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
437         if utils::contains_skip(attrs) {
438             return true;
439         }
440
441         let outers: Vec<_> = attrs.iter()
442                                   .filter(|a| a.node.style == ast::AttrStyle::Outer)
443                                   .cloned()
444                                   .collect();
445         if outers.is_empty() {
446             return false;
447         }
448
449         let first = &outers[0];
450         self.format_missing_with_indent(first.span.lo);
451
452         let rewrite = outers.rewrite(&self.get_context(),
453                                      self.config.max_width - self.block_indent.width(),
454                                      self.block_indent)
455                             .unwrap();
456         self.buffer.push_str(&rewrite);
457         let last = outers.last().unwrap();
458         self.last_pos = last.span.hi;
459         false
460     }
461
462     fn walk_mod_items(&mut self, m: &ast::Mod) {
463         for item in &m.items {
464             self.visit_item(&item);
465         }
466     }
467
468     fn format_mod(&mut self, m: &ast::Mod, vis: ast::Visibility, s: Span, ident: ast::Ident) {
469         // Decide whether this is an inline mod or an external mod.
470         let local_file_name = self.codemap.span_to_filename(s);
471         let is_internal = local_file_name == self.codemap.span_to_filename(m.inner);
472
473         self.buffer.push_str(utils::format_visibility(vis));
474         self.buffer.push_str("mod ");
475         self.buffer.push_str(&ident.to_string());
476
477         if is_internal {
478             self.buffer.push_str(" {");
479             // Hackery to account for the closing }.
480             let mod_lo = ::utils::span_after(s, "{", self.codemap);
481             let body_snippet = self.snippet(codemap::mk_sp(mod_lo, m.inner.hi - BytePos(1)));
482             let body_snippet = body_snippet.trim();
483             if body_snippet.is_empty() {
484                 self.buffer.push_str("}");
485             } else {
486                 self.last_pos = mod_lo;
487                 self.block_indent = self.block_indent.block_indent(self.config);
488                 self.walk_mod_items(m);
489                 self.format_missing_with_indent(m.inner.hi - BytePos(1));
490                 self.close_block();
491             }
492             self.last_pos = m.inner.hi;
493         } else {
494             self.buffer.push_str(";");
495             self.last_pos = s.hi;
496         }
497     }
498
499     pub fn format_separate_mod(&mut self, m: &ast::Mod) {
500         let filemap = self.codemap.lookup_char_pos(m.inner.lo).file;
501         self.last_pos = filemap.start_pos;
502         self.block_indent = Indent::empty();
503         self.walk_mod_items(m);
504         self.format_missing(filemap.end_pos);
505     }
506
507     fn format_import(&mut self, vis: ast::Visibility, vp: &ast::ViewPath, span: Span) {
508         let vis = utils::format_visibility(vis);
509         let mut offset = self.block_indent;
510         offset.alignment += vis.len() + "use ".len();
511         // 1 = ";"
512         match vp.rewrite(&self.get_context(),
513                          self.config.max_width - offset.width() - 1,
514                          offset) {
515             Some(ref s) if s.is_empty() => {
516                 // Format up to last newline
517                 let prev_span = codemap::mk_sp(self.last_pos, span.lo);
518                 let span_end = match self.snippet(prev_span).rfind('\n') {
519                     Some(offset) => self.last_pos + BytePos(offset as u32),
520                     None => span.lo,
521                 };
522                 self.format_missing(span_end);
523                 self.last_pos = span.hi;
524             }
525             Some(ref s) => {
526                 let s = format!("{}use {};", vis, s);
527                 self.format_missing_with_indent(span.lo);
528                 self.buffer.push_str(&s);
529                 self.last_pos = span.hi;
530             }
531             None => {
532                 self.format_missing_with_indent(span.lo);
533                 self.format_missing(span.hi);
534             }
535         }
536     }
537
538     pub fn get_context(&self) -> RewriteContext {
539         RewriteContext {
540             parse_session: self.parse_session,
541             codemap: self.codemap,
542             config: self.config,
543             block_indent: self.block_indent,
544         }
545     }
546 }
547
548 impl<'a> Rewrite for [ast::Attribute] {
549     fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
550         let mut result = String::new();
551         if self.is_empty() {
552             return Some(result);
553         }
554         let indent = offset.to_string(context.config);
555
556         for (i, a) in self.iter().enumerate() {
557             let a_str = context.snippet(a.span);
558
559             // Write comments and blank lines between attributes.
560             if i > 0 {
561                 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
562                 // This particular horror show is to preserve line breaks in between doc
563                 // comments. An alternative would be to force such line breaks to start
564                 // with the usual doc comment token.
565                 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
566                 let comment = comment.trim();
567                 if !comment.is_empty() {
568                     let comment = try_opt!(rewrite_comment(comment,
569                                                            false,
570                                                            context.config.max_width -
571                                                            offset.width(),
572                                                            offset,
573                                                            context.config));
574                     result.push_str(&indent);
575                     result.push_str(&comment);
576                     result.push('\n');
577                 } else if multi_line {
578                     result.push('\n');
579                 }
580                 result.push_str(&indent);
581             }
582
583             // Write the attribute itself.
584             result.push_str(&a_str);
585
586             if i < self.len() - 1 {
587                 result.push('\n');
588             }
589         }
590
591         Some(result)
592     }
593 }