]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Merge pull request #2513 from rtsuk/master
[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::{ast, visit};
12 use syntax::attr::HasAttrs;
13 use syntax::codemap::{self, BytePos, CodeMap, Pos, Span};
14 use syntax::parse::ParseSess;
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                 )
272             }
273             visit::FnKind::Closure(_) => unreachable!(),
274         };
275
276         if let Some(fn_str) = rewrite {
277             self.format_missing_with_indent(source!(self, s).lo());
278             self.push_str(&fn_str);
279             if let Some(c) = fn_str.chars().last() {
280                 if c == '}' {
281                     self.last_pos = source!(self, block.span).hi();
282                     return;
283                 }
284             }
285         } else {
286             self.format_missing(source!(self, block.span).lo());
287         }
288
289         self.last_pos = source!(self, block.span).lo();
290         self.visit_block(block, inner_attrs, true)
291     }
292
293     pub fn visit_item(&mut self, item: &ast::Item) {
294         skip_out_of_file_lines_range_visitor!(self, item.span);
295
296         // This is where we bail out if there is a skip attribute. This is only
297         // complex in the module case. It is complex because the module could be
298         // in a separate file and there might be attributes in both files, but
299         // the AST lumps them all together.
300         let filtered_attrs;
301         let mut attrs = &item.attrs;
302         match item.node {
303             // Module is inline, in this case we treat it like any other item.
304             _ if !is_mod_decl(item) => {
305                 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
306                     self.push_skipped_with_span(item.span());
307                     return;
308                 }
309             }
310             // Module is not inline, but should be skipped.
311             ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
312                 return;
313             }
314             // Module is not inline and should not be skipped. We want
315             // to process only the attributes in the current file.
316             ast::ItemKind::Mod(..) => {
317                 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
318                 // Assert because if we should skip it should be caught by
319                 // the above case.
320                 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
321                 attrs = &filtered_attrs;
322             }
323             _ => {
324                 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
325                     self.push_skipped_with_span(item.span());
326                     return;
327                 }
328             }
329         }
330
331         match item.node {
332             ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
333             ast::ItemKind::Impl(..) => {
334                 let snippet = self.snippet(item.span);
335                 let where_span_end = snippet
336                     .find_uncommented("{")
337                     .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
338                 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
339                 self.push_rewrite(item.span, rw);
340             }
341             ast::ItemKind::Trait(..) => {
342                 let rw = format_trait(&self.get_context(), item, self.block_indent);
343                 self.push_rewrite(item.span, rw);
344             }
345             ast::ItemKind::TraitAlias(ref generics, ref ty_param_bounds) => {
346                 let shape = Shape::indented(self.block_indent, self.config);
347                 let rw = format_trait_alias(
348                     &self.get_context(),
349                     item.ident,
350                     generics,
351                     ty_param_bounds,
352                     shape,
353                 );
354                 self.push_rewrite(item.span, rw);
355             }
356             ast::ItemKind::ExternCrate(_) => {
357                 let rw = rewrite_extern_crate(&self.get_context(), item);
358                 self.push_rewrite(item.span, rw);
359             }
360             ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
361                 self.visit_struct(&StructParts::from_item(item));
362             }
363             ast::ItemKind::Enum(ref def, ref generics) => {
364                 self.format_missing_with_indent(source!(self, item.span).lo());
365                 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
366                 self.last_pos = source!(self, item.span).hi();
367             }
368             ast::ItemKind::Mod(ref module) => {
369                 let is_inline = !is_mod_decl(item);
370                 self.format_missing_with_indent(source!(self, item.span).lo());
371                 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
372             }
373             ast::ItemKind::Mac(ref mac) => {
374                 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
375             }
376             ast::ItemKind::ForeignMod(ref foreign_mod) => {
377                 self.format_missing_with_indent(source!(self, item.span).lo());
378                 self.format_foreign_mod(foreign_mod, item.span);
379             }
380             ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
381                 self.visit_static(&StaticParts::from_item(item));
382             }
383             ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
384                 self.visit_fn(
385                     visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
386                     generics,
387                     decl,
388                     item.span,
389                     ast::Defaultness::Final,
390                     Some(&item.attrs),
391                 )
392             }
393             ast::ItemKind::Ty(ref ty, ref generics) => {
394                 let rewrite = rewrite_type_alias(
395                     &self.get_context(),
396                     self.block_indent,
397                     item.ident,
398                     ty,
399                     generics,
400                     &item.vis,
401                     item.span,
402                 );
403                 self.push_rewrite(item.span, rewrite);
404             }
405             ast::ItemKind::GlobalAsm(..) => {
406                 let snippet = Some(self.snippet(item.span).to_owned());
407                 self.push_rewrite(item.span, snippet);
408             }
409             ast::ItemKind::MacroDef(ref def) => {
410                 let rewrite = rewrite_macro_def(
411                     &self.get_context(),
412                     self.shape(),
413                     self.block_indent,
414                     def,
415                     item.ident,
416                     &item.vis,
417                     item.span,
418                 );
419                 self.push_rewrite(item.span, rewrite);
420             }
421         }
422     }
423
424     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
425         skip_out_of_file_lines_range_visitor!(self, ti.span);
426
427         if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
428             self.push_skipped_with_span(ti.span());
429             return;
430         }
431
432         match ti.node {
433             ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
434             ast::TraitItemKind::Method(ref sig, None) => {
435                 let indent = self.block_indent;
436                 let rewrite =
437                     self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
438                 self.push_rewrite(ti.span, rewrite);
439             }
440             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
441                 self.visit_fn(
442                     visit::FnKind::Method(ti.ident, sig, None, body),
443                     &ti.generics,
444                     &sig.decl,
445                     ti.span,
446                     ast::Defaultness::Final,
447                     Some(&ti.attrs),
448                 );
449             }
450             ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
451                 let rewrite = rewrite_associated_type(
452                     ti.ident,
453                     type_default.as_ref(),
454                     Some(type_param_bounds),
455                     &self.get_context(),
456                     self.block_indent,
457                 );
458                 self.push_rewrite(ti.span, rewrite);
459             }
460             ast::TraitItemKind::Macro(ref mac) => {
461                 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
462             }
463         }
464     }
465
466     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
467         skip_out_of_file_lines_range_visitor!(self, ii.span);
468
469         if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
470             self.push_skipped_with_span(ii.span());
471             return;
472         }
473
474         match ii.node {
475             ast::ImplItemKind::Method(ref sig, ref body) => {
476                 self.visit_fn(
477                     visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
478                     &ii.generics,
479                     &sig.decl,
480                     ii.span,
481                     ii.defaultness,
482                     Some(&ii.attrs),
483                 );
484             }
485             ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
486             ast::ImplItemKind::Type(ref ty) => {
487                 let rewrite = rewrite_associated_impl_type(
488                     ii.ident,
489                     ii.defaultness,
490                     Some(ty),
491                     None,
492                     &self.get_context(),
493                     self.block_indent,
494                 );
495                 self.push_rewrite(ii.span, rewrite);
496             }
497             ast::ImplItemKind::Macro(ref mac) => {
498                 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
499             }
500         }
501     }
502
503     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
504         skip_out_of_file_lines_range_visitor!(self, mac.span);
505
506         // 1 = ;
507         let shape = self.shape().sub_width(1).unwrap();
508         let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
509         self.push_rewrite(mac.span, rewrite);
510     }
511
512     pub fn push_str(&mut self, s: &str) {
513         self.line_number += count_newlines(s);
514         self.buffer.push_str(s);
515     }
516
517     #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
518     fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
519         if let Some(ref s) = rewrite {
520             self.push_str(s);
521         } else {
522             let snippet = self.snippet(span);
523             self.push_str(snippet);
524         }
525         self.last_pos = source!(self, span).hi();
526     }
527
528     pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
529         self.format_missing_with_indent(source!(self, span).lo());
530         self.push_rewrite_inner(span, rewrite);
531     }
532
533     pub fn push_skipped_with_span(&mut self, span: Span) {
534         self.format_missing_with_indent(source!(self, span).lo());
535         let lo = self.line_number + 1;
536         self.push_rewrite_inner(span, None);
537         let hi = self.line_number + 1;
538         self.skipped_range.push((lo, hi));
539     }
540
541     pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
542         FmtVisitor::from_codemap(ctx.parse_session, ctx.config, ctx.snippet_provider)
543     }
544
545     pub fn from_codemap(
546         parse_session: &'a ParseSess,
547         config: &'a Config,
548         snippet_provider: &'a SnippetProvider,
549     ) -> FmtVisitor<'a> {
550         FmtVisitor {
551             parse_session,
552             codemap: parse_session.codemap(),
553             buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
554             last_pos: BytePos(0),
555             block_indent: Indent::empty(),
556             config,
557             is_if_else_block: false,
558             snippet_provider,
559             line_number: 0,
560             skipped_range: vec![],
561         }
562     }
563
564     pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
565         self.snippet_provider.span_to_snippet(span)
566     }
567
568     pub fn snippet(&'b self, span: Span) -> &'a str {
569         self.opt_snippet(span).unwrap()
570     }
571
572     // Returns true if we should skip the following item.
573     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
574         if contains_skip(attrs) {
575             return true;
576         }
577
578         let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
579         if attrs.is_empty() {
580             return false;
581         }
582
583         let rewrite = attrs.rewrite(&self.get_context(), self.shape());
584         let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
585         self.push_rewrite(span, rewrite);
586
587         false
588     }
589
590     fn walk_mod_items(&mut self, m: &ast::Mod) {
591         self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
592     }
593
594     fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
595         fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
596             match stmt.node {
597                 ast::StmtKind::Item(ref item) => Some(&**item),
598                 _ => None,
599             }
600         }
601
602         if stmts.is_empty() {
603             return;
604         }
605
606         // Extract leading `use ...;`.
607         let items: Vec<_> = stmts
608             .iter()
609             .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
610             .filter_map(|stmt| to_stmt_item(stmt))
611             .collect();
612
613         if items.is_empty() {
614             self.visit_stmt(&stmts[0]);
615             self.walk_stmts(&stmts[1..]);
616         } else {
617             self.visit_items_with_reordering(&items);
618             self.walk_stmts(&stmts[items.len()..]);
619         }
620     }
621
622     fn walk_block_stmts(&mut self, b: &ast::Block) {
623         self.walk_stmts(&b.stmts)
624     }
625
626     fn format_mod(
627         &mut self,
628         m: &ast::Mod,
629         vis: &ast::Visibility,
630         s: Span,
631         ident: ast::Ident,
632         attrs: &[ast::Attribute],
633         is_internal: bool,
634     ) {
635         self.push_str(&*utils::format_visibility(vis));
636         self.push_str("mod ");
637         self.push_str(&ident.to_string());
638
639         if is_internal {
640             match self.config.brace_style() {
641                 BraceStyle::AlwaysNextLine => {
642                     let indent_str = self.block_indent.to_string_with_newline(self.config);
643                     self.push_str(&indent_str);
644                     self.push_str("{");
645                 }
646                 _ => self.push_str(" {"),
647             }
648             // Hackery to account for the closing }.
649             let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
650             let body_snippet =
651                 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
652             let body_snippet = body_snippet.trim();
653             if body_snippet.is_empty() {
654                 self.push_str("}");
655             } else {
656                 self.last_pos = mod_lo;
657                 self.block_indent = self.block_indent.block_indent(self.config);
658                 self.visit_attrs(attrs, ast::AttrStyle::Inner);
659                 self.walk_mod_items(m);
660                 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
661                 self.close_block(false);
662             }
663             self.last_pos = source!(self, m.inner).hi();
664         } else {
665             self.push_str(";");
666             self.last_pos = source!(self, s).hi();
667         }
668     }
669
670     pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
671         self.block_indent = Indent::empty();
672         self.walk_mod_items(m);
673         self.format_missing_with_indent(filemap.end_pos);
674     }
675
676     pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
677         while let Some(pos) = self.snippet_provider
678             .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
679         {
680             if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
681                 if snippet.trim().is_empty() {
682                     self.last_pos = pos;
683                 } else {
684                     return;
685                 }
686             }
687         }
688     }
689
690     pub fn get_context(&self) -> RewriteContext {
691         RewriteContext {
692             parse_session: self.parse_session,
693             codemap: self.codemap,
694             config: self.config,
695             inside_macro: false,
696             use_block: RefCell::new(false),
697             is_if_else_block: false,
698             force_one_line_chain: RefCell::new(false),
699             snippet_provider: self.snippet_provider,
700         }
701     }
702 }