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