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