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