]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Merge pull request #2873 from aloucks/auto-detect-newline-style
[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_existential_impl_type,
23     rewrite_existential_type, rewrite_extern_crate, rewrite_type_alias, FnSig, StaticParts,
24     StructParts,
25 };
26 use macros::{rewrite_macro, rewrite_macro_def, MacroPosition};
27 use rewrite::{Rewrite, RewriteContext};
28 use shape::{Indent, Shape};
29 use spanned::Spanned;
30 use utils::{
31     self, contains_skip, count_newlines, inner_attributes, mk_sp, ptr_vec_to_ref_vec,
32     rewrite_ident, DEPR_SKIP_ANNOTATION,
33 };
34 use {ErrorKind, FormatReport, FormattingError};
35
36 use std::cell::RefCell;
37
38 /// Creates a string slice corresponding to the specified span.
39 pub struct SnippetProvider<'a> {
40     /// A pointer to the content of the file we are formatting.
41     big_snippet: &'a str,
42     /// A position of the start of `big_snippet`, used as an offset.
43     start_pos: usize,
44 }
45
46 impl<'a> SnippetProvider<'a> {
47     pub fn span_to_snippet(&self, span: Span) -> Option<&str> {
48         let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
49         let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
50         Some(&self.big_snippet[start_index..end_index])
51     }
52
53     pub fn new(start_pos: BytePos, big_snippet: &'a str) -> Self {
54         let start_pos = start_pos.to_usize();
55         SnippetProvider {
56             big_snippet,
57             start_pos,
58         }
59     }
60 }
61
62 pub struct FmtVisitor<'a> {
63     pub parse_session: &'a ParseSess,
64     pub codemap: &'a CodeMap,
65     pub buffer: String,
66     pub last_pos: BytePos,
67     // FIXME: use an RAII util or closure for indenting
68     pub block_indent: Indent,
69     pub config: &'a Config,
70     pub is_if_else_block: bool,
71     pub snippet_provider: &'a SnippetProvider<'a>,
72     pub line_number: usize,
73     pub skipped_range: Vec<(usize, usize)>,
74     pub macro_rewrite_failure: bool,
75     pub(crate) report: FormatReport,
76 }
77
78 impl<'b, 'a: 'b> FmtVisitor<'a> {
79     pub fn shape(&self) -> Shape {
80         Shape::indented(self.block_indent, self.config)
81     }
82
83     fn visit_stmt(&mut self, stmt: &ast::Stmt) {
84         debug!(
85             "visit_stmt: {:?} {:?}",
86             self.codemap.lookup_char_pos(stmt.span.lo()),
87             self.codemap.lookup_char_pos(stmt.span.hi())
88         );
89
90         match stmt.node {
91             ast::StmtKind::Item(ref item) => {
92                 self.visit_item(item);
93             }
94             ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
95                 if contains_skip(get_attrs_from_stmt(stmt)) {
96                     self.push_skipped_with_span(stmt.span());
97                 } else {
98                     let rewrite = stmt.rewrite(&self.get_context(), self.shape());
99                     self.push_rewrite(stmt.span(), rewrite)
100                 }
101             }
102             ast::StmtKind::Mac(ref mac) => {
103                 let (ref mac, _macro_style, ref attrs) = **mac;
104                 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
105                     self.push_skipped_with_span(stmt.span());
106                 } else {
107                     self.visit_mac(mac, None, MacroPosition::Statement);
108                 }
109                 self.format_missing(stmt.span.hi());
110             }
111         }
112     }
113
114     pub fn visit_block(
115         &mut self,
116         b: &ast::Block,
117         inner_attrs: Option<&[ast::Attribute]>,
118         has_braces: bool,
119     ) {
120         debug!(
121             "visit_block: {:?} {:?}",
122             self.codemap.lookup_char_pos(b.span.lo()),
123             self.codemap.lookup_char_pos(b.span.hi())
124         );
125
126         // Check if this block has braces.
127         let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
128
129         self.last_pos = self.last_pos + brace_compensation;
130         self.block_indent = self.block_indent.block_indent(self.config);
131         self.push_str("{");
132
133         if let Some(first_stmt) = b.stmts.first() {
134             let attr_lo = inner_attrs
135                 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
136                 .or_else(|| {
137                     // Attributes for an item in a statement position
138                     // do not belong to the statement. (rust-lang/rust#34459)
139                     if let ast::StmtKind::Item(ref item) = first_stmt.node {
140                         item.attrs.first()
141                     } else {
142                         first_stmt.attrs().first()
143                     }.and_then(|attr| {
144                         // Some stmts can have embedded attributes.
145                         // e.g. `match { #![attr] ... }`
146                         let attr_lo = attr.span.lo();
147                         if attr_lo < first_stmt.span.lo() {
148                             Some(attr_lo)
149                         } else {
150                             None
151                         }
152                     })
153                 });
154
155             let snippet = self.snippet(mk_sp(
156                 self.last_pos,
157                 attr_lo.unwrap_or_else(|| first_stmt.span.lo()),
158             ));
159             let len = CommentCodeSlices::new(snippet)
160                 .nth(0)
161                 .and_then(|(kind, _, s)| {
162                     if kind == CodeCharKind::Normal {
163                         s.rfind('\n')
164                     } else {
165                         None
166                     }
167                 });
168             if let Some(len) = len {
169                 self.last_pos = self.last_pos + BytePos::from_usize(len);
170             }
171         }
172
173         // Format inner attributes if available.
174         let skip_rewrite = if let Some(attrs) = inner_attrs {
175             self.visit_attrs(attrs, ast::AttrStyle::Inner)
176         } else {
177             false
178         };
179
180         if skip_rewrite {
181             self.push_rewrite(b.span, None);
182             self.close_block(false);
183             self.last_pos = source!(self, b.span).hi();
184             return;
185         }
186
187         self.walk_block_stmts(b);
188
189         if !b.stmts.is_empty() {
190             if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
191                 if utils::semicolon_for_expr(&self.get_context(), expr) {
192                     self.push_str(";");
193                 }
194             }
195         }
196
197         let mut remove_len = BytePos(0);
198         if let Some(stmt) = b.stmts.last() {
199             let snippet = self.snippet(mk_sp(
200                 stmt.span.hi(),
201                 source!(self, b.span).hi() - brace_compensation,
202             ));
203             let len = CommentCodeSlices::new(snippet)
204                 .last()
205                 .and_then(|(kind, _, s)| {
206                     if kind == CodeCharKind::Normal && s.trim().is_empty() {
207                         Some(s.len())
208                     } else {
209                         None
210                     }
211                 });
212             if let Some(len) = len {
213                 remove_len = BytePos::from_usize(len);
214             }
215         }
216
217         let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
218             let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
219             let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
220             snippet.contains("//") || snippet.contains("/*")
221         };
222         // FIXME: we should compress any newlines here to just one
223         if unindent_comment {
224             self.block_indent = self.block_indent.block_unindent(self.config);
225         }
226         self.format_missing_with_indent(
227             source!(self, b.span).hi() - brace_compensation - remove_len,
228         );
229         if unindent_comment {
230             self.block_indent = self.block_indent.block_indent(self.config);
231         }
232         self.close_block(unindent_comment);
233         self.last_pos = source!(self, b.span).hi();
234     }
235
236     // FIXME: this is a terrible hack to indent the comments between the last
237     // item in the block and the closing brace to the block's level.
238     // The closing brace itself, however, should be indented at a shallower
239     // level.
240     fn close_block(&mut self, unindent_comment: bool) {
241         let total_len = self.buffer.len();
242         let chars_too_many = if unindent_comment {
243             0
244         } else if self.config.hard_tabs() {
245             1
246         } else {
247             self.config.tab_spaces()
248         };
249         self.buffer.truncate(total_len - chars_too_many);
250         self.push_str("}");
251         self.block_indent = self.block_indent.block_unindent(self.config);
252     }
253
254     // Note that this only gets called for function definitions. Required methods
255     // on traits do not get handled here.
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                 );
416                 self.push_rewrite(item.span, rewrite);
417             }
418             ast::ItemKind::Existential(ref generic_bounds, ref generics) => {
419                 let rewrite = rewrite_existential_type(
420                     &self.get_context(),
421                     self.block_indent,
422                     item.ident,
423                     generic_bounds,
424                     generics,
425                     &item.vis,
426                 );
427                 self.push_rewrite(item.span, rewrite);
428             }
429             ast::ItemKind::GlobalAsm(..) => {
430                 let snippet = Some(self.snippet(item.span).to_owned());
431                 self.push_rewrite(item.span, snippet);
432             }
433             ast::ItemKind::MacroDef(ref def) => {
434                 let rewrite = rewrite_macro_def(
435                     &self.get_context(),
436                     self.shape(),
437                     self.block_indent,
438                     def,
439                     item.ident,
440                     &item.vis,
441                     item.span,
442                 );
443                 self.push_rewrite(item.span, rewrite);
444             }
445         }
446     }
447
448     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
449         skip_out_of_file_lines_range_visitor!(self, ti.span);
450
451         if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
452             self.push_skipped_with_span(ti.span());
453             return;
454         }
455
456         match ti.node {
457             ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
458             ast::TraitItemKind::Method(ref sig, None) => {
459                 let indent = self.block_indent;
460                 let rewrite =
461                     self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
462                 self.push_rewrite(ti.span, rewrite);
463             }
464             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
465                 let inner_attrs = inner_attributes(&ti.attrs);
466                 self.visit_fn(
467                     visit::FnKind::Method(ti.ident, sig, None, body),
468                     &ti.generics,
469                     &sig.decl,
470                     ti.span,
471                     ast::Defaultness::Final,
472                     Some(&inner_attrs),
473                 );
474             }
475             ast::TraitItemKind::Type(ref generic_bounds, ref type_default) => {
476                 let rewrite = rewrite_associated_type(
477                     ti.ident,
478                     type_default.as_ref(),
479                     Some(generic_bounds),
480                     &self.get_context(),
481                     self.block_indent,
482                 );
483                 self.push_rewrite(ti.span, rewrite);
484             }
485             ast::TraitItemKind::Macro(ref mac) => {
486                 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
487             }
488         }
489     }
490
491     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
492         skip_out_of_file_lines_range_visitor!(self, ii.span);
493
494         if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
495             self.push_skipped_with_span(ii.span());
496             return;
497         }
498
499         match ii.node {
500             ast::ImplItemKind::Method(ref sig, ref body) => {
501                 let inner_attrs = inner_attributes(&ii.attrs);
502                 self.visit_fn(
503                     visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
504                     &ii.generics,
505                     &sig.decl,
506                     ii.span,
507                     ii.defaultness,
508                     Some(&inner_attrs),
509                 );
510             }
511             ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
512             ast::ImplItemKind::Type(ref ty) => {
513                 let rewrite = rewrite_associated_impl_type(
514                     ii.ident,
515                     ii.defaultness,
516                     Some(ty),
517                     &self.get_context(),
518                     self.block_indent,
519                 );
520                 self.push_rewrite(ii.span, rewrite);
521             }
522             ast::ImplItemKind::Existential(ref generic_bounds) => {
523                 let rewrite = rewrite_existential_impl_type(
524                     &self.get_context(),
525                     ii.ident,
526                     generic_bounds,
527                     self.block_indent,
528                 );
529                 self.push_rewrite(ii.span, rewrite);
530             }
531             ast::ImplItemKind::Macro(ref mac) => {
532                 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
533             }
534         }
535     }
536
537     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
538         skip_out_of_file_lines_range_visitor!(self, mac.span);
539
540         // 1 = ;
541         let shape = self.shape().sub_width(1).unwrap();
542         let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos));
543         self.push_rewrite(mac.span, rewrite);
544     }
545
546     pub fn push_str(&mut self, s: &str) {
547         self.line_number += count_newlines(s);
548         self.buffer.push_str(s);
549     }
550
551     #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
552     fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
553         if let Some(ref s) = rewrite {
554             self.push_str(s);
555         } else {
556             let snippet = self.snippet(span);
557             self.push_str(snippet);
558         }
559         self.last_pos = source!(self, span).hi();
560     }
561
562     pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
563         self.format_missing_with_indent(source!(self, span).lo());
564         self.push_rewrite_inner(span, rewrite);
565     }
566
567     pub fn push_skipped_with_span(&mut self, span: Span) {
568         self.format_missing_with_indent(source!(self, span).lo());
569         let lo = self.line_number + 1;
570         self.push_rewrite_inner(span, None);
571         let hi = self.line_number + 1;
572         self.skipped_range.push((lo, hi));
573     }
574
575     pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
576         FmtVisitor::from_codemap(
577             ctx.parse_session,
578             ctx.config,
579             ctx.snippet_provider,
580             ctx.report.clone(),
581         )
582     }
583
584     pub(crate) fn from_codemap(
585         parse_session: &'a ParseSess,
586         config: &'a Config,
587         snippet_provider: &'a SnippetProvider,
588         report: FormatReport,
589     ) -> FmtVisitor<'a> {
590         FmtVisitor {
591             parse_session,
592             codemap: parse_session.codemap(),
593             buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
594             last_pos: BytePos(0),
595             block_indent: Indent::empty(),
596             config,
597             is_if_else_block: false,
598             snippet_provider,
599             line_number: 0,
600             skipped_range: vec![],
601             macro_rewrite_failure: false,
602             report,
603         }
604     }
605
606     pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
607         self.snippet_provider.span_to_snippet(span)
608     }
609
610     pub fn snippet(&'b self, span: Span) -> &'a str {
611         self.opt_snippet(span).unwrap()
612     }
613
614     // Returns true if we should skip the following item.
615     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
616         for attr in attrs {
617             if attr.name() == DEPR_SKIP_ANNOTATION {
618                 let file_name = self.codemap.span_to_filename(attr.span).into();
619                 self.report.append(
620                     file_name,
621                     vec![FormattingError::from_span(
622                         &attr.span,
623                         &self.codemap,
624                         ErrorKind::DeprecatedAttr,
625                     )],
626                 );
627             } else if attr.path.segments[0].ident.to_string() == "rustfmt" {
628                 if attr.path.segments.len() == 1
629                     || attr.path.segments[1].ident.to_string() != "skip"
630                 {
631                     let file_name = self.codemap.span_to_filename(attr.span).into();
632                     self.report.append(
633                         file_name,
634                         vec![FormattingError::from_span(
635                             &attr.span,
636                             &self.codemap,
637                             ErrorKind::BadAttr,
638                         )],
639                     );
640                 }
641             }
642         }
643         if contains_skip(attrs) {
644             return true;
645         }
646
647         let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
648         if attrs.is_empty() {
649             return false;
650         }
651
652         let rewrite = attrs.rewrite(&self.get_context(), self.shape());
653         let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
654         self.push_rewrite(span, rewrite);
655
656         false
657     }
658
659     fn walk_mod_items(&mut self, m: &ast::Mod) {
660         self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
661     }
662
663     fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
664         fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
665             match stmt.node {
666                 ast::StmtKind::Item(ref item) => Some(&**item),
667                 _ => None,
668             }
669         }
670
671         if stmts.is_empty() {
672             return;
673         }
674
675         // Extract leading `use ...;`.
676         let items: Vec<_> = stmts
677             .iter()
678             .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
679             .filter_map(|stmt| to_stmt_item(stmt))
680             .collect();
681
682         if items.is_empty() {
683             self.visit_stmt(&stmts[0]);
684             self.walk_stmts(&stmts[1..]);
685         } else {
686             self.visit_items_with_reordering(&items);
687             self.walk_stmts(&stmts[items.len()..]);
688         }
689     }
690
691     fn walk_block_stmts(&mut self, b: &ast::Block) {
692         self.walk_stmts(&b.stmts)
693     }
694
695     fn format_mod(
696         &mut self,
697         m: &ast::Mod,
698         vis: &ast::Visibility,
699         s: Span,
700         ident: ast::Ident,
701         attrs: &[ast::Attribute],
702         is_internal: bool,
703     ) {
704         let vis_str = utils::format_visibility(&self.get_context(), vis);
705         self.push_str(&*vis_str);
706         self.push_str("mod ");
707         // Calling `to_owned()` to work around borrow checker.
708         let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
709         self.push_str(&ident_str);
710
711         if is_internal {
712             match self.config.brace_style() {
713                 BraceStyle::AlwaysNextLine => {
714                     let indent_str = self.block_indent.to_string_with_newline(self.config);
715                     self.push_str(&indent_str);
716                     self.push_str("{");
717                 }
718                 _ => self.push_str(" {"),
719             }
720             // Hackery to account for the closing }.
721             let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
722             let body_snippet =
723                 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
724             let body_snippet = body_snippet.trim();
725             if body_snippet.is_empty() {
726                 self.push_str("}");
727             } else {
728                 self.last_pos = mod_lo;
729                 self.block_indent = self.block_indent.block_indent(self.config);
730                 self.visit_attrs(attrs, ast::AttrStyle::Inner);
731                 self.walk_mod_items(m);
732                 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
733                 self.close_block(false);
734             }
735             self.last_pos = source!(self, m.inner).hi();
736         } else {
737             self.push_str(";");
738             self.last_pos = source!(self, s).hi();
739         }
740     }
741
742     pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
743         self.block_indent = Indent::empty();
744         self.walk_mod_items(m);
745         self.format_missing_with_indent(filemap.end_pos);
746     }
747
748     pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
749         while let Some(pos) = self
750             .snippet_provider
751             .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
752         {
753             if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
754                 if snippet.trim().is_empty() {
755                     self.last_pos = pos;
756                 } else {
757                     return;
758                 }
759             }
760         }
761     }
762
763     pub fn with_context<F>(&mut self, f: F) -> Option<String>
764     where
765         F: Fn(&RewriteContext) -> Option<String>,
766     {
767         let result;
768         let macro_rewrite_failure = {
769             let context = self.get_context();
770             result = f(&context);
771             unsafe { *context.macro_rewrite_failure.as_ptr() }
772         };
773         self.macro_rewrite_failure |= macro_rewrite_failure;
774         result
775     }
776
777     pub fn get_context(&self) -> RewriteContext {
778         RewriteContext {
779             parse_session: self.parse_session,
780             codemap: self.codemap,
781             config: self.config,
782             inside_macro: RefCell::new(false),
783             use_block: RefCell::new(false),
784             is_if_else_block: RefCell::new(false),
785             force_one_line_chain: RefCell::new(false),
786             snippet_provider: self.snippet_provider,
787             macro_rewrite_failure: RefCell::new(false),
788             report: self.report.clone(),
789         }
790     }
791 }