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