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