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