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