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