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