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