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