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