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