]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Merge pull request #3028 from scampi/issue2973
[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 syntax::attr::HasAttrs;
12 use syntax::parse::ParseSess;
13 use syntax::source_map::{self, BytePos, Pos, SourceMap, Span};
14 use syntax::{ast, visit};
15
16 use attr::*;
17 use comment::{CodeCharKind, CommentCodeSlices, FindUncommented};
18 use config::{BraceStyle, Config};
19 use items::{
20     format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item,
21     rewrite_associated_impl_type, rewrite_associated_type, rewrite_existential_impl_type,
22     rewrite_existential_type, rewrite_extern_crate, rewrite_type_alias, FnSig, StaticParts,
23     StructParts,
24 };
25 use macros::{rewrite_macro, rewrite_macro_def, MacroPosition};
26 use rewrite::{Rewrite, RewriteContext};
27 use shape::{Indent, Shape};
28 use source_map::{LineRangeUtils, SpanUtils};
29 use spanned::Spanned;
30 use utils::{
31     self, contains_skip, count_newlines, inner_attributes, mk_sp, ptr_vec_to_ref_vec,
32     rewrite_ident, DEPR_SKIP_ANNOTATION,
33 };
34 use {ErrorKind, FormatReport, FormattingError};
35
36 use std::cell::RefCell;
37
38 /// Creates a string slice corresponding to the specified span.
39 pub struct SnippetProvider<'a> {
40     /// A pointer to the content of the file we are formatting.
41     big_snippet: &'a str,
42     /// A position of the start of `big_snippet`, used as an offset.
43     start_pos: usize,
44 }
45
46 impl<'a> SnippetProvider<'a> {
47     pub fn span_to_snippet(&self, span: Span) -> Option<&str> {
48         let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
49         let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
50         Some(&self.big_snippet[start_index..end_index])
51     }
52
53     pub fn new(start_pos: BytePos, big_snippet: &'a str) -> Self {
54         let start_pos = start_pos.to_usize();
55         SnippetProvider {
56             big_snippet,
57             start_pos,
58         }
59     }
60 }
61
62 pub struct FmtVisitor<'a> {
63     parent_context: Option<&'a RewriteContext<'a>>,
64     pub parse_session: &'a ParseSess,
65     pub source_map: &'a SourceMap,
66     pub buffer: String,
67     pub last_pos: BytePos,
68     // FIXME: use an RAII util or closure for indenting
69     pub block_indent: Indent,
70     pub config: &'a Config,
71     pub is_if_else_block: bool,
72     pub snippet_provider: &'a SnippetProvider<'a>,
73     pub line_number: usize,
74     pub skipped_range: Vec<(usize, usize)>,
75     pub macro_rewrite_failure: bool,
76     pub(crate) report: FormatReport,
77 }
78
79 impl<'a> Drop for FmtVisitor<'a> {
80     fn drop(&mut self) {
81         if let Some(ctx) = self.parent_context {
82             if self.macro_rewrite_failure {
83                 ctx.macro_rewrite_failure.replace(true);
84             }
85         }
86     }
87 }
88
89 impl<'b, 'a: 'b> FmtVisitor<'a> {
90     fn set_parent_context(&mut self, context: &'a RewriteContext) {
91         self.parent_context = Some(context);
92     }
93
94     pub fn shape(&self) -> Shape {
95         Shape::indented(self.block_indent, self.config)
96     }
97
98     fn visit_stmt(&mut self, stmt: &ast::Stmt) {
99         debug!(
100             "visit_stmt: {:?} {:?}",
101             self.source_map.lookup_char_pos(stmt.span.lo()),
102             self.source_map.lookup_char_pos(stmt.span.hi())
103         );
104
105         match stmt.node {
106             ast::StmtKind::Item(ref item) => {
107                 self.visit_item(item);
108                 // Handle potential `;` after the item.
109                 self.format_missing(stmt.span.hi());
110             }
111             ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
112                 if contains_skip(get_attrs_from_stmt(stmt)) {
113                     self.push_skipped_with_span(stmt.span());
114                 } else {
115                     let shape = self.shape().clone();
116                     let rewrite = self.with_context(|ctx| stmt.rewrite(&ctx, shape));
117                     self.push_rewrite(stmt.span(), rewrite)
118                 }
119             }
120             ast::StmtKind::Mac(ref mac) => {
121                 let (ref mac, _macro_style, ref attrs) = **mac;
122                 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
123                     self.push_skipped_with_span(stmt.span());
124                 } else {
125                     self.visit_mac(mac, None, MacroPosition::Statement);
126                 }
127                 self.format_missing(stmt.span.hi());
128             }
129         }
130     }
131
132     pub fn visit_block(
133         &mut self,
134         b: &ast::Block,
135         inner_attrs: Option<&[ast::Attribute]>,
136         has_braces: bool,
137     ) {
138         debug!(
139             "visit_block: {:?} {:?}",
140             self.source_map.lookup_char_pos(b.span.lo()),
141             self.source_map.lookup_char_pos(b.span.hi())
142         );
143
144         // Check if this block has braces.
145         let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
146
147         self.last_pos = self.last_pos + brace_compensation;
148         self.block_indent = self.block_indent.block_indent(self.config);
149         self.push_str("{");
150
151         if let Some(first_stmt) = b.stmts.first() {
152             let attr_lo = inner_attrs
153                 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
154                 .or_else(|| {
155                     // Attributes for an item in a statement position
156                     // do not belong to the statement. (rust-lang/rust#34459)
157                     if let ast::StmtKind::Item(ref item) = first_stmt.node {
158                         item.attrs.first()
159                     } else {
160                         first_stmt.attrs().first()
161                     }.and_then(|attr| {
162                         // Some stmts can have embedded attributes.
163                         // e.g. `match { #![attr] ... }`
164                         let attr_lo = attr.span.lo();
165                         if attr_lo < first_stmt.span.lo() {
166                             Some(attr_lo)
167                         } else {
168                             None
169                         }
170                     })
171                 });
172
173             let snippet = self.snippet(mk_sp(
174                 self.last_pos,
175                 attr_lo.unwrap_or_else(|| first_stmt.span.lo()),
176             ));
177             let len = CommentCodeSlices::new(snippet)
178                 .nth(0)
179                 .and_then(|(kind, _, s)| {
180                     if kind == CodeCharKind::Normal {
181                         s.rfind('\n')
182                     } else {
183                         None
184                     }
185                 });
186             if let Some(len) = len {
187                 self.last_pos = self.last_pos + BytePos::from_usize(len);
188             }
189         }
190
191         // Format inner attributes if available.
192         let skip_rewrite = if let Some(attrs) = inner_attrs {
193             self.visit_attrs(attrs, ast::AttrStyle::Inner)
194         } else {
195             false
196         };
197
198         if skip_rewrite {
199             self.push_rewrite(b.span, None);
200             self.close_block(false);
201             self.last_pos = source!(self, b.span).hi();
202             return;
203         }
204
205         self.walk_block_stmts(b);
206
207         if !b.stmts.is_empty() {
208             if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
209                 if utils::semicolon_for_expr(&self.get_context(), expr) {
210                     self.push_str(";");
211                 }
212             }
213         }
214
215         let mut remove_len = BytePos(0);
216         if let Some(stmt) = b.stmts.last() {
217             let snippet = self.snippet(mk_sp(
218                 stmt.span.hi(),
219                 source!(self, b.span).hi() - brace_compensation,
220             ));
221             let len = CommentCodeSlices::new(snippet)
222                 .last()
223                 .and_then(|(kind, _, s)| {
224                     if kind == CodeCharKind::Normal && s.trim().is_empty() {
225                         Some(s.len())
226                     } else {
227                         None
228                     }
229                 });
230             if let Some(len) = len {
231                 remove_len = BytePos::from_usize(len);
232             }
233         }
234
235         let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
236             let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
237             let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
238             snippet.contains("//") || snippet.contains("/*")
239         };
240         // FIXME: we should compress any newlines here to just one
241         if unindent_comment {
242             self.block_indent = self.block_indent.block_unindent(self.config);
243         }
244         self.format_missing_with_indent(
245             source!(self, b.span).hi() - brace_compensation - remove_len,
246         );
247         if unindent_comment {
248             self.block_indent = self.block_indent.block_indent(self.config);
249         }
250         self.close_block(unindent_comment);
251         self.last_pos = source!(self, b.span).hi();
252     }
253
254     // FIXME: this is a terrible hack to indent the comments between the last
255     // item in the block and the closing brace to the block's level.
256     // The closing brace itself, however, should be indented at a shallower
257     // level.
258     fn close_block(&mut self, unindent_comment: bool) {
259         let total_len = self.buffer.len();
260         let chars_too_many = if unindent_comment {
261             0
262         } else if self.config.hard_tabs() {
263             1
264         } else {
265             self.config.tab_spaces()
266         };
267         self.buffer.truncate(total_len - chars_too_many);
268         self.push_str("}");
269         self.block_indent = self.block_indent.block_unindent(self.config);
270     }
271
272     // Note that this only gets called for function definitions. Required methods
273     // on traits do not get handled here.
274     fn visit_fn(
275         &mut self,
276         fk: visit::FnKind,
277         generics: &ast::Generics,
278         fd: &ast::FnDecl,
279         s: Span,
280         defaultness: ast::Defaultness,
281         inner_attrs: Option<&[ast::Attribute]>,
282     ) {
283         let indent = self.block_indent;
284         let block;
285         let rewrite = match fk {
286             visit::FnKind::ItemFn(ident, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
287                 block = b;
288                 self.rewrite_fn(
289                     indent,
290                     ident,
291                     &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
292                     mk_sp(s.lo(), b.span.lo()),
293                     b,
294                     inner_attrs,
295                 )
296             }
297             visit::FnKind::Closure(_) => unreachable!(),
298         };
299
300         if let Some(fn_str) = rewrite {
301             self.format_missing_with_indent(source!(self, s).lo());
302             self.push_str(&fn_str);
303             if let Some(c) = fn_str.chars().last() {
304                 if c == '}' {
305                     self.last_pos = source!(self, block.span).hi();
306                     return;
307                 }
308             }
309         } else {
310             self.format_missing(source!(self, block.span).lo());
311         }
312
313         self.last_pos = source!(self, block.span).lo();
314         self.visit_block(block, inner_attrs, true)
315     }
316
317     pub fn visit_item(&mut self, item: &ast::Item) {
318         skip_out_of_file_lines_range_visitor!(self, item.span);
319
320         // This is where we bail out if there is a skip attribute. This is only
321         // complex in the module case. It is complex because the module could be
322         // in a separate file and there might be attributes in both files, but
323         // the AST lumps them all together.
324         let filtered_attrs;
325         let mut attrs = &item.attrs;
326         match item.node {
327             // For use items, skip rewriting attributes. Just check for a skip attribute.
328             ast::ItemKind::Use(..) => {
329                 if contains_skip(attrs) {
330                     self.push_skipped_with_span(item.span());
331                     return;
332                 }
333             }
334             // Module is inline, in this case we treat it like any other item.
335             _ if !is_mod_decl(item) => {
336                 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
337                     self.push_skipped_with_span(item.span());
338                     return;
339                 }
340             }
341             // Module is not inline, but should be skipped.
342             ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
343                 return;
344             }
345             // Module is not inline and should not be skipped. We want
346             // to process only the attributes in the current file.
347             ast::ItemKind::Mod(..) => {
348                 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
349                 // Assert because if we should skip it should be caught by
350                 // the above case.
351                 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
352                 attrs = &filtered_attrs;
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 block_indent = self.block_indent.clone();
370                 let rw =
371                     self.with_context(|ctx| format_impl(&ctx, item, block_indent, where_span_end));
372                 self.push_rewrite(item.span, rw);
373             }
374             ast::ItemKind::Trait(..) => {
375                 let block_indent = self.block_indent.clone();
376                 let rw = self.with_context(|ctx| format_trait(&ctx, item, block_indent));
377                 self.push_rewrite(item.span, rw);
378             }
379             ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => {
380                 let shape = Shape::indented(self.block_indent, self.config);
381                 let rw = format_trait_alias(
382                     &self.get_context(),
383                     item.ident,
384                     generics,
385                     generic_bounds,
386                     shape,
387                 );
388                 self.push_rewrite(item.span, rw);
389             }
390             ast::ItemKind::ExternCrate(_) => {
391                 let rw = rewrite_extern_crate(&self.get_context(), item);
392                 self.push_rewrite(item.span, rw);
393             }
394             ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
395                 self.visit_struct(&StructParts::from_item(item));
396             }
397             ast::ItemKind::Enum(ref def, ref generics) => {
398                 self.format_missing_with_indent(source!(self, item.span).lo());
399                 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
400                 self.last_pos = source!(self, item.span).hi();
401             }
402             ast::ItemKind::Mod(ref module) => {
403                 let is_inline = !is_mod_decl(item);
404                 self.format_missing_with_indent(source!(self, item.span).lo());
405                 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
406             }
407             ast::ItemKind::Mac(ref mac) => {
408                 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
409             }
410             ast::ItemKind::ForeignMod(ref foreign_mod) => {
411                 self.format_missing_with_indent(source!(self, item.span).lo());
412                 self.format_foreign_mod(foreign_mod, item.span);
413             }
414             ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
415                 self.visit_static(&StaticParts::from_item(item));
416             }
417             ast::ItemKind::Fn(ref decl, fn_header, ref generics, ref body) => {
418                 let inner_attrs = inner_attributes(&item.attrs);
419                 self.visit_fn(
420                     visit::FnKind::ItemFn(item.ident, fn_header, &item.vis, body),
421                     generics,
422                     decl,
423                     item.span,
424                     ast::Defaultness::Final,
425                     Some(&inner_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                 );
437                 self.push_rewrite(item.span, rewrite);
438             }
439             ast::ItemKind::Existential(ref generic_bounds, ref generics) => {
440                 let rewrite = rewrite_existential_type(
441                     &self.get_context(),
442                     self.block_indent,
443                     item.ident,
444                     generic_bounds,
445                     generics,
446                     &item.vis,
447                 );
448                 self.push_rewrite(item.span, rewrite);
449             }
450             ast::ItemKind::GlobalAsm(..) => {
451                 let snippet = Some(self.snippet(item.span).to_owned());
452                 self.push_rewrite(item.span, snippet);
453             }
454             ast::ItemKind::MacroDef(ref def) => {
455                 let rewrite = rewrite_macro_def(
456                     &self.get_context(),
457                     self.shape(),
458                     self.block_indent,
459                     def,
460                     item.ident,
461                     &item.vis,
462                     item.span,
463                 );
464                 self.push_rewrite(item.span, rewrite);
465             }
466         }
467     }
468
469     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
470         skip_out_of_file_lines_range_visitor!(self, ti.span);
471
472         if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
473             self.push_skipped_with_span(ti.span());
474             return;
475         }
476
477         match ti.node {
478             ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
479             ast::TraitItemKind::Method(ref sig, None) => {
480                 let indent = self.block_indent;
481                 let rewrite =
482                     self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
483                 self.push_rewrite(ti.span, rewrite);
484             }
485             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
486                 let inner_attrs = inner_attributes(&ti.attrs);
487                 self.visit_fn(
488                     visit::FnKind::Method(ti.ident, sig, None, body),
489                     &ti.generics,
490                     &sig.decl,
491                     ti.span,
492                     ast::Defaultness::Final,
493                     Some(&inner_attrs),
494                 );
495             }
496             ast::TraitItemKind::Type(ref generic_bounds, ref type_default) => {
497                 let rewrite = rewrite_associated_type(
498                     ti.ident,
499                     type_default.as_ref(),
500                     Some(generic_bounds),
501                     &self.get_context(),
502                     self.block_indent,
503                 );
504                 self.push_rewrite(ti.span, rewrite);
505             }
506             ast::TraitItemKind::Macro(ref mac) => {
507                 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
508             }
509         }
510     }
511
512     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
513         skip_out_of_file_lines_range_visitor!(self, ii.span);
514
515         if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
516             self.push_skipped_with_span(ii.span());
517             return;
518         }
519
520         match ii.node {
521             ast::ImplItemKind::Method(ref sig, ref body) => {
522                 let inner_attrs = inner_attributes(&ii.attrs);
523                 self.visit_fn(
524                     visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
525                     &ii.generics,
526                     &sig.decl,
527                     ii.span,
528                     ii.defaultness,
529                     Some(&inner_attrs),
530                 );
531             }
532             ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
533             ast::ImplItemKind::Type(ref ty) => {
534                 let rewrite = rewrite_associated_impl_type(
535                     ii.ident,
536                     ii.defaultness,
537                     Some(ty),
538                     &self.get_context(),
539                     self.block_indent,
540                 );
541                 self.push_rewrite(ii.span, rewrite);
542             }
543             ast::ImplItemKind::Existential(ref generic_bounds) => {
544                 let rewrite = rewrite_existential_impl_type(
545                     &self.get_context(),
546                     ii.ident,
547                     generic_bounds,
548                     self.block_indent,
549                 );
550                 self.push_rewrite(ii.span, rewrite);
551             }
552             ast::ImplItemKind::Macro(ref mac) => {
553                 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
554             }
555         }
556     }
557
558     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
559         skip_out_of_file_lines_range_visitor!(self, mac.span);
560
561         // 1 = ;
562         let shape = self.shape().sub_width(1).unwrap();
563         let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos));
564         self.push_rewrite(mac.span, rewrite);
565     }
566
567     pub fn push_str(&mut self, s: &str) {
568         self.line_number += count_newlines(s);
569         self.buffer.push_str(s);
570     }
571
572     #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
573     fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
574         if let Some(ref s) = rewrite {
575             self.push_str(s);
576         } else {
577             let snippet = self.snippet(span);
578             self.push_str(snippet);
579         }
580         self.last_pos = source!(self, span).hi();
581     }
582
583     pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
584         self.format_missing_with_indent(source!(self, span).lo());
585         self.push_rewrite_inner(span, rewrite);
586     }
587
588     pub fn push_skipped_with_span(&mut self, span: Span) {
589         self.format_missing_with_indent(source!(self, span).lo());
590         let lo = self.line_number + 1;
591         self.push_rewrite_inner(span, None);
592         let hi = self.line_number + 1;
593         self.skipped_range.push((lo, hi));
594     }
595
596     pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
597         let mut visitor = FmtVisitor::from_source_map(
598             ctx.parse_session,
599             ctx.config,
600             ctx.snippet_provider,
601             ctx.report.clone(),
602         );
603         visitor.set_parent_context(ctx);
604         visitor
605     }
606
607     pub(crate) fn from_source_map(
608         parse_session: &'a ParseSess,
609         config: &'a Config,
610         snippet_provider: &'a SnippetProvider,
611         report: FormatReport,
612     ) -> FmtVisitor<'a> {
613         FmtVisitor {
614             parent_context: None,
615             parse_session,
616             source_map: parse_session.source_map(),
617             buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
618             last_pos: BytePos(0),
619             block_indent: Indent::empty(),
620             config,
621             is_if_else_block: false,
622             snippet_provider,
623             line_number: 0,
624             skipped_range: vec![],
625             macro_rewrite_failure: false,
626             report,
627         }
628     }
629
630     pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
631         self.snippet_provider.span_to_snippet(span)
632     }
633
634     pub fn snippet(&'b self, span: Span) -> &'a str {
635         self.opt_snippet(span).unwrap()
636     }
637
638     // Returns true if we should skip the following item.
639     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
640         for attr in attrs {
641             if attr.name() == DEPR_SKIP_ANNOTATION {
642                 let file_name = self.source_map.span_to_filename(attr.span).into();
643                 self.report.append(
644                     file_name,
645                     vec![FormattingError::from_span(
646                         attr.span,
647                         &self.source_map,
648                         ErrorKind::DeprecatedAttr,
649                     )],
650                 );
651             } else if attr.path.segments[0].ident.to_string() == "rustfmt" {
652                 if attr.path.segments.len() == 1
653                     || attr.path.segments[1].ident.to_string() != "skip"
654                 {
655                     let file_name = self.source_map.span_to_filename(attr.span).into();
656                     self.report.append(
657                         file_name,
658                         vec![FormattingError::from_span(
659                             attr.span,
660                             &self.source_map,
661                             ErrorKind::BadAttr,
662                         )],
663                     );
664                 }
665             }
666         }
667         if contains_skip(attrs) {
668             return true;
669         }
670
671         let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
672         if attrs.is_empty() {
673             return false;
674         }
675
676         let rewrite = attrs.rewrite(&self.get_context(), self.shape());
677         let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
678         self.push_rewrite(span, rewrite);
679
680         false
681     }
682
683     fn walk_mod_items(&mut self, m: &ast::Mod) {
684         self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
685     }
686
687     fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
688         fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
689             match stmt.node {
690                 ast::StmtKind::Item(ref item) => Some(&**item),
691                 _ => None,
692             }
693         }
694
695         if stmts.is_empty() {
696             return;
697         }
698
699         // Extract leading `use ...;`.
700         let items: Vec<_> = stmts
701             .iter()
702             .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
703             .filter_map(|stmt| to_stmt_item(stmt))
704             .collect();
705
706         if items.is_empty() {
707             self.visit_stmt(&stmts[0]);
708             self.walk_stmts(&stmts[1..]);
709         } else {
710             self.visit_items_with_reordering(&items);
711             self.walk_stmts(&stmts[items.len()..]);
712         }
713     }
714
715     fn walk_block_stmts(&mut self, b: &ast::Block) {
716         self.walk_stmts(&b.stmts)
717     }
718
719     fn format_mod(
720         &mut self,
721         m: &ast::Mod,
722         vis: &ast::Visibility,
723         s: Span,
724         ident: ast::Ident,
725         attrs: &[ast::Attribute],
726         is_internal: bool,
727     ) {
728         let vis_str = utils::format_visibility(&self.get_context(), vis);
729         self.push_str(&*vis_str);
730         self.push_str("mod ");
731         // Calling `to_owned()` to work around borrow checker.
732         let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
733         self.push_str(&ident_str);
734
735         if is_internal {
736             match self.config.brace_style() {
737                 BraceStyle::AlwaysNextLine => {
738                     let indent_str = self.block_indent.to_string_with_newline(self.config);
739                     self.push_str(&indent_str);
740                     self.push_str("{");
741                 }
742                 _ => self.push_str(" {"),
743             }
744             // Hackery to account for the closing }.
745             let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
746             let body_snippet =
747                 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
748             let body_snippet = body_snippet.trim();
749             if body_snippet.is_empty() {
750                 self.push_str("}");
751             } else {
752                 self.last_pos = mod_lo;
753                 self.block_indent = self.block_indent.block_indent(self.config);
754                 self.visit_attrs(attrs, ast::AttrStyle::Inner);
755                 self.walk_mod_items(m);
756                 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
757                 self.close_block(false);
758             }
759             self.last_pos = source!(self, m.inner).hi();
760         } else {
761             self.push_str(";");
762             self.last_pos = source!(self, s).hi();
763         }
764     }
765
766     pub fn format_separate_mod(&mut self, m: &ast::Mod, source_file: &source_map::SourceFile) {
767         self.block_indent = Indent::empty();
768         self.walk_mod_items(m);
769         self.format_missing_with_indent(source_file.end_pos);
770     }
771
772     pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
773         while let Some(pos) = self
774             .snippet_provider
775             .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
776         {
777             if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
778                 if snippet.trim().is_empty() {
779                     self.last_pos = pos;
780                 } else {
781                     return;
782                 }
783             }
784         }
785     }
786
787     pub fn with_context<F>(&mut self, f: F) -> Option<String>
788     where
789         F: Fn(&RewriteContext) -> Option<String>,
790     {
791         let result;
792         let macro_rewrite_failure = {
793             let context = self.get_context();
794             result = f(&context);
795             unsafe { *context.macro_rewrite_failure.as_ptr() }
796         };
797         self.macro_rewrite_failure |= macro_rewrite_failure;
798         result
799     }
800
801     pub fn get_context(&self) -> RewriteContext {
802         RewriteContext {
803             parse_session: self.parse_session,
804             source_map: self.source_map,
805             config: self.config,
806             inside_macro: RefCell::new(false),
807             use_block: RefCell::new(false),
808             is_if_else_block: RefCell::new(false),
809             force_one_line_chain: RefCell::new(false),
810             snippet_provider: self.snippet_provider,
811             macro_rewrite_failure: RefCell::new(false),
812             report: self.report.clone(),
813         }
814     }
815 }