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