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