]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Merge pull request #2014 from topecongiro/fn-sig
[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 std::cmp;
12
13 use strings::string_buffer::StringBuffer;
14 use syntax::{ast, visit};
15 use syntax::attr::HasAttrs;
16 use syntax::codemap::{self, BytePos, CodeMap, Pos, Span};
17 use syntax::parse::ParseSess;
18
19 use spanned::Spanned;
20 use codemap::{LineRangeUtils, SpanUtils};
21 use comment::{contains_comment, recover_missing_comment_in_span, CodeCharKind, CommentCodeSlices,
22               FindUncommented};
23 use comment::rewrite_comment;
24 use config::{BraceStyle, Config};
25 use items::{format_impl, format_struct, format_struct_struct, format_trait,
26             rewrite_associated_impl_type, rewrite_associated_type, rewrite_static,
27             rewrite_type_alias, FnSig};
28 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
29             SeparatorTactic};
30 use macros::{rewrite_macro, MacroPosition};
31 use regex::Regex;
32 use rewrite::{Rewrite, RewriteContext};
33 use shape::{Indent, Shape};
34 use utils::{self, contains_skip, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
35
36 fn is_use_item(item: &ast::Item) -> bool {
37     match item.node {
38         ast::ItemKind::Use(_) => true,
39         _ => false,
40     }
41 }
42
43 fn is_extern_crate(item: &ast::Item) -> bool {
44     match item.node {
45         ast::ItemKind::ExternCrate(..) => true,
46         _ => false,
47     }
48 }
49
50 pub struct FmtVisitor<'a> {
51     pub parse_session: &'a ParseSess,
52     pub codemap: &'a CodeMap,
53     pub buffer: StringBuffer,
54     pub last_pos: BytePos,
55     // FIXME: use an RAII util or closure for indenting
56     pub block_indent: Indent,
57     pub config: &'a Config,
58     pub is_if_else_block: bool,
59 }
60
61 impl<'a> FmtVisitor<'a> {
62     pub fn shape(&self) -> Shape {
63         Shape::indented(self.block_indent, self.config)
64     }
65
66     fn visit_stmt(&mut self, stmt: &ast::Stmt) {
67         debug!(
68             "visit_stmt: {:?} {:?}",
69             self.codemap.lookup_char_pos(stmt.span.lo()),
70             self.codemap.lookup_char_pos(stmt.span.hi())
71         );
72
73         match stmt.node {
74             ast::StmtKind::Item(ref item) => {
75                 self.visit_item(item);
76             }
77             ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
78                 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
79                 self.push_rewrite(stmt.span(), rewrite)
80             }
81             ast::StmtKind::Mac(ref mac) => {
82                 let (ref mac, _macro_style, ref attrs) = **mac;
83                 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
84                     self.push_rewrite(stmt.span(), None);
85                 } else {
86                     self.visit_mac(mac, None, MacroPosition::Statement);
87                 }
88                 self.format_missing(stmt.span.hi());
89             }
90         }
91     }
92
93     pub fn visit_block(&mut self, b: &ast::Block, inner_attrs: Option<&[ast::Attribute]>) {
94         debug!(
95             "visit_block: {:?} {:?}",
96             self.codemap.lookup_char_pos(b.span.lo()),
97             self.codemap.lookup_char_pos(b.span.hi())
98         );
99
100         // Check if this block has braces.
101         let snippet = self.snippet(b.span);
102         let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
103         let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
104
105         self.last_pos = self.last_pos + brace_compensation;
106         self.block_indent = self.block_indent.block_indent(self.config);
107         self.buffer.push_str("{");
108
109         if self.config.remove_blank_lines_at_start_or_end_of_block() {
110             if let Some(first_stmt) = b.stmts.first() {
111                 let attr_lo = inner_attrs
112                     .and_then(|attrs| {
113                         inner_attributes(attrs).first().map(|attr| attr.span.lo())
114                     })
115                     .or_else(|| {
116                         // Attributes for an item in a statement position
117                         // do not belong to the statement. (rust-lang/rust#34459)
118                         if let ast::StmtKind::Item(ref item) = first_stmt.node {
119                             item.attrs.first()
120                         } else {
121                             first_stmt.attrs().first()
122                         }.and_then(|attr| {
123                             // Some stmts can have embedded attributes.
124                             // e.g. `match { #![attr] ... }`
125                             let attr_lo = attr.span.lo();
126                             if attr_lo < first_stmt.span.lo() {
127                                 Some(attr_lo)
128                             } else {
129                                 None
130                             }
131                         })
132                     });
133
134                 let snippet = self.snippet(mk_sp(
135                     self.last_pos,
136                     attr_lo.unwrap_or(first_stmt.span.lo()),
137                 ));
138                 let len = CommentCodeSlices::new(&snippet).nth(0).and_then(
139                     |(kind, _, s)| if kind == CodeCharKind::Normal {
140                         s.rfind('\n')
141                     } else {
142                         None
143                     },
144                 );
145                 if let Some(len) = len {
146                     self.last_pos = self.last_pos + BytePos::from_usize(len);
147                 }
148             }
149         }
150
151         // Format inner attributes if available.
152         if let Some(attrs) = inner_attrs {
153             self.visit_attrs(attrs, ast::AttrStyle::Inner);
154         }
155
156         self.walk_block_stmts(b);
157
158         if !b.stmts.is_empty() {
159             if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
160                 if utils::semicolon_for_expr(&self.get_context(), expr) {
161                     self.buffer.push_str(";");
162                 }
163             }
164         }
165
166         let mut remove_len = BytePos(0);
167         if self.config.remove_blank_lines_at_start_or_end_of_block() {
168             if let Some(stmt) = b.stmts.last() {
169                 let snippet = self.snippet(mk_sp(
170                     stmt.span.hi(),
171                     source!(self, b.span).hi() - brace_compensation,
172                 ));
173                 let len = CommentCodeSlices::new(&snippet)
174                     .last()
175                     .and_then(|(kind, _, s)| {
176                         if kind == CodeCharKind::Normal && s.trim().is_empty() {
177                             Some(s.len())
178                         } else {
179                             None
180                         }
181                     });
182                 if let Some(len) = len {
183                     remove_len = BytePos::from_usize(len);
184                 }
185             }
186         }
187
188         let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
189         if unindent_comment {
190             let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
191             let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
192             unindent_comment = snippet.contains("//") || snippet.contains("/*");
193         }
194         // FIXME: we should compress any newlines here to just one
195         if unindent_comment {
196             self.block_indent = self.block_indent.block_unindent(self.config);
197         }
198         self.format_missing_with_indent(
199             source!(self, b.span).hi() - brace_compensation - remove_len,
200         );
201         if unindent_comment {
202             self.block_indent = self.block_indent.block_indent(self.config);
203         }
204         self.close_block(unindent_comment);
205         self.last_pos = source!(self, b.span).hi();
206     }
207
208     // FIXME: this is a terrible hack to indent the comments between the last
209     // item in the block and the closing brace to the block's level.
210     // The closing brace itself, however, should be indented at a shallower
211     // level.
212     fn close_block(&mut self, unindent_comment: bool) {
213         let total_len = self.buffer.len;
214         let chars_too_many = if unindent_comment {
215             0
216         } else if self.config.hard_tabs() {
217             1
218         } else {
219             self.config.tab_spaces()
220         };
221         self.buffer.truncate(total_len - chars_too_many);
222         self.buffer.push_str("}");
223         self.block_indent = self.block_indent.block_unindent(self.config);
224     }
225
226     // Note that this only gets called for function definitions. Required methods
227     // on traits do not get handled here.
228     fn visit_fn(
229         &mut self,
230         fk: visit::FnKind,
231         fd: &ast::FnDecl,
232         s: Span,
233         _: ast::NodeId,
234         defaultness: ast::Defaultness,
235         inner_attrs: Option<&[ast::Attribute]>,
236     ) {
237         let indent = self.block_indent;
238         let block;
239         let rewrite = match fk {
240             visit::FnKind::ItemFn(ident, _, _, _, _, _, b) => {
241                 block = b;
242                 self.rewrite_fn(
243                     indent,
244                     ident,
245                     &FnSig::from_fn_kind(&fk, fd, defaultness),
246                     mk_sp(s.lo(), b.span.lo()),
247                     b,
248                 )
249             }
250             visit::FnKind::Method(ident, _, _, b) => {
251                 block = b;
252                 self.rewrite_fn(
253                     indent,
254                     ident,
255                     &FnSig::from_fn_kind(&fk, fd, defaultness),
256                     mk_sp(s.lo(), b.span.lo()),
257                     b,
258                 )
259             }
260             visit::FnKind::Closure(_) => unreachable!(),
261         };
262
263         if let Some(fn_str) = rewrite {
264             self.format_missing_with_indent(source!(self, s).lo());
265             self.buffer.push_str(&fn_str);
266             if let Some(c) = fn_str.chars().last() {
267                 if c == '}' {
268                     self.last_pos = source!(self, block.span).hi();
269                     return;
270                 }
271             }
272         } else {
273             self.format_missing(source!(self, block.span).lo());
274         }
275
276         self.last_pos = source!(self, block.span).lo();
277         self.visit_block(block, inner_attrs)
278     }
279
280     pub fn visit_item(&mut self, item: &ast::Item) {
281         skip_out_of_file_lines_range_visitor!(self, item.span);
282
283         // This is where we bail out if there is a skip attribute. This is only
284         // complex in the module case. It is complex because the module could be
285         // in a separate file and there might be attributes in both files, but
286         // the AST lumps them all together.
287         let filterd_attrs;
288         let mut attrs = &item.attrs;
289         match item.node {
290             ast::ItemKind::Mod(ref m) => {
291                 let outer_file = self.codemap.lookup_char_pos(item.span.lo()).file;
292                 let inner_file = self.codemap.lookup_char_pos(m.inner.lo()).file;
293                 if outer_file.name == inner_file.name {
294                     // Module is inline, in this case we treat modules like any
295                     // other item.
296                     if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
297                         self.push_rewrite(item.span, None);
298                         return;
299                     }
300                 } else if contains_skip(&item.attrs) {
301                     // Module is not inline, but should be skipped.
302                     return;
303                 } else {
304                     // Module is not inline and should not be skipped. We want
305                     // to process only the attributes in the current file.
306                     filterd_attrs = item.attrs
307                         .iter()
308                         .filter_map(|a| {
309                             let attr_file = self.codemap.lookup_char_pos(a.span.lo()).file;
310                             if attr_file.name == outer_file.name {
311                                 Some(a.clone())
312                             } else {
313                                 None
314                             }
315                         })
316                         .collect::<Vec<_>>();
317                     // Assert because if we should skip it should be caught by
318                     // the above case.
319                     assert!(!self.visit_attrs(&filterd_attrs, ast::AttrStyle::Outer));
320                     attrs = &filterd_attrs;
321                 }
322             }
323             _ => if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
324                 self.push_rewrite(item.span, None);
325                 return;
326             },
327         }
328
329         match item.node {
330             ast::ItemKind::Use(ref vp) => self.format_import(item, vp),
331             ast::ItemKind::Impl(..) => {
332                 let snippet = self.snippet(item.span);
333                 let where_span_end = snippet
334                     .find_uncommented("{")
335                     .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
336                 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
337                 self.push_rewrite(item.span, rw);
338             }
339             ast::ItemKind::Trait(..) => {
340                 let rw = format_trait(&self.get_context(), item, self.block_indent);
341                 self.push_rewrite(item.span, rw);
342             }
343             ast::ItemKind::ExternCrate(_) => {
344                 let rw = rewrite_extern_crate(&self.get_context(), item);
345                 self.push_rewrite(item.span, rw);
346             }
347             ast::ItemKind::Struct(ref def, ref generics) => {
348                 let rewrite = format_struct(
349                     &self.get_context(),
350                     "struct ",
351                     item.ident,
352                     &item.vis,
353                     def,
354                     Some(generics),
355                     item.span,
356                     self.block_indent,
357                     None,
358                 ).map(|s| match *def {
359                     ast::VariantData::Tuple(..) => s + ";",
360                     _ => s,
361                 });
362                 self.push_rewrite(item.span, rewrite);
363             }
364             ast::ItemKind::Enum(ref def, ref generics) => {
365                 self.format_missing_with_indent(source!(self, item.span).lo());
366                 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
367                 self.last_pos = source!(self, item.span).hi();
368             }
369             ast::ItemKind::Mod(ref module) => {
370                 self.format_missing_with_indent(source!(self, item.span).lo());
371                 self.format_mod(module, &item.vis, item.span, item.ident, attrs);
372             }
373             ast::ItemKind::Mac(ref mac) => {
374                 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
375             }
376             ast::ItemKind::ForeignMod(ref foreign_mod) => {
377                 self.format_missing_with_indent(source!(self, item.span).lo());
378                 self.format_foreign_mod(foreign_mod, item.span);
379             }
380             ast::ItemKind::Static(ref ty, mutability, ref expr) => {
381                 let rewrite = rewrite_static(
382                     "static",
383                     &item.vis,
384                     item.ident,
385                     ty,
386                     mutability,
387                     Some(expr),
388                     self.block_indent,
389                     item.span,
390                     &self.get_context(),
391                 );
392                 self.push_rewrite(item.span, rewrite);
393             }
394             ast::ItemKind::Const(ref ty, ref expr) => {
395                 let rewrite = rewrite_static(
396                     "const",
397                     &item.vis,
398                     item.ident,
399                     ty,
400                     ast::Mutability::Immutable,
401                     Some(expr),
402                     self.block_indent,
403                     item.span,
404                     &self.get_context(),
405                 );
406                 self.push_rewrite(item.span, rewrite);
407             }
408             ast::ItemKind::DefaultImpl(..) => {
409                 // FIXME(#78): format impl definitions.
410             }
411             ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
412                 self.visit_fn(
413                     visit::FnKind::ItemFn(
414                         item.ident,
415                         generics,
416                         unsafety,
417                         constness,
418                         abi,
419                         &item.vis,
420                         body,
421                     ),
422                     decl,
423                     item.span,
424                     item.id,
425                     ast::Defaultness::Final,
426                     Some(&item.attrs),
427                 )
428             }
429             ast::ItemKind::Ty(ref ty, ref generics) => {
430                 let rewrite = rewrite_type_alias(
431                     &self.get_context(),
432                     self.block_indent,
433                     item.ident,
434                     ty,
435                     generics,
436                     &item.vis,
437                     item.span,
438                 );
439                 self.push_rewrite(item.span, rewrite);
440             }
441             ast::ItemKind::Union(ref def, ref generics) => {
442                 let rewrite = format_struct_struct(
443                     &self.get_context(),
444                     "union ",
445                     item.ident,
446                     &item.vis,
447                     def.fields(),
448                     Some(generics),
449                     item.span,
450                     self.block_indent,
451                     None,
452                 );
453                 self.push_rewrite(item.span, rewrite);
454             }
455             ast::ItemKind::GlobalAsm(..) => {
456                 let snippet = Some(self.snippet(item.span));
457                 self.push_rewrite(item.span, snippet);
458             }
459             ast::ItemKind::MacroDef(..) => {
460                 // FIXME(#1539): macros 2.0
461                 let mac_snippet = Some(self.snippet(item.span));
462                 self.push_rewrite(item.span, mac_snippet);
463             }
464         }
465     }
466
467     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
468         skip_out_of_file_lines_range_visitor!(self, ti.span);
469
470         if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
471             self.push_rewrite(ti.span, None);
472             return;
473         }
474
475         match ti.node {
476             ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
477                 let rewrite = rewrite_static(
478                     "const",
479                     &ast::Visibility::Inherited,
480                     ti.ident,
481                     ty,
482                     ast::Mutability::Immutable,
483                     expr_opt.as_ref(),
484                     self.block_indent,
485                     ti.span,
486                     &self.get_context(),
487                 );
488                 self.push_rewrite(ti.span, rewrite);
489             }
490             ast::TraitItemKind::Method(ref sig, None) => {
491                 let indent = self.block_indent;
492                 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
493                 self.push_rewrite(ti.span, rewrite);
494             }
495             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
496                 self.visit_fn(
497                     visit::FnKind::Method(ti.ident, sig, None, body),
498                     &sig.decl,
499                     ti.span,
500                     ti.id,
501                     ast::Defaultness::Final,
502                     Some(&ti.attrs),
503                 );
504             }
505             ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
506                 let rewrite = rewrite_associated_type(
507                     ti.ident,
508                     type_default.as_ref(),
509                     Some(type_param_bounds),
510                     &self.get_context(),
511                     self.block_indent,
512                 );
513                 self.push_rewrite(ti.span, rewrite);
514             }
515             ast::TraitItemKind::Macro(ref mac) => {
516                 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
517             }
518         }
519     }
520
521     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
522         skip_out_of_file_lines_range_visitor!(self, ii.span);
523
524         if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
525             self.push_rewrite(ii.span, None);
526             return;
527         }
528
529         match ii.node {
530             ast::ImplItemKind::Method(ref sig, ref body) => {
531                 self.visit_fn(
532                     visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
533                     &sig.decl,
534                     ii.span,
535                     ii.id,
536                     ii.defaultness,
537                     Some(&ii.attrs),
538                 );
539             }
540             ast::ImplItemKind::Const(ref ty, ref expr) => {
541                 let rewrite = rewrite_static(
542                     "const",
543                     &ii.vis,
544                     ii.ident,
545                     ty,
546                     ast::Mutability::Immutable,
547                     Some(expr),
548                     self.block_indent,
549                     ii.span,
550                     &self.get_context(),
551                 );
552                 self.push_rewrite(ii.span, rewrite);
553             }
554             ast::ImplItemKind::Type(ref ty) => {
555                 let rewrite = rewrite_associated_impl_type(
556                     ii.ident,
557                     ii.defaultness,
558                     Some(ty),
559                     None,
560                     &self.get_context(),
561                     self.block_indent,
562                 );
563                 self.push_rewrite(ii.span, rewrite);
564             }
565             ast::ImplItemKind::Macro(ref mac) => {
566                 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
567             }
568         }
569     }
570
571     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
572         skip_out_of_file_lines_range_visitor!(self, mac.span);
573
574         // 1 = ;
575         let shape = self.shape().sub_width(1).unwrap();
576         let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
577         self.push_rewrite(mac.span, rewrite);
578     }
579
580     pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
581         self.format_missing_with_indent(source!(self, span).lo());
582         let result = rewrite.unwrap_or_else(|| self.snippet(span));
583         self.buffer.push_str(&result);
584         self.last_pos = source!(self, span).hi();
585     }
586
587     pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
588         FmtVisitor {
589             parse_session: parse_session,
590             codemap: parse_session.codemap(),
591             buffer: StringBuffer::new(),
592             last_pos: BytePos(0),
593             block_indent: Indent::empty(),
594             config: config,
595             is_if_else_block: false,
596         }
597     }
598
599     pub fn snippet(&self, span: Span) -> String {
600         match self.codemap.span_to_snippet(span) {
601             Ok(s) => s,
602             Err(_) => {
603                 println!(
604                     "Couldn't make snippet for span {:?}->{:?}",
605                     self.codemap.lookup_char_pos(span.lo()),
606                     self.codemap.lookup_char_pos(span.hi())
607                 );
608                 "".to_owned()
609             }
610         }
611     }
612
613     // Returns true if we should skip the following item.
614     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
615         if contains_skip(attrs) {
616             return true;
617         }
618
619         let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
620         if attrs.is_empty() {
621             return false;
622         }
623
624         let rewrite = attrs.rewrite(&self.get_context(), self.shape());
625         let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
626         self.push_rewrite(span, rewrite);
627
628         false
629     }
630
631     fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
632     where
633         F: Fn(&ast::Item) -> bool,
634     {
635         let mut last = self.codemap.lookup_line_range(items_left[0].span());
636         let item_length = items_left
637             .iter()
638             .take_while(|ppi| {
639                 is_item(&***ppi) && (!in_group || {
640                     let current = self.codemap.lookup_line_range(ppi.span());
641                     let in_same_group = current.lo < last.hi + 2;
642                     last = current;
643                     in_same_group
644                 })
645             })
646             .count();
647         let items = &items_left[..item_length];
648
649         let at_least_one_in_file_lines = items
650             .iter()
651             .any(|item| !out_of_file_lines_range!(self, item.span));
652
653         if at_least_one_in_file_lines {
654             self.format_imports(items);
655         } else {
656             for item in items {
657                 self.push_rewrite(item.span, None);
658             }
659         }
660
661         item_length
662     }
663
664     fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
665         while !items_left.is_empty() {
666             // If the next item is a `use` declaration, then extract it and any subsequent `use`s
667             // to be potentially reordered within `format_imports`. Otherwise, just format the
668             // next item for output.
669             if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
670                 let used_items_len = self.reorder_items(
671                     items_left,
672                     &is_use_item,
673                     self.config.reorder_imports_in_group(),
674                 );
675                 let (_, rest) = items_left.split_at(used_items_len);
676                 items_left = rest;
677             } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
678                 let used_items_len = self.reorder_items(
679                     items_left,
680                     &is_extern_crate,
681                     self.config.reorder_extern_crates_in_group(),
682                 );
683                 let (_, rest) = items_left.split_at(used_items_len);
684                 items_left = rest;
685             } else {
686                 // `unwrap()` is safe here because we know `items_left`
687                 // has elements from the loop condition
688                 let (item, rest) = items_left.split_first().unwrap();
689                 self.visit_item(item);
690                 items_left = rest;
691             }
692         }
693     }
694
695     fn walk_mod_items(&mut self, m: &ast::Mod) {
696         self.walk_items(&ptr_vec_to_ref_vec(&m.items));
697     }
698
699     fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
700         fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
701             match stmt.node {
702                 ast::StmtKind::Item(ref item) => Some(&**item),
703                 _ => None,
704             }
705         }
706
707         if stmts.is_empty() {
708             return;
709         }
710
711         // Extract leading `use ...;`.
712         let items: Vec<_> = stmts
713             .iter()
714             .take_while(|stmt| to_stmt_item(stmt).is_some())
715             .filter_map(|stmt| to_stmt_item(stmt))
716             .take_while(|item| is_use_item(item))
717             .collect();
718
719         if items.is_empty() {
720             self.visit_stmt(&stmts[0]);
721             self.walk_stmts(&stmts[1..]);
722         } else {
723             self.walk_items(&items);
724             self.walk_stmts(&stmts[items.len()..]);
725         }
726     }
727
728     fn walk_block_stmts(&mut self, b: &ast::Block) {
729         self.walk_stmts(&b.stmts)
730     }
731
732     fn format_mod(
733         &mut self,
734         m: &ast::Mod,
735         vis: &ast::Visibility,
736         s: Span,
737         ident: ast::Ident,
738         attrs: &[ast::Attribute],
739     ) {
740         // Decide whether this is an inline mod or an external mod.
741         let local_file_name = self.codemap.span_to_filename(s);
742         let inner_span = source!(self, m.inner);
743         let is_internal = !(inner_span.lo().0 == 0 && inner_span.hi().0 == 0)
744             && local_file_name == self.codemap.span_to_filename(inner_span);
745
746         self.buffer.push_str(&*utils::format_visibility(vis));
747         self.buffer.push_str("mod ");
748         self.buffer.push_str(&ident.to_string());
749
750         if is_internal {
751             match self.config.item_brace_style() {
752                 BraceStyle::AlwaysNextLine => self.buffer
753                     .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
754                 _ => self.buffer.push_str(" {"),
755             }
756             // Hackery to account for the closing }.
757             let mod_lo = self.codemap.span_after(source!(self, s), "{");
758             let body_snippet =
759                 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
760             let body_snippet = body_snippet.trim();
761             if body_snippet.is_empty() {
762                 self.buffer.push_str("}");
763             } else {
764                 self.last_pos = mod_lo;
765                 self.block_indent = self.block_indent.block_indent(self.config);
766                 self.visit_attrs(attrs, ast::AttrStyle::Inner);
767                 self.walk_mod_items(m);
768                 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
769                 self.close_block(false);
770             }
771             self.last_pos = source!(self, m.inner).hi();
772         } else {
773             self.buffer.push_str(";");
774             self.last_pos = source!(self, s).hi();
775         }
776     }
777
778     pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
779         self.block_indent = Indent::empty();
780         self.walk_mod_items(m);
781         self.format_missing_with_indent(filemap.end_pos);
782     }
783
784     pub fn get_context(&self) -> RewriteContext {
785         RewriteContext {
786             parse_session: self.parse_session,
787             codemap: self.codemap,
788             config: self.config,
789             inside_macro: false,
790             use_block: false,
791             is_if_else_block: false,
792             force_one_line_chain: false,
793         }
794     }
795 }
796
797 impl Rewrite for ast::NestedMetaItem {
798     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
799         match self.node {
800             ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
801             ast::NestedMetaItemKind::Literal(..) => Some(context.snippet(self.span)),
802         }
803     }
804 }
805
806 impl Rewrite for ast::MetaItem {
807     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
808         Some(match self.node {
809             ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
810             ast::MetaItemKind::List(ref list) => {
811                 let name = self.name.as_str();
812                 // 3 = `#[` and `(`, 2 = `]` and `)`
813                 let item_shape = try_opt!(
814                     shape
815                         .shrink_left(name.len() + 3)
816                         .and_then(|s| s.sub_width(2))
817                 );
818                 let items = itemize_list(
819                     context.codemap,
820                     list.iter(),
821                     ")",
822                     |nested_meta_item| nested_meta_item.span.lo(),
823                     |nested_meta_item| nested_meta_item.span.hi(),
824                     |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
825                     self.span.lo(),
826                     self.span.hi(),
827                     false,
828                 );
829                 let item_vec = items.collect::<Vec<_>>();
830                 let fmt = ListFormatting {
831                     tactic: DefinitiveListTactic::Mixed,
832                     separator: ",",
833                     trailing_separator: SeparatorTactic::Never,
834                     separator_place: SeparatorPlace::Back,
835                     shape: item_shape,
836                     ends_with_newline: false,
837                     preserve_newline: false,
838                     config: context.config,
839                 };
840                 format!("{}({})", name, try_opt!(write_list(&item_vec, &fmt)))
841             }
842             ast::MetaItemKind::NameValue(ref literal) => {
843                 let name = self.name.as_str();
844                 let value = context.snippet(literal.span);
845                 if &*name == "doc" && contains_comment(&value) {
846                     let doc_shape = Shape {
847                         width: cmp::min(shape.width, context.config.comment_width())
848                             .checked_sub(shape.indent.width())
849                             .unwrap_or(0),
850                         ..shape
851                     };
852                     try_opt!(rewrite_comment(&value, false, doc_shape, context.config))
853                 } else {
854                     format!("{} = {}", name, value)
855                 }
856             }
857         })
858     }
859 }
860
861 impl Rewrite for ast::Attribute {
862     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
863         try_opt!(self.meta())
864             .rewrite(context, shape)
865             .map(|rw| if self.is_sugared_doc {
866                 rw
867             } else {
868                 let original = context.snippet(self.span);
869                 let prefix = match self.style {
870                     ast::AttrStyle::Inner => "#!",
871                     ast::AttrStyle::Outer => "#",
872                 };
873                 if contains_comment(&original) {
874                     original
875                 } else {
876                     format!("{}[{}]", prefix, rw)
877                 }
878             })
879     }
880 }
881
882 impl<'a> Rewrite for [ast::Attribute] {
883     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
884         if self.is_empty() {
885             return Some(String::new());
886         }
887         let mut result = String::with_capacity(128);
888         let indent = shape.indent.to_string(context.config);
889
890         let mut derive_args = Vec::new();
891
892         let mut iter = self.iter().enumerate().peekable();
893         let mut insert_new_line = true;
894         let mut is_prev_sugared_doc = false;
895         while let Some((i, a)) = iter.next() {
896             let a_str = try_opt!(a.rewrite(context, shape));
897
898             // Write comments and blank lines between attributes.
899             if i > 0 {
900                 let comment = context.snippet(mk_sp(self[i - 1].span.hi(), a.span.lo()));
901                 // This particular horror show is to preserve line breaks in between doc
902                 // comments. An alternative would be to force such line breaks to start
903                 // with the usual doc comment token.
904                 let (multi_line_before, multi_line_after) = if a.is_sugared_doc
905                     || is_prev_sugared_doc
906                 {
907                     // Look at before and after comment and see if there are any empty lines.
908                     let comment_begin = comment.chars().position(|c| c == '/');
909                     let len = comment_begin.unwrap_or_else(|| comment.len());
910                     let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
911                     let mla = if comment_begin.is_none() {
912                         mlb
913                     } else {
914                         let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
915                         let len = comment_end.unwrap();
916                         comment
917                             .chars()
918                             .rev()
919                             .take(len)
920                             .filter(|c| *c == '\n')
921                             .count() > 1
922                     };
923                     (mlb, mla)
924                 } else {
925                     (false, false)
926                 };
927
928                 let comment = try_opt!(recover_missing_comment_in_span(
929                     mk_sp(self[i - 1].span.hi(), a.span.lo()),
930                     shape.with_max_width(context.config),
931                     context,
932                     0,
933                 ));
934
935                 if !comment.is_empty() {
936                     if multi_line_before {
937                         result.push('\n');
938                     }
939                     result.push_str(&comment);
940                     result.push('\n');
941                     if multi_line_after {
942                         result.push('\n')
943                     }
944                 } else if insert_new_line {
945                     result.push('\n');
946                     if multi_line_after {
947                         result.push('\n')
948                     }
949                 }
950
951                 if derive_args.is_empty() {
952                     result.push_str(&indent);
953                 }
954
955                 insert_new_line = true;
956             }
957
958             // Write the attribute itself.
959             if context.config.merge_derives() {
960                 // If the attribute is `#[derive(...)]`, take the arguments.
961                 if let Some(mut args) = get_derive_args(context, a) {
962                     derive_args.append(&mut args);
963                     match iter.peek() {
964                         // If the next attribute is `#[derive(...)]` as well, skip rewriting.
965                         Some(&(_, next_attr)) if is_derive(next_attr) => insert_new_line = false,
966                         // If not, rewrite the merged derives.
967                         _ => {
968                             result.push_str(&try_opt!(format_derive(context, &derive_args, shape)));
969                             derive_args.clear();
970                         }
971                     }
972                 } else {
973                     result.push_str(&a_str);
974                 }
975             } else {
976                 result.push_str(&a_str);
977             }
978
979             is_prev_sugared_doc = a.is_sugared_doc;
980         }
981         Some(result)
982     }
983 }
984
985 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
986 fn format_derive(context: &RewriteContext, derive_args: &[String], shape: Shape) -> Option<String> {
987     let mut result = String::with_capacity(128);
988     result.push_str("#[derive(");
989     // 11 = `#[derive()]`
990     let initial_budget = try_opt!(shape.width.checked_sub(11));
991     let mut budget = initial_budget;
992     let num = derive_args.len();
993     for (i, a) in derive_args.iter().enumerate() {
994         // 2 = `, ` or `)]`
995         let width = a.len() + 2;
996         if width > budget {
997             if i > 0 {
998                 // Remove trailing whitespace.
999                 result.pop();
1000             }
1001             result.push('\n');
1002             // 9 = `#[derive(`
1003             result.push_str(&(shape.indent + 9).to_string(context.config));
1004             budget = initial_budget;
1005         } else {
1006             budget = budget.checked_sub(width).unwrap_or(0);
1007         }
1008         result.push_str(a);
1009         if i != num - 1 {
1010             result.push_str(", ")
1011         }
1012     }
1013     result.push_str(")]");
1014     Some(result)
1015 }
1016
1017 fn is_derive(attr: &ast::Attribute) -> bool {
1018     match attr.meta() {
1019         Some(meta_item) => match meta_item.node {
1020             ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1021             _ => false,
1022         },
1023         _ => false,
1024     }
1025 }
1026
1027 /// Returns the arguments of `#[derive(...)]`.
1028 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
1029     attr.meta().and_then(|meta_item| match meta_item.node {
1030         ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1031             // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1032             Some(
1033                 args.iter()
1034                     .map(|a| context.snippet(a.span))
1035                     .collect::<Vec<_>>(),
1036             )
1037         }
1038         _ => None,
1039     })
1040 }
1041
1042 // Rewrite `extern crate foo;` WITHOUT attributes.
1043 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1044     assert!(is_extern_crate(item));
1045     let new_str = context.snippet(item.span);
1046     Some(if contains_comment(&new_str) {
1047         new_str
1048     } else {
1049         let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1050         String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
1051     })
1052 }