]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Remove String::rewrite()
[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 std::cmp;
12
13 use strings::string_buffer::StringBuffer;
14 use syntax::{ast, visit};
15 use syntax::attr::HasAttrs;
16 use syntax::codemap::{self, BytePos, CodeMap, Pos, Span};
17 use syntax::parse::ParseSess;
18
19 use expr::rewrite_literal;
20 use spanned::Spanned;
21 use codemap::{LineRangeUtils, SpanUtils};
22 use comment::{contains_comment, recover_missing_comment_in_span, remove_trailing_white_spaces,
23               CodeCharKind, CommentCodeSlices, FindUncommented};
24 use comment::rewrite_comment;
25 use config::{BraceStyle, Config};
26 use items::{format_impl, format_struct, format_struct_struct, format_trait,
27             rewrite_associated_impl_type, rewrite_associated_type, rewrite_static,
28             rewrite_type_alias, FnSig};
29 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
30             SeparatorTactic};
31 use macros::{rewrite_macro, MacroPosition};
32 use regex::Regex;
33 use rewrite::{Rewrite, RewriteContext};
34 use shape::{Indent, Shape};
35 use utils::{self, contains_skip, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
36
37 fn is_use_item(item: &ast::Item) -> bool {
38     match item.node {
39         ast::ItemKind::Use(_) => true,
40         _ => false,
41     }
42 }
43
44 fn is_extern_crate(item: &ast::Item) -> bool {
45     match item.node {
46         ast::ItemKind::ExternCrate(..) => true,
47         _ => false,
48     }
49 }
50
51 pub struct FmtVisitor<'a> {
52     pub parse_session: &'a ParseSess,
53     pub codemap: &'a CodeMap,
54     pub buffer: StringBuffer,
55     pub last_pos: BytePos,
56     // FIXME: use an RAII util or closure for indenting
57     pub block_indent: Indent,
58     pub config: &'a Config,
59     pub is_if_else_block: bool,
60 }
61
62 impl<'a> FmtVisitor<'a> {
63     pub fn shape(&self) -> Shape {
64         Shape::indented(self.block_indent, self.config)
65     }
66
67     fn visit_stmt(&mut self, stmt: &ast::Stmt) {
68         debug!(
69             "visit_stmt: {:?} {:?}",
70             self.codemap.lookup_char_pos(stmt.span.lo()),
71             self.codemap.lookup_char_pos(stmt.span.hi())
72         );
73
74         match stmt.node {
75             ast::StmtKind::Item(ref item) => {
76                 self.visit_item(item);
77             }
78             ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
79                 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
80                 self.push_rewrite(stmt.span(), rewrite)
81             }
82             ast::StmtKind::Mac(ref mac) => {
83                 let (ref mac, _macro_style, ref attrs) = **mac;
84                 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
85                     self.push_rewrite(stmt.span(), None);
86                 } else {
87                     self.visit_mac(mac, None, MacroPosition::Statement);
88                 }
89                 self.format_missing(stmt.span.hi());
90             }
91         }
92     }
93
94     pub fn visit_block(&mut self, b: &ast::Block, inner_attrs: Option<&[ast::Attribute]>) {
95         debug!(
96             "visit_block: {:?} {:?}",
97             self.codemap.lookup_char_pos(b.span.lo()),
98             self.codemap.lookup_char_pos(b.span.hi())
99         );
100
101         // Check if this block has braces.
102         let snippet = self.snippet(b.span);
103         let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
104         let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
105
106         self.last_pos = self.last_pos + brace_compensation;
107         self.block_indent = self.block_indent.block_indent(self.config);
108         self.buffer.push_str("{");
109
110         if self.config.remove_blank_lines_at_start_or_end_of_block() {
111             if let Some(first_stmt) = b.stmts.first() {
112                 let attr_lo = inner_attrs
113                     .and_then(|attrs| {
114                         inner_attributes(attrs).first().map(|attr| attr.span.lo())
115                     })
116                     .or_else(|| {
117                         // Attributes for an item in a statement position
118                         // do not belong to the statement. (rust-lang/rust#34459)
119                         if let ast::StmtKind::Item(ref item) = first_stmt.node {
120                             item.attrs.first()
121                         } else {
122                             first_stmt.attrs().first()
123                         }.and_then(|attr| {
124                             // Some stmts can have embedded attributes.
125                             // e.g. `match { #![attr] ... }`
126                             let attr_lo = attr.span.lo();
127                             if attr_lo < first_stmt.span.lo() {
128                                 Some(attr_lo)
129                             } else {
130                                 None
131                             }
132                         })
133                     });
134
135                 let snippet = self.snippet(mk_sp(
136                     self.last_pos,
137                     attr_lo.unwrap_or(first_stmt.span.lo()),
138                 ));
139                 let len = CommentCodeSlices::new(&snippet).nth(0).and_then(
140                     |(kind, _, s)| if kind == CodeCharKind::Normal {
141                         s.rfind('\n')
142                     } else {
143                         None
144                     },
145                 );
146                 if let Some(len) = len {
147                     self.last_pos = self.last_pos + BytePos::from_usize(len);
148                 }
149             }
150         }
151
152         // Format inner attributes if available.
153         if let Some(attrs) = inner_attrs {
154             self.visit_attrs(attrs, ast::AttrStyle::Inner);
155         }
156
157         self.walk_block_stmts(b);
158
159         if !b.stmts.is_empty() {
160             if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
161                 if utils::semicolon_for_expr(&self.get_context(), expr) {
162                     self.buffer.push_str(";");
163                 }
164             }
165         }
166
167         let mut remove_len = BytePos(0);
168         if self.config.remove_blank_lines_at_start_or_end_of_block() {
169             if let Some(stmt) = b.stmts.last() {
170                 let snippet = self.snippet(mk_sp(
171                     stmt.span.hi(),
172                     source!(self, b.span).hi() - brace_compensation,
173                 ));
174                 let len = CommentCodeSlices::new(&snippet)
175                     .last()
176                     .and_then(|(kind, _, s)| {
177                         if kind == CodeCharKind::Normal && s.trim().is_empty() {
178                             Some(s.len())
179                         } else {
180                             None
181                         }
182                     });
183                 if let Some(len) = len {
184                     remove_len = BytePos::from_usize(len);
185                 }
186             }
187         }
188
189         let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
190         if unindent_comment {
191             let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
192             let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
193             unindent_comment = snippet.contains("//") || snippet.contains("/*");
194         }
195         // FIXME: we should compress any newlines here to just one
196         if unindent_comment {
197             self.block_indent = self.block_indent.block_unindent(self.config);
198         }
199         self.format_missing_with_indent(
200             source!(self, b.span).hi() - brace_compensation - remove_len,
201         );
202         if unindent_comment {
203             self.block_indent = self.block_indent.block_indent(self.config);
204         }
205         self.close_block(unindent_comment);
206         self.last_pos = source!(self, b.span).hi();
207     }
208
209     // FIXME: this is a terrible hack to indent the comments between the last
210     // item in the block and the closing brace to the block's level.
211     // The closing brace itself, however, should be indented at a shallower
212     // level.
213     fn close_block(&mut self, unindent_comment: bool) {
214         let total_len = self.buffer.len;
215         let chars_too_many = if unindent_comment {
216             0
217         } else if self.config.hard_tabs() {
218             1
219         } else {
220             self.config.tab_spaces()
221         };
222         self.buffer.truncate(total_len - chars_too_many);
223         self.buffer.push_str("}");
224         self.block_indent = self.block_indent.block_unindent(self.config);
225     }
226
227     // Note that this only gets called for function definitions. Required methods
228     // on traits do not get handled here.
229     fn visit_fn(
230         &mut self,
231         fk: visit::FnKind,
232         fd: &ast::FnDecl,
233         s: Span,
234         _: ast::NodeId,
235         defaultness: ast::Defaultness,
236         inner_attrs: Option<&[ast::Attribute]>,
237     ) {
238         let indent = self.block_indent;
239         let block;
240         let rewrite = match fk {
241             visit::FnKind::ItemFn(ident, _, _, _, _, _, b) => {
242                 block = b;
243                 self.rewrite_fn(
244                     indent,
245                     ident,
246                     &FnSig::from_fn_kind(&fk, fd, defaultness),
247                     mk_sp(s.lo(), b.span.lo()),
248                     b,
249                 )
250             }
251             visit::FnKind::Method(ident, _, _, b) => {
252                 block = b;
253                 self.rewrite_fn(
254                     indent,
255                     ident,
256                     &FnSig::from_fn_kind(&fk, fd, defaultness),
257                     mk_sp(s.lo(), b.span.lo()),
258                     b,
259                 )
260             }
261             visit::FnKind::Closure(_) => unreachable!(),
262         };
263
264         if let Some(fn_str) = rewrite {
265             self.format_missing_with_indent(source!(self, s).lo());
266             self.buffer.push_str(&fn_str);
267             if let Some(c) = fn_str.chars().last() {
268                 if c == '}' {
269                     self.last_pos = source!(self, block.span).hi();
270                     return;
271                 }
272             }
273         } else {
274             self.format_missing(source!(self, block.span).lo());
275         }
276
277         self.last_pos = source!(self, block.span).lo();
278         self.visit_block(block, inner_attrs)
279     }
280
281     pub fn visit_item(&mut self, item: &ast::Item) {
282         skip_out_of_file_lines_range_visitor!(self, item.span);
283
284         // This is where we bail out if there is a skip attribute. This is only
285         // complex in the module case. It is complex because the module could be
286         // in a separate file and there might be attributes in both files, but
287         // the AST lumps them all together.
288         let filterd_attrs;
289         let mut attrs = &item.attrs;
290         match item.node {
291             ast::ItemKind::Mod(ref m) => {
292                 let outer_file = self.codemap.lookup_char_pos(item.span.lo()).file;
293                 let inner_file = self.codemap.lookup_char_pos(m.inner.lo()).file;
294                 if outer_file.name == inner_file.name {
295                     // Module is inline, in this case we treat modules like any
296                     // other item.
297                     if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
298                         self.push_rewrite(item.span, None);
299                         return;
300                     }
301                 } else if contains_skip(&item.attrs) {
302                     // Module is not inline, but should be skipped.
303                     return;
304                 } else {
305                     // Module is not inline and should not be skipped. We want
306                     // to process only the attributes in the current file.
307                     filterd_attrs = item.attrs
308                         .iter()
309                         .filter_map(|a| {
310                             let attr_file = self.codemap.lookup_char_pos(a.span.lo()).file;
311                             if attr_file.name == outer_file.name {
312                                 Some(a.clone())
313                             } else {
314                                 None
315                             }
316                         })
317                         .collect::<Vec<_>>();
318                     // Assert because if we should skip it should be caught by
319                     // the above case.
320                     assert!(!self.visit_attrs(&filterd_attrs, ast::AttrStyle::Outer));
321                     attrs = &filterd_attrs;
322                 }
323             }
324             _ => if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
325                 self.push_rewrite(item.span, None);
326                 return;
327             },
328         }
329
330         match item.node {
331             ast::ItemKind::Use(ref vp) => self.format_import(item, vp),
332             ast::ItemKind::Impl(..) => {
333                 let snippet = self.snippet(item.span);
334                 let where_span_end = snippet
335                     .find_uncommented("{")
336                     .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
337                 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
338                 self.push_rewrite(item.span, rw);
339             }
340             ast::ItemKind::Trait(..) => {
341                 let rw = format_trait(&self.get_context(), item, self.block_indent);
342                 self.push_rewrite(item.span, rw);
343             }
344             ast::ItemKind::ExternCrate(_) => {
345                 let rw = rewrite_extern_crate(&self.get_context(), item);
346                 self.push_rewrite(item.span, rw);
347             }
348             ast::ItemKind::Struct(ref def, ref generics) => {
349                 let rewrite = format_struct(
350                     &self.get_context(),
351                     "struct ",
352                     item.ident,
353                     &item.vis,
354                     def,
355                     Some(generics),
356                     item.span,
357                     self.block_indent,
358                     None,
359                 ).map(|s| match *def {
360                     ast::VariantData::Tuple(..) => s + ";",
361                     _ => s,
362                 });
363                 self.push_rewrite(item.span, rewrite);
364             }
365             ast::ItemKind::Enum(ref def, ref generics) => {
366                 self.format_missing_with_indent(source!(self, item.span).lo());
367                 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
368                 self.last_pos = source!(self, item.span).hi();
369             }
370             ast::ItemKind::Mod(ref module) => {
371                 self.format_missing_with_indent(source!(self, item.span).lo());
372                 self.format_mod(module, &item.vis, item.span, item.ident, attrs);
373             }
374             ast::ItemKind::Mac(ref mac) => {
375                 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
376             }
377             ast::ItemKind::ForeignMod(ref foreign_mod) => {
378                 self.format_missing_with_indent(source!(self, item.span).lo());
379                 self.format_foreign_mod(foreign_mod, item.span);
380             }
381             ast::ItemKind::Static(ref ty, mutability, ref expr) => {
382                 let rewrite = rewrite_static(
383                     "static",
384                     &item.vis,
385                     item.ident,
386                     ty,
387                     mutability,
388                     Some(expr),
389                     self.block_indent,
390                     item.span,
391                     &self.get_context(),
392                 );
393                 self.push_rewrite(item.span, rewrite);
394             }
395             ast::ItemKind::Const(ref ty, ref expr) => {
396                 let rewrite = rewrite_static(
397                     "const",
398                     &item.vis,
399                     item.ident,
400                     ty,
401                     ast::Mutability::Immutable,
402                     Some(expr),
403                     self.block_indent,
404                     item.span,
405                     &self.get_context(),
406                 );
407                 self.push_rewrite(item.span, rewrite);
408             }
409             ast::ItemKind::DefaultImpl(..) => {
410                 // FIXME(#78): format impl definitions.
411             }
412             ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
413                 self.visit_fn(
414                     visit::FnKind::ItemFn(
415                         item.ident,
416                         generics,
417                         unsafety,
418                         constness,
419                         abi,
420                         &item.vis,
421                         body,
422                     ),
423                     decl,
424                     item.span,
425                     item.id,
426                     ast::Defaultness::Final,
427                     Some(&item.attrs),
428                 )
429             }
430             ast::ItemKind::Ty(ref ty, ref generics) => {
431                 let rewrite = rewrite_type_alias(
432                     &self.get_context(),
433                     self.block_indent,
434                     item.ident,
435                     ty,
436                     generics,
437                     &item.vis,
438                     item.span,
439                 );
440                 self.push_rewrite(item.span, rewrite);
441             }
442             ast::ItemKind::Union(ref def, ref generics) => {
443                 let rewrite = format_struct_struct(
444                     &self.get_context(),
445                     "union ",
446                     item.ident,
447                     &item.vis,
448                     def.fields(),
449                     Some(generics),
450                     item.span,
451                     self.block_indent,
452                     None,
453                 );
454                 self.push_rewrite(item.span, rewrite);
455             }
456             ast::ItemKind::GlobalAsm(..) => {
457                 let snippet = Some(self.snippet(item.span));
458                 self.push_rewrite(item.span, snippet);
459             }
460             ast::ItemKind::MacroDef(..) => {
461                 // FIXME(#1539): macros 2.0
462                 let mac_snippet = Some(remove_trailing_white_spaces(&self.snippet(item.span)));
463                 self.push_rewrite(item.span, mac_snippet);
464             }
465         }
466     }
467
468     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
469         skip_out_of_file_lines_range_visitor!(self, ti.span);
470
471         if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
472             self.push_rewrite(ti.span, None);
473             return;
474         }
475
476         match ti.node {
477             ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
478                 let rewrite = rewrite_static(
479                     "const",
480                     &ast::Visibility::Inherited,
481                     ti.ident,
482                     ty,
483                     ast::Mutability::Immutable,
484                     expr_opt.as_ref(),
485                     self.block_indent,
486                     ti.span,
487                     &self.get_context(),
488                 );
489                 self.push_rewrite(ti.span, rewrite);
490             }
491             ast::TraitItemKind::Method(ref sig, None) => {
492                 let indent = self.block_indent;
493                 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
494                 self.push_rewrite(ti.span, rewrite);
495             }
496             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
497                 self.visit_fn(
498                     visit::FnKind::Method(ti.ident, sig, None, body),
499                     &sig.decl,
500                     ti.span,
501                     ti.id,
502                     ast::Defaultness::Final,
503                     Some(&ti.attrs),
504                 );
505             }
506             ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
507                 let rewrite = rewrite_associated_type(
508                     ti.ident,
509                     type_default.as_ref(),
510                     Some(type_param_bounds),
511                     &self.get_context(),
512                     self.block_indent,
513                 );
514                 self.push_rewrite(ti.span, rewrite);
515             }
516             ast::TraitItemKind::Macro(ref mac) => {
517                 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
518             }
519         }
520     }
521
522     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
523         skip_out_of_file_lines_range_visitor!(self, ii.span);
524
525         if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
526             self.push_rewrite(ii.span, None);
527             return;
528         }
529
530         match ii.node {
531             ast::ImplItemKind::Method(ref sig, ref body) => {
532                 self.visit_fn(
533                     visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
534                     &sig.decl,
535                     ii.span,
536                     ii.id,
537                     ii.defaultness,
538                     Some(&ii.attrs),
539                 );
540             }
541             ast::ImplItemKind::Const(ref ty, ref expr) => {
542                 let rewrite = rewrite_static(
543                     "const",
544                     &ii.vis,
545                     ii.ident,
546                     ty,
547                     ast::Mutability::Immutable,
548                     Some(expr),
549                     self.block_indent,
550                     ii.span,
551                     &self.get_context(),
552                 );
553                 self.push_rewrite(ii.span, rewrite);
554             }
555             ast::ImplItemKind::Type(ref ty) => {
556                 let rewrite = rewrite_associated_impl_type(
557                     ii.ident,
558                     ii.defaultness,
559                     Some(ty),
560                     None,
561                     &self.get_context(),
562                     self.block_indent,
563                 );
564                 self.push_rewrite(ii.span, rewrite);
565             }
566             ast::ImplItemKind::Macro(ref mac) => {
567                 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
568             }
569         }
570     }
571
572     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
573         skip_out_of_file_lines_range_visitor!(self, mac.span);
574
575         // 1 = ;
576         let shape = self.shape().sub_width(1).unwrap();
577         let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
578         self.push_rewrite(mac.span, rewrite);
579     }
580
581     pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
582         self.format_missing_with_indent(source!(self, span).lo());
583         let result = rewrite.unwrap_or_else(|| self.snippet(span));
584         self.buffer.push_str(&result);
585         self.last_pos = source!(self, span).hi();
586     }
587
588     pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
589         FmtVisitor {
590             parse_session: parse_session,
591             codemap: parse_session.codemap(),
592             buffer: StringBuffer::new(),
593             last_pos: BytePos(0),
594             block_indent: Indent::empty(),
595             config: config,
596             is_if_else_block: false,
597         }
598     }
599
600     pub fn snippet(&self, span: Span) -> String {
601         match self.codemap.span_to_snippet(span) {
602             Ok(s) => s,
603             Err(_) => {
604                 println!(
605                     "Couldn't make snippet for span {:?}->{:?}",
606                     self.codemap.lookup_char_pos(span.lo()),
607                     self.codemap.lookup_char_pos(span.hi())
608                 );
609                 "".to_owned()
610             }
611         }
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         if contains_skip(attrs) {
617             return true;
618         }
619
620         let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
621         if attrs.is_empty() {
622             return false;
623         }
624
625         let rewrite = attrs.rewrite(&self.get_context(), self.shape());
626         let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
627         self.push_rewrite(span, rewrite);
628
629         false
630     }
631
632     fn reorder_items<F>(&mut self, items_left: &[&ast::Item], is_item: &F, in_group: bool) -> usize
633     where
634         F: Fn(&ast::Item) -> bool,
635     {
636         let mut last = self.codemap.lookup_line_range(items_left[0].span());
637         let item_length = items_left
638             .iter()
639             .take_while(|ppi| {
640                 is_item(&***ppi) && (!in_group || {
641                     let current = self.codemap.lookup_line_range(ppi.span());
642                     let in_same_group = current.lo < last.hi + 2;
643                     last = current;
644                     in_same_group
645                 })
646             })
647             .count();
648         let items = &items_left[..item_length];
649
650         let at_least_one_in_file_lines = items
651             .iter()
652             .any(|item| !out_of_file_lines_range!(self, item.span));
653
654         if at_least_one_in_file_lines {
655             self.format_imports(items);
656         } else {
657             for item in items {
658                 self.push_rewrite(item.span, None);
659             }
660         }
661
662         item_length
663     }
664
665     fn walk_items(&mut self, mut items_left: &[&ast::Item]) {
666         while !items_left.is_empty() {
667             // If the next item is a `use` declaration, then extract it and any subsequent `use`s
668             // to be potentially reordered within `format_imports`. Otherwise, just format the
669             // next item for output.
670             if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
671                 let used_items_len = self.reorder_items(
672                     items_left,
673                     &is_use_item,
674                     self.config.reorder_imports_in_group(),
675                 );
676                 let (_, rest) = items_left.split_at(used_items_len);
677                 items_left = rest;
678             } else if self.config.reorder_extern_crates() && is_extern_crate(&*items_left[0]) {
679                 let used_items_len = self.reorder_items(
680                     items_left,
681                     &is_extern_crate,
682                     self.config.reorder_extern_crates_in_group(),
683                 );
684                 let (_, rest) = items_left.split_at(used_items_len);
685                 items_left = rest;
686             } else {
687                 // `unwrap()` is safe here because we know `items_left`
688                 // has elements from the loop condition
689                 let (item, rest) = items_left.split_first().unwrap();
690                 self.visit_item(item);
691                 items_left = rest;
692             }
693         }
694     }
695
696     fn walk_mod_items(&mut self, m: &ast::Mod) {
697         self.walk_items(&ptr_vec_to_ref_vec(&m.items));
698     }
699
700     fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
701         fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
702             match stmt.node {
703                 ast::StmtKind::Item(ref item) => Some(&**item),
704                 _ => None,
705             }
706         }
707
708         if stmts.is_empty() {
709             return;
710         }
711
712         // Extract leading `use ...;`.
713         let items: Vec<_> = stmts
714             .iter()
715             .take_while(|stmt| to_stmt_item(stmt).is_some())
716             .filter_map(|stmt| to_stmt_item(stmt))
717             .take_while(|item| is_use_item(item))
718             .collect();
719
720         if items.is_empty() {
721             self.visit_stmt(&stmts[0]);
722             self.walk_stmts(&stmts[1..]);
723         } else {
724             self.walk_items(&items);
725             self.walk_stmts(&stmts[items.len()..]);
726         }
727     }
728
729     fn walk_block_stmts(&mut self, b: &ast::Block) {
730         self.walk_stmts(&b.stmts)
731     }
732
733     fn format_mod(
734         &mut self,
735         m: &ast::Mod,
736         vis: &ast::Visibility,
737         s: Span,
738         ident: ast::Ident,
739         attrs: &[ast::Attribute],
740     ) {
741         // Decide whether this is an inline mod or an external mod.
742         let local_file_name = self.codemap.span_to_filename(s);
743         let inner_span = source!(self, m.inner);
744         let is_internal = !(inner_span.lo().0 == 0 && inner_span.hi().0 == 0)
745             && local_file_name == self.codemap.span_to_filename(inner_span);
746
747         self.buffer.push_str(&*utils::format_visibility(vis));
748         self.buffer.push_str("mod ");
749         self.buffer.push_str(&ident.to_string());
750
751         if is_internal {
752             match self.config.item_brace_style() {
753                 BraceStyle::AlwaysNextLine => self.buffer
754                     .push_str(&format!("\n{}{{", self.block_indent.to_string(self.config))),
755                 _ => self.buffer.push_str(" {"),
756             }
757             // Hackery to account for the closing }.
758             let mod_lo = self.codemap.span_after(source!(self, s), "{");
759             let body_snippet =
760                 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
761             let body_snippet = body_snippet.trim();
762             if body_snippet.is_empty() {
763                 self.buffer.push_str("}");
764             } else {
765                 self.last_pos = mod_lo;
766                 self.block_indent = self.block_indent.block_indent(self.config);
767                 self.visit_attrs(attrs, ast::AttrStyle::Inner);
768                 self.walk_mod_items(m);
769                 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
770                 self.close_block(false);
771             }
772             self.last_pos = source!(self, m.inner).hi();
773         } else {
774             self.buffer.push_str(";");
775             self.last_pos = source!(self, s).hi();
776         }
777     }
778
779     pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
780         self.block_indent = Indent::empty();
781         self.walk_mod_items(m);
782         self.format_missing_with_indent(filemap.end_pos);
783     }
784
785     pub fn get_context(&self) -> RewriteContext {
786         RewriteContext {
787             parse_session: self.parse_session,
788             codemap: self.codemap,
789             config: self.config,
790             inside_macro: false,
791             use_block: false,
792             is_if_else_block: false,
793             force_one_line_chain: false,
794         }
795     }
796 }
797
798 impl Rewrite for ast::NestedMetaItem {
799     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
800         match self.node {
801             ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
802             ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
803         }
804     }
805 }
806
807 impl Rewrite for ast::MetaItem {
808     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
809         Some(match self.node {
810             ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
811             ast::MetaItemKind::List(ref list) => {
812                 let name = self.name.as_str();
813                 // 1 = `(`, 2 = `]` and `)`
814                 let item_shape = shape
815                     .visual_indent(0)
816                     .shrink_left(name.len() + 1)
817                     .and_then(|s| s.sub_width(2))?;
818                 let items = itemize_list(
819                     context.codemap,
820                     list.iter(),
821                     ")",
822                     |nested_meta_item| nested_meta_item.span.lo(),
823                     |nested_meta_item| nested_meta_item.span.hi(),
824                     |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
825                     self.span.lo(),
826                     self.span.hi(),
827                     false,
828                 );
829                 let item_vec = items.collect::<Vec<_>>();
830                 let fmt = ListFormatting {
831                     tactic: DefinitiveListTactic::Mixed,
832                     separator: ",",
833                     trailing_separator: SeparatorTactic::Never,
834                     separator_place: SeparatorPlace::Back,
835                     shape: item_shape,
836                     ends_with_newline: false,
837                     preserve_newline: false,
838                     config: context.config,
839                 };
840                 format!("{}({})", name, write_list(&item_vec, &fmt)?)
841             }
842             ast::MetaItemKind::NameValue(ref literal) => {
843                 let name = self.name.as_str();
844                 // 3 = ` = `
845                 let lit_shape = shape.shrink_left(name.len() + 3)?;
846                 let value = rewrite_literal(context, literal, lit_shape)?;
847                 format!("{} = {}", name, value)
848             }
849         })
850     }
851 }
852
853 impl Rewrite for ast::Attribute {
854     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
855         let prefix = match self.style {
856             ast::AttrStyle::Inner => "#!",
857             ast::AttrStyle::Outer => "#",
858         };
859         let snippet = context.snippet(self.span);
860         if self.is_sugared_doc {
861             let doc_shape = Shape {
862                 width: cmp::min(shape.width, context.config.comment_width())
863                     .checked_sub(shape.indent.width())
864                     .unwrap_or(0),
865                 ..shape
866             };
867             rewrite_comment(&snippet, false, doc_shape, context.config)
868         } else {
869             if contains_comment(&snippet) {
870                 return Some(snippet);
871             }
872             // 1 = `[`
873             let shape = shape.offset_left(prefix.len() + 1)?;
874             self.meta()?
875                 .rewrite(context, shape)
876                 .map(|rw| format!("{}[{}]", prefix, rw))
877         }
878     }
879 }
880
881 impl<'a> Rewrite for [ast::Attribute] {
882     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
883         if self.is_empty() {
884             return Some(String::new());
885         }
886         let mut result = String::with_capacity(128);
887         let indent = shape.indent.to_string(context.config);
888
889         let mut derive_args = Vec::new();
890
891         let mut iter = self.iter().enumerate().peekable();
892         let mut insert_new_line = true;
893         let mut is_prev_sugared_doc = false;
894         while let Some((i, a)) = iter.next() {
895             let a_str = a.rewrite(context, shape)?;
896
897             // Write comments and blank lines between attributes.
898             if i > 0 {
899                 let comment = context.snippet(mk_sp(self[i - 1].span.hi(), a.span.lo()));
900                 // This particular horror show is to preserve line breaks in between doc
901                 // comments. An alternative would be to force such line breaks to start
902                 // with the usual doc comment token.
903                 let (multi_line_before, multi_line_after) = if a.is_sugared_doc
904                     || is_prev_sugared_doc
905                 {
906                     // Look at before and after comment and see if there are any empty lines.
907                     let comment_begin = comment.chars().position(|c| c == '/');
908                     let len = comment_begin.unwrap_or_else(|| comment.len());
909                     let mlb = comment.chars().take(len).filter(|c| *c == '\n').count() > 1;
910                     let mla = if comment_begin.is_none() {
911                         mlb
912                     } else {
913                         let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
914                         let len = comment_end.unwrap();
915                         comment
916                             .chars()
917                             .rev()
918                             .take(len)
919                             .filter(|c| *c == '\n')
920                             .count() > 1
921                     };
922                     (mlb, mla)
923                 } else {
924                     (false, false)
925                 };
926
927                 let comment = recover_missing_comment_in_span(
928                     mk_sp(self[i - 1].span.hi(), a.span.lo()),
929                     shape.with_max_width(context.config),
930                     context,
931                     0,
932                 )?;
933
934                 if !comment.is_empty() {
935                     if multi_line_before {
936                         result.push('\n');
937                     }
938                     result.push_str(&comment);
939                     result.push('\n');
940                     if multi_line_after {
941                         result.push('\n')
942                     }
943                 } else if insert_new_line {
944                     result.push('\n');
945                     if multi_line_after {
946                         result.push('\n')
947                     }
948                 }
949
950                 if derive_args.is_empty() {
951                     result.push_str(&indent);
952                 }
953
954                 insert_new_line = true;
955             }
956
957             // Write the attribute itself.
958             if context.config.merge_derives() {
959                 // If the attribute is `#[derive(...)]`, take the arguments.
960                 if let Some(mut args) = get_derive_args(context, a) {
961                     derive_args.append(&mut args);
962                     match iter.peek() {
963                         // If the next attribute is `#[derive(...)]` as well, skip rewriting.
964                         Some(&(_, next_attr)) if is_derive(next_attr) => insert_new_line = false,
965                         // If not, rewrite the merged derives.
966                         _ => {
967                             result.push_str(&format_derive(context, &derive_args, shape)?);
968                             derive_args.clear();
969                         }
970                     }
971                 } else {
972                     result.push_str(&a_str);
973                 }
974             } else {
975                 result.push_str(&a_str);
976             }
977
978             is_prev_sugared_doc = a.is_sugared_doc;
979         }
980         Some(result)
981     }
982 }
983
984 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
985 fn format_derive(context: &RewriteContext, derive_args: &[String], shape: Shape) -> Option<String> {
986     let mut result = String::with_capacity(128);
987     result.push_str("#[derive(");
988     // 11 = `#[derive()]`
989     let initial_budget = shape.width.checked_sub(11)?;
990     let mut budget = initial_budget;
991     let num = derive_args.len();
992     for (i, a) in derive_args.iter().enumerate() {
993         // 2 = `, ` or `)]`
994         let width = a.len() + 2;
995         if width > budget {
996             if i > 0 {
997                 // Remove trailing whitespace.
998                 result.pop();
999             }
1000             result.push('\n');
1001             // 9 = `#[derive(`
1002             result.push_str(&(shape.indent + 9).to_string(context.config));
1003             budget = initial_budget;
1004         } else {
1005             budget = budget.checked_sub(width).unwrap_or(0);
1006         }
1007         result.push_str(a);
1008         if i != num - 1 {
1009             result.push_str(", ")
1010         }
1011     }
1012     result.push_str(")]");
1013     Some(result)
1014 }
1015
1016 fn is_derive(attr: &ast::Attribute) -> bool {
1017     match attr.meta() {
1018         Some(meta_item) => match meta_item.node {
1019             ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1020             _ => false,
1021         },
1022         _ => false,
1023     }
1024 }
1025
1026 /// Returns the arguments of `#[derive(...)]`.
1027 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
1028     attr.meta().and_then(|meta_item| match meta_item.node {
1029         ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1030             // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1031             Some(
1032                 args.iter()
1033                     .map(|a| context.snippet(a.span))
1034                     .collect::<Vec<_>>(),
1035             )
1036         }
1037         _ => None,
1038     })
1039 }
1040
1041 // Rewrite `extern crate foo;` WITHOUT attributes.
1042 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1043     assert!(is_extern_crate(item));
1044     let new_str = context.snippet(item.span);
1045     Some(if contains_comment(&new_str) {
1046         new_str
1047     } else {
1048         let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1049         String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
1050     })
1051 }