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