]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Do not add parens around lifetimes
[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                     }
162                     .and_then(|attr| {
163                         // Some stmts can have embedded attributes.
164                         // e.g. `match { #![attr] ... }`
165                         let attr_lo = attr.span.lo();
166                         if attr_lo < first_stmt.span.lo() {
167                             Some(attr_lo)
168                         } else {
169                             None
170                         }
171                     })
172                 });
173
174             let snippet = self.snippet(mk_sp(
175                 self.last_pos,
176                 attr_lo.unwrap_or_else(|| first_stmt.span.lo()),
177             ));
178             let len = CommentCodeSlices::new(snippet)
179                 .nth(0)
180                 .and_then(|(kind, _, s)| {
181                     if kind == CodeCharKind::Normal {
182                         s.rfind('\n')
183                     } else {
184                         None
185                     }
186                 });
187             if let Some(len) = len {
188                 self.last_pos = self.last_pos + BytePos::from_usize(len);
189             }
190         }
191
192         // Format inner attributes if available.
193         let skip_rewrite = if let Some(attrs) = inner_attrs {
194             self.visit_attrs(attrs, ast::AttrStyle::Inner)
195         } else {
196             false
197         };
198
199         if skip_rewrite {
200             self.push_rewrite(b.span, None);
201             self.close_block(false);
202             self.last_pos = source!(self, b.span).hi();
203             return;
204         }
205
206         self.walk_block_stmts(b);
207
208         if !b.stmts.is_empty() {
209             if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
210                 if utils::semicolon_for_expr(&self.get_context(), expr) {
211                     self.push_str(";");
212                 }
213             }
214         }
215
216         let mut remove_len = BytePos(0);
217         if let Some(stmt) = b.stmts.last() {
218             let snippet = self.snippet(mk_sp(
219                 stmt.span.hi(),
220                 source!(self, b.span).hi() - brace_compensation,
221             ));
222             let len = CommentCodeSlices::new(snippet)
223                 .last()
224                 .and_then(|(kind, _, s)| {
225                     if kind == CodeCharKind::Normal && s.trim().is_empty() {
226                         Some(s.len())
227                     } else {
228                         None
229                     }
230                 });
231             if let Some(len) = len {
232                 remove_len = BytePos::from_usize(len);
233             }
234         }
235
236         let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
237             let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
238             let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
239             snippet.contains("//") || snippet.contains("/*")
240         };
241         // FIXME: we should compress any newlines here to just one
242         if unindent_comment {
243             self.block_indent = self.block_indent.block_unindent(self.config);
244         }
245         self.format_missing_with_indent(
246             source!(self, b.span).hi() - brace_compensation - remove_len,
247         );
248         if unindent_comment {
249             self.block_indent = self.block_indent.block_indent(self.config);
250         }
251         self.close_block(unindent_comment);
252         self.last_pos = source!(self, b.span).hi();
253     }
254
255     // FIXME: this is a terrible hack to indent the comments between the last
256     // item in the block and the closing brace to the block's level.
257     // The closing brace itself, however, should be indented at a shallower
258     // level.
259     fn close_block(&mut self, unindent_comment: bool) {
260         let total_len = self.buffer.len();
261         let chars_too_many = if unindent_comment {
262             0
263         } else if self.config.hard_tabs() {
264             1
265         } else {
266             self.config.tab_spaces()
267         };
268         self.buffer.truncate(total_len - chars_too_many);
269         self.push_str("}");
270         self.block_indent = self.block_indent.block_unindent(self.config);
271     }
272
273     // Note that this only gets called for function definitions. Required methods
274     // on traits do not get handled here.
275     fn visit_fn(
276         &mut self,
277         fk: visit::FnKind,
278         generics: &ast::Generics,
279         fd: &ast::FnDecl,
280         s: Span,
281         defaultness: ast::Defaultness,
282         inner_attrs: Option<&[ast::Attribute]>,
283     ) {
284         let indent = self.block_indent;
285         let block;
286         let rewrite = match fk {
287             visit::FnKind::ItemFn(ident, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
288                 block = b;
289                 self.rewrite_fn(
290                     indent,
291                     ident,
292                     &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
293                     mk_sp(s.lo(), b.span.lo()),
294                     b,
295                     inner_attrs,
296                 )
297             }
298             visit::FnKind::Closure(_) => unreachable!(),
299         };
300
301         if let Some(fn_str) = rewrite {
302             self.format_missing_with_indent(source!(self, s).lo());
303             self.push_str(&fn_str);
304             if let Some(c) = fn_str.chars().last() {
305                 if c == '}' {
306                     self.last_pos = source!(self, block.span).hi();
307                     return;
308                 }
309             }
310         } else {
311             self.format_missing(source!(self, block.span).lo());
312         }
313
314         self.last_pos = source!(self, block.span).lo();
315         self.visit_block(block, inner_attrs, true)
316     }
317
318     pub fn visit_item(&mut self, item: &ast::Item) {
319         skip_out_of_file_lines_range_visitor!(self, item.span);
320
321         // This is where we bail out if there is a skip attribute. This is only
322         // complex in the module case. It is complex because the module could be
323         // in a separate file and there might be attributes in both files, but
324         // the AST lumps them all together.
325         let filtered_attrs;
326         let mut attrs = &item.attrs;
327         match item.node {
328             // For use items, skip rewriting attributes. Just check for a skip attribute.
329             ast::ItemKind::Use(..) => {
330                 if contains_skip(attrs) {
331                     self.push_skipped_with_span(item.span());
332                     return;
333                 }
334             }
335             // Module is inline, in this case we treat it like any other item.
336             _ if !is_mod_decl(item) => {
337                 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
338                     self.push_skipped_with_span(item.span());
339                     return;
340                 }
341             }
342             // Module is not inline, but should be skipped.
343             ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
344                 return;
345             }
346             // Module is not inline and should not be skipped. We want
347             // to process only the attributes in the current file.
348             ast::ItemKind::Mod(..) => {
349                 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
350                 // Assert because if we should skip it should be caught by
351                 // the above case.
352                 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
353                 attrs = &filtered_attrs;
354             }
355             _ => {
356                 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
357                     self.push_skipped_with_span(item.span());
358                     return;
359                 }
360             }
361         }
362
363         match item.node {
364             ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
365             ast::ItemKind::Impl(..) => {
366                 let snippet = self.snippet(item.span);
367                 let where_span_end = snippet
368                     .find_uncommented("{")
369                     .map(|x| BytePos(x as u32) + source!(self, item.span).lo());
370                 let block_indent = self.block_indent.clone();
371                 let rw =
372                     self.with_context(|ctx| format_impl(&ctx, item, block_indent, where_span_end));
373                 self.push_rewrite(item.span, rw);
374             }
375             ast::ItemKind::Trait(..) => {
376                 let block_indent = self.block_indent.clone();
377                 let rw = self.with_context(|ctx| format_trait(&ctx, item, block_indent));
378                 self.push_rewrite(item.span, rw);
379             }
380             ast::ItemKind::TraitAlias(ref generics, ref generic_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                     generic_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, fn_header, ref generics, ref body) => {
419                 let inner_attrs = inner_attributes(&item.attrs);
420                 self.visit_fn(
421                     visit::FnKind::ItemFn(item.ident, fn_header, &item.vis, body),
422                     generics,
423                     decl,
424                     item.span,
425                     ast::Defaultness::Final,
426                     Some(&inner_attrs),
427                 )
428             }
429             ast::ItemKind::Ty(ref ty, ref generics) => {
430                 let rewrite = rewrite_type_alias(
431                     &self.get_context(),
432                     self.block_indent,
433                     item.ident,
434                     ty,
435                     generics,
436                     &item.vis,
437                 );
438                 self.push_rewrite(item.span, rewrite);
439             }
440             ast::ItemKind::Existential(ref generic_bounds, ref generics) => {
441                 let rewrite = rewrite_existential_type(
442                     &self.get_context(),
443                     self.block_indent,
444                     item.ident,
445                     generic_bounds,
446                     generics,
447                     &item.vis,
448                 );
449                 self.push_rewrite(item.span, rewrite);
450             }
451             ast::ItemKind::GlobalAsm(..) => {
452                 let snippet = Some(self.snippet(item.span).to_owned());
453                 self.push_rewrite(item.span, snippet);
454             }
455             ast::ItemKind::MacroDef(ref def) => {
456                 let rewrite = rewrite_macro_def(
457                     &self.get_context(),
458                     self.shape(),
459                     self.block_indent,
460                     def,
461                     item.ident,
462                     &item.vis,
463                     item.span,
464                 );
465                 self.push_rewrite(item.span, rewrite);
466             }
467         }
468     }
469
470     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
471         skip_out_of_file_lines_range_visitor!(self, ti.span);
472
473         if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
474             self.push_skipped_with_span(ti.span());
475             return;
476         }
477
478         match ti.node {
479             ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
480             ast::TraitItemKind::Method(ref sig, None) => {
481                 let indent = self.block_indent;
482                 let rewrite =
483                     self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
484                 self.push_rewrite(ti.span, rewrite);
485             }
486             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
487                 let inner_attrs = inner_attributes(&ti.attrs);
488                 self.visit_fn(
489                     visit::FnKind::Method(ti.ident, sig, None, body),
490                     &ti.generics,
491                     &sig.decl,
492                     ti.span,
493                     ast::Defaultness::Final,
494                     Some(&inner_attrs),
495                 );
496             }
497             ast::TraitItemKind::Type(ref generic_bounds, ref type_default) => {
498                 let rewrite = rewrite_associated_type(
499                     ti.ident,
500                     type_default.as_ref(),
501                     &ti.generics,
502                     Some(generic_bounds),
503                     &self.get_context(),
504                     self.block_indent,
505                 );
506                 self.push_rewrite(ti.span, rewrite);
507             }
508             ast::TraitItemKind::Macro(ref mac) => {
509                 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
510             }
511         }
512     }
513
514     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
515         skip_out_of_file_lines_range_visitor!(self, ii.span);
516
517         if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
518             self.push_skipped_with_span(ii.span());
519             return;
520         }
521
522         match ii.node {
523             ast::ImplItemKind::Method(ref sig, ref body) => {
524                 let inner_attrs = inner_attributes(&ii.attrs);
525                 self.visit_fn(
526                     visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
527                     &ii.generics,
528                     &sig.decl,
529                     ii.span,
530                     ii.defaultness,
531                     Some(&inner_attrs),
532                 );
533             }
534             ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
535             ast::ImplItemKind::Type(ref ty) => {
536                 let rewrite = rewrite_associated_impl_type(
537                     ii.ident,
538                     ii.defaultness,
539                     Some(ty),
540                     &ii.generics,
541                     &self.get_context(),
542                     self.block_indent,
543                 );
544                 self.push_rewrite(ii.span, rewrite);
545             }
546             ast::ImplItemKind::Existential(ref generic_bounds) => {
547                 let rewrite = rewrite_existential_impl_type(
548                     &self.get_context(),
549                     ii.ident,
550                     &ii.generics,
551                     generic_bounds,
552                     self.block_indent,
553                 );
554                 self.push_rewrite(ii.span, rewrite);
555             }
556             ast::ImplItemKind::Macro(ref mac) => {
557                 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
558             }
559         }
560     }
561
562     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
563         skip_out_of_file_lines_range_visitor!(self, mac.span);
564
565         // 1 = ;
566         let shape = self.shape().sub_width(1).unwrap();
567         let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos));
568         self.push_rewrite(mac.span, rewrite);
569     }
570
571     pub fn push_str(&mut self, s: &str) {
572         self.line_number += count_newlines(s);
573         self.buffer.push_str(s);
574     }
575
576     #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
577     fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
578         if let Some(ref s) = rewrite {
579             self.push_str(s);
580         } else {
581             let snippet = self.snippet(span);
582             self.push_str(snippet);
583         }
584         self.last_pos = source!(self, span).hi();
585     }
586
587     pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
588         self.format_missing_with_indent(source!(self, span).lo());
589         self.push_rewrite_inner(span, rewrite);
590     }
591
592     pub fn push_skipped_with_span(&mut self, span: Span) {
593         self.format_missing_with_indent(source!(self, span).lo());
594         let lo = self.line_number + 1;
595         self.push_rewrite_inner(span, None);
596         let hi = self.line_number + 1;
597         self.skipped_range.push((lo, hi));
598     }
599
600     pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
601         let mut visitor = FmtVisitor::from_source_map(
602             ctx.parse_session,
603             ctx.config,
604             ctx.snippet_provider,
605             ctx.report.clone(),
606         );
607         visitor.set_parent_context(ctx);
608         visitor
609     }
610
611     pub(crate) fn from_source_map(
612         parse_session: &'a ParseSess,
613         config: &'a Config,
614         snippet_provider: &'a SnippetProvider,
615         report: FormatReport,
616     ) -> FmtVisitor<'a> {
617         FmtVisitor {
618             parent_context: None,
619             parse_session,
620             source_map: parse_session.source_map(),
621             buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
622             last_pos: BytePos(0),
623             block_indent: Indent::empty(),
624             config,
625             is_if_else_block: false,
626             snippet_provider,
627             line_number: 0,
628             skipped_range: vec![],
629             macro_rewrite_failure: false,
630             report,
631         }
632     }
633
634     pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
635         self.snippet_provider.span_to_snippet(span)
636     }
637
638     pub fn snippet(&'b self, span: Span) -> &'a str {
639         self.opt_snippet(span).unwrap()
640     }
641
642     // Returns true if we should skip the following item.
643     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
644         for attr in attrs {
645             if attr.name() == DEPR_SKIP_ANNOTATION {
646                 let file_name = self.source_map.span_to_filename(attr.span).into();
647                 self.report.append(
648                     file_name,
649                     vec![FormattingError::from_span(
650                         attr.span,
651                         &self.source_map,
652                         ErrorKind::DeprecatedAttr,
653                     )],
654                 );
655             } else if attr.path.segments[0].ident.to_string() == "rustfmt" {
656                 if attr.path.segments.len() == 1
657                     || attr.path.segments[1].ident.to_string() != "skip"
658                 {
659                     let file_name = self.source_map.span_to_filename(attr.span).into();
660                     self.report.append(
661                         file_name,
662                         vec![FormattingError::from_span(
663                             attr.span,
664                             &self.source_map,
665                             ErrorKind::BadAttr,
666                         )],
667                     );
668                 }
669             }
670         }
671         if contains_skip(attrs) {
672             return true;
673         }
674
675         let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
676         if attrs.is_empty() {
677             return false;
678         }
679
680         let rewrite = attrs.rewrite(&self.get_context(), self.shape());
681         let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
682         self.push_rewrite(span, rewrite);
683
684         false
685     }
686
687     fn walk_mod_items(&mut self, m: &ast::Mod) {
688         self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
689     }
690
691     fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
692         fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
693             match stmt.node {
694                 ast::StmtKind::Item(ref item) => Some(&**item),
695                 _ => None,
696             }
697         }
698
699         if stmts.is_empty() {
700             return;
701         }
702
703         // Extract leading `use ...;`.
704         let items: Vec<_> = stmts
705             .iter()
706             .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
707             .filter_map(|stmt| to_stmt_item(stmt))
708             .collect();
709
710         if items.is_empty() {
711             self.visit_stmt(&stmts[0]);
712             self.walk_stmts(&stmts[1..]);
713         } else {
714             self.visit_items_with_reordering(&items);
715             self.walk_stmts(&stmts[items.len()..]);
716         }
717     }
718
719     fn walk_block_stmts(&mut self, b: &ast::Block) {
720         self.walk_stmts(&b.stmts)
721     }
722
723     fn format_mod(
724         &mut self,
725         m: &ast::Mod,
726         vis: &ast::Visibility,
727         s: Span,
728         ident: ast::Ident,
729         attrs: &[ast::Attribute],
730         is_internal: bool,
731     ) {
732         let vis_str = utils::format_visibility(&self.get_context(), vis);
733         self.push_str(&*vis_str);
734         self.push_str("mod ");
735         // Calling `to_owned()` to work around borrow checker.
736         let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
737         self.push_str(&ident_str);
738
739         if is_internal {
740             match self.config.brace_style() {
741                 BraceStyle::AlwaysNextLine => {
742                     let indent_str = self.block_indent.to_string_with_newline(self.config);
743                     self.push_str(&indent_str);
744                     self.push_str("{");
745                 }
746                 _ => self.push_str(" {"),
747             }
748             // Hackery to account for the closing }.
749             let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
750             let body_snippet =
751                 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
752             let body_snippet = body_snippet.trim();
753             if body_snippet.is_empty() {
754                 self.push_str("}");
755             } else {
756                 self.last_pos = mod_lo;
757                 self.block_indent = self.block_indent.block_indent(self.config);
758                 self.visit_attrs(attrs, ast::AttrStyle::Inner);
759                 self.walk_mod_items(m);
760                 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
761                 self.close_block(false);
762             }
763             self.last_pos = source!(self, m.inner).hi();
764         } else {
765             self.push_str(";");
766             self.last_pos = source!(self, s).hi();
767         }
768     }
769
770     pub fn format_separate_mod(&mut self, m: &ast::Mod, source_file: &source_map::SourceFile) {
771         self.block_indent = Indent::empty();
772         self.walk_mod_items(m);
773         self.format_missing_with_indent(source_file.end_pos);
774     }
775
776     pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
777         while let Some(pos) = self
778             .snippet_provider
779             .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
780         {
781             if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
782                 if snippet.trim().is_empty() {
783                     self.last_pos = pos;
784                 } else {
785                     return;
786                 }
787             }
788         }
789     }
790
791     pub fn with_context<F>(&mut self, f: F) -> Option<String>
792     where
793         F: Fn(&RewriteContext) -> Option<String>,
794     {
795         let result;
796         let macro_rewrite_failure = {
797             let context = self.get_context();
798             result = f(&context);
799             unsafe { *context.macro_rewrite_failure.as_ptr() }
800         };
801         self.macro_rewrite_failure |= macro_rewrite_failure;
802         result
803     }
804
805     pub fn get_context(&self) -> RewriteContext {
806         RewriteContext {
807             parse_session: self.parse_session,
808             source_map: self.source_map,
809             config: self.config,
810             inside_macro: RefCell::new(false),
811             use_block: RefCell::new(false),
812             is_if_else_block: RefCell::new(false),
813             force_one_line_chain: RefCell::new(false),
814             snippet_provider: self.snippet_provider,
815             macro_rewrite_failure: RefCell::new(false),
816             report: self.report.clone(),
817         }
818     }
819 }