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