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