]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Add SnippetProvider
[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::rc::Rc;
12 use std::cmp;
13 use std::mem;
14
15 use strings::string_buffer::StringBuffer;
16 use syntax::{ast, visit};
17 use syntax::attr::HasAttrs;
18 use syntax::codemap::{self, BytePos, CodeMap, Pos, Span};
19 use syntax::parse::ParseSess;
20
21 use expr::rewrite_literal;
22 use spanned::Spanned;
23 use codemap::{LineRangeUtils, SpanUtils};
24 use comment::{combine_strs_with_missing_comments, contains_comment, remove_trailing_white_spaces,
25               CodeCharKind, CommentCodeSlices, FindUncommented};
26 use comment::rewrite_comment;
27 use config::{BraceStyle, Config};
28 use items::{format_impl, format_trait, rewrite_associated_impl_type, rewrite_associated_type,
29             rewrite_type_alias, FnSig, StaticParts, StructParts};
30 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorPlace,
31             SeparatorTactic};
32 use macros::{rewrite_macro, MacroPosition};
33 use regex::Regex;
34 use rewrite::{Rewrite, RewriteContext};
35 use shape::{Indent, Shape};
36 use utils::{self, contains_skip, count_newlines, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
37
38 fn is_use_item(item: &ast::Item) -> bool {
39     match item.node {
40         ast::ItemKind::Use(_) => true,
41         _ => false,
42     }
43 }
44
45 fn is_extern_crate(item: &ast::Item) -> bool {
46     match item.node {
47         ast::ItemKind::ExternCrate(..) => true,
48         _ => false,
49     }
50 }
51
52 /// Creates a string slice corresponding to the specified span.
53 pub struct SnippetProvider {
54     /// A pointer to the content of the file we are formatting.
55     big_snippet: *const Rc<String>,
56     /// A position of the start of `big_snippet`, used as an offset.
57     start_pos: usize,
58 }
59
60 impl SnippetProvider {
61     pub fn span_to_snippet(&self, span: Span) -> Option<&str> {
62         let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
63         let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
64         unsafe { Some(&(*self.big_snippet)[start_index..end_index]) }
65     }
66
67     pub fn from_codemap(codemap: &CodeMap, span: Span) -> Self {
68         let filemap = codemap.lookup_char_pos(span.lo()).file;
69         let big_snippet = unsafe { mem::transmute(&filemap.src) };
70         let start_pos = filemap.start_pos.to_usize();
71         SnippetProvider {
72             big_snippet,
73             start_pos,
74         }
75     }
76 }
77
78 pub struct FmtVisitor<'a> {
79     pub parse_session: &'a ParseSess,
80     pub codemap: &'a CodeMap,
81     pub buffer: StringBuffer,
82     pub last_pos: BytePos,
83     // FIXME: use an RAII util or closure for indenting
84     pub block_indent: Indent,
85     pub config: &'a Config,
86     pub is_if_else_block: bool,
87 }
88
89 impl<'a> FmtVisitor<'a> {
90     pub fn shape(&self) -> Shape {
91         Shape::indented(self.block_indent, self.config)
92     }
93
94     fn visit_stmt(&mut self, stmt: &ast::Stmt) {
95         debug!(
96             "visit_stmt: {:?} {:?}",
97             self.codemap.lookup_char_pos(stmt.span.lo()),
98             self.codemap.lookup_char_pos(stmt.span.hi())
99         );
100
101         match stmt.node {
102             ast::StmtKind::Item(ref item) => {
103                 self.visit_item(item);
104             }
105             ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
106                 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
107                 self.push_rewrite(stmt.span(), rewrite)
108             }
109             ast::StmtKind::Mac(ref mac) => {
110                 let (ref mac, _macro_style, ref attrs) = **mac;
111                 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
112                     self.push_rewrite(stmt.span(), None);
113                 } else {
114                     self.visit_mac(mac, None, MacroPosition::Statement);
115                 }
116                 self.format_missing(stmt.span.hi());
117             }
118         }
119     }
120
121     pub fn visit_block(
122         &mut self,
123         b: &ast::Block,
124         inner_attrs: Option<&[ast::Attribute]>,
125         has_braces: bool,
126     ) {
127         debug!(
128             "visit_block: {:?} {:?}",
129             self.codemap.lookup_char_pos(b.span.lo()),
130             self.codemap.lookup_char_pos(b.span.hi())
131         );
132
133         // Check if this block has braces.
134         let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
135
136         self.last_pos = self.last_pos + brace_compensation;
137         self.block_indent = self.block_indent.block_indent(self.config);
138         self.buffer.push_str("{");
139
140         if self.config.remove_blank_lines_at_start_or_end_of_block() {
141             if let Some(first_stmt) = b.stmts.first() {
142                 let attr_lo = inner_attrs
143                     .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
144                     .or_else(|| {
145                         // Attributes for an item in a statement position
146                         // do not belong to the statement. (rust-lang/rust#34459)
147                         if let ast::StmtKind::Item(ref item) = first_stmt.node {
148                             item.attrs.first()
149                         } else {
150                             first_stmt.attrs().first()
151                         }.and_then(|attr| {
152                             // Some stmts can have embedded attributes.
153                             // e.g. `match { #![attr] ... }`
154                             let attr_lo = attr.span.lo();
155                             if attr_lo < first_stmt.span.lo() {
156                                 Some(attr_lo)
157                             } else {
158                                 None
159                             }
160                         })
161                     });
162
163                 let snippet = self.snippet(mk_sp(
164                     self.last_pos,
165                     attr_lo.unwrap_or(first_stmt.span.lo()),
166                 ));
167                 let len = CommentCodeSlices::new(&snippet)
168                     .nth(0)
169                     .and_then(|(kind, _, s)| {
170                         if kind == CodeCharKind::Normal {
171                             s.rfind('\n')
172                         } else {
173                             None
174                         }
175                     });
176                 if let Some(len) = len {
177                     self.last_pos = self.last_pos + BytePos::from_usize(len);
178                 }
179             }
180         }
181
182         // Format inner attributes if available.
183         let skip_rewrite = if let Some(attrs) = inner_attrs {
184             self.visit_attrs(attrs, ast::AttrStyle::Inner)
185         } else {
186             false
187         };
188
189         if skip_rewrite {
190             self.push_rewrite(b.span, None);
191             self.close_block(false);
192             self.last_pos = source!(self, b.span).hi();
193             return;
194         }
195
196         self.walk_block_stmts(b);
197
198         if !b.stmts.is_empty() {
199             if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
200                 if utils::semicolon_for_expr(&self.get_context(), expr) {
201                     self.buffer.push_str(";");
202                 }
203             }
204         }
205
206         let mut remove_len = BytePos(0);
207         if self.config.remove_blank_lines_at_start_or_end_of_block() {
208             if let Some(stmt) = b.stmts.last() {
209                 let snippet = self.snippet(mk_sp(
210                     stmt.span.hi(),
211                     source!(self, b.span).hi() - brace_compensation,
212                 ));
213                 let len = CommentCodeSlices::new(&snippet)
214                     .last()
215                     .and_then(|(kind, _, s)| {
216                         if kind == CodeCharKind::Normal && s.trim().is_empty() {
217                             Some(s.len())
218                         } else {
219                             None
220                         }
221                     });
222                 if let Some(len) = len {
223                     remove_len = BytePos::from_usize(len);
224                 }
225             }
226         }
227
228         let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
229             let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
230             let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
231             snippet.contains("//") || snippet.contains("/*")
232         };
233         // FIXME: we should compress any newlines here to just one
234         if unindent_comment {
235             self.block_indent = self.block_indent.block_unindent(self.config);
236         }
237         self.format_missing_with_indent(
238             source!(self, b.span).hi() - brace_compensation - remove_len,
239         );
240         if unindent_comment {
241             self.block_indent = self.block_indent.block_indent(self.config);
242         }
243         self.close_block(unindent_comment);
244         self.last_pos = source!(self, b.span).hi();
245     }
246
247     // FIXME: this is a terrible hack to indent the comments between the last
248     // item in the block and the closing brace to the block's level.
249     // The closing brace itself, however, should be indented at a shallower
250     // level.
251     fn close_block(&mut self, unindent_comment: bool) {
252         let total_len = self.buffer.len;
253         let chars_too_many = if unindent_comment {
254             0
255         } else if self.config.hard_tabs() {
256             1
257         } else {
258             self.config.tab_spaces()
259         };
260         self.buffer.truncate(total_len - chars_too_many);
261         self.buffer.push_str("}");
262         self.block_indent = self.block_indent.block_unindent(self.config);
263     }
264
265     // Note that this only gets called for function definitions. Required methods
266     // on traits do not get handled here.
267     fn visit_fn(
268         &mut self,
269         fk: visit::FnKind,
270         generics: &ast::Generics,
271         fd: &ast::FnDecl,
272         s: Span,
273         defaultness: ast::Defaultness,
274         inner_attrs: Option<&[ast::Attribute]>,
275     ) {
276         let indent = self.block_indent;
277         let block;
278         let rewrite = match fk {
279             visit::FnKind::ItemFn(ident, _, _, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
280                 block = b;
281                 self.rewrite_fn(
282                     indent,
283                     ident,
284                     &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
285                     mk_sp(s.lo(), b.span.lo()),
286                     b,
287                 )
288             }
289             visit::FnKind::Closure(_) => unreachable!(),
290         };
291
292         if let Some(fn_str) = rewrite {
293             self.format_missing_with_indent(source!(self, s).lo());
294             self.buffer.push_str(&fn_str);
295             if let Some(c) = fn_str.chars().last() {
296                 if c == '}' {
297                     self.last_pos = source!(self, block.span).hi();
298                     return;
299                 }
300             }
301         } else {
302             self.format_missing(source!(self, block.span).lo());
303         }
304
305         self.last_pos = source!(self, block.span).lo();
306         self.visit_block(block, inner_attrs, true)
307     }
308
309     pub fn visit_item(&mut self, item: &ast::Item) {
310         skip_out_of_file_lines_range_visitor!(self, item.span);
311
312         // This is where we bail out if there is a skip attribute. This is only
313         // complex in the module case. It is complex because the module could be
314         // in a separate file and there might be attributes in both files, but
315         // the AST lumps them all together.
316         let filtered_attrs;
317         let mut attrs = &item.attrs;
318         match item.node {
319             ast::ItemKind::Mod(ref m) => {
320                 let outer_file = self.codemap.lookup_char_pos(item.span.lo()).file;
321                 let inner_file = self.codemap.lookup_char_pos(m.inner.lo()).file;
322                 if outer_file.name == inner_file.name {
323                     // Module is inline, in this case we treat modules like any
324                     // other item.
325                     if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
326                         self.push_rewrite(item.span, None);
327                         return;
328                     }
329                 } else if contains_skip(&item.attrs) {
330                     // Module is not inline, but should be skipped.
331                     return;
332                 } else {
333                     // Module is not inline and should not be skipped. We want
334                     // to process only the attributes in the current file.
335                     filtered_attrs = item.attrs
336                         .iter()
337                         .filter_map(|a| {
338                             let attr_file = self.codemap.lookup_char_pos(a.span.lo()).file;
339                             if attr_file.name == outer_file.name {
340                                 Some(a.clone())
341                             } else {
342                                 None
343                             }
344                         })
345                         .collect::<Vec<_>>();
346                     // Assert because if we should skip it should be caught by
347                     // the above case.
348                     assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
349                     attrs = &filtered_attrs;
350                 }
351             }
352             _ => {
353                 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
354                     self.push_rewrite(item.span, None);
355                     return;
356                 }
357             }
358         }
359
360         match item.node {
361             ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
362             ast::ItemKind::Impl(..) => {
363                 let snippet = self.snippet(item.span);
364                 let where_span_end = snippet
365                     .find_uncommented("{")
366                     .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
367                 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
368                 self.push_rewrite(item.span, rw);
369             }
370             ast::ItemKind::Trait(..) => {
371                 let rw = format_trait(&self.get_context(), item, self.block_indent);
372                 self.push_rewrite(item.span, rw);
373             }
374             ast::ItemKind::ExternCrate(_) => {
375                 let rw = rewrite_extern_crate(&self.get_context(), item);
376                 self.push_rewrite(item.span, rw);
377             }
378             ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
379                 self.visit_struct(&StructParts::from_item(item));
380             }
381             ast::ItemKind::Enum(ref def, ref generics) => {
382                 self.format_missing_with_indent(source!(self, item.span).lo());
383                 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
384                 self.last_pos = source!(self, item.span).hi();
385             }
386             ast::ItemKind::Mod(ref module) => {
387                 self.format_missing_with_indent(source!(self, item.span).lo());
388                 self.format_mod(module, &item.vis, item.span, item.ident, attrs);
389             }
390             ast::ItemKind::Mac(ref mac) => {
391                 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
392             }
393             ast::ItemKind::ForeignMod(ref foreign_mod) => {
394                 self.format_missing_with_indent(source!(self, item.span).lo());
395                 self.format_foreign_mod(foreign_mod, item.span);
396             }
397             ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
398                 self.visit_static(&StaticParts::from_item(item));
399             }
400             ast::ItemKind::AutoImpl(..) => {
401                 // FIXME(#78): format impl definitions.
402             }
403             ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
404                 self.visit_fn(
405                     visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
406                     generics,
407                     decl,
408                     item.span,
409                     ast::Defaultness::Final,
410                     Some(&item.attrs),
411                 )
412             }
413             ast::ItemKind::Ty(ref ty, ref generics) => {
414                 let rewrite = rewrite_type_alias(
415                     &self.get_context(),
416                     self.block_indent,
417                     item.ident,
418                     ty,
419                     generics,
420                     &item.vis,
421                     item.span,
422                 );
423                 self.push_rewrite(item.span, rewrite);
424             }
425             ast::ItemKind::GlobalAsm(..) => {
426                 let snippet = Some(self.snippet(item.span));
427                 self.push_rewrite(item.span, snippet);
428             }
429             ast::ItemKind::MacroDef(..) => {
430                 // FIXME(#1539): macros 2.0
431                 let mac_snippet = Some(remove_trailing_white_spaces(&self.snippet(item.span)));
432                 self.push_rewrite(item.span, mac_snippet);
433             }
434         }
435     }
436
437     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
438         skip_out_of_file_lines_range_visitor!(self, ti.span);
439
440         if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
441             self.push_rewrite(ti.span, None);
442             return;
443         }
444
445         match ti.node {
446             ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
447             ast::TraitItemKind::Method(ref sig, None) => {
448                 let indent = self.block_indent;
449                 let rewrite =
450                     self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
451                 self.push_rewrite(ti.span, rewrite);
452             }
453             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
454                 self.visit_fn(
455                     visit::FnKind::Method(ti.ident, sig, None, body),
456                     &ti.generics,
457                     &sig.decl,
458                     ti.span,
459                     ast::Defaultness::Final,
460                     Some(&ti.attrs),
461                 );
462             }
463             ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
464                 let rewrite = rewrite_associated_type(
465                     ti.ident,
466                     type_default.as_ref(),
467                     Some(type_param_bounds),
468                     &self.get_context(),
469                     self.block_indent,
470                 );
471                 self.push_rewrite(ti.span, rewrite);
472             }
473             ast::TraitItemKind::Macro(ref mac) => {
474                 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
475             }
476         }
477     }
478
479     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
480         skip_out_of_file_lines_range_visitor!(self, ii.span);
481
482         if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
483             self.push_rewrite(ii.span, None);
484             return;
485         }
486
487         match ii.node {
488             ast::ImplItemKind::Method(ref sig, ref body) => {
489                 self.visit_fn(
490                     visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
491                     &ii.generics,
492                     &sig.decl,
493                     ii.span,
494                     ii.defaultness,
495                     Some(&ii.attrs),
496                 );
497             }
498             ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
499             ast::ImplItemKind::Type(ref ty) => {
500                 let rewrite = rewrite_associated_impl_type(
501                     ii.ident,
502                     ii.defaultness,
503                     Some(ty),
504                     None,
505                     &self.get_context(),
506                     self.block_indent,
507                 );
508                 self.push_rewrite(ii.span, rewrite);
509             }
510             ast::ImplItemKind::Macro(ref mac) => {
511                 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
512             }
513         }
514     }
515
516     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
517         skip_out_of_file_lines_range_visitor!(self, mac.span);
518
519         // 1 = ;
520         let shape = self.shape().sub_width(1).unwrap();
521         let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
522         self.push_rewrite(mac.span, rewrite);
523     }
524
525     pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
526         self.format_missing_with_indent(source!(self, span).lo());
527         let result = rewrite.unwrap_or_else(|| self.snippet(span));
528         self.buffer.push_str(&result);
529         self.last_pos = source!(self, span).hi();
530     }
531
532     pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
533         FmtVisitor {
534             parse_session: parse_session,
535             codemap: parse_session.codemap(),
536             buffer: StringBuffer::new(),
537             last_pos: BytePos(0),
538             block_indent: Indent::empty(),
539             config: config,
540             is_if_else_block: false,
541         }
542     }
543
544     pub fn opt_snippet(&self, span: Span) -> Option<String> {
545         self.codemap.span_to_snippet(span).ok()
546     }
547
548     pub fn snippet(&self, span: Span) -> String {
549         match self.codemap.span_to_snippet(span) {
550             Ok(s) => s,
551             Err(_) => {
552                 eprintln!(
553                     "Couldn't make snippet for span {:?}->{:?}",
554                     self.codemap.lookup_char_pos(span.lo()),
555                     self.codemap.lookup_char_pos(span.hi())
556                 );
557                 "".to_owned()
558             }
559         }
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         }
757     }
758 }
759
760 impl Rewrite for ast::NestedMetaItem {
761     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
762         match self.node {
763             ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
764             ast::NestedMetaItemKind::Literal(ref l) => rewrite_literal(context, l, shape),
765         }
766     }
767 }
768
769 impl Rewrite for ast::MetaItem {
770     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
771         Some(match self.node {
772             ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
773             ast::MetaItemKind::List(ref list) => {
774                 let name = self.name.as_str();
775                 // 1 = `(`, 2 = `]` and `)`
776                 let item_shape = shape
777                     .visual_indent(0)
778                     .shrink_left(name.len() + 1)
779                     .and_then(|s| s.sub_width(2))?;
780                 let items = itemize_list(
781                     context.codemap,
782                     list.iter(),
783                     ")",
784                     ",",
785                     |nested_meta_item| nested_meta_item.span.lo(),
786                     |nested_meta_item| nested_meta_item.span.hi(),
787                     |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
788                     self.span.lo(),
789                     self.span.hi(),
790                     false,
791                 );
792                 let item_vec = items.collect::<Vec<_>>();
793                 let fmt = ListFormatting {
794                     tactic: DefinitiveListTactic::Mixed,
795                     separator: ",",
796                     trailing_separator: SeparatorTactic::Never,
797                     separator_place: SeparatorPlace::Back,
798                     shape: item_shape,
799                     ends_with_newline: false,
800                     preserve_newline: false,
801                     config: context.config,
802                 };
803                 format!("{}({})", name, write_list(&item_vec, &fmt)?)
804             }
805             ast::MetaItemKind::NameValue(ref literal) => {
806                 let name = self.name.as_str();
807                 // 3 = ` = `
808                 let lit_shape = shape.shrink_left(name.len() + 3)?;
809                 let value = rewrite_literal(context, literal, lit_shape)?;
810                 format!("{} = {}", name, value)
811             }
812         })
813     }
814 }
815
816 impl Rewrite for ast::Attribute {
817     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
818         let prefix = match self.style {
819             ast::AttrStyle::Inner => "#!",
820             ast::AttrStyle::Outer => "#",
821         };
822         let snippet = context.snippet(self.span);
823         if self.is_sugared_doc {
824             let doc_shape = Shape {
825                 width: cmp::min(shape.width, context.config.comment_width())
826                     .checked_sub(shape.indent.width())
827                     .unwrap_or(0),
828                 ..shape
829             };
830             rewrite_comment(&snippet, false, doc_shape, context.config)
831         } else {
832             if contains_comment(&snippet) {
833                 return Some(snippet);
834             }
835             // 1 = `[`
836             let shape = shape.offset_left(prefix.len() + 1)?;
837             self.meta()?
838                 .rewrite(context, shape)
839                 .map(|rw| format!("{}[{}]", prefix, rw))
840         }
841     }
842 }
843
844 /// Returns the first group of attributes that fills the given predicate.
845 /// We consider two doc comments are in different group if they are separated by normal comments.
846 fn take_while_with_pred<'a, P>(
847     context: &RewriteContext,
848     attrs: &'a [ast::Attribute],
849     pred: P,
850 ) -> &'a [ast::Attribute]
851 where
852     P: Fn(&ast::Attribute) -> bool,
853 {
854     let mut last_index = 0;
855     let mut iter = attrs.iter().enumerate().peekable();
856     while let Some((i, attr)) = iter.next() {
857         if !pred(attr) {
858             break;
859         }
860         if let Some(&(_, next_attr)) = iter.peek() {
861             // Extract comments between two attributes.
862             let span_between_attr = mk_sp(attr.span.hi(), next_attr.span.lo());
863             let snippet = context.snippet(span_between_attr);
864             if count_newlines(&snippet) >= 2 || snippet.contains('/') {
865                 break;
866             }
867         }
868         last_index = i;
869     }
870     if last_index == 0 {
871         &[]
872     } else {
873         &attrs[..last_index + 1]
874     }
875 }
876
877 fn rewrite_first_group_attrs(
878     context: &RewriteContext,
879     attrs: &[ast::Attribute],
880     shape: Shape,
881 ) -> Option<(usize, String)> {
882     if attrs.is_empty() {
883         return Some((0, String::new()));
884     }
885     // Rewrite doc comments
886     let sugared_docs = take_while_with_pred(context, attrs, |a| a.is_sugared_doc);
887     if !sugared_docs.is_empty() {
888         let snippet = sugared_docs
889             .iter()
890             .map(|a| context.snippet(a.span))
891             .collect::<Vec<_>>()
892             .join("\n");
893         return Some((
894             sugared_docs.len(),
895             rewrite_comment(&snippet, false, shape, context.config)?,
896         ));
897     }
898     // Rewrite `#[derive(..)]`s.
899     if context.config.merge_derives() {
900         let derives = take_while_with_pred(context, attrs, is_derive);
901         if !derives.is_empty() {
902             let mut derive_args = vec![];
903             for derive in derives {
904                 derive_args.append(&mut get_derive_args(context, derive)?);
905             }
906             return Some((derives.len(), format_derive(context, &derive_args, shape)?));
907         }
908     }
909     // Rewrite the first attribute.
910     Some((1, attrs[0].rewrite(context, shape)?))
911 }
912
913 fn has_newlines_before_after_comment(comment: &str) -> (&str, &str) {
914     // Look at before and after comment and see if there are any empty lines.
915     let comment_begin = comment.chars().position(|c| c == '/');
916     let len = comment_begin.unwrap_or_else(|| comment.len());
917     let mlb = count_newlines(&comment[..len]) > 1;
918     let mla = if comment_begin.is_none() {
919         mlb
920     } else {
921         let comment_end = comment.chars().rev().position(|c| !c.is_whitespace());
922         let len = comment_end.unwrap();
923         comment
924             .chars()
925             .rev()
926             .take(len)
927             .filter(|c| *c == '\n')
928             .count() > 1
929     };
930     (if mlb { "\n" } else { "" }, if mla { "\n" } else { "" })
931 }
932
933 impl<'a> Rewrite for [ast::Attribute] {
934     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
935         if self.is_empty() {
936             return Some(String::new());
937         }
938         let (first_group_len, first_group_str) = rewrite_first_group_attrs(context, self, shape)?;
939         if self.len() == 1 || first_group_len == self.len() {
940             Some(first_group_str)
941         } else {
942             let rest_str = self[first_group_len..].rewrite(context, shape)?;
943             let missing_span = mk_sp(
944                 self[first_group_len - 1].span.hi(),
945                 self[first_group_len].span.lo(),
946             );
947             // Preserve an empty line before/after doc comments.
948             if self[0].is_sugared_doc || self[first_group_len].is_sugared_doc {
949                 let snippet = context.snippet(missing_span);
950                 let (mla, mlb) = has_newlines_before_after_comment(&snippet);
951                 let comment = ::comment::recover_missing_comment_in_span(
952                     missing_span,
953                     shape.with_max_width(context.config),
954                     context,
955                     0,
956                 )?;
957                 let comment = if comment.is_empty() {
958                     format!("\n{}", mlb)
959                 } else {
960                     format!("{}{}\n{}", mla, comment, mlb)
961                 };
962                 Some(format!(
963                     "{}{}{}{}",
964                     first_group_str,
965                     comment,
966                     shape.indent.to_string(context.config),
967                     rest_str
968                 ))
969             } else {
970                 combine_strs_with_missing_comments(
971                     context,
972                     &first_group_str,
973                     &rest_str,
974                     missing_span,
975                     shape,
976                     false,
977                 )
978             }
979         }
980     }
981 }
982
983 // Format `#[derive(..)]`, using visual indent & mixed style when we need to go multiline.
984 fn format_derive(context: &RewriteContext, derive_args: &[String], shape: Shape) -> Option<String> {
985     let mut result = String::with_capacity(128);
986     result.push_str("#[derive(");
987     // 11 = `#[derive()]`
988     let initial_budget = shape.width.checked_sub(11)?;
989     let mut budget = initial_budget;
990     let num = derive_args.len();
991     for (i, a) in derive_args.iter().enumerate() {
992         // 2 = `, ` or `)]`
993         let width = a.len() + 2;
994         if width > budget {
995             if i > 0 {
996                 // Remove trailing whitespace.
997                 result.pop();
998             }
999             result.push('\n');
1000             // 9 = `#[derive(`
1001             result.push_str(&(shape.indent + 9).to_string(context.config));
1002             budget = initial_budget;
1003         } else {
1004             budget = budget.checked_sub(width).unwrap_or(0);
1005         }
1006         result.push_str(a);
1007         if i != num - 1 {
1008             result.push_str(", ")
1009         }
1010     }
1011     result.push_str(")]");
1012     Some(result)
1013 }
1014
1015 fn is_derive(attr: &ast::Attribute) -> bool {
1016     match attr.meta() {
1017         Some(meta_item) => match meta_item.node {
1018             ast::MetaItemKind::List(..) => meta_item.name.as_str() == "derive",
1019             _ => false,
1020         },
1021         _ => false,
1022     }
1023 }
1024
1025 /// Returns the arguments of `#[derive(...)]`.
1026 fn get_derive_args(context: &RewriteContext, attr: &ast::Attribute) -> Option<Vec<String>> {
1027     attr.meta().and_then(|meta_item| match meta_item.node {
1028         ast::MetaItemKind::List(ref args) if meta_item.name.as_str() == "derive" => {
1029             // Every argument of `derive` should be `NestedMetaItemKind::Literal`.
1030             Some(
1031                 args.iter()
1032                     .map(|a| context.snippet(a.span))
1033                     .collect::<Vec<_>>(),
1034             )
1035         }
1036         _ => None,
1037     })
1038 }
1039
1040 // Rewrite `extern crate foo;` WITHOUT attributes.
1041 pub fn rewrite_extern_crate(context: &RewriteContext, item: &ast::Item) -> Option<String> {
1042     assert!(is_extern_crate(item));
1043     let new_str = context.snippet(item.span);
1044     Some(if contains_comment(&new_str) {
1045         new_str
1046     } else {
1047         let no_whitespace = &new_str.split_whitespace().collect::<Vec<&str>>().join(" ");
1048         String::from(&*Regex::new(r"\s;").unwrap().replace(no_whitespace, ";"))
1049     })
1050 }