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