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