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