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