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