]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Merge pull request #2393 from RReverser/macro_rules
[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.shape(),
467                     self.block_indent,
468                     def,
469                     item.ident,
470                     &item.vis,
471                     item.span,
472                 );
473                 self.push_rewrite(item.span, rewrite);
474             }
475         }
476     }
477
478     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
479         skip_out_of_file_lines_range_visitor!(self, ti.span);
480
481         if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
482             self.push_skipped_with_span(ti.span());
483             return;
484         }
485
486         match ti.node {
487             ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
488             ast::TraitItemKind::Method(ref sig, None) => {
489                 let indent = self.block_indent;
490                 let rewrite =
491                     self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
492                 self.push_rewrite(ti.span, rewrite);
493             }
494             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
495                 self.visit_fn(
496                     visit::FnKind::Method(ti.ident, sig, None, body),
497                     &ti.generics,
498                     &sig.decl,
499                     ti.span,
500                     ast::Defaultness::Final,
501                     Some(&ti.attrs),
502                 );
503             }
504             ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
505                 let rewrite = rewrite_associated_type(
506                     ti.ident,
507                     type_default.as_ref(),
508                     Some(type_param_bounds),
509                     &self.get_context(),
510                     self.block_indent,
511                 );
512                 self.push_rewrite(ti.span, rewrite);
513             }
514             ast::TraitItemKind::Macro(ref mac) => {
515                 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
516             }
517         }
518     }
519
520     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
521         skip_out_of_file_lines_range_visitor!(self, ii.span);
522
523         if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
524             self.push_skipped_with_span(ii.span());
525             return;
526         }
527
528         match ii.node {
529             ast::ImplItemKind::Method(ref sig, ref body) => {
530                 self.visit_fn(
531                     visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
532                     &ii.generics,
533                     &sig.decl,
534                     ii.span,
535                     ii.defaultness,
536                     Some(&ii.attrs),
537                 );
538             }
539             ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
540             ast::ImplItemKind::Type(ref ty) => {
541                 let rewrite = rewrite_associated_impl_type(
542                     ii.ident,
543                     ii.defaultness,
544                     Some(ty),
545                     None,
546                     &self.get_context(),
547                     self.block_indent,
548                 );
549                 self.push_rewrite(ii.span, rewrite);
550             }
551             ast::ImplItemKind::Macro(ref mac) => {
552                 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
553             }
554         }
555     }
556
557     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
558         skip_out_of_file_lines_range_visitor!(self, mac.span);
559
560         // 1 = ;
561         let shape = self.shape().sub_width(1).unwrap();
562         let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
563         self.push_rewrite(mac.span, rewrite);
564     }
565
566     pub fn push_str(&mut self, s: &str) {
567         self.line_number += count_newlines(s);
568         self.buffer.push_str(s);
569     }
570
571     fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
572         if let Some(ref s) = rewrite {
573             self.push_str(s);
574         } else {
575             let snippet = self.snippet(span);
576             self.push_str(snippet);
577         }
578         self.last_pos = source!(self, span).hi();
579     }
580
581     pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
582         self.format_missing_with_indent(source!(self, span).lo());
583         self.push_rewrite_inner(span, rewrite);
584     }
585
586     pub fn push_skipped_with_span(&mut self, span: Span) {
587         self.format_missing_with_indent(source!(self, span).lo());
588         let lo = self.line_number + 1;
589         self.push_rewrite_inner(span, None);
590         let hi = self.line_number + 1;
591         self.skipped_range.push((lo, hi));
592     }
593
594     pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
595         FmtVisitor::from_codemap(ctx.parse_session, ctx.config, ctx.snippet_provider)
596     }
597
598     pub fn from_codemap(
599         parse_session: &'a ParseSess,
600         config: &'a Config,
601         snippet_provider: &'a SnippetProvider,
602     ) -> FmtVisitor<'a> {
603         FmtVisitor {
604             parse_session,
605             codemap: parse_session.codemap(),
606             buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
607             last_pos: BytePos(0),
608             block_indent: Indent::empty(),
609             config,
610             is_if_else_block: false,
611             snippet_provider,
612             line_number: 0,
613             skipped_range: vec![],
614         }
615     }
616
617     pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
618         self.snippet_provider.span_to_snippet(span)
619     }
620
621     pub fn snippet(&'b self, span: Span) -> &'a str {
622         self.opt_snippet(span).unwrap()
623     }
624
625     // Returns true if we should skip the following item.
626     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
627         if contains_skip(attrs) {
628             return true;
629         }
630
631         let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
632         if attrs.is_empty() {
633             return false;
634         }
635
636         let rewrite = attrs.rewrite(&self.get_context(), self.shape());
637         let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
638         self.push_rewrite(span, rewrite);
639
640         false
641     }
642
643     fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
644     where
645         F: Fn(&ast::Item) -> bool,
646     {
647         let mut last = self.codemap.lookup_line_range(items_left[0].span());
648         let item_length = items_left
649             .iter()
650             .take_while(|ppi| {
651                 is_item(&***ppi) && (!in_group || {
652                     let current = self.codemap.lookup_line_range(ppi.span());
653                     let in_same_group = current.lo < last.hi + 2;
654                     last = current;
655                     in_same_group
656                 })
657             })
658             .count();
659         let items = &items_left[..item_length];
660
661         let at_least_one_in_file_lines = items
662             .iter()
663             .any(|item| !out_of_file_lines_range!(self, item.span));
664
665         if at_least_one_in_file_lines {
666             self.format_imports(items);
667         } else {
668             for item in items {
669                 self.push_rewrite(item.span, None);
670             }
671         }
672
673         item_length
674     }
675
676     fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
677         macro try_reorder_items_with($reorder: ident, $in_group: ident, $pred: ident) {
678             if self.config.$reorder() && $pred(&*items_left[0]) {
679                 let used_items_len =
680                     self.reorder_items(items_left, &$pred, self.config.$in_group());
681                 let (_, rest) = items_left.split_at(used_items_len);
682                 items_left = rest;
683                 continue;
684             }
685         }
686
687         while !items_left.is_empty() {
688             // If the next item is a `use`, `extern crate` or `mod`, then extract it and any
689             // subsequent items that have the same item kind to be reordered within
690             // `format_imports`. Otherwise, just format the next item for output.
691             {
692                 try_reorder_items_with!(
693                     reorder_imports,
694                     reorder_imports_in_group,
695                     is_use_item_without_attr
696                 );
697                 try_reorder_items_with!(
698                     reorder_extern_crates,
699                     reorder_extern_crates_in_group,
700                     is_extern_crate_without_attr
701                 );
702                 try_reorder_items_with!(reorder_modules, reorder_modules, is_mod_decl_without_attr);
703             }
704             // Reaching here means items were not reordered. There must be at least
705             // one item left in `items_left`, so calling `unwrap()` here is safe.
706             let (item, rest) = items_left.split_first().unwrap();
707             self.visit_item(item);
708             items_left = rest;
709         }
710     }
711
712     fn walk_mod_items(&mut self, m: &ast::Mod) {
713         self.walk_items(&ptr_vec_to_ref_vec(&m.items));
714     }
715
716     fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
717         fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
718             match stmt.node {
719                 ast::StmtKind::Item(ref item) => Some(&**item),
720                 _ => None,
721             }
722         }
723
724         if stmts.is_empty() {
725             return;
726         }
727
728         // Extract leading `use ...;`.
729         let items: Vec<_> = stmts
730             .iter()
731             .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
732             .filter_map(|stmt| to_stmt_item(stmt))
733             .collect();
734
735         if items.is_empty() {
736             self.visit_stmt(&stmts[0]);
737             self.walk_stmts(&stmts[1..]);
738         } else {
739             self.walk_items(&items);
740             self.walk_stmts(&stmts[items.len()..]);
741         }
742     }
743
744     fn walk_block_stmts(&mut self, b: &ast::Block) {
745         self.walk_stmts(&b.stmts)
746     }
747
748     fn format_mod(
749         &mut self,
750         m: &ast::Mod,
751         vis: &ast::Visibility,
752         s: Span,
753         ident: ast::Ident,
754         attrs: &[ast::Attribute],
755         is_internal: bool,
756     ) {
757         self.push_str(&*utils::format_visibility(vis));
758         self.push_str("mod ");
759         self.push_str(&ident.to_string());
760
761         if is_internal {
762             match self.config.brace_style() {
763                 BraceStyle::AlwaysNextLine => {
764                     let sep_str = format!("\n{}{{", self.block_indent.to_string(self.config));
765                     self.push_str(&sep_str);
766                 }
767                 _ => self.push_str(" {"),
768             }
769             // Hackery to account for the closing }.
770             let mod_lo = self.codemap.span_after(source!(self, s), "{");
771             let body_snippet =
772                 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
773             let body_snippet = body_snippet.trim();
774             if body_snippet.is_empty() {
775                 self.push_str("}");
776             } else {
777                 self.last_pos = mod_lo;
778                 self.block_indent = self.block_indent.block_indent(self.config);
779                 self.visit_attrs(attrs, ast::AttrStyle::Inner);
780                 self.walk_mod_items(m);
781                 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
782                 self.close_block(false);
783             }
784             self.last_pos = source!(self, m.inner).hi();
785         } else {
786             self.push_str(";");
787             self.last_pos = source!(self, s).hi();
788         }
789     }
790
791     pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
792         self.block_indent = Indent::empty();
793         self.walk_mod_items(m);
794         self.format_missing_with_indent(filemap.end_pos);
795     }
796
797     pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
798         while let Some(pos) = self.codemap
799             .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
800         {
801             if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
802                 if snippet.trim().is_empty() {
803                     self.last_pos = pos;
804                 } else {
805                     return;
806                 }
807             }
808         }
809     }
810
811     pub fn get_context(&self) -> RewriteContext {
812         RewriteContext {
813             parse_session: self.parse_session,
814             codemap: self.codemap,
815             config: self.config,
816             inside_macro: false,
817             use_block: false,
818             is_if_else_block: false,
819             force_one_line_chain: false,
820             snippet_provider: self.snippet_provider,
821         }
822     }
823 }
824
825 impl Rewrite for ast::NestedMetaItem {
826     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
827         match self.node {
828             ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
829             ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
830         }
831     }
832 }
833
834 impl Rewrite for ast::MetaItem {
835     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
836         Some(match self.node {
837             ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
838             ast::MetaItemKind::List(ref list) => {
839                 let name = self.name.as_str();
840                 // 1 = `(`, 2 = `]` and `)`
841                 let item_shape = shape
842                     .visual_indent(0)
843                     .shrink_left(name.len() + 1)
844                     .and_then(|s| s.sub_width(2))?;
845                 let items = itemize_list(
846                     context.codemap,
847                     list.iter(),
848                     ")",
849                     ",",
850                     |nested_meta_item| nested_meta_item.span.lo(),
851                     |nested_meta_item| nested_meta_item.span.hi(),
852                     |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
853                     self.span.lo(),
854                     self.span.hi(),
855                     false,
856                 );
857                 let item_vec = items.collect::<Vec<_>>();
858                 let fmt = ListFormatting {
859                     tactic: DefinitiveListTactic::Mixed,
860                     separator: ",",
861                     trailing_separator: SeparatorTactic::Never,
862                     separator_place: SeparatorPlace::Back,
863                     shape: item_shape,
864                     ends_with_newline: false,
865                     preserve_newline: false,
866                     config: context.config,
867                 };
868                 format!("{}({})", name, write_list(&item_vec, &fmt)?)
869             }
870             ast::MetaItemKind::NameValue(ref literal) => {
871                 let name = self.name.as_str();
872                 // 3 = ` = `
873                 let lit_shape = shape.shrink_left(name.len() + 3)?;
874                 let value = rewrite_literal(context, literal, lit_shape)?;
875                 format!("{} = {}", name, value)
876             }
877         })
878     }
879 }
880
881 impl Rewrite for ast::Attribute {
882     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
883         let prefix = match self.style {
884             ast::AttrStyle::Inner => "#!",
885             ast::AttrStyle::Outer => "#",
886         };
887         let snippet = context.snippet(self.span);
888         if self.is_sugared_doc {
889             let doc_shape = Shape {
890                 width: cmp::min(shape.width, context.config.comment_width())
891                     .checked_sub(shape.indent.width())
892                     .unwrap_or(0),
893                 ..shape
894             };
895             rewrite_comment(snippet, false, doc_shape, context.config)
896         } else {
897             if contains_comment(snippet) {
898                 return Some(snippet.to_owned());
899             }
900             // 1 = `[`
901             let shape = shape.offset_left(prefix.len() + 1)?;
902             self.meta()?
903                 .rewrite(context, shape)
904                 .map(|rw| format!("{}[{}]", prefix, rw))
905         }
906     }
907 }
908
909 /// Returns the first group of attributes that fills the given predicate.
910 /// We consider two doc comments are in different group if they are separated by normal comments.
911 fn take_while_with_pred<'a, P>(
912     context: &RewriteContext,
913     attrs: &'a [ast::Attribute],
914     pred: P,
915 ) -> &'a [ast::Attribute]
916 where
917     P: Fn(&ast::Attribute) -> bool,
918 {
919     let mut last_index = 0;
920     let mut iter = attrs.iter().enumerate().peekable();
921     while let Some((i, attr)) = iter.next() {
922         if !pred(attr) {
923             break;
924         }
925         if let Some(&(_, next_attr)) = iter.peek() {
926             // Extract comments between two attributes.
927             let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
928             let snippet = context.snippet(span_between_attr);
929             if count_newlines(snippet) >= 2 || snippet.contains('/') {
930                 break;
931             }
932         }
933         last_index = i;
934     }
935     if last_index == 0 {
936         &[]
937     } else {
938         &attrs[..last_index + 1]
939     }
940 }
941
942 fn rewrite_first_group_attrs(
943     context: &RewriteContext,
944     attrs: &[ast::Attribute],
945     shape: Shape,
946 ) -> Option<(usize, String)> {
947     if attrs.is_empty() {
948         return Some((0, String::new()));
949     }
950     // Rewrite doc comments
951     let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_sugared_doc);
952     if !sugared_docs.is_empty() {
953         let snippet = sugared_docs
954             .iter()
955             .map(|a| context.snippet(a.span))
956             .collect::<Vec<_>>()
957             .join("\n");
958         return Some((
959             sugared_docs.len(),
960             rewrite_comment(&snippet, false, shape, context.config)?,
961         ));
962     }
963     // Rewrite `#[derive(..)]`s.
964     if context.config.merge_derives() {
965         let derives = take_while_with_pred(context, attrs, is_derive);
966         if !derives.is_empty() {
967             let mut derive_args = vec![];
968             for derive in derives {
969                 derive_args.append(&mut get_derive_args(context, derive)?);
970             }
971             return Some((derives.len(), format_derive(context, &derive_args, shape)?));
972         }
973     }
974     // Rewrite the first attribute.
975     Some((1, attrs[0].rewrite(context, shape)?))
976 }
977
978 fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
979     // Look at before and after comment and see if there are any empty lines.
980     let comment_begin = comment.chars().position(|c| c == '/');
981     let len = comment_begin.unwrap_or_else(|| comment.len());
982     let mlb = count_newlines(&comment[..len]) > 1;
983     let mla = if comment_begin.is_none() {
984         mlb
985     } else {
986         let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
987         let len = comment_end.unwrap();
988         comment
989             .chars()
990             .rev()
991             .take(len)
992             .filter(|c| *c == '\n')
993             .count() > 1
994     };
995     (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
996 }
997
998 impl<'a> Rewrite for [ast::Attribute] {
999     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1000         if self.is_empty() {
1001             return Some(String::new());
1002         }
1003         let (first_group_len, first_group_str) = rewrite_first_group_attrs(context, self, shape)?;
1004         if self.len() == 1 || first_group_len == self.len() {
1005             Some(first_group_str)
1006         } else {
1007             let rest_str = self[first_group_len..].rewrite(context, shape)?;
1008             let missing_span = mk_sp(
1009                 self[first_group_len - 1].span.hi(),
1010                 self[first_group_len].span.lo(),
1011             );
1012             // Preserve an empty line before/after doc comments.
1013             if self[0].is_sugared_doc || self[first_group_len].is_sugared_doc {
1014                 let snippet = context.snippet(missing_span);
1015                 let (mla, mlb) = has_newlines_before_after_comment(snippet);
1016                 let comment = ::comment::recover_missing_comment_in_span(
1017                     missing_span,
1018                     shape.with_max_width(context.config),
1019                     context,
1020                     0,
1021                 )?;
1022                 let comment = if comment.is_empty() {
1023                     format!("\n{}", mlb)
1024                 } else {
1025                     format!("{}{}\n{}", mla, comment, mlb)
1026                 };
1027                 Some(format!(
1028                     "{}{}{}{}",
1029                     first_group_str,
1030                     comment,
1031                     shape.indent.to_string(context.config),
1032                     rest_str
1033                 ))
1034             } else {
1035                 combine_strs_with_missing_comments(
1036                     context,
1037                     &first_group_str,
1038                     &rest_str,
1039                     missing_span,
1040                     shape,
1041                     false,
1042                 )
1043             }
1044         }
1045     }
1046 }
1047
1048 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
1049 fn format_derive(context: &RewriteContext, derive_args: &[&str], shape: Shape) -> Option<String> {
1050     let mut result = String::with_capacity(128);
1051     result.push_str("#[derive(");
1052     // 11 = `#[derive()]`
1053     let initial_budget = shape.width.checked_sub(11)?;
1054     let mut budget = initial_budget;
1055     let num = derive_args.len();
1056     for (i, a) in derive_args.iter().enumerate() {
1057         // 2 = `, ` or `)]`
1058         let width = a.len() + 2;
1059         if width > budget {
1060             if i > 0 {
1061                 // Remove trailing whitespace.
1062                 result.pop();
1063             }
1064             result.push('\n');
1065             // 9 = `#[derive(`
1066             result.push_str(&(shape.indent + 9).to_string(context.config));
1067             budget = initial_budget;
1068         } else {
1069             budget = budget.checked_sub(width).unwrap_or(0);
1070         }
1071         result.push_str(a);
1072         if i != num - 1 {
1073             result.push_str(", ")
1074         }
1075     }
1076     result.push_str(")]");
1077     Some(result)
1078 }
1079
1080 fn is_derive(attr: &ast::Attribute) -> bool {
1081     attr.check_name("derive")
1082 }
1083
1084 /// Returns the arguments of `#[derive(...)]`.
1085 fn get_derive_args<'a>(context: &'a RewriteContext, attr: &ast::Attribute) -> Option<Vec<&'a str>> {
1086     attr.meta_item_list().map(|meta_item_list| {
1087         meta_item_list
1088             .iter()
1089             .map(|nested_meta_item| context.snippet(nested_meta_item.span))
1090             .collect()
1091     })
1092 }
1093
1094 // Rewrite `extern crate foo;` WITHOUT attributes.
1095 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1096     assert!(is_extern_crate(item));
1097     let new_str = context.snippet(item.span);
1098     Some(if contains_comment(new_str) {
1099         new_str.to_owned()
1100     } else {
1101         let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1102         String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
1103     })
1104 }
1105
1106 fn get_attrs_from_stmt(stmt: &ast::Stmt) -> &[ast::Attribute] {
1107     match stmt.node {
1108         ast::StmtKind::Local(ref local) => &local.attrs,
1109         ast::StmtKind::Item(ref item) => &item.attrs,
1110         ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => &expr.attrs,
1111         ast::StmtKind::Mac(ref mac) => &mac.2,
1112     }
1113 }