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