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