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