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